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
change latex author to & contributors
2513efc27af3e0f7b6e66d1b8cf8ea4c4190d83a
<ide><path>docs/conf.py <ide> <ide> # General information about the project. <ide> project = u'Celery' <del>copyright = u'2009-2011, Ask Solem & contributors' <add>copyright = u'2009-2011, Ask Solem & Contributors' <ide> <ide> # The version info for the project you're documenting, acts as replacement for <ide> # |version| and |release|, also used in various other places throughout the <ide> <ide> latex_documents = [ <ide> ('index', 'Celery.tex', ur'Celery Documentation', <del> ur'Ask Solem', 'manual'), <add> ur'Ask Solem & Contributors', 'manual'), <ide> ] <ide> <ide> html_theme = "celery"
1
Javascript
Javascript
fix code block of ember.string.capitalize
018661de496991d9b7d8e1eadcbbf4e7973bbd1e
<ide><path>packages/ember-runtime/lib/system/string.js <ide> Ember.String = { <ide> /** <ide> Returns the Capitalized form of a string <ide> <del> 'innerHTML'.capitalize() // 'InnerHTML' <del> 'action_name'.capitalize() // 'Action_name' <del> 'css-class-name'.capitalize() // 'Css-class-name' <del> 'my favorite items'.capitalize() // 'My favorite items' <add> ```javascript <add> 'innerHTML'.capitalize() // 'InnerHTML' <add> 'action_name'.capitalize() // 'Action_name' <add> 'css-class-name'.capitalize() // 'Css-class-name' <add> 'my favorite items'.capitalize() // 'My favorite items' <add> ``` <ide> <ide> @method capitalize <ide> @param {String} str
1
Python
Python
create simple binary search
7b3d385ad62a74b7e984c9b5424006566e4f848d
<ide><path>searches/simple-binary-search.py <add># A binary search implementation to test if a number is in a list of elements <add> <add> <add>def binary_search(a_list, item): <add> """ <add> >>> test_list = [0, 1, 2, 8, 13, 17, 19, 32, 42] <add> >>> print(binary_search(test_list, 3)) <add> False <add> >>> print(binary_search(test_list, 13)) <add> True <add> """ <add> if len(a_list) == 0: <add> return False <add> midpoint = len(a_list) // 2 <add> if a_list[midpoint] == item: <add> return True <add> if item < a_list[midpoint]: <add> return binary_search(a_list[:midpoint], item) <add> else: <add> return binary_search(a_list[midpoint + 1 :], item) <add> <add> <add>if __name__ == "__main__": <add> import doctest <add> <add> doctest.testmod()
1
Text
Text
add example of ternary operator
25b6f1d9249d260d392e0ddd4c6887bebf842b50
<ide><path>guide/english/ruby/ruby-conditionals/index.md <ide> The above statement equal to the statement below <ide> ``` <ide> ## Ternary Statement <ide> A ternary statement is used as a short conditional statement. It is written as follows <add> <add> *variable = condition ? true_result : false_result* <ide> * ```ruby <ide> game = "won" <ide> fans = game == "won" ? "happy" : unhappy <ide> A case statement is similar to an if/elsif/else statement <ide> else <ide> puts "This is not an apple or an orange" <ide> end <del> ``` <ide>\ No newline at end of file <add> ```
1
Ruby
Ruby
add module for managing git config settings
f1f3fdc315238e6f86892f6228f7da5c5eb462a3
<ide><path>Library/Homebrew/brew.rb <ide> class MissingEnvironmentVariables < RuntimeError; end <ide> ENV["PATH"] = path <ide> <ide> require "commands" <add> require "settings" <ide> <ide> if cmd <ide> internal_cmd = Commands.valid_internal_cmd?(cmd) <ide> internal_cmd ||= begin <ide> internal_dev_cmd = Commands.valid_internal_dev_cmd?(cmd) <ide> if internal_dev_cmd && !Homebrew::EnvConfig.developer? <del> if (HOMEBREW_REPOSITORY/".git/config").exist? <del> system "git", "config", "--file=#{HOMEBREW_REPOSITORY}/.git/config", <del> "--replace-all", "homebrew.devcmdrun", "true" <del> end <add> Settings.write "devcmdrun", true <ide> ENV["HOMEBREW_DEV_CMD_RUN"] = "1" <ide> end <ide> internal_dev_cmd <ide><path>Library/Homebrew/cmd/update-report.rb <ide> require "cleanup" <ide> require "description_cache_store" <ide> require "cli/parser" <add>require "settings" <ide> <ide> module Homebrew <ide> extend T::Sig <ide> def update_report <ide> Utils::Analytics.messages_displayed! if $stdout.tty? <ide> end <ide> <del> HOMEBREW_REPOSITORY.cd do <del> donation_message_displayed = <del> Utils.popen_read("git", "config", "--get", "homebrew.donationmessage").chomp == "true" <del> if !donation_message_displayed && !args.quiet? <del> ohai "Homebrew is run entirely by unpaid volunteers. Please consider donating:" <del> puts " #{Formatter.url("https://github.com/Homebrew/brew#donations")}\n" <add> if Settings.read("donationmessage") != "true" && !args.quiet? <add> ohai "Homebrew is run entirely by unpaid volunteers. Please consider donating:" <add> puts " #{Formatter.url("https://github.com/Homebrew/brew#donations")}\n" <ide> <del> # Consider the message possibly missed if not a TTY. <del> safe_system "git", "config", "--replace-all", "homebrew.donationmessage", "true" if $stdout.tty? <del> end <add> # Consider the message possibly missed if not a TTY. <add> Settings.write "donationmessage", true if $stdout.tty? <ide> end <ide> <ide> install_core_tap_if_necessary <ide> def update_report <ide> puts "Updated Homebrew from #{shorten_revision(initial_revision)} to #{shorten_revision(current_revision)}." <ide> updated = true <ide> <del> old_tag = if (HOMEBREW_REPOSITORY/".git/config").exist? <del> Utils.popen_read( <del> "git", "config", "--file=#{HOMEBREW_REPOSITORY}/.git/config", "--get", "homebrew.latesttag" <del> ).chomp.presence <del> end <add> old_tag = Settings.read "latesttag" <ide> <ide> new_tag = Utils.popen_read( <ide> "git", "-C", HOMEBREW_REPOSITORY, "tag", "--list", "--sort=-version:refname", "*.*" <ide> ).lines.first.chomp <ide> <ide> if new_tag != old_tag <del> system "git", "config", "--file=#{HOMEBREW_REPOSITORY}/.git/config", <del> "--replace-all", "homebrew.latesttag", new_tag <add> Settings.write "latesttag", new_tag <ide> new_repository_version = new_tag <ide> end <ide> end <ide><path>Library/Homebrew/completions.rb <ide> # frozen_string_literal: true <ide> <ide> require "utils/link" <add>require "settings" <ide> <ide> # Helper functions for generating shell completions. <ide> # <ide> module Completions <ide> <ide> sig { void } <ide> def link! <del> write_completions_option "yes" <add> Settings.write :linkcompletions, true <ide> Tap.each do |tap| <ide> Utils::Link.link_completions tap.path, "brew completions link" <ide> end <ide> end <ide> <ide> sig { void } <ide> def unlink! <del> write_completions_option "no" <add> Settings.write :linkcompletions, false <ide> Tap.each do |tap| <ide> next if tap.official? <ide> <ide> def unlink! <ide> <ide> sig { returns(T::Boolean) } <ide> def link_completions? <del> read_completions_option == "yes" <add> Settings.read(:linkcompletions) == "true" <ide> end <ide> <ide> sig { returns(T::Boolean) } <ide> def completions_to_link? <ide> false <ide> end <ide> <del> sig { params(option: String).returns(String) } <del> def read_completions_option(option: "linkcompletions") <del> HOMEBREW_REPOSITORY.cd do <del> Utils.popen_read("git", "config", "--get", "homebrew.#{option}").chomp <del> end <del> end <del> <del> sig { params(state: String, option: String).void } <del> def write_completions_option(state, option: "linkcompletions") <del> HOMEBREW_REPOSITORY.cd do <del> T.unsafe(self).safe_system "git", "config", "--replace-all", "homebrew.#{option}", state.to_s <del> end <del> end <del> <ide> sig { void } <ide> def show_completions_message_if_needed <del> return if read_completions_option(option: "completionsmessageshown") == "yes" <add> return if Settings.read(:completionsmessageshown) == "true" <ide> return unless completions_to_link? <ide> <ide> T.unsafe(self).ohai "Homebrew completions for external commands are unlinked by default!" <ide> def show_completions_message_if_needed <ide> Then, follow the directions at #{Formatter.url("https://docs.brew.sh/Shell-Completion")} <ide> EOS <ide> <del> write_completions_option("yes", option: "completionsmessageshown") <add> Settings.write :completionsmessageshown, true <ide> end <ide> end <ide><path>Library/Homebrew/settings.rb <add># typed: true <add># frozen_string_literal: true <add> <add># Helper functions for reading and writing settings. <add># <add># @api private <add>module Settings <add> extend T::Sig <add> <add> module_function <add> <add> sig { params(setting: T.any(String, Symbol), repo: Pathname).returns(T.nilable(String)) } <add> def read(setting, repo: HOMEBREW_REPOSITORY) <add> return unless (repo/".git/config").exist? <add> <add> repo.cd do <add> Utils.popen_read("git", "config", "--get", "homebrew.#{setting}").chomp.presence <add> end <add> end <add> <add> sig { params(setting: T.any(String, Symbol), value: T.any(String, T::Boolean), repo: Pathname).void } <add> def write(setting, value, repo: HOMEBREW_REPOSITORY) <add> return unless (repo/".git/config").exist? <add> <add> repo.cd do <add> T.unsafe(self).safe_system "git", "config", "--replace-all", "homebrew.#{setting}", value.to_s <add> end <add> end <add> <add> sig { params(setting: T.any(String, Symbol), repo: Pathname).void } <add> def delete(setting, repo: HOMEBREW_REPOSITORY) <add> return unless (repo/".git/config").exist? <add> return if read(setting, repo: repo).blank? <add> <add> repo.cd do <add> T.unsafe(self).safe_system "git", "config", "--unset-all", "homebrew.#{setting}" <add> end <add> end <add>end <ide><path>Library/Homebrew/tap.rb <ide> require "completions" <ide> require "extend/cachable" <ide> require "description_cache_store" <add>require "settings" <ide> <ide> # A {Tap} is used to extend the formulae provided by Homebrew core. <ide> # Usually, it's synced with a remote Git repository. And it's likely <ide> def [](key) <ide> return unless tap.git? <ide> return unless Utils::Git.available? <ide> <del> tap.path.cd do <del> Utils.popen_read("git", "config", "--get", "homebrew.#{key}").chomp.presence <del> end <add> Settings.read key, repo: tap.path <ide> end <ide> <ide> def []=(key, value) <ide> return unless tap.git? <ide> return unless Utils::Git.available? <ide> <del> tap.path.cd do <del> safe_system "git", "config", "--replace-all", "homebrew.#{key}", value.to_s <del> end <add> Settings.write key, value.to_s, repo: tap.path <ide> end <ide> end <ide> <ide><path>Library/Homebrew/test/completions_spec.rb <add># typed: false <add># frozen_string_literal: true <add> <add>require "completions" <add> <add>describe Completions do <add> let(:internal_path) { HOMEBREW_REPOSITORY/"Library/Taps/homebrew/homebrew-bar" } <add> let(:external_path) { HOMEBREW_REPOSITORY/"Library/Taps/foo/homebrew-bar" } <add> <add> before do <add> HOMEBREW_REPOSITORY.cd do <add> system "git", "init" <add> end <add> internal_path.mkpath <add> external_path.mkpath <add> end <add> <add> def setup_completions(external:) <add> (internal_path/"completions/bash/foo_internal").write "#foo completions" <add> if external <add> (external_path/"completions/bash/foo_external").write "#foo completions" <add> elsif (external_path/"completions/bash/foo_external").exist? <add> (external_path/"completions/bash/foo_external").delete <add> end <add> end <add> <add> def setup_completions_setting(state, setting: "linkcompletions") <add> HOMEBREW_REPOSITORY.cd do <add> system "git", "config", "--replace-all", "homebrew.#{setting}", state.to_s <add> end <add> end <add> <add> def read_completions_setting(setting: "linkcompletions") <add> HOMEBREW_REPOSITORY.cd do <add> Utils.popen_read("git", "config", "--get", "homebrew.#{setting}").chomp.presence <add> end <add> end <add> <add> def delete_completions_setting(setting: "linkcompletions") <add> HOMEBREW_REPOSITORY.cd do <add> system "git", "config", "--unset-all", "homebrew.#{setting}" <add> end <add> end <add> <add> after do <add> FileUtils.rm_rf internal_path <add> FileUtils.rm_rf external_path.dirname <add> end <add> <add> describe ".link!" do <add> it "sets homebrew.linkcompletions to true" do <add> setup_completions_setting false <add> expect { described_class.link! }.not_to raise_error <add> expect(read_completions_setting).to eq "true" <add> end <add> <add> it "sets homebrew.linkcompletions to true if unset" do <add> delete_completions_setting <add> expect { described_class.link! }.not_to raise_error <add> expect(read_completions_setting).to eq "true" <add> end <add> <add> it "keeps homebrew.linkcompletions set to true" do <add> setup_completions_setting true <add> expect { described_class.link! }.not_to raise_error <add> expect(read_completions_setting).to eq "true" <add> end <add> end <add> <add> describe ".unlink!" do <add> it "sets homebrew.linkcompletions to false" do <add> setup_completions_setting true <add> expect { described_class.unlink! }.not_to raise_error <add> expect(read_completions_setting).to eq "false" <add> end <add> <add> it "sets homebrew.linkcompletions to false if unset" do <add> delete_completions_setting <add> expect { described_class.unlink! }.not_to raise_error <add> expect(read_completions_setting).to eq "false" <add> end <add> <add> it "keeps homebrew.linkcompletions set to false" do <add> setup_completions_setting false <add> expect { described_class.unlink! }.not_to raise_error <add> expect(read_completions_setting).to eq "false" <add> end <add> end <add> <add> describe ".link_completions?" do <add> it "returns true if homebrew.linkcompletions is true" do <add> setup_completions_setting true <add> expect(described_class.link_completions?).to be true <add> end <add> <add> it "returns false if homebrew.linkcompletions is false" do <add> setup_completions_setting false <add> expect(described_class.link_completions?).to be false <add> end <add> <add> it "returns false if homebrew.linkcompletions is not set" do <add> expect(described_class.link_completions?).to be false <add> end <add> end <add> <add> describe ".completions_to_link?" do <add> it "returns false if only internal taps have completions" do <add> setup_completions external: false <add> expect(described_class.completions_to_link?).to be false <add> end <add> <add> it "returns true if external taps have completions" do <add> setup_completions external: true <add> expect(described_class.completions_to_link?).to be true <add> end <add> end <add> <add> describe ".show_completions_message_if_needed" do <add> it "doesn't show the message if there are no completions to link" do <add> setup_completions external: false <add> delete_completions_setting setting: :completionsmessageshown <add> expect { described_class.show_completions_message_if_needed }.not_to output.to_stdout <add> end <add> <add> it "doesn't show the message if there are completions to link but the message has already been shown" do <add> setup_completions external: true <add> setup_completions_setting true, setting: :completionsmessageshown <add> expect { described_class.show_completions_message_if_needed }.not_to output.to_stdout <add> end <add> <add> it "shows the message if there are completions to link and the message hasn't already been shown" do <add> setup_completions external: true <add> delete_completions_setting setting: :completionsmessageshown <add> <add> # This will fail because the method calls `puts`. <add> # If we output the `ohai` andcatch the error, we can be usre that the message is showing. <add> error_message = "private method `puts' called for Completions:Module" <add> expect { described_class.show_completions_message_if_needed } <add> .to output.to_stdout <add> .and raise_error(NoMethodError, error_message) <add> end <add> end <add>end <ide><path>Library/Homebrew/test/settings_spec.rb <add># typed: false <add># frozen_string_literal: true <add> <add>require "settings" <add> <add>describe Settings do <add> before do <add> HOMEBREW_REPOSITORY.cd do <add> system "git", "init" <add> end <add> end <add> <add> def setup_setting <add> HOMEBREW_REPOSITORY.cd do <add> system "git", "config", "--replace-all", "homebrew.foo", "true" <add> end <add> end <add> <add> describe ".read" do <add> it "returns the correct value for a setting" do <add> setup_setting <add> expect(described_class.read("foo")).to eq "true" <add> end <add> <add> it "returns the correct value for a setting as a symbol" do <add> setup_setting <add> expect(described_class.read(:foo)).to eq "true" <add> end <add> <add> it "returns nil when setting is not set" do <add> setup_setting <add> expect(described_class.read("bar")).to be_nil <add> end <add> <add> it "runs on a repo without a configuration file" do <add> expect { described_class.read("foo", repo: HOMEBREW_REPOSITORY/"bar") }.not_to raise_error <add> end <add> end <add> <add> describe ".write" do <add> it "writes over an existing value" do <add> setup_setting <add> described_class.write :foo, false <add> expect(described_class.read("foo")).to eq "false" <add> end <add> <add> it "writes a new value" do <add> setup_setting <add> described_class.write :bar, "abcde" <add> expect(described_class.read("bar")).to eq "abcde" <add> end <add> <add> it "returns if the repo doesn't have a configuration file" do <add> expect { described_class.write("foo", repo: HOMEBREW_REPOSITORY/"bar") }.not_to raise_error <add> end <add> end <add> <add> describe ".delete" do <add> it "deletes an existing setting" do <add> setup_setting <add> described_class.delete(:foo) <add> expect(described_class.read("foo")).to be_nil <add> end <add> <add> it "deletes a non-existing setting" do <add> setup_setting <add> expect { described_class.delete(:bar) }.not_to raise_error <add> end <add> <add> it "returns if the repo doesn't have a configuration file" do <add> expect { described_class.delete("foo", repo: HOMEBREW_REPOSITORY/"bar") }.not_to raise_error <add> end <add> end <add>end <ide><path>Library/Homebrew/test/tap_spec.rb <ide> def setup_git_repo <ide> def setup_completion(link:) <ide> HOMEBREW_REPOSITORY.cd do <ide> system "git", "init" <del> system "git", "config", "--replace-all", "homebrew.linkcompletions", link <del> system "git", "config", "--replace-all", "homebrew.completionsmessageshown", "yes" <add> system "git", "config", "--replace-all", "homebrew.linkcompletions", link.to_s <add> system "git", "config", "--replace-all", "homebrew.completionsmessageshown", "true" <ide> end <ide> end <ide> <ide> def setup_completion(link:) <ide> specify "#install and #uninstall" do <ide> setup_tap_files <ide> setup_git_repo <del> setup_completion link: "yes" <add> setup_completion link: true <ide> <ide> tap = described_class.new("Homebrew", "bar") <ide> <ide> def setup_completion(link:) <ide> specify "#link_completions_and_manpages when completions are enabled for non-official tap" do <ide> setup_tap_files <ide> setup_git_repo <del> setup_completion link: "yes" <add> setup_completion link: true <ide> tap = described_class.new("NotHomebrew", "baz") <ide> tap.install clone_target: subject.path/".git" <ide> (HOMEBREW_PREFIX/"share/man/man1/brew-tap-cmd.1").delete <ide> def setup_completion(link:) <ide> specify "#link_completions_and_manpages when completions are disabled for non-official tap" do <ide> setup_tap_files <ide> setup_git_repo <del> setup_completion link: "no" <add> setup_completion link: false <ide> tap = described_class.new("NotHomebrew", "baz") <ide> tap.install clone_target: subject.path/".git" <ide> (HOMEBREW_PREFIX/"share/man/man1/brew-tap-cmd.1").delete <ide> def setup_completion(link:) <ide> specify "#link_completions_and_manpages when completions are enabled for official tap" do <ide> setup_tap_files <ide> setup_git_repo <del> setup_completion link: "no" <add> setup_completion link: false <ide> tap = described_class.new("Homebrew", "baz") <ide> tap.install clone_target: subject.path/".git" <ide> (HOMEBREW_PREFIX/"share/man/man1/brew-tap-cmd.1").delete <ide><path>Library/Homebrew/utils/analytics.rb <ide> <ide> require "context" <ide> require "erb" <add>require "settings" <ide> <ide> module Utils <ide> # Helper module for fetching and reporting analytics data. <ide> def no_message_output? <ide> end <ide> <ide> def uuid <del> config_get(:analyticsuuid) <add> Settings.read :analyticsuuid <ide> end <ide> <ide> def messages_displayed! <del> config_set(:analyticsmessage, true) <del> config_set(:caskanalyticsmessage, true) <add> Settings.write :analyticsmessage, true <add> Settings.write :caskanalyticsmessage, true <ide> end <ide> <ide> def enable! <del> config_set(:analyticsdisabled, false) <add> Settings.write :analyticsdisabled, false <ide> messages_displayed! <ide> end <ide> <ide> def disable! <del> config_set(:analyticsdisabled, true) <add> Settings.write :analyticsdisabled, true <ide> regenerate_uuid! <ide> end <ide> <ide> def regenerate_uuid! <ide> # it will be regenerated in next run unless disabled. <del> config_delete(:analyticsuuid) <add> Settings.delete :analyticsuuid <ide> end <ide> <ide> def output(args:, filter: nil) <ide> def table_output(category, days, results, os_version: false, cask_install: false <ide> end <ide> <ide> def config_true?(key) <del> config_get(key) == "true" <del> end <del> <del> def config_get(key) <del> HOMEBREW_REPOSITORY.cd do <del> Utils.popen_read("git", "config", "--get", "homebrew.#{key}").chomp <del> end <del> end <del> <del> def config_set(key, value) <del> HOMEBREW_REPOSITORY.cd do <del> safe_system "git", "config", "--replace-all", "homebrew.#{key}", value.to_s <del> end <del> end <del> <del> def config_delete(key) <del> HOMEBREW_REPOSITORY.cd do <del> system "git", "config", "--unset-all", "homebrew.#{key}" <del> end <add> Settings.read(key) == "true" <ide> end <ide> <ide> def formulae_brew_sh_json(endpoint)
9
Text
Text
add more help on using glamor (#165)
47d057134185c5a60d5690c94e339e5f5bcace8b
<ide><path>README.md <ide> That means pages never load unnecessary code! <ide> <ide> ### CSS <ide> <del>We use [glamor](https://github.com/threepointone/glamor) to provide a great built-in solution for CSS isolation and modularization without trading off any CSS features <add>We use [glamor](https://github.com/threepointone/glamor) to provide a great built-in solution for CSS isolation and modularization without trading off any CSS features. <add> <add>Glamor's [HowTo](https://github.com/threepointone/glamor/blob/master/docs/howto.md) shows converting various CSS use cases to Glamor. See Glamor's [API docs](https://github.com/threepointone/glamor/blob/master/docs/api.md) for more details. <ide> <ide> ```jsx <ide> import React from 'react' <del>import css from 'next/css' <add>import css, {insertRule} from 'next/css' <ide> <ide> export default () => ( <ide> <div className={style}> <ide> Hello world <ide> </div> <ide> ) <ide> <add>// Global CSS rule <add>insertRule("html, body { margin: 0; padding: 0; }") <add> <ide> const style = css({ <ide> background: 'red', <ide> ':hover': {
1
PHP
PHP
add coverage for invalid renderer
3a9c474205aa55849c353e106620f0b963b3a6e7
<ide><path>tests/TestCase/Error/DebuggerTest.php <ide> public function testOutputErrorDescriptionEncoding(): void <ide> } <ide> <ide> /** <del> * Test setOutputFormat overwrite <add> * Test invalid class and addRenderer() <add> */ <add> public function testAddRendererInvalid(): void <add> { <add> $this->expectException(InvalidArgumentException::class); <add> Debugger::addRenderer('test', stdClass::class); <add> } <add> <add> /** <add> * Test addFormat() overwriting addRenderer() <ide> */ <ide> public function testAddOutputFormatOverwrite(): void <ide> {
1
Javascript
Javascript
fix typo in comment
f15640f551aca825b0ac5e50a48c751e7ec267ad
<ide><path>lib/JsonpMainTemplatePlugin.js <ide> JsonpMainTemplatePlugin.prototype.apply = function(mainTemplate) { <ide> "return Promise.resolve();" <ide> ]), <ide> "", <del> "// an Promise means \"currently loading\".", <add> "// a Promise means \"currently loading\".", <ide> "if(installedChunks[chunkId]) {", <ide> this.indent([ <ide> "return installedChunks[chunkId][2];"
1
PHP
PHP
use associative array
06e7eeae00434d600beafcc42d63fef63bff9a78
<ide><path>src/Mailer/Email.php <ide> public function send($content = null): array <ide> */ <ide> public function render(?string $content = null): void <ide> { <del> list($this->_message, <del> $this->_boundary, <del> $this->_textMessage, <del> $this->_htmlMessage <del> ) = $this->getRenderer()->render($this, $content); <add> $content = $this->getRenderer()->render($this, $content); <add> <add> $this->_message = $content['message']; <add> $this->_boundary = $content['boundary']; <add> $this->_textMessage = $content['textMessage']; <add> $this->_htmlMessage = $content['htmlMessage']; <ide> } <ide> <ide> /** <ide><path>src/Mailer/Renderer.php <ide> public function render(Email $email, ?string $content = null): array <ide> $msg[] = ''; <ide> } <ide> <del> return [$msg, $boundary, $textMessage, $htmlMessage]; <add> return [ <add> 'message' => $msg, <add> 'boundary' => $boundary, <add> 'textMessage' => $textMessage, <add> 'htmlMessage' => $htmlMessage, <add> ]; <ide> } <ide> <ide> /**
2
PHP
PHP
remove port numbers from message-id domains
853d866c3567da6a832f4617d07ef3796110af01
<ide><path>lib/Cake/Network/Email/CakeEmail.php <ide> public function __construct($config = null) { <ide> if ($this->_appCharset !== null) { <ide> $this->charset = $this->_appCharset; <ide> } <del> $this->_domain = env('HTTP_HOST'); <add> $this->_domain = preg_replace('/\:\d+$/', '', env('HTTP_HOST')); <ide> if (empty($this->_domain)) { <ide> $this->_domain = php_uname('n'); <ide> } <ide><path>lib/Cake/Test/Case/Network/Email/CakeEmailTest.php <ide> public function testDomain() { <ide> * @return void <ide> */ <ide> public function testMessageIdWithDomain() { <del> $result = $this->CakeEmail->getHeaders(); <del> $expected = '@' . (env('HTTP_HOST') ? env('HTTP_HOST') : php_uname('n')) . '>'; <del> $this->assertTextContains($expected, $result['Message-ID']); <del> <ide> $this->CakeEmail->domain('example.org'); <ide> $result = $this->CakeEmail->getHeaders(); <ide> $expected = '@example.org>'; <ide> $this->assertTextContains($expected, $result['Message-ID']); <add> <add> $_SERVER['HTTP_HOST'] = 'example.org'; <add> $result = $this->CakeEmail->getHeaders(); <add> $this->assertTextContains('example.org', $result['Message-ID']); <add> <add> $_SERVER['HTTP_HOST'] = 'example.org:81'; <add> $result = $this->CakeEmail->getHeaders(); <add> $this->assertTextNotContains(':81', $result['Message-ID']); <ide> } <ide> <ide> /**
2
Ruby
Ruby
allow commands that look like options
326321c1fdcba7717ec27e3db8cec9c0dfe15069
<ide><path>Library/Homebrew/cli/parser.rb <ide> def parse_remaining(argv, ignore_invalid_options: false) <ide> remaining = [] <ide> <ide> argv, non_options = split_non_options(argv) <add> allow_commands = Array(@named_args_type).include?(:command) <ide> <ide> while i < argv.count <ide> begin <ide> def parse_remaining(argv, ignore_invalid_options: false) <ide> i += 1 <ide> end <ide> rescue OptionParser::InvalidOption <del> if ignore_invalid_options <add> if ignore_invalid_options || (allow_commands && Commands.path(arg)) <ide> remaining << arg <ide> else <ide> $stderr.puts generate_help_text <ide><path>Library/Homebrew/test/cli/parser_spec.rb <ide> Homebrew::CLI::MaxNamedArgumentsError, /This command does not take more than 1 formula or cask argument/ <ide> ) <ide> end <add> <add> it "accepts commands with :command" do <add> parser = described_class.new do <add> named_args :command <add> end <add> expect { parser.parse(["--prefix", "--version"]) }.not_to raise_error <add> end <add> <add> it "doesn't accept invalid options with :command" do <add> parser = described_class.new do <add> named_args :command <add> end <add> expect { parser.parse(["--not-a-command"]) }.to raise_error(OptionParser::InvalidOption, /--not-a-command/) <add> end <ide> end <ide> end
2
Text
Text
add guide of certificate/api/create a model
3eab20af322c42d1ef1fa0e8a5dd73f6f9d16cc3
<ide><path>guide/english/certifications/apis-and-microservices/mongodb-and-mongoose/create-a-model/index.md <ide> title: Create a Model <ide> --- <ide> ## Create a Model <ide> <del>This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/apis-and-microservices/mongodb-and-mongoose/create-a-model/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>. <del> <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>### Creating Schema <add>See the [Mongoose docs](https://mongoosejs.com/docs/guide.html) first where is a lot of useful stuff. <add>When you are building schema you can use either of three options for name validation <add>```javascript <add>name: String <add>name: {type: String} <add>name: {type: String, required: true} //preferred <add>``` <add>For array of favoriteFoods here is the validation: <add>```javascript <add>favoriteFoods: [{ type: String }] <add>``` <add>### Creating a Model <add>Now that we have the schema of our model, we can actually create a model by: <add>```javascript <add>var Model = mongoose.model('Model', modelSchema); <add>``` <ide> <ide> <!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
1
Javascript
Javascript
deprecate nonstandard promise.prototype.done
35800962c16a33eb8e9ff1adfd428cf00bb670d3
<ide><path>Libraries/Core/polyfillPromise.js <ide> 'use strict'; <ide> <ide> const {polyfillGlobal} = require('../Utilities/PolyfillFunctions'); <add>const warnOnce = require('../Utilities/warnOnce'); <ide> <ide> /** <ide> * Set up Promise. The native Promise implementation throws the following error: <ide> if (global?.HermesInternal?.hasPromise?.()) { <ide> } else { <ide> polyfillGlobal('Promise', () => require('../Promise')); <ide> } <add> <add>if (__DEV__) { <add> // $FlowFixMe <add> const done = Promise.prototype.done; <add> if (done != null) { <add> let depth = 0; <add> /* eslint-disable no-extend-native */ <add> // $FlowFixMe <add> Promise.prototype.done = function () { <add> ++depth; <add> try { <add> // Avoid infinite recursion if done() happens to be triggered by warnOnce. <add> if (depth === 1) { <add> // Warn once per unique call stack. Not super efficient, but we're in <add> // __DEV__ and .done() calls are rare to begin with. <add> const key = new Error().stack; <add> warnOnce( <add> key, <add> 'Promise.prototype.done(): This nonstandard polyfill ' + <add> 'has been deprecated and will be removed in a future release. ' + <add> 'Please instead use `.then()`.', <add> ); <add> } <add> } finally { <add> --depth; <add> } <add> return done.apply(this, arguments); <add> }; <add> /* eslint-enable no-extend-native */ <add> } <add>} <ide><path>Libraries/Interaction/InteractionManager.js <ide> const InteractionManager = { <ide> onFulfill?: ?(void) => ?(Promise<U> | U), <ide> onReject?: ?(error: mixed) => ?(Promise<U> | U), <ide> ) => Promise<U>, <del> done: () => void, <ide> cancel: () => void, <ide> ... <ide> } { <ide> const InteractionManager = { <ide> return { <ide> // $FlowFixMe[method-unbinding] added when improving typing for this parameters <ide> then: promise.then.bind(promise), <del> done: (...args) => { <del> // $FlowFixMe[method-unbinding] added when improving typing for this parameters <del> if (promise.done) { <del> return promise.done(...args); <del> } else { <del> console.warn( <del> 'Tried to call done when not supported by current Promise implementation.', <del> ); <del> } <del> }, <ide> cancel: function () { <ide> _taskQueue.cancelTasks(tasks); <ide> }, <ide><path>Libraries/Interaction/TaskQueue.js <ide> class TaskQueue { <ide> this.hasTasksToProcess() && this._onMoreTasks(); <ide> }) <ide> .catch(ex => { <del> ex.message = `TaskQueue: Error resolving Promise in task ${task.name}: ${ex.message}`; <del> throw ex; <del> }) <del> .done(); <add> setTimeout(() => { <add> ex.message = `TaskQueue: Error resolving Promise in task ${task.name}: ${ex.message}`; <add> throw ex; <add> }, 0); <add> }); <ide> } <ide> } <ide> <ide><path>flow/Promise.js <del>/** <del> * Copyright (c) Meta Platforms, Inc. and 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 strict <del> * @format <del> */ <del> <del>// These annotations are copy/pasted from the built-in Flow definitions for <del>// Native Promises with some non-standard APIs added in <del>declare class Promise<+R> { <del> constructor( <del> callback: ( <del> resolve: (result?: Promise<R> | R) => void, <del> reject: (error?: any) => void, <del> ) => mixed, <del> ): void; <del> <del> then<U>( <del> onFulfill?: ?(value: R) => Promise<U> | ?U, <del> onReject?: ?(error: any) => Promise<U> | ?U, <del> ): Promise<U>; <del> <del> catch<U>(onReject?: (error: any) => ?Promise<U> | U): Promise<U>; <del> <del> static resolve<T>(object?: Promise<T> | T): Promise<T>; <del> static reject<T>(error?: any): Promise<T>; <del> <del> static all<T: Iterable<mixed>>( <del> promises: T, <del> ): Promise<$TupleMap<T, typeof $await>>; <del> static race<T>(promises: Array<Promise<T>>): Promise<T>; <del> <del> // Non-standard APIs <del> <del> // See https://github.com/facebook/fbjs/blob/master/packages/fbjs/src/__forks__/Promise.native.js#L21 <del> finally<U>(onFinally?: ?(value: any) => Promise<U> | U): Promise<U>; <del> <del> done<U>( <del> onFulfill?: ?(value: R) => mixed, <del> onReject?: ?(error: any) => mixed, <del> ): void; <del> <del> static cast<T>(object?: T): Promise<T>; <del>}
4
PHP
PHP
remove testing accessor
5062a9b42632e55ee90b7397141c0b12622447e1
<ide><path>src/Illuminate/Foundation/Testing/Concerns/InteractsWithPages.php <ide> use Exception; <ide> use Illuminate\Support\Str; <ide> use InvalidArgumentException; <add>use Illuminate\Http\UploadedFile; <ide> use Symfony\Component\DomCrawler\Form; <ide> use Symfony\Component\DomCrawler\Crawler; <ide> use Illuminate\Foundation\Testing\HttpException; <del>use Symfony\Component\HttpFoundation\File\UploadedFile; <ide> use PHPUnit_Framework_ExpectationFailedException as PHPUnitException; <ide> <ide> trait InteractsWithPages <ide> protected function convertUploadsForTesting(Form $form, array $uploads) <ide> * @param array $file <ide> * @param array $uploads <ide> * @param string $name <del> * @return \Symfony\Component\HttpFoundation\File\UploadedFile <add> * @return \Illuminate\Http\UploadedFile <ide> */ <ide> protected function getUploadedFileForTesting($file, $uploads, $name) <ide> { <ide><path>src/Illuminate/Http/Request.php <ide> use Closure; <ide> use ArrayAccess; <ide> use SplFileInfo; <del>use ReflectionClass; <ide> use RuntimeException; <ide> use Illuminate\Support\Arr; <ide> use Illuminate\Support\Str; <ide> public function allFiles() <ide> */ <ide> protected function convertUploadedFiles(array $files) <ide> { <del> // Pending "test" property of Symfony's becoming accessible... <del> $property = (new ReflectionClass(SymfonyUploadedFile::class))->getProperty('test'); <del> <del> $property->setAccessible(true); <del> <del> return array_map(function ($file) use ($property) { <add> return array_map(function ($file) { <ide> return is_array($file) <ide> ? $this->convertUploadedFiles($file) <del> : UploadedFile::createFromBase($file, $property->getValue($file)); <add> : UploadedFile::createFromBase($file); <ide> }, $files); <ide> } <ide> <ide><path>src/Illuminate/Http/UploadedFile.php <ide> public function hashName() <ide> * Create a new file instance from a base instance. <ide> * <ide> * @param \Symfony\Component\HttpFoundation\File\UploadedFile $file <del> * @param bool $testing <ide> * @return static <ide> */ <del> public static function createFromBase(SymfonyUploadedFile $file, $testing = false) <add> public static function createFromBase(SymfonyUploadedFile $file) <ide> { <ide> return $file instanceof static ? $file : new static( <ide> $file->getRealPath(), $file->getClientOriginalName(), $file->getClientMimeType(), <del> $file->getClientSize(), $file->getError(), $testing <add> $file->getClientSize(), $file->getError() <ide> ); <ide> } <ide> }
3
Text
Text
adjust markdown table for linting
a4eb7b07e0bea8e340dba61bef6bb12e09ac6c26
<ide><path>test/README.md <ide> GitHub with the `autocrlf` git config flag set to true. <ide> <ide> ## Test Directories <ide> <del>|Directory |Runs on CI |Purpose | <del>|-------------------|---------------|---------------| <del>|abort |Yes |Tests for when the ``` --abort-on-uncaught-exception ``` flag is used.| <del>|addons |Yes |Tests for [addon](https://nodejs.org/api/addons.html) functionality along with some tests that require an addon to function properly.| <del>|addons-napi |Yes |Tests for [n-api](https://nodejs.org/api/n-api.html) functionality.| <del>|async-hooks |Yes |Tests for [async_hooks](https://nodejs.org/api/async_hooks.html) functionality.| <del>|cctest |Yes |C++ tests that are run as part of the build process.| <del>|code-cache |No |Tests for a Node.js binary compiled with V8 code cache.| <del>|common | |Common modules shared among many tests. [Documentation](./common/README.md)| <del>|doctool |Yes |Tests for the documentation generator.| <del>|es-module |Yes |Test ESM module loading.| <del>|fixtures | |Test fixtures used in various tests throughout the test suite.| <del>|internet |No |Tests that make real outbound connections (mainly networking related modules). Tests for networking related modules may also be present in other directories, but those tests do not make outbound connections.| <del>|known_issues |Yes |Tests reproducing known issues within the system. All tests inside of this directory are expected to fail consistently. If a test doesn't fail on certain platforms, those should be skipped via `known_issues.status`.| <del>|message |Yes |Tests for messages that are output for various conditions (```console.log```, error messages etc.)| <del>|parallel |Yes |Various tests that are able to be run in parallel.| <del>|pseudo-tty |Yes |Tests that require stdin/stdout/stderr to be a TTY.| <del>|pummel |No |Various tests for various modules / system functionality operating under load.| <del>|sequential |Yes |Various tests that are run sequentially.| <del>|testpy | |Test configuration utility used by various test suites.| <del>|tick-processor |No |Tests for the V8 tick processor integration. The tests are for the logic in ```lib/internal/v8_prof_processor.js``` and ```lib/internal/v8_prof_polyfill.js```. The tests confirm that the profile processor packages the correct set of scripts from V8 and introduces the correct platform specific logic.| <del>|v8-updates |No |Tests for V8 performance integration.| <add>| Directory | Runs on CI | Purpose | <add>| ------------------- | --------------- | --------------- | <add>| `abort` | Yes | Tests for when the ``` --abort-on-uncaught-exception ``` flag is used. | <add>| `addons` | Yes | Tests for [addon](https://nodejs.org/api/addons.html) functionality along with some tests that require an addon to function properly. | <add>| `addons-napi` | Yes | Tests for [n-api](https://nodejs.org/api/n-api.html) functionality. | <add>| `async-hooks` | Yes | Tests for [async_hooks](https://nodejs.org/api/async_hooks.html) functionality. | <add>| `cctest` | Yes | C++ tests that are run as part of the build process. | <add>| `code-cache` | No | Tests for a Node.js binary compiled with V8 code cache. | <add>| `common` | | Common modules shared among many tests. [Documentation](./common/README.md) | <add>| `doctool` | Yes | Tests for the documentation generator. | <add>| `es-module` | Yes | Test ESM module loading. | <add>| `fixtures` | | Test fixtures used in various tests throughout the test suite. | <add>| `internet` | No | Tests that make real outbound connections (mainly networking related modules). Tests for networking related modules may also be present in other directories, but those tests do not make outbound connections. | <add>| `known_issues` | Yes | Tests reproducing known issues within the system. All tests inside of this directory are expected to fail consistently. If a test doesn't fail on certain platforms, those should be skipped via `known_issues.status`. | <add>| `message` | Yes | Tests for messages that are output for various conditions (```console.log```, error messages etc.) | <add>| `parallel` | Yes | Various tests that are able to be run in parallel. | <add>| `pseudo-tty` | Yes | Tests that require stdin/stdout/stderr to be a TTY. | <add>| `pummel` | No | Various tests for various modules / system functionality operating under load. | <add>| `sequential` | Yes | Various tests that are run sequentially. | <add>| `testpy` | | Test configuration utility used by various test suites. | <add>| `tick-processor` | No | Tests for the V8 tick processor integration. The tests are for the logic in ```lib/internal/v8_prof_processor.js``` and ```lib/internal/v8_prof_polyfill.js```. The tests confirm that the profile processor packages the correct set of scripts from V8 and introduces the correct platform specific logic. | <add>| `v8-updates` | No | Tests for V8 performance integration. |
1
Javascript
Javascript
remove rctlog from prod builds
5db4aad347ad8aec754e227e9afd3f5b4922c120
<ide><path>Libraries/JavaScriptAppEngine/Initialization/InitializeJavaScriptAppEngine.js <ide> function setUpConsole() { <ide> const ExceptionsManager = require('ExceptionsManager'); <ide> ExceptionsManager.installConsoleErrorReporter(); <ide> <del> require('RCTLog'); <add> if (__DEV__) { <add> require('RCTLog'); <add> } <ide> } <ide> <ide> /**
1
Text
Text
add details to with-scoped-external-css
ebfa08fdff12f5de546ec8b303980d206418c672
<ide><path>examples/with-external-scoped-css/README.md <ide> yarn start <ide> #### Supported Langs <ide> The plugin supports the `less`, `scss` and `css` file extensions. It is possible to add support for another pre-processor by creating a function to compile the code. In the example we use `sass` as our css pre-processor <ide> <del>To edit the types you need to go to `.babelrc` <del> <add>You need to edit the `.babelrc` and sometimes the `pre-processor.js` to work with another languages, if you want to use SCSS the solution and explanation (fit with other css-pre-processors) are in this issue <3 [#3053](https://github.com/zeit/next.js/issues/3053) <ide> <ide> #### Attention Points <ide> - Next.js doesn't have support for watching `*.css files. So you will have to edit a Javascript file to re-compile the css. In the future this will be fixed by [#823](https://github.com/zeit/next.js/pull/823). <ide>\ No newline at end of file
1
Python
Python
match typing declaration with implementation
9a134da31bafc12d31f75474a4b354c80545b9b5
<ide><path>src/flask/templating.py <ide> def _render(template: Template, context: dict, app: "Flask") -> str: <ide> <ide> <ide> def render_template( <del> template_name_or_list: t.Union[str, t.List[str]], **context: t.Any <add> template_name_or_list: t.Union[str, Template, t.List[t.Union[str, Template]]], <add> **context: t.Any <ide> ) -> str: <ide> """Renders a template from the template folder with the given <ide> context.
1
Text
Text
add v4.3.0 to changelog
0e2f7e26384eea39bda21111b24b511ee8444525
<ide><path>CHANGELOG.md <ide> # Ember Changelog <ide> <del>### v4.3.0-beta.2 (March 1, 2022) <add>### v4.3.0 (March 21, 2022) <ide> <add>- [#20025](https://github.com/emberjs/ember.js/pull/20025) [BUGFIX] Fix a memory leak in the Router Service class <ide> - [#19971](https://github.com/emberjs/ember.js/pull/19971) [BUGFIX] Don't serialize default Query Params on RouterService <del> <del>### v4.3.0-beta.1 (February 7, 2022) <del> <del>No public API changes or bugfixes. <add>- [#20024](https://github.com/emberjs/ember.js/pull/20024) [BUGFIX] Correctly associate props with factory and owner in FactoryManager <ide> <ide> ### v4.2.0 (February 7, 2022) <ide>
1
Javascript
Javascript
fix prettier issue after merge
830163239131f83304b07584ce299938a975bfad
<ide><path>test/SourceMapDevToolModuleOptionsPlugin.unittest.js <ide> describe("SourceMapDevToolModuleOptionsPlugin", () => { <ide> }); <ide> <ide> describe("with line-to-line true", () => { <del> beforeEach( <del> () => <del> (eventBindings = applyPluginWithOptions( <del> SourceMapDevToolModuleOptionsPlugin, <del> { <del> module: false, <del> lineToLine: true <del> } <del> )) <del> ); <add> beforeEach(() => <add> (eventBindings = applyPluginWithOptions( <add> SourceMapDevToolModuleOptionsPlugin, <add> { <add> module: false, <add> lineToLine: true <add> } <add> ))); <ide> <ide> it("binds one event handler", () => { <ide> expect(eventBindings.length).toBe(1);
1
PHP
PHP
fix wrong phpdoc
ede6ee6b8743449cbef3fa4b59f115cf764c24e0
<ide><path>src/Illuminate/Database/Query/JoinClause.php <ide> public function on($first, $operator = null, $second = null, $boolean = 'and') <ide> * <ide> * @param \Closure|string $first <ide> * @param string|null $operator <del> * @param string|null $second <add> * @param \Illuminate\Database\Query\Expression|string|null $second <ide> * @return \Illuminate\Database\Query\JoinClause <ide> */ <ide> public function orOn($first, $operator = null, $second = null)
1
PHP
PHP
fix failing tests related to table counts
dd201c6da621e952fdfd3ea9d4ba0e5794ef79d9
<ide><path>tests/TestCase/Database/Schema/MysqlSchemaTest.php <ide> public function testListTables() { <ide> $result = $schema->listTables(); <ide> <ide> $this->assertInternalType('array', $result); <del> $this->assertCount(2, $result); <del> $this->assertEquals('schema_articles', $result[0]); <del> $this->assertEquals('schema_authors', $result[1]); <add> $this->assertContains('schema_articles', $result); <add> $this->assertContains('schema_authors', $result); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Database/Schema/PostgresSchemaTest.php <ide> public function testListTables() { <ide> $schema = new SchemaCollection($connection); <ide> $result = $schema->listTables(); <ide> $this->assertInternalType('array', $result); <del> $this->assertCount(2, $result); <del> $this->assertEquals('schema_articles', $result[0]); <del> $this->assertEquals('schema_authors', $result[1]); <add> $this->assertContains('schema_articles', $result); <add> $this->assertContains('schema_authors', $result); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Database/Schema/SqliteSchemaTest.php <ide> public function testConvertCompositePrimaryKey() { <ide> */ <ide> protected function _createTables($connection) { <ide> $this->_needsConnection(); <del> $connection->execute('DROP TABLE IF EXISTS schema_articles'); <del> $connection->execute('DROP TABLE IF EXISTS schema_authors'); <add> <add> $schema = new SchemaCollection($connection); <add> $result = $schema->listTables(); <add> if ( <add> in_array('schema_articles', $result) && <add> in_array('schema_authors', $result) <add> ) { <add> return; <add> } <ide> <ide> $table = <<<SQL <ide> CREATE TABLE schema_authors ( <ide> public function testListTables() { <ide> $result = $schema->listTables(); <ide> <ide> $this->assertInternalType('array', $result); <del> $this->assertCount(3, $result); <del> $this->assertEquals('schema_articles', $result[0]); <del> $this->assertEquals('schema_authors', $result[1]); <del> $this->assertEquals('sqlite_sequence', $result[2]); <add> $this->assertContains('schema_articles', $result); <add> $this->assertContains('schema_authors', $result); <ide> } <ide> <ide> /**
3
Go
Go
log fallback errors as "info"
86061441593f8c768781681db2268bc1ab6d043e
<ide><path>distribution/pull.go <ide> func Pull(ctx context.Context, ref reference.Named, imagePullConfig *ImagePullCo <ide> // append subsequent errors <ide> lastErr = err <ide> } <del> logrus.Errorf("Attempting next endpoint for pull after error: %v", err) <add> logrus.Infof("Attempting next endpoint for pull after error: %v", err) <ide> continue <ide> } <ide> logrus.Errorf("Not continuing with pull after error: %v", err) <ide><path>distribution/pull_v2.go <ide> func (p *v2Puller) Pull(ctx context.Context, ref reference.Named) (err error) { <ide> return err <ide> } <ide> if continueOnError(err) { <del> logrus.Errorf("Error trying v2 registry: %v", err) <ide> return fallbackError{ <ide> err: err, <ide> confirmedV2: p.confirmedV2, <ide><path>distribution/push.go <ide> func Push(ctx context.Context, ref reference.Named, imagePushConfig *ImagePushCo <ide> } <ide> err = fallbackErr.err <ide> lastErr = err <del> logrus.Errorf("Attempting next endpoint for push after error: %v", err) <add> logrus.Infof("Attempting next endpoint for push after error: %v", err) <ide> continue <ide> } <ide> }
3
Javascript
Javascript
compare binaries equal times
31314b697874eabe2308bd26b98b72aff3e13ef6
<ide><path>benchmark/compare.js <ide> if (nodes.length !== 2) <ide> <ide> var spawn = require('child_process').spawn; <ide> var results = {}; <del>var n = 1; <add>var toggle = 1; <add>var r = (+process.env.NODE_BENCH_RUNS || 1) * 2; <ide> <ide> run(); <del> <del>var RUNS = +process.env.NODE_BENCH_RUNS || 1; <del>var r = RUNS; <ide> function run() { <del> // Flip back and forth between the two binaries. <del> if (n === 1) { <del> n--; <del> } else { <del> r--; <del> if (r === 0) <del> return compare(); <del> else <del> n++; <del> } <del> <del> if (n === -1) <add> if (--r < 0) <ide> return compare(); <add> toggle = ++toggle % 2; <ide> <del> var node = nodes[n]; <add> var node = nodes[toggle]; <ide> console.error('running %s', node); <ide> var env = {}; <ide> for (var i in process.env) <ide> env[i] = process.env[i]; <ide> env.NODE = node; <del> var child = spawn('make', [runBench], { env: env }); <ide> <ide> var out = ''; <add> var child = spawn('make', [runBench], { env: env }); <ide> child.stdout.setEncoding('utf8'); <ide> child.stdout.on('data', function(c) { <ide> out += c;
1
Javascript
Javascript
remove private enumerable observers
d342a2a1dc89200a941040e7eefaaede161a39bb
<ide><path>packages/ember-runtime/lib/mixins/array.js <ide> export function objectAt(content, idx) { <ide> } <ide> <ide> export function arrayContentWillChange(array, startIdx, removeAmt, addAmt) { <del> let removing, lim; <del> <ide> // if no args are passed assume everything changes <ide> if (startIdx === undefined) { <ide> startIdx = 0; <ide> export function arrayContentWillChange(array, startIdx, removeAmt, addAmt) { <ide> <ide> sendEvent(array, '@array:before', [array, startIdx, removeAmt, addAmt]); <ide> <del> if (startIdx >= 0 && removeAmt >= 0 && get(array, 'hasEnumerableObservers')) { <del> removing = []; <del> lim = startIdx + removeAmt; <del> <del> for (let idx = startIdx; idx < lim; idx++) { <del> removing.push(objectAt(array, idx)); <del> } <del> } else { <del> removing = removeAmt; <del> } <del> <del> array.enumerableContentWillChange(removing, addAmt); <add> array.enumerableContentWillChange(removeAmt, addAmt); <ide> <ide> return array; <ide> } <ide> export function arrayContentDidChange(array, startIdx, removeAmt, addAmt) { <ide> } <ide> } <ide> <del> let adding; <del> if (startIdx >= 0 && addAmt >= 0 && get(array, 'hasEnumerableObservers')) { <del> adding = []; <del> let lim = startIdx + addAmt; <del> <del> for (let idx = startIdx; idx < lim; idx++) { <del> adding.push(objectAt(array, idx)); <del> } <del> } else { <del> adding = addAmt; <del> } <del> <del> array.enumerableContentDidChange(removeAmt, adding); <add> array.enumerableContentDidChange(removeAmt, addAmt); <ide> <ide> if (array.__each) { <ide> array.__each.arrayDidChange(array, startIdx, removeAmt, addAmt); <ide><path>packages/ember-runtime/lib/mixins/enumerable.js <ide> import { <ide> aliasMethod, <ide> computed, <ide> propertyWillChange, <del> propertyDidChange, <del> addListener, <del> removeListener, <del> sendEvent, <del> hasListeners <add> propertyDidChange <ide> } from 'ember-metal'; <ide> import { assert } from 'ember-debug'; <ide> import compare from '../compare'; <ide> const Enumerable = Mixin.create({ <ide> // ENUMERABLE OBSERVERS <ide> // <ide> <del> /** <del> Registers an enumerable observer. Must implement `Ember.EnumerableObserver` <del> mixin. <del> <del> @method addEnumerableObserver <del> @param {Object} target <del> @param {Object} [opts] <del> @return this <del> @private <del> */ <del> addEnumerableObserver(target, opts) { <del> let willChange = (opts && opts.willChange) || 'enumerableWillChange'; <del> let didChange = (opts && opts.didChange) || 'enumerableDidChange'; <del> let hasObservers = get(this, 'hasEnumerableObservers'); <del> <del> if (!hasObservers) { <del> propertyWillChange(this, 'hasEnumerableObservers'); <del> } <del> <del> addListener(this, '@enumerable:before', target, willChange); <del> addListener(this, '@enumerable:change', target, didChange); <del> <del> if (!hasObservers) { <del> propertyDidChange(this, 'hasEnumerableObservers'); <del> } <del> <del> return this; <del> }, <del> <del> /** <del> Removes a registered enumerable observer. <del> <del> @method removeEnumerableObserver <del> @param {Object} target <del> @param {Object} [opts] <del> @return this <del> @private <del> */ <del> removeEnumerableObserver(target, opts) { <del> let willChange = (opts && opts.willChange) || 'enumerableWillChange'; <del> let didChange = (opts && opts.didChange) || 'enumerableDidChange'; <del> let hasObservers = get(this, 'hasEnumerableObservers'); <del> <del> if (hasObservers) { <del> propertyWillChange(this, 'hasEnumerableObservers'); <del> } <del> <del> removeListener(this, '@enumerable:before', target, willChange); <del> removeListener(this, '@enumerable:change', target, didChange); <del> <del> if (hasObservers) { <del> propertyDidChange(this, 'hasEnumerableObservers'); <del> } <del> <del> return this; <del> }, <del> <del> /** <del> Becomes true whenever the array currently has observers watching changes <del> on the array. <del> <del> @property hasEnumerableObservers <del> @type Boolean <del> @private <del> */ <del> hasEnumerableObservers: computed(function() { <del> return hasListeners(this, '@enumerable:change') || hasListeners(this, '@enumerable:before'); <del> }), <del> <del> <ide> /** <ide> Invoke this method just before the contents of your enumerable will <ide> change. You can either omit the parameters completely or pass the objects <ide> const Enumerable = Mixin.create({ <ide> propertyWillChange(this, 'length'); <ide> } <ide> <del> sendEvent(this, '@enumerable:before', [this, removing, adding]); <del> <ide> return this; <ide> }, <ide> <ide> const Enumerable = Mixin.create({ <ide> adding = null; <ide> } <ide> <del> sendEvent(this, '@enumerable:change', [this, removing, adding]); <del> <ide> if (hasDelta) { <ide> propertyDidChange(this, 'length'); <ide> } <ide><path>packages/ember-runtime/tests/mixins/array_test.js <ide> QUnit.module('notify array observers', { <ide> } <ide> }); <ide> <del>QUnit.test('should notify enumerable observers when called with no params', function(assert) { <add>QUnit.test('should notify array observers when called with no params', function(assert) { <ide> arrayContentWillChange(obj); <ide> assert.deepEqual(observer._before, [obj, 0, -1, -1]); <ide> <ide> QUnit.test('should notify when called with diff length items', function(assert) <ide> assert.deepEqual(observer._after, [obj, 0, 2, 1]); <ide> }); <ide> <del>QUnit.test('removing enumerable observer should disable', function(assert) { <add>QUnit.test('removing array observer should disable', function(assert) { <ide> removeArrayObserver(obj, observer); <ide> arrayContentWillChange(obj); <ide> assert.deepEqual(observer._before, null); <ide> QUnit.test('removing enumerable observer should disable', function(assert) { <ide> assert.deepEqual(observer._after, null); <ide> }); <ide> <del>// .......................................................... <del>// NOTIFY ENUMERABLE OBSERVER <del>// <del> <del>QUnit.module('notify enumerable observers as well', { <del> beforeEach(assert) { <del> obj = DummyArray.create(); <del> <del> observer = EmberObject.extend({ <del> enumerableWillChange() { <del> assert.equal(this._before, null); // should only call once <del> this._before = Array.prototype.slice.call(arguments); <del> }, <del> <del> enumerableDidChange() { <del> assert.equal(this._after, null); // should only call once <del> this._after = Array.prototype.slice.call(arguments); <del> } <del> }).create({ <del> _before: null, <del> _after: null <del> }); <del> <del> obj.addEnumerableObserver(observer); <del> }, <del> <del> afterEach() { <del> obj = observer = null; <del> } <del>}); <del> <del>QUnit.test('should notify enumerable observers when called with no params', function(assert) { <del> arrayContentWillChange(obj); <del> assert.deepEqual(observer._before, [obj, null, null], 'before'); <del> <del> arrayContentDidChange(obj); <del> assert.deepEqual(observer._after, [obj, null, null], 'after'); <del>}); <del> <del>// API variation that included items only <del>QUnit.test('should notify when called with same length items', function(assert) { <del> arrayContentWillChange(obj, 0, 1, 1); <del> assert.deepEqual(observer._before, [obj, ['ITEM-0'], 1], 'before'); <del> <del> arrayContentDidChange(obj, 0, 1, 1); <del> assert.deepEqual(observer._after, [obj, 1, ['ITEM-0']], 'after'); <del>}); <del> <del>QUnit.test('should notify when called with diff length items', function(assert) { <del> arrayContentWillChange(obj, 0, 2, 1); <del> assert.deepEqual(observer._before, [obj, ['ITEM-0', 'ITEM-1'], 1], 'before'); <del> <del> arrayContentDidChange(obj, 0, 2, 1); <del> assert.deepEqual(observer._after, [obj, 2, ['ITEM-0']], 'after'); <del>}); <del> <del>QUnit.test('removing enumerable observer should disable', function(assert) { <del> obj.removeEnumerableObserver(observer); <del> arrayContentWillChange(obj); <del> assert.deepEqual(observer._before, null, 'before'); <del> <del> arrayContentDidChange(obj); <del> assert.deepEqual(observer._after, null, 'after'); <del>}); <del> <ide> // .......................................................... <ide> // @each <ide> // <ide><path>packages/ember-runtime/tests/mixins/enumerable_test.js <ide> let DummyEnum = EmberObject.extend(Enumerable, { <ide> length: 0 <ide> }); <ide> <del>let obj, observer; <add>let obj; <ide> <ide> // .......................................................... <ide> // NOTIFY ENUMERABLE PROPERTY <ide> QUnit.test('should notify when passed old index API with delta', function(assert <ide> obj.enumerableContentDidChange(1, 2); <ide> assert.equal(obj._after, 1); <ide> }); <del> <del>// .......................................................... <del>// NOTIFY ENUMERABLE OBSERVER <del>// <del> <del>QUnit.module('notify enumerable observers', { <del> beforeEach(assert) { <del> obj = DummyEnum.create(); <del> <del> observer = EmberObject.extend({ <del> enumerableWillChange() { <del> assert.equal(this._before, null); // should only call once <del> this._before = Array.prototype.slice.call(arguments); <del> }, <del> <del> enumerableDidChange() { <del> assert.equal(this._after, null); // should only call once <del> this._after = Array.prototype.slice.call(arguments); <del> } <del> }).create({ <del> _before: null, <del> _after: null <del> }); <del> <del> obj.addEnumerableObserver(observer); <del> }, <del> <del> afterEach() { <del> obj = observer = null; <del> } <del>}); <del> <del>QUnit.test('should notify enumerable observers when called with no params', function(assert) { <del> obj.enumerableContentWillChange(); <del> assert.deepEqual(observer._before, [obj, null, null]); <del> <del> obj.enumerableContentDidChange(); <del> assert.deepEqual(observer._after, [obj, null, null]); <del>}); <del> <del>// API variation that included items only <del>QUnit.test('should notify when called with same length items', function(assert) { <del> let added = ['foo']; <del> let removed = ['bar']; <del> <del> obj.enumerableContentWillChange(removed, added); <del> assert.deepEqual(observer._before, [obj, removed, added]); <del> <del> obj.enumerableContentDidChange(removed, added); <del> assert.deepEqual(observer._after, [obj, removed, added]); <del>}); <del> <del>QUnit.test('should notify when called with diff length items', function(assert) { <del> let added = ['foo', 'baz']; <del> let removed = ['bar']; <del> <del> obj.enumerableContentWillChange(removed, added); <del> assert.deepEqual(observer._before, [obj, removed, added]); <del> <del> obj.enumerableContentDidChange(removed, added); <del> assert.deepEqual(observer._after, [obj, removed, added]); <del>}); <del> <del>QUnit.test('should not notify when passed with indexes only', function(assert) { <del> obj.enumerableContentWillChange(1, 2); <del> assert.deepEqual(observer._before, [obj, 1, 2]); <del> <del> obj.enumerableContentDidChange(1, 2); <del> assert.deepEqual(observer._after, [obj, 1, 2]); <del>}); <del> <del>QUnit.test('removing enumerable observer should disable', function(assert) { <del> obj.removeEnumerableObserver(observer); <del> obj.enumerableContentWillChange(); <del> assert.deepEqual(observer._before, null); <del> <del> obj.enumerableContentDidChange(); <del> assert.deepEqual(observer._after, null); <del>}); <ide><path>packages/ember-runtime/tests/suites/enumerable.js <ide> const ObserverClass = EmberObject.extend({ <ide> */ <ide> timesCalled(key) { <ide> return this._keys[key] || 0; <del> }, <del> <del> /* <del> begins acting as an enumerable observer. <del> */ <del> observeEnumerable(obj) { <del> obj.addEnumerableObserver(this); <del> return this; <del> }, <del> <del> stopObserveEnumerable(obj) { <del> obj.removeEnumerableObserver(this); <del> return this; <del> }, <del> <del> enumerableWillChange() { <del> QUnit.config.current.assert.equal(this._before, null, 'should only call once'); <del> this._before = Array.prototype.slice.call(arguments); <del> }, <del> <del> enumerableDidChange() { <del> QUnit.config.current.assert.equal(this._after, null, 'should only call once'); <del> this._after = Array.prototype.slice.call(arguments); <ide> } <ide> }); <ide> <ide><path>packages/ember-runtime/tests/suites/mutable_array/replace.js <ide> suite.test('[A,B,C,D].replace(-1,1) => [A,B,C] + notify', function(assert) { <ide> assert.equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject once'); <ide> }); <ide> <del>suite.test('Adding object should notify enumerable observer', function(assert) { <del> let fixtures = this.newFixture(4); <del> let obj = this.newObject(fixtures); <del> let observer = this.newObserver(obj).observeEnumerable(obj); <del> let item = this.newFixture(1)[0]; <del> <del> obj.replace(2, 2, [item]); <del> <del> assert.deepEqual(observer._before, [obj, [fixtures[2], fixtures[3]], 1], 'before'); <del> assert.deepEqual(observer._after, [obj, 2, [item]], 'after'); <del>}); <del> <ide> suite.test('Adding object should notify array observer', function(assert) { <ide> let fixtures = this.newFixture(4); <ide> let obj = this.newObject(fixtures); <ide><path>packages/ember-runtime/tests/suites/mutable_enumerable/addObject.js <ide> suite.test('[A,B,C].addObject(A) => [A,B,C] + NO notify', function(assert) { <ide> } <ide> }); <ide> <del>suite.test('Adding object should notify enumerable observer', function(assert) { <del> let obj = this.newObject(this.newFixture(3)); <del> let observer = this.newObserver(obj).observeEnumerable(obj); <del> let item = this.newFixture(1)[0]; <del> <del> obj.addObject(item); <del> <del> assert.deepEqual(observer._before, [obj, null, [item]]); <del> assert.deepEqual(observer._after, [obj, null, [item]]); <del>}); <del> <ide> export default suite; <ide><path>packages/ember-runtime/tests/suites/mutable_enumerable/removeObject.js <ide> suite.test('[A,B,C].removeObject(D) => [A,B,C]', function(assert) { <ide> } <ide> }); <ide> <del>suite.test('Removing object should notify enumerable observer', function(assert) { <del> let fixtures = this.newFixture(3); <del> let obj = this.newObject(fixtures); <del> let observer = this.newObserver(obj).observeEnumerable(obj); <del> let item = fixtures[1]; <del> <del> obj.removeObject(item); <del> <del> assert.deepEqual(observer._before, [obj, [item], null]); <del> assert.deepEqual(observer._after, [obj, [item], null]); <del>}); <del> <ide> export default suite; <ide><path>packages/ember-runtime/tests/suites/mutable_enumerable/removeObjects.js <ide> suite.test('[A,B,C].removeObjects([D]) => [A,B,C]', function(assert) { <ide> } <ide> }); <ide> <del>suite.test('Removing objects should notify enumerable observer', function(assert) { <del> let fixtures = this.newFixture(3); <del> let obj = this.newObject(fixtures); <del> let observer = this.newObserver(obj).observeEnumerable(obj); <del> let item = fixtures[1]; <del> <del> obj.removeObjects([item]); <del> <del> assert.deepEqual(observer._before, [obj, [item], null]); <del> assert.deepEqual(observer._after, [obj, [item], null]); <del>}); <del> <ide> export default suite;
9
Javascript
Javascript
clarify ember.nativearray docs
44283a24d5fe3ab809a3a981a51e02e2e82ac68f
<ide><path>packages/ember-runtime/lib/system/native_array.js <ide> NativeArray = NativeArray.without(...ignore); <ide> <ide> /** <ide> Creates an `Ember.NativeArray` from an Array like object. <del> Does not modify the original object. Ember.A is not needed if <add> Does not modify the original object's contents. Ember.A is not needed if <ide> `EmberENV.EXTEND_PROTOTYPES` is `true` (the default value). However, <ide> it is recommended that you use Ember.A when creating addons for <ide> ember or when you can not guarantee that `EmberENV.EXTEND_PROTOTYPES`
1
PHP
PHP
add support for cookies with "samesite" option
8b5c0d849faf5669e3e2930982cb7e26e24d6217
<ide><path>src/Http/Cookie/Cookie.php <ide> class Cookie implements CookieInterface <ide> */ <ide> protected $httpOnly = false; <ide> <add> /** <add> * Samesite <add> * <add> * @var string|null <add> * @psalm-var CookieInterface::SAMESITE_LAX|CookieInterface::SAMESITE_STRICT|null <add> */ <add> protected $sameSite = null; <add> <ide> /** <ide> * Constructor <ide> * <ide> class Cookie implements CookieInterface <ide> * @param string $domain Domain <ide> * @param bool $secure Is secure <ide> * @param bool $httpOnly HTTP Only <add> * @param string|null $sameSite Samesite <ide> */ <ide> public function __construct( <ide> string $name, <ide> public function __construct( <ide> string $path = '/', <ide> string $domain = '', <ide> bool $secure = false, <del> bool $httpOnly = false <add> bool $httpOnly = false, <add> ?string $sameSite = null <ide> ) { <ide> $this->validateName($name); <ide> $this->name = $name; <ide> public function __construct( <ide> $this->httpOnly = $httpOnly; <ide> $this->path = $path; <ide> $this->secure = $secure; <add> if ($sameSite !== null) { <add> $this->validateSameSiteValue($sameSite); <add> $this->sameSite = $sameSite; <add> } <ide> <ide> if ($expiresAt) { <ide> $expiresAt = $expiresAt->setTimezone(new DateTimeZone('GMT')); <ide> } <ide> $this->expiresAt = $expiresAt; <ide> } <ide> <add> /** <add> * Factory method to create Cookie instances. <add> * <add> * @param string $name Cookie name <add> * @param string|array $value Value of the cookie <add> * @param array $options Cookies options. Can contain one of following keys: <add> * expires, path, domain, secure, httponly and samesite. <add> * (Keys must be lowercase). <add> * @return static <add> */ <add> public static function create(string $name, $value, array $options = []) <add> { <add> $options += [ <add> 'expires' => null, <add> 'path' => '/', <add> 'domain' => '', <add> 'secure' => false, <add> 'httponly' => false, <add> 'samesite' => null, <add> ]; <add> <add> return new static( <add> $name, <add> $value, <add> $options['expires'], <add> $options['path'], <add> $options['domain'], <add> $options['secure'], <add> $options['httponly'], <add> $options['samesite'] <add> ); <add> } <add> <ide> /** <ide> * Returns a header value as string <ide> * <ide> public function toHeaderValue(): string <ide> if ($this->domain !== '') { <ide> $headerValue[] = sprintf('domain=%s', $this->domain); <ide> } <add> if ($this->sameSite) { <add> $headerValue[] = sprintf('samesite=%s', $this->sameSite); <add> } <ide> if ($this->secure) { <ide> $headerValue[] = 'secure'; <ide> } <ide> public function withExpired() <ide> return $new; <ide> } <ide> <add> /** <add> * @inheritDoc <add> */ <add> public function getSameSite(): ?string <add> { <add> return $this->sameSite; <add> } <add> <add> /** <add> * @inheritDoc <add> */ <add> public function withSameSite(?string $sameSite) <add> { <add> if ($sameSite !== null) { <add> $this->validateSameSiteValue($sameSite); <add> } <add> <add> $new = clone $this; <add> $new->sameSite = $sameSite; <add> <add> return $new; <add> } <add> <add> /** <add> * Check that value passed for SameSite is valid. <add> * <add> * @param string $sameSite SameSite value <add> * @return void <add> * @throws \InvalidArgumentException <add> */ <add> protected function validateSameSiteValue(string $sameSite) <add> { <add> if (!in_array($sameSite, CookieInterface::SAMESITE_VALUES)) { <add> throw new InvalidArgumentException( <add> 'Samesite value must be either of: ' . implode(',', CookieInterface::SAMESITE_VALUES) <add> ); <add> } <add> } <add> <ide> /** <ide> * Checks if a value exists in the cookie data. <ide> * <ide> public function isExpanded(): bool <ide> return $this->isExpanded; <ide> } <ide> <add> /** <add> * @inheritDoc <add> */ <add> public function getOptions(): array <add> { <add> $options = [ <add> 'expires' => $this->getExpiresTimestamp(), <add> 'path' => $this->path, <add> 'domain' => $this->domain, <add> 'secure' => $this->secure, <add> 'httponly' => $this->httpOnly, <add> ]; <add> <add> if ($this->sameSite !== null) { <add> $options['samesite'] = $this->sameSite; <add> } <add> <add> return $options; <add> } <add> <ide> /** <ide> * Implode method to keep keys are multidimensional arrays <ide> * <ide><path>src/Http/Cookie/CookieCollection.php <ide> protected static function parseSetCookieHeader(array $values): array <ide> $parts = preg_split('/\;[ \t]*/', $value); <ide> <ide> $name = ''; <del> $cookie = [ <add> $cookieOptions = [ <ide> 'value' => '', <ide> 'path' => '', <ide> 'domain' => '', <ide> protected static function parseSetCookieHeader(array $values): array <ide> } <ide> if ($i === 0) { <ide> $name = $key; <del> $cookie['value'] = urldecode((string)$value); <add> $cookieOptions['value'] = urldecode((string)$value); <ide> continue; <ide> } <ide> $key = strtolower($key); <del> if (array_key_exists($key, $cookie) && !strlen((string)$cookie[$key])) { <del> $cookie[$key] = $value; <add> if (array_key_exists($key, $cookieOptions) && !strlen((string)$cookieOptions[$key])) { <add> $cookieOptions[$key] = $value; <ide> } <ide> } <ide> try { <ide> $expires = null; <del> if ($cookie['max-age'] !== null) { <del> $expires = new DateTimeImmutable('@' . (time() + (int)$cookie['max-age'])); <del> } elseif ($cookie['expires'] !== null) { <del> $expires = new DateTimeImmutable('@' . strtotime((string)$cookie['expires'])); <add> if ($cookieOptions['max-age'] !== null) { <add> $expires = new DateTimeImmutable('@' . (time() + (int)$cookieOptions['max-age'])); <add> } elseif ($cookieOptions['expires'] !== null) { <add> $expires = new DateTimeImmutable('@' . strtotime((string)$cookieOptions['expires'])); <ide> } <ide> } catch (Exception $e) { <ide> $expires = null; <ide> } <ide> <add> $cookieOptions['expires'] = $expires; <add> /** @psalm-suppress PossiblyInvalidCast */ <add> $value = (string)$cookieOptions['value']; <add> unset($cookieOptions['value'], $cookieOptions['max-age']); <add> <ide> try { <del> $cookies[] = new Cookie( <add> $cookies[] = Cookie::create( <ide> $name, <del> (string)$cookie['value'], <del> $expires, <del> (string)$cookie['path'], <del> (string)$cookie['domain'], <del> (bool)$cookie['secure'], <del> (bool)$cookie['httponly'] <add> $value, <add> $cookieOptions <ide> ); <ide> } catch (Exception $e) { <ide> // Don't blow up on invalid cookies <ide><path>src/Http/Cookie/CookieInterface.php <ide> interface CookieInterface <ide> */ <ide> public const EXPIRES_FORMAT = 'D, d-M-Y H:i:s T'; <ide> <add> /** <add> * SameSite option value: Lax <add> * <add> * @var string <add> */ <add> public const SAMESITE_LAX = 'Lax'; <add> <add> /** <add> * SameSite option value: Strict <add> * <add> * @var string <add> */ <add> public const SAMESITE_STRICT = 'Strict'; <add> <add> /** <add> * Valid values for "SameSite" option. <add> */ <add> public const SAMESITE_VALUES = [ <add> self::SAMESITE_LAX, <add> self::SAMESITE_STRICT, <add> ]; <add> <ide> /** <ide> * Sets the cookie name <ide> * <ide> public function isSecure(): bool; <ide> */ <ide> public function withSecure(bool $secure); <ide> <add> /** <add> * Get the SameSite attribute. <add> * <add> * @return string|null <add> */ <add> public function getSameSite(): ?string; <add> <add> /** <add> * Create a cookie with an updated SameSite option <add> * <add> * @param string|null $sameSite Value for to set for Samesite option <add> * @return static <add> */ <add> public function withSameSite(?string $sameSite); <add> <add> /** <add> * Get cookie options <add> * <add> * @return array <add> */ <add> public function getOptions(): array; <add> <ide> /** <ide> * Returns the cookie as header value <ide> * <ide><path>src/Http/Response.php <ide> public function getCookies(): array <ide> * where `httponly` is `httpOnly` and `expires` is `expire` <ide> * <ide> * @param \Cake\Http\Cookie\CookieInterface $cookie Cookie object. <del> * @return array <add> * @return array Array with keys 'name', 'value', 'options'. <ide> */ <ide> protected function convertCookieToArray(CookieInterface $cookie): array <ide> { <ide> return [ <ide> 'name' => $cookie->getName(), <ide> 'value' => $cookie->getScalarValue(), <del> 'path' => $cookie->getPath(), <del> 'domain' => $cookie->getDomain(), <del> 'secure' => $cookie->isSecure(), <del> 'httpOnly' => $cookie->isHttpOnly(), <del> 'expire' => $cookie->getExpiresTimestamp(), <add> 'options' => $cookie->getOptions(), <ide> ]; <ide> } <ide> <ide><path>src/Http/ResponseEmitter.php <ide> protected function emitCookies(array $cookies): void <ide> { <ide> foreach ($cookies as $cookie) { <ide> if (is_array($cookie)) { <del> setcookie( <del> $cookie['name'], <del> $cookie['value'], <del> $cookie['expire'], <del> $cookie['path'], <del> $cookie['domain'], <del> $cookie['secure'], <del> $cookie['httpOnly'] <del> ); <add> if (PHP_VERSION_ID >= 70300) { <add> setcookie($cookie['name'], $cookie['value'], $cookie['options']); <add> } else { <add> setcookie( <add> $cookie['name'], <add> $cookie['value'], <add> $cookie['options']['expire'], <add> $cookie['options']['path'], <add> $cookie['options']['domain'], <add> $cookie['options']['secure'], <add> $cookie['options']['httpOnly'] <add> ); <add> } <ide> continue; <ide> } <ide> <ide> protected function emitCookies(array $cookies): void <ide> 'domain' => '', <ide> 'secure' => false, <ide> 'httponly' => false, <add> 'samesite' => null, <ide> ]; <ide> <ide> foreach ($parts as $part) { <ide> protected function emitCookies(array $cookies): void <ide> if (is_string($data['expires'])) { <ide> $data['expires'] = strtotime($data['expires']); <ide> } <del> /** @psalm-suppress PossiblyInvalidArgument */ <del> setcookie( <del> $data['name'], <del> $data['value'], <del> $data['expires'], <del> $data['path'], <del> $data['domain'], <del> $data['secure'], <del> $data['httponly'] <del> ); <add> <add> $name = $data['name']; <add> $value = $data['value']; <add> unset($data['name'], $data['value']); <add> if (!$data['samesite']) { <add> unset($data['samesite']); <add> } <add> <add> if (PHP_VERSION_ID >= 70300) { <add> setcookie($name, $value, $cookie['options']); <add> } else { <add> /** @psalm-suppress PossiblyInvalidArgument */ <add> setcookie( <add> $name, <add> $value, <add> $data['expires'], <add> $data['path'], <add> $data['domain'], <add> $data['secure'], <add> $data['httponly'] <add> ); <add> } <ide> } <ide> } <ide>
5
Javascript
Javascript
use arrow function for callback in lint-sh.js
27c6fdf3b2960c31c8573eb92d3431a5faf0d018
<ide><path>tools/lint-sh.js <ide> if ( <ide> const entryPoint = resolve(process.argv[2]); <ide> const stats = statSync(entryPoint, { throwIfNoEntry: false }); <ide> <del> function onError(e) { <add> const onError = (e) => { <ide> console.log(USAGE_STR); <ide> console.error(e); <ide> process.exitCode = 1; <del> } <add> }; <ide> if (stats?.isDirectory()) { <ide> SPAWN_OPTIONS.cwd = entryPoint; <ide> checkFiles(...findScriptFilesRecursively(entryPoint)).catch(onError);
1
Javascript
Javascript
use colon for hour-minute delimiter in czech
99ae5bbace116733facc03df57d214654c174319
<ide><path>locale/cs.js <ide> weekdaysShort : 'ne_po_út_st_čt_pá_so'.split('_'), <ide> weekdaysMin : 'ne_po_út_st_čt_pá_so'.split('_'), <ide> longDateFormat : { <del> LT: 'H.mm', <add> LT: 'H:mm', <ide> L : 'DD. MM. YYYY', <ide> LL : 'D. MMMM YYYY', <ide> LLL : 'D. MMMM YYYY LT', <ide><path>test/locale/cs.js <ide> exports['locale:cs'] = { <ide> ['DDDo [den v roce]', '45. den v roce'], <ide> ['L', '14. 02. 2010'], <ide> ['LL', '14. únor 2010'], <del> ['LLL', '14. únor 2010 15.25'], <del> ['LLLL', 'neděle 14. únor 2010 15.25'], <add> ['LLL', '14. únor 2010 15:25'], <add> ['LLLL', 'neděle 14. únor 2010 15:25'], <ide> ['l', '14. 2. 2010'], <ide> ['ll', '14. úno 2010'], <del> ['lll', '14. úno 2010 15.25'], <del> ['llll', 'ne 14. úno 2010 15.25'] <add> ['lll', '14. úno 2010 15:25'], <add> ['llll', 'ne 14. úno 2010 15:25'] <ide> ], <ide> b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), <ide> i; <ide> exports['locale:cs'] = { <ide> 'calendar day' : function (test) { <ide> var a = moment().hours(2).minutes(0).seconds(0); <ide> <del> test.equal(moment(a).calendar(), 'dnes v 2.00', 'today at the same time'); <del> test.equal(moment(a).add({m: 25}).calendar(), 'dnes v 2.25', 'Now plus 25 min'); <del> test.equal(moment(a).add({h: 1}).calendar(), 'dnes v 3.00', 'Now plus 1 hour'); <del> test.equal(moment(a).add({d: 1}).calendar(), 'zítra v 2.00', 'tomorrow at the same time'); <del> test.equal(moment(a).subtract({h: 1}).calendar(), 'dnes v 1.00', 'Now minus 1 hour'); <del> test.equal(moment(a).subtract({d: 1}).calendar(), 'včera v 2.00', 'yesterday at the same time'); <add> test.equal(moment(a).calendar(), 'dnes v 2:00', 'today at the same time'); <add> test.equal(moment(a).add({m: 25}).calendar(), 'dnes v 2:25', 'Now plus 25 min'); <add> test.equal(moment(a).add({h: 1}).calendar(), 'dnes v 3:00', 'Now plus 1 hour'); <add> test.equal(moment(a).add({d: 1}).calendar(), 'zítra v 2:00', 'tomorrow at the same time'); <add> test.equal(moment(a).subtract({h: 1}).calendar(), 'dnes v 1:00', 'Now minus 1 hour'); <add> test.equal(moment(a).subtract({d: 1}).calendar(), 'včera v 2:00', 'yesterday at the same time'); <ide> test.done(); <ide> }, <ide>
2
Javascript
Javascript
help button tests
626d286bcacf2a7367b4196c939a84100a27bce0
<ide><path>cypress/integration/learn/common-components/helpButton.js <add>/* global cy */ <add> <add>describe('Help Button', () => { <add> it('should be visible', () => { <add> cy.visit( <add> '/learn/responsive-web-design/basic-html-and-html5/say-hello-to-html-elements' <add> ); <add> cy.get('#get-help-dropdown').scrollIntoView().should('be.visible'); <add> }); <add> <add> it('should toggle the dropdown menu', () => { <add> cy.get('#get-help-dropdown').scrollIntoView().click(); <add> cy.get('ul[role="menu"]').should('be.visible'); <add> }); <add> <add> it('should render three links when video is available', () => { <add> cy.get('ul[role="menu"]').within(() => { <add> cy.get('a').should('have.length', 3); <add> cy.get('a').eq(0).contains('Get a Hint'); <add> cy.get('a').eq(1).contains('Watch a Video'); <add> cy.get('a').eq(2).contains('Ask for Help'); <add> }); <add> }); <add> <add> it('should render two links when video is not available', () => { <add> cy.visit( <add> '/learn/front-end-libraries/bootstrap/apply-the-default-bootstrap-button-style' <add> ); <add> cy.get('#get-help-dropdown').scrollIntoView().click(); <add> cy.get('ul[role="menu"]').within(() => { <add> cy.get('a').should('have.length', 2); <add> cy.get('a').eq(0).contains('Get a Hint'); <add> cy.get('a').eq(1).contains('Ask for Help'); <add> }); <add> }); <add>});
1
Javascript
Javascript
move the debugger tests back to parallel
b95160daae00a5c39b3815c29a0cfcbc395e3824
<add><path>test/parallel/test-debugger-repeat-last.js <del><path>test/sequential/test-debugger-repeat-last.js <ide> const fixture = path.join( <ide> <ide> const args = [ <ide> 'debug', <add> `--port=${common.PORT}`, <ide> fixture <ide> ]; <ide> <add><path>test/parallel/test-debugger-util-regression.js <del><path>test/sequential/test-debugger-util-regression.js <ide> const fixture = path.join( <ide> <ide> const args = [ <ide> 'debug', <add> `--port=${common.PORT}`, <ide> fixture <ide> ]; <ide>
2
PHP
PHP
apply fixes from styleci
4d13ad92ee9dd881d7eb59dde0f31572b8605cf5
<ide><path>tests/View/Blade/BladeComponentTagCompilerTest.php <ide> use Illuminate\Container\Container; <ide> use Illuminate\Contracts\Foundation\Application; <ide> use Illuminate\Contracts\View\Factory; <del>use Illuminate\Filesystem\Filesystem; <ide> use Illuminate\View\Compilers\BladeCompiler; <ide> use Illuminate\View\Compilers\ComponentTagCompiler; <ide> use Illuminate\View\Component;
1
Javascript
Javascript
move lastappprops back where it should be
20c7d98efe0ce4483ff6d06e1ac1060f584530fb
<ide><path>client/index.js <ide> async function doRender ({ Component, props, err, emitter }) { <ide> props = props || lastAppProps.props <ide> <ide> const appProps = { Component, props, err, router, headManager } <add> // lastAppProps has to be set before ReactDom.render to account for ReactDom throwing an error. <add> lastAppProps = appProps <add> <ide> ReactDOM.render(createElement(App, appProps), container) <ide> <ide> if (emitter) { <ide> emitter.emit('after-reactdom-render', { Component }) <ide> } <del> <del> lastAppProps = appProps <ide> }
1
Javascript
Javascript
remove unused flow suppressions
a2aa008b33f9a62b0ed7c30e5c6908e1cc864163
<ide><path>Libraries/Components/ProgressViewIOS/ProgressViewIOS.ios.js <ide> const styles = StyleSheet.create({ <ide> <ide> const ProgressViewIOSWithRef = React.forwardRef(ProgressViewIOS); <ide> <del>/* $FlowFixMe(>=0.89.0 site=react_native_ios_fb) This comment suppresses an <del> * error found when Flow v0.89 was deployed. To see the error, delete this <del> * comment and run Flow. */ <ide> module.exports = (ProgressViewIOSWithRef: typeof RCTProgressViewNativeComponent);
1
Javascript
Javascript
fix issue with how chart.pluginbase is defined
8c90b9f2de6863cca3051276648e363aa332d6a2
<ide><path>src/chart.js <ide> var Chart = require('./core/core.js')(); <ide> require('./core/core.helpers')(Chart); <ide> require('./platforms/platform.js')(Chart); <ide> require('./core/core.canvasHelpers')(Chart); <del>require('./core/core.plugin.js')(Chart); <ide> require('./core/core.element')(Chart); <add>require('./core/core.plugin.js')(Chart); <ide> require('./core/core.animation')(Chart); <ide> require('./core/core.controller')(Chart); <ide> require('./core/core.datasetController')(Chart); <ide><path>src/core/core.plugin.js <ide> module.exports = function(Chart) { <ide> * @todo remove at version 3 <ide> * @private <ide> */ <del> Chart.PluginBase = helpers.inherits({}); <add> Chart.PluginBase = Chart.Element.extend({}); <ide> };
2
Javascript
Javascript
add deprecation helpers
f47febd04503ce49bf5ce56f7e1d57966cc28310
<ide><path>lib/util/deprecation.js <add>/* <add> MIT License http://www.opensource.org/licenses/mit-license.php <add> Author Tobias Koppers @sokra <add>*/ <add> <add>"use strict"; <add> <add>const util = require("util"); <add> <add>const COPY_METHODS = [ <add> "concat", <add> "entry", <add> "filter", <add> "find", <add> "findIndex", <add> "includes", <add> "indexOf", <add> "join", <add> "lastIndexOf", <add> "map", <add> "reduce", <add> "reduceRight", <add> "slice", <add> "some" <add>]; <add> <add>const DISABLED_METHODS = [ <add> "copyWithin", <add> "entries", <add> "fill", <add> "keys", <add> "pop", <add> "reverse", <add> "shift", <add> "splice", <add> "sort", <add> "unshift" <add>]; <add> <add>/** <add> * @param {any} set new set <add> * @param {string} name property name <add> * @returns {void} <add> */ <add>exports.arrayToSetDeprecation = (set, name) => { <add> for (const method of COPY_METHODS) { <add> if (set[method]) continue; <add> set[method] = util.deprecate( <add> /** <add> * @template T <add> * @this {Set} <add> * @returns {any} something <add> */ <add> function() { <add> const array = Array.from(this); <add> return Array.prototype[method].apply(array, arguments); <add> }, <add> `${name} was changed from Array to Set (using Array methods is deprecated)` <add> ); <add> } <add> set.push = util.deprecate( <add> /** <add> * @deprecated <add> * @this {Set} <add> * @returns {number} count <add> */ <add> function() { <add> for (const item of Array.from(arguments)) { <add> this.add(item); <add> } <add> return this.size; <add> }, <add> `${name} was changed from Array to Set (using Array methods is deprecated)` <add> ); <add> for (const method of DISABLED_METHODS) { <add> if (set[method]) continue; <add> set[method] = () => { <add> throw new Error( <add> `${name} was changed from Array to Set (using Array methods is deprecated)` <add> ); <add> }; <add> } <add> Object.defineProperty(set, "length", { <add> get() { <add> return set.size; <add> }, <add> set(value) { <add> throw new Error( <add> `${name} was changed from Array to Set (using Array methods is deprecated)` <add> ); <add> } <add> }); <add>};
1
Go
Go
remove support for runtime v1 api
658a4b0feca1e8d8a885edd8511f55efeeea3950
<ide><path>libcontainerd/remote/client.go <ide> import ( <ide> containerderrors "github.com/containerd/containerd/errdefs" <ide> "github.com/containerd/containerd/events" <ide> "github.com/containerd/containerd/images" <del> "github.com/containerd/containerd/runtime/linux/runctypes" <ide> v2runcoptions "github.com/containerd/containerd/runtime/v2/runc/options" <ide> "github.com/containerd/typeurl" <ide> "github.com/docker/docker/errdefs" <ide> func (c *client) Start(ctx context.Context, id, checkpointDir string, withStdin <ide> opts.IoUid = uint32(uid) <ide> opts.IoGid = uint32(gid) <ide> info.Options = &opts <del> } else { <del> info.Options = &runctypes.CreateOptions{ <del> IoUid: uint32(uid), <del> IoGid: uint32(gid), <del> NoPivotRoot: os.Getenv("DOCKER_RAMDISK") != "", <del> } <ide> } <ide> return nil <ide> }) <ide> func (c *client) getCheckpointOptions(id string, exit bool) containerd.Checkpoin <ide> return func(r *containerd.CheckpointTaskInfo) error { <ide> if r.Options == nil { <ide> c.v2runcoptionsMu.Lock() <del> _, isV2 := c.v2runcoptions[id] <add> _, ok := c.v2runcoptions[id] <ide> c.v2runcoptionsMu.Unlock() <del> <del> if isV2 { <add> if ok { <ide> r.Options = &v2runcoptions.CheckpointOptions{Exit: exit} <del> } else { <del> r.Options = &runctypes.CheckpointOptions{Exit: exit} <ide> } <ide> return nil <ide> } <ide> <ide> switch opts := r.Options.(type) { <ide> case *v2runcoptions.CheckpointOptions: <ide> opts.Exit = exit <del> case *runctypes.CheckpointOptions: <del> opts.Exit = exit <ide> } <ide> <ide> return nil
1
Text
Text
remove extra newline
622b8776631d3739313fc402ade089c05cdbcb26
<ide><path>CHANGELOG.md <ide> * Improved: Use grunt (instead of rake) for build system <del> <ide> * Fixed: Java files not syntax highlighting correctly. <ide> * Fixed: LESS/CSS now indents properly after hitting enter. <ide> * Added: Support for browsing .tar.gz and .zip files in the editor
1
Text
Text
fix typo in `url.md`
8bfb4b98156a653c396bee4f4ab64091d1bb49ad
<ide><path>doc/api/url.md <ide> expected by the [`http.request()`][] and [`https.request()`][] APIs. <ide> import { urlToHttpOptions } from 'url'; <ide> const myURL = new URL('https://a:b@測試?abc#foo'); <ide> <del>console.log(urlToHttpOptions(myUrl)); <add>console.log(urlToHttpOptions(myURL)); <ide> /** <ide> { <ide> protocol: 'https:',
1
Text
Text
add note about asset pipeline and cdns
e85cb2d3bb95ae5cf2f524ffc6828fd40723c83e
<ide><path>guides/source/asset_pipeline.md <ide> group :production do <ide> end <ide> ``` <ide> <add>### CDNs <add> <add>If your assets are being served by a CDN, ensure they don't stick around in <add>your cache forever. This can cause problems. If you use <add>`config.action_controller.perform_caching = true`, Rack::Cache will use <add>`Rails.cache` to store assets. This can cause your cache to fill up quickly. <add> <add>Every CDN is different, so evaluate how your CDN handles caching and make sure <add>that it plays nicely with the pipeline; you may find quirks related to your <add>specific set up. <add> <ide> Customizing the Pipeline <ide> ------------------------ <ide>
1
Python
Python
run memcache tests if any cache is configured
27192564c3193a54165752e8803b4d7b635f9022
<ide><path>tests/regressiontests/cache/tests.py <ide> def test_incr_decr_timeout(self): <ide> <ide> # memcached backend isn't guaranteed to be available. <ide> # To check the memcached backend, the test settings file will <del># need to contain a cache backend setting that points at <add># need to contain at least one cache backend setting that points at <ide> # your memcache server. <ide> @unittest.skipUnless( <del> settings.CACHES[DEFAULT_CACHE_ALIAS]['BACKEND'].startswith('django.core.cache.backends.memcached.'), <add> any(cache['BACKEND'].startswith('django.core.cache.backends.memcached.') <add> for cache in settings.CACHES.values()), <ide> "memcached not available") <ide> class MemcachedCacheTests(unittest.TestCase, BaseCacheTests): <ide> backend_name = 'django.core.cache.backends.memcached.MemcachedCache' <ide> <ide> def setUp(self): <del> name = settings.CACHES[DEFAULT_CACHE_ALIAS]['LOCATION'] <add> for cache in settings.CACHES.values(): <add> if cache['BACKEND'].startswith('django.core.cache.backends.memcached.'): <add> name = cache['LOCATION'] <add> break <ide> self.cache = get_cache(self.backend_name, LOCATION=name) <ide> self.prefix_cache = get_cache(self.backend_name, LOCATION=name, KEY_PREFIX='cacheprefix') <ide> self.v2_cache = get_cache(self.backend_name, LOCATION=name, VERSION=2)
1
Ruby
Ruby
remove superfluous odie
0d3e1119a1155dc60fb9a0840ea4fb2783dc3f37
<ide><path>Library/Homebrew/dev-cmd/bottle.rb <ide> def merge <ide> --keep-old was passed but there are changes in: <ide> #{mismatches.join("\n")} <ide> EOS <del> odie "--keep-old was passed but there were changes in #{mismatches.join(", ")}!" <ide> end <ide> output = bottle_output bottle <ide> end
1
Python
Python
add ner converter for conll 2003 data
735d18654da9481a860c11c398abaa754e05f263
<ide><path>spacy/cli/convert.py <ide> import plac <ide> from pathlib import Path <ide> <del>from .converters import conllu2json, iob2json <add>from .converters import conllu2json, iob2json, conll_ner2json <ide> from ..util import prints <ide> <ide> # Converters are matched by file extension. To add a converter, add a new entry <ide> # to this dict with the file extension mapped to the converter function imported <ide> # from /converters. <ide> <ide> CONVERTERS = { <del> '.conllu': conllu2json, <del> '.conll': conllu2json, <del> '.iob': iob2json, <add> 'conllu': conllu2json, <add> 'conll': conllu2json, <add> 'ner': conll_ner2json, <add> 'iob': iob2json, <ide> } <ide> <ide> <ide> @plac.annotations( <ide> input_file=("input file", "positional", None, str), <ide> output_dir=("output directory for converted file", "positional", None, str), <ide> n_sents=("Number of sentences per doc", "option", "n", int), <add> converter=("Name of converter (auto, iob, conllu or ner)", "option", "c", str), <ide> morphology=("Enable appending morphology to tags", "flag", "m", bool) <ide> ) <del>def convert(cmd, input_file, output_dir, n_sents=1, morphology=False): <add>def convert(cmd, input_file, output_dir, n_sents=1, morphology=False, <add> converter='auto'): <ide> """ <ide> Convert files into JSON format for use with train command and other <ide> experiment management functions. <ide> def convert(cmd, input_file, output_dir, n_sents=1, morphology=False): <ide> prints(input_path, title="Input file not found", exits=1) <ide> if not output_path.exists(): <ide> prints(output_path, title="Output directory not found", exits=1) <del> file_ext = input_path.suffix <del> if not file_ext in CONVERTERS: <del> prints("Can't find converter for %s" % input_path.parts[-1], <del> title="Unknown format", exits=1) <del> CONVERTERS[file_ext](input_path, output_path, <del> n_sents=n_sents, use_morphology=morphology) <add> if converter == 'auto': <add> converter = input_path.suffix[1:] <add> if not converter in CONVERTERS: <add> prints("Can't find converter for %s" % converter, <add> title="Unknown format", exits=1) <add> func = CONVERTERS[converter] <add> func(input_path, output_path, <add> n_sents=n_sents, use_morphology=morphology) <ide><path>spacy/cli/converters/__init__.py <ide> from .conllu2json import conllu2json <ide> from .iob2json import iob2json <add>from .conll_ner2json import conll_ner2json
2
Text
Text
change the instruction text in step 31
414ecbf1c20e3ac4eeec1784a7a8dd2de24b4eb8
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-forms-by-building-a-registration-form/60fabf0dd4959805dbae09e6.md <ide> dashedName: step-31 <ide> <ide> Add another `label` after the first, with the text `Input your age (years): `. Then, nest an `input` with the `type` of `number`. <ide> <del>As we do not want users under the age of 13 to register, add a `min` attribute to the `input` with a value of `13`. Also, we can probably assume users over the age of 120 will not register; add a `max` attribute with a value of `120`. <add>Next, add a `min` attribute to the `input` with a value of `13` because users under the age of 13 should not register. Also, users probably will not be over the age of 120; add a `max` attribute with a value of `120`. <ide> <ide> Now, if someone tries to submit the form with values outside of the range, a warning will appear, and the form will not submit. Give it a try. <ide>
1
Python
Python
remove misleading docstring
1650130b0fd71eb80380c47c8ffed89d49ff3481
<ide><path>examples/text-classification/run_glue.py <ide> # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <ide> # See the License for the specific language governing permissions and <ide> # limitations under the License. <del>""" Finetuning the library models for sequence classification on GLUE (Bert, XLM, XLNet, RoBERTa, Albert, XLM-RoBERTa).""" <add>""" Finetuning the library models for sequence classification on GLUE.""" <ide> <ide> <ide> import dataclasses
1
Javascript
Javascript
add edge to browserstack tests
5ec46b0372147dcecf907b5e6b523b95d93871f7
<ide><path>build/grunt.js <ide> module.exports = function(grunt) { <ide> chrome_bs: { browsers: ['chrome_bs'] }, <ide> firefox_bs: { browsers: ['firefox_bs'] }, <ide> safari_bs: { browsers: ['safari_bs'] }, <add> edge_bs: { browsers: ['edge_bs'] }, <ide> ie11_bs: { browsers: ['ie11_bs'] }, <ide> ie10_bs: { browsers: ['ie10_bs'] }, <ide> ie9_bs: { browsers: ['ie9_bs'] }, <ide><path>test/karma.conf.js <ide> module.exports = function(config) { <ide> 'chrome_bs', <ide> 'firefox_bs', <ide> 'safari_bs', <add> 'edge_bs', <ide> 'ie11_bs', <ide> 'ie10_bs', <ide> 'ie9_bs', <ide> function getCustomLaunchers(){ <ide> os_version: 'Yosemite' <ide> }, <ide> <add> edge_bs: { <add> base: 'BrowserStack', <add> browser: 'edge', <add> os: 'Windows', <add> os_version: '10' <add> }, <add> <ide> ie11_bs: { <ide> base: 'BrowserStack', <ide> browser: 'ie',
2
PHP
PHP
add support for handling redirects
b6253885f08d42e3b1101e3945aa761f62a5735f
<ide><path>lib/Cake/Network/Http/Adapter/Stream.php <ide> class Stream { <ide> * <ide> * @param Cake\Network\Http\Request $request The request object to send. <ide> * @param array $options Array of options for the stream. <del> * @return Cake\Network\Http\Response <add> * @return array Array of populated Response objects <ide> */ <ide> public function send(Request $request, $options) { <ide> $this->_stream = null; <ide> public function send(Request $request, $options) { <ide> return $this->_send($request); <ide> } <ide> <add>/** <add> * Create the response list based on the headers & content <add> * <add> * Creates one or many response objects based on the number <add> * of redirects that occured. <add> * <add> * @param array $headers The list of headers from the request(s) <add> * @param string $content The response content. <add> * @return array The list of responses from the request(s) <add> */ <add> public function createResponses($headers, $content) { <add> $indexes = $responses = []; <add> foreach ($headers as $i => $header) { <add> if (strtoupper(substr($header, 0, 5)) === 'HTTP/') { <add> $indexes[] = $i; <add> } <add> } <add> $last = count($indexes) - 1; <add> foreach ($indexes as $i => $start) { <add> $end = isset($indexes[$i + 1]) ? $indexes[$i + 1] - $start : null; <add> $headerSlice = array_slice($headers, $start, $end); <add> $body = $i == $last ? $content : ''; <add> $responses[] = new Response($headerSlice, $body); <add> } <add> return $responses; <add> } <add> <ide> /** <ide> * Build the stream context out of the request object. <ide> * <ide> protected function _buildOptions(Request $request, $options) { <ide> if (isset($options['timeout'])) { <ide> $this->_contextOptions['timeout'] = $options['timeout']; <ide> } <del> if (!empty($options['redirect'])) { <del> $this->_contextOptions['max_redirects'] = $options['redirect']; <add> if (isset($options['redirect'])) { <add> $this->_contextOptions['max_redirects'] = (int)$options['redirect']; <ide> } <ide> } <ide> <ide> protected function _buildSslContext(Request $request, $options) { <ide> * Open the stream and send the request. <ide> * <ide> * @param Request $request <del> * @return Response The populated response object. <add> * @return array Array of populated Response objects <ide> * @throws Cake\Error\Exception <ide> */ <ide> protected function _send(Request $request) { <ide> protected function _send(Request $request) { <ide> if (isset($meta['wrapper_type']) && $meta['wrapper_type'] === 'curl') { <ide> $headers = $meta['wrapper_data']['headers']; <ide> } <del> return new Response($headers, $content); <add> return $this->createResponses($headers, $content); <ide> } <ide> <ide> /** <ide><path>lib/Cake/Network/Http/Client.php <ide> protected function _mergeOptions($options) { <ide> */ <ide> public function send(Request $request, $options = []) { <ide> // TODO possibly implment support for <del> // holding onto cookies so subsequent requests <add> // holding onto cookies so subsequent requests <ide> // can share cookies. <del> return $this->_adapter->send($request, $options); <add> $responses = $this->_adapter->send($request, $options); <add> return array_pop($responses); <ide> } <ide> <ide> /** <ide><path>lib/Cake/Network/Http/Message.php <ide> public function cookies() { <ide> /** <ide> * Get the HTTP version used. <ide> * <add> * @param null|string $version <ide> * @return string <ide> */ <ide> public function version() { <ide><path>lib/Cake/Test/TestCase/Network/Http/Adapter/StreamTest.php <ide> public function testSend() { <ide> ->header('User-Agent', 'CakePHP TestSuite') <ide> ->cookie('testing', 'value'); <ide> <del> $response = $stream->send($request, []); <del> $this->assertInstanceOf('Cake\Network\Http\Response', $response); <add> $responses = $stream->send($request, []); <add> $this->assertInstanceOf('Cake\Network\Http\Response', $responses[0]); <ide> } <ide> <ide> /** <ide> public function testSendContextSsl() { <ide> } <ide> } <ide> <add>/** <add> * The PHP stream API returns ALL the headers for ALL the requests when <add> * there are redirects. <add> * <add> * @return void <add> */ <add> public function testCreateResponseWithRedirects() { <add> $headers = [ <add> 'HTTP/1.1 302 Found', <add> 'Date: Mon, 31 Dec 2012 16:53:16 GMT', <add> 'Server: Apache/2.2.22 (Unix) DAV/2 PHP/5.4.9 mod_ssl/2.2.22 OpenSSL/0.9.8r', <add> 'X-Powered-By: PHP/5.4.9', <add> 'Location: http://localhost/cake3/tasks/second', <add> 'Content-Length: 0', <add> 'Connection: close', <add> 'Content-Type: text/html; charset=UTF-8', <add> 'Set-Cookie: first=value', <add> 'HTTP/1.1 302 Found', <add> 'Date: Mon, 31 Dec 2012 16:53:16 GMT', <add> 'Server: Apache/2.2.22 (Unix) DAV/2 PHP/5.4.9 mod_ssl/2.2.22 OpenSSL/0.9.8r', <add> 'X-Powered-By: PHP/5.4.9', <add> 'Location: http://localhost/cake3/tasks/third', <add> 'Content-Length: 0', <add> 'Connection: close', <add> 'Content-Type: text/html; charset=UTF-8', <add> 'Set-Cookie: second=val', <add> 'HTTP/1.1 200 OK', <add> 'Date: Mon, 31 Dec 2012 16:53:16 GMT', <add> 'Server: Apache/2.2.22 (Unix) DAV/2 PHP/5.4.9 mod_ssl/2.2.22 OpenSSL/0.9.8r', <add> 'X-Powered-By: PHP/5.4.9', <add> 'Content-Length: 22', <add> 'Connection: close', <add> 'Content-Type: text/html; charset=UTF-8', <add> 'Set-Cookie: third=works', <add> ]; <add> $content = 'This is the third page'; <add> <add> $responses = $this->stream->createResponses($headers, $content); <add> $this->assertCount(3, $responses); <add> $this->assertEquals('close', $responses[0]->header('Connection')); <add> $this->assertEquals('', $responses[0]->body()); <add> $this->assertEquals('', $responses[1]->body()); <add> $this->assertEquals($content, $responses[2]->body()); <add> <add> $this->assertEquals(302, $responses[0]->statusCode()); <add> $this->assertEquals(302, $responses[1]->statusCode()); <add> $this->assertEquals(200, $responses[2]->statusCode()); <add> <add> $this->assertEquals('value', $responses[0]->cookie('first')); <add> $this->assertEquals(null, $responses[0]->cookie('second')); <add> $this->assertEquals(null, $responses[0]->cookie('third')); <add> <add> $this->assertEquals(null, $responses[1]->cookie('first')); <add> $this->assertEquals('val', $responses[1]->cookie('second')); <add> $this->assertEquals(null, $responses[1]->cookie('third')); <add> <add> $this->assertEquals(null, $responses[2]->cookie('first')); <add> $this->assertEquals(null, $responses[2]->cookie('second')); <add> $this->assertEquals('works', $responses[2]->cookie('third')); <add> } <add> <ide> } <ide><path>lib/Cake/Test/TestCase/Network/Http/ClientTest.php <ide> public function testGetSimpleWithHeadersAndCookies() { <ide> $this->attributeEqualTo('_headers', $headers), <ide> $this->attributeEqualTo('_cookies', $cookies) <ide> )) <del> ->will($this->returnValue($response)); <add> ->will($this->returnValue([$response])); <ide> <ide> $http = new Client(['adapter' => $mock]); <ide> $result = $http->get('http://cakephp.org/test.html', [], [ <ide> public function testGetQuerystring() { <ide> $this->attributeEqualTo('_method', Request::METHOD_GET), <ide> $this->attributeEqualTo('_url', 'http://cakephp.org/search?q=hi+there&Category%5Bid%5D%5B0%5D=2&Category%5Bid%5D%5B1%5D=3') <ide> )) <del> ->will($this->returnValue($response)); <add> ->will($this->returnValue([$response])); <ide> <ide> $http = new Client([ <ide> 'host' => 'cakephp.org', <ide> public function testGetWithContent() { <ide> $this->attributeEqualTo('_url', 'http://cakephp.org/search'), <ide> $this->attributeEqualTo('_body', 'some data') <ide> )) <del> ->will($this->returnValue($response)); <add> ->will($this->returnValue([$response])); <ide> <ide> $http = new Client([ <ide> 'host' => 'cakephp.org', <ide> public function testGetWithAuthenticationAndProxy() { <ide> $this->attributeEqualTo('_url', 'http://cakephp.org/'), <ide> $this->attributeEqualTo('_headers', $headers) <ide> )) <del> ->will($this->returnValue($response)); <add> ->will($this->returnValue([$response])); <ide> <ide> $http = new Client([ <ide> 'host' => 'cakephp.org', <ide> public function testMethodsSimple($method) { <ide> $this->attributeEqualTo('_method', $method), <ide> $this->attributeEqualTo('_url', 'http://cakephp.org/projects/add') <ide> )) <del> ->will($this->returnValue($response)); <add> ->will($this->returnValue([$response])); <ide> <ide> $http = new Client([ <ide> 'host' => 'cakephp.org', <ide> public function testPostWithTypeKey($type, $mime) { <ide> $this->attributeEqualTo('_body', $data), <ide> $this->attributeEqualTo('_headers', $headers) <ide> )) <del> ->will($this->returnValue($response)); <add> ->will($this->returnValue([$response])); <ide> <ide> $http = new Client([ <ide> 'host' => 'cakephp.org',
5
Javascript
Javascript
fix some lint nits
7e64ad8fc4defb68deabf10c4bf1d8582e3cbf95
<ide><path>packager/react-packager/src/DependencyResolver/DependencyGraph/ResolutionRequest.js <ide> class ResolutionRequest { <ide> <ide> _resolveNodeDependency(fromModule, toModuleName) { <ide> if (toModuleName[0] === '.' || toModuleName[1] === '/') { <del> return this._resolveFileOrDir(fromModule, toModuleName) <add> return this._resolveFileOrDir(fromModule, toModuleName); <ide> } else { <ide> return this._redirectRequire(fromModule, toModuleName).then( <ide> realModuleName => { <ide> if (realModuleName[0] === '.' || realModuleName[1] === '/') { <ide> // derive absolute path /.../node_modules/fromModuleDir/realModuleName <del> let fromModuleParentIdx = fromModule.path.lastIndexOf('node_modules/') + 13 <del> let fromModuleDir = fromModule.path.slice(0, fromModule.path.indexOf('/', fromModuleParentIdx)) <del> let absPath = path.join(fromModuleDir, realModuleName) <del> return this._resolveFileOrDir(fromModule, absPath) <add> const fromModuleParentIdx = fromModule.path.lastIndexOf('node_modules/') + 13; <add> const fromModuleDir = fromModule.path.slice(0, fromModule.path.indexOf('/', fromModuleParentIdx)); <add> const absPath = path.join(fromModuleDir, realModuleName); <add> return this._resolveFileOrDir(fromModule, absPath); <ide> } <ide> <ide> const searchQueue = [];
1
Javascript
Javascript
fix property name in code comment
147fb6f637dcf788249f622df6f38b591dc81b4d
<ide><path>packages/ember-runtime/lib/mixins/array.js <ide> Ember.Array = Ember.Mixin.create(Ember.Enumerable, /** @scope Ember.Array.protot <ide> Becomes true whenever the array currently has observers watching changes <ide> on the array. <ide> <del> @property Boolean <add> @property {Boolean} hasArrayObservers <ide> */ <ide> hasArrayObservers: Ember.computed(function() { <ide> return Ember.hasListeners(this, '@array:change') || Ember.hasListeners(this, '@array:before');
1
Mixed
Python
update nel examples and documentation
cafe94ee045fe9937cadbdc0e1c96d6eabde5dec
<ide><path>bin/wiki_entity_linking/README.md <del>## Entity Linking with Wikipedia and Wikidata <del> <del>### Step 1: Create a Knowledge Base (KB) and training data <del> <del>Run `wikidata_pretrain_kb.py` <del>* This takes as input the locations of a **Wikipedia and a Wikidata dump**, and produces a **KB directory** + **training file** <del> * WikiData: get `latest-all.json.bz2` from https://dumps.wikimedia.org/wikidatawiki/entities/ <del> * Wikipedia: get `enwiki-latest-pages-articles-multistream.xml.bz2` from https://dumps.wikimedia.org/enwiki/latest/ (or for any other language) <del>* You can set the filtering parameters for KB construction: <del> * `max_per_alias` (`-a`): (max) number of candidate entities in the KB per alias/synonym <del> * `min_freq` (`-f`): threshold of number of times an entity should occur in the corpus to be included in the KB <del> * `min_pair` (`-c`): threshold of number of times an entity+alias combination should occur in the corpus to be included in the KB <del>* Further parameters to set: <del> * `descriptions_from_wikipedia` (`-wp`): whether to parse descriptions from Wikipedia (`True`) or Wikidata (`False`) <del> * `entity_vector_length` (`-v`): length of the pre-trained entity description vectors <del> * `lang` (`-la`): language for which to fetch Wikidata information (as the dump contains all languages) <del> <del>Quick testing and rerunning: <del>* When trying out the pipeline for a quick test, set `limit_prior` (`-lp`), `limit_train` (`-lt`) and/or `limit_wd` (`-lw`) to read only parts of the dumps instead of everything. <del> * e.g. set `-lt 20000 -lp 2000 -lw 3000 -f 1` <del>* If you only want to (re)run certain parts of the pipeline, just remove the corresponding files and they will be recalculated or reparsed. <del> <del> <del>### Step 2: Train an Entity Linking model <del> <del>Run `wikidata_train_entity_linker.py` <del>* This takes the **KB directory** produced by Step 1, and trains an **Entity Linking model** <del>* Specify the output directory (`-o`) in which the final, trained model will be saved <del>* You can set the learning parameters for the EL training: <del> * `epochs` (`-e`): number of training iterations <del> * `dropout` (`-p`): dropout rate <del> * `lr` (`-n`): learning rate <del> * `l2` (`-r`): L2 regularization <del>* Specify the number of training and dev testing articles with `train_articles` (`-t`) and `dev_articles` (`-d`) respectively <del> * If not specified, the full dataset will be processed - this may take a LONG time ! <del>* Further parameters to set: <del> * `labels_discard` (`-l`): NER label types to discard during training <ide><path>bin/wiki_entity_linking/__init__.py <del>TRAINING_DATA_FILE = "gold_entities.jsonl" <del>KB_FILE = "kb" <del>KB_MODEL_DIR = "nlp_kb" <del>OUTPUT_MODEL_DIR = "nlp" <del> <del>PRIOR_PROB_PATH = "prior_prob.csv" <del>ENTITY_DEFS_PATH = "entity_defs.csv" <del>ENTITY_FREQ_PATH = "entity_freq.csv" <del>ENTITY_ALIAS_PATH = "entity_alias.csv" <del>ENTITY_DESCR_PATH = "entity_descriptions.csv" <del> <del>LOG_FORMAT = '%(asctime)s - %(levelname)s - %(name)s - %(message)s' <ide><path>bin/wiki_entity_linking/entity_linker_evaluation.py <del># coding: utf-8 <del>from __future__ import unicode_literals <del> <del>import logging <del>import random <del>from tqdm import tqdm <del>from collections import defaultdict <del> <del>logger = logging.getLogger(__name__) <del> <del> <del>class Metrics(object): <del> true_pos = 0 <del> false_pos = 0 <del> false_neg = 0 <del> <del> def update_results(self, true_entity, candidate): <del> candidate_is_correct = true_entity == candidate <del> <del> # Assume that we have no labeled negatives in the data (i.e. cases where true_entity is "NIL") <del> # Therefore, if candidate_is_correct then we have a true positive and never a true negative. <del> self.true_pos += candidate_is_correct <del> self.false_neg += not candidate_is_correct <del> if candidate and candidate not in {"", "NIL"}: <del> # A wrong prediction (e.g. Q42 != Q3) counts both as a FP as well as a FN. <del> self.false_pos += not candidate_is_correct <del> <del> def calculate_precision(self): <del> if self.true_pos == 0: <del> return 0.0 <del> else: <del> return self.true_pos / (self.true_pos + self.false_pos) <del> <del> def calculate_recall(self): <del> if self.true_pos == 0: <del> return 0.0 <del> else: <del> return self.true_pos / (self.true_pos + self.false_neg) <del> <del> def calculate_fscore(self): <del> p = self.calculate_precision() <del> r = self.calculate_recall() <del> if p + r == 0: <del> return 0.0 <del> else: <del> return 2 * p * r / (p + r) <del> <del> <del>class EvaluationResults(object): <del> def __init__(self): <del> self.metrics = Metrics() <del> self.metrics_by_label = defaultdict(Metrics) <del> <del> def update_metrics(self, ent_label, true_entity, candidate): <del> self.metrics.update_results(true_entity, candidate) <del> self.metrics_by_label[ent_label].update_results(true_entity, candidate) <del> <del> def report_metrics(self, model_name): <del> model_str = model_name.title() <del> recall = self.metrics.calculate_recall() <del> precision = self.metrics.calculate_precision() <del> fscore = self.metrics.calculate_fscore() <del> return ( <del> "{}: ".format(model_str) <del> + "F-score = {} | ".format(round(fscore, 3)) <del> + "Recall = {} | ".format(round(recall, 3)) <del> + "Precision = {} | ".format(round(precision, 3)) <del> + "F-score by label = {}".format( <del> {k: v.calculate_fscore() for k, v in sorted(self.metrics_by_label.items())} <del> ) <del> ) <del> <del> <del>class BaselineResults(object): <del> def __init__(self): <del> self.random = EvaluationResults() <del> self.prior = EvaluationResults() <del> self.oracle = EvaluationResults() <del> <del> def report_performance(self, model): <del> results = getattr(self, model) <del> return results.report_metrics(model) <del> <del> def update_baselines( <del> self, <del> true_entity, <del> ent_label, <del> random_candidate, <del> prior_candidate, <del> oracle_candidate, <del> ): <del> self.oracle.update_metrics(ent_label, true_entity, oracle_candidate) <del> self.prior.update_metrics(ent_label, true_entity, prior_candidate) <del> self.random.update_metrics(ent_label, true_entity, random_candidate) <del> <del> <del>def measure_performance(dev_data, kb, el_pipe, baseline=True, context=True, dev_limit=None): <del> counts = dict() <del> baseline_results = BaselineResults() <del> context_results = EvaluationResults() <del> combo_results = EvaluationResults() <del> <del> for doc, gold in tqdm(dev_data, total=dev_limit, leave=False, desc='Processing dev data'): <del> if len(doc) > 0: <del> correct_ents = dict() <del> for entity, kb_dict in gold.links.items(): <del> start, end = entity <del> for gold_kb, value in kb_dict.items(): <del> if value: <del> # only evaluating on positive examples <del> offset = _offset(start, end) <del> correct_ents[offset] = gold_kb <del> <del> if baseline: <del> _add_baseline(baseline_results, counts, doc, correct_ents, kb) <del> <del> if context: <del> # using only context <del> el_pipe.cfg["incl_context"] = True <del> el_pipe.cfg["incl_prior"] = False <del> _add_eval_result(context_results, doc, correct_ents, el_pipe) <del> <del> # measuring combined accuracy (prior + context) <del> el_pipe.cfg["incl_context"] = True <del> el_pipe.cfg["incl_prior"] = True <del> _add_eval_result(combo_results, doc, correct_ents, el_pipe) <del> <del> if baseline: <del> logger.info("Counts: {}".format({k: v for k, v in sorted(counts.items())})) <del> logger.info(baseline_results.report_performance("random")) <del> logger.info(baseline_results.report_performance("prior")) <del> logger.info(baseline_results.report_performance("oracle")) <del> <del> if context: <del> logger.info(context_results.report_metrics("context only")) <del> logger.info(combo_results.report_metrics("context and prior")) <del> <del> <del>def _add_eval_result(results, doc, correct_ents, el_pipe): <del> """ <del> Evaluate the ent.kb_id_ annotations against the gold standard. <del> Only evaluate entities that overlap between gold and NER, to isolate the performance of the NEL. <del> """ <del> try: <del> doc = el_pipe(doc) <del> for ent in doc.ents: <del> ent_label = ent.label_ <del> start = ent.start_char <del> end = ent.end_char <del> offset = _offset(start, end) <del> gold_entity = correct_ents.get(offset, None) <del> # the gold annotations are not complete so we can't evaluate missing annotations as 'wrong' <del> if gold_entity is not None: <del> pred_entity = ent.kb_id_ <del> results.update_metrics(ent_label, gold_entity, pred_entity) <del> <del> except Exception as e: <del> logging.error("Error assessing accuracy " + str(e)) <del> <del> <del>def _add_baseline(baseline_results, counts, doc, correct_ents, kb): <del> """ <del> Measure 3 performance baselines: random selection, prior probabilities, and 'oracle' prediction for upper bound. <del> Only evaluate entities that overlap between gold and NER, to isolate the performance of the NEL. <del> """ <del> for ent in doc.ents: <del> ent_label = ent.label_ <del> start = ent.start_char <del> end = ent.end_char <del> offset = _offset(start, end) <del> gold_entity = correct_ents.get(offset, None) <del> <del> # the gold annotations are not complete so we can't evaluate missing annotations as 'wrong' <del> if gold_entity is not None: <del> candidates = kb.get_candidates(ent.text) <del> oracle_candidate = "" <del> prior_candidate = "" <del> random_candidate = "" <del> if candidates: <del> scores = [] <del> <del> for c in candidates: <del> scores.append(c.prior_prob) <del> if c.entity_ == gold_entity: <del> oracle_candidate = c.entity_ <del> <del> best_index = scores.index(max(scores)) <del> prior_candidate = candidates[best_index].entity_ <del> random_candidate = random.choice(candidates).entity_ <del> <del> current_count = counts.get(ent_label, 0) <del> counts[ent_label] = current_count+1 <del> <del> baseline_results.update_baselines( <del> gold_entity, <del> ent_label, <del> random_candidate, <del> prior_candidate, <del> oracle_candidate, <del> ) <del> <del> <del>def _offset(start, end): <del> return "{}_{}".format(start, end) <ide><path>bin/wiki_entity_linking/kb_creator.py <del># coding: utf-8 <del>from __future__ import unicode_literals <del> <del>import logging <del> <del>from spacy.kb import KnowledgeBase <del> <del>from bin.wiki_entity_linking.train_descriptions import EntityEncoder <del>from bin.wiki_entity_linking import wiki_io as io <del> <del> <del>logger = logging.getLogger(__name__) <del> <del> <del>def create_kb( <del> nlp, <del> max_entities_per_alias, <del> min_entity_freq, <del> min_occ, <del> entity_def_path, <del> entity_descr_path, <del> entity_alias_path, <del> entity_freq_path, <del> prior_prob_path, <del> entity_vector_length, <del>): <del> # Create the knowledge base from Wikidata entries <del> kb = KnowledgeBase(vocab=nlp.vocab, entity_vector_length=entity_vector_length) <del> entity_list, filtered_title_to_id = _define_entities(nlp, kb, entity_def_path, entity_descr_path, min_entity_freq, entity_freq_path, entity_vector_length) <del> _define_aliases(kb, entity_alias_path, entity_list, filtered_title_to_id, max_entities_per_alias, min_occ, prior_prob_path) <del> return kb <del> <del> <del>def _define_entities(nlp, kb, entity_def_path, entity_descr_path, min_entity_freq, entity_freq_path, entity_vector_length): <del> # read the mappings from file <del> title_to_id = io.read_title_to_id(entity_def_path) <del> id_to_descr = io.read_id_to_descr(entity_descr_path) <del> <del> # check the length of the nlp vectors <del> if "vectors" in nlp.meta and nlp.vocab.vectors.size: <del> input_dim = nlp.vocab.vectors_length <del> logger.info("Loaded pretrained vectors of size %s" % input_dim) <del> else: <del> raise ValueError( <del> "The `nlp` object should have access to pretrained word vectors, " <del> " cf. https://spacy.io/usage/models#languages." <del> ) <del> <del> logger.info("Filtering entities with fewer than {} mentions".format(min_entity_freq)) <del> entity_frequencies = io.read_entity_to_count(entity_freq_path) <del> # filter the entities for in the KB by frequency, because there's just too much data (8M entities) otherwise <del> filtered_title_to_id, entity_list, description_list, frequency_list = get_filtered_entities( <del> title_to_id, <del> id_to_descr, <del> entity_frequencies, <del> min_entity_freq <del> ) <del> logger.info("Kept {} entities from the set of {}".format(len(description_list), len(title_to_id.keys()))) <del> <del> logger.info("Training entity encoder") <del> encoder = EntityEncoder(nlp, input_dim, entity_vector_length) <del> encoder.train(description_list=description_list, to_print=True) <del> <del> logger.info("Getting entity embeddings") <del> embeddings = encoder.apply_encoder(description_list) <del> <del> logger.info("Adding {} entities".format(len(entity_list))) <del> kb.set_entities( <del> entity_list=entity_list, freq_list=frequency_list, vector_list=embeddings <del> ) <del> return entity_list, filtered_title_to_id <del> <del> <del>def _define_aliases(kb, entity_alias_path, entity_list, filtered_title_to_id, max_entities_per_alias, min_occ, prior_prob_path): <del> logger.info("Adding aliases from Wikipedia and Wikidata") <del> _add_aliases( <del> kb, <del> entity_list=entity_list, <del> title_to_id=filtered_title_to_id, <del> max_entities_per_alias=max_entities_per_alias, <del> min_occ=min_occ, <del> prior_prob_path=prior_prob_path, <del> ) <del> <del> <del>def get_filtered_entities(title_to_id, id_to_descr, entity_frequencies, <del> min_entity_freq: int = 10): <del> filtered_title_to_id = dict() <del> entity_list = [] <del> description_list = [] <del> frequency_list = [] <del> for title, entity in title_to_id.items(): <del> freq = entity_frequencies.get(title, 0) <del> desc = id_to_descr.get(entity, None) <del> if desc and freq > min_entity_freq: <del> entity_list.append(entity) <del> description_list.append(desc) <del> frequency_list.append(freq) <del> filtered_title_to_id[title] = entity <del> return filtered_title_to_id, entity_list, description_list, frequency_list <del> <del> <del>def _add_aliases(kb, entity_list, title_to_id, max_entities_per_alias, min_occ, prior_prob_path): <del> wp_titles = title_to_id.keys() <del> <del> # adding aliases with prior probabilities <del> # we can read this file sequentially, it's sorted by alias, and then by count <del> logger.info("Adding WP aliases") <del> with prior_prob_path.open("r", encoding="utf8") as prior_file: <del> # skip header <del> prior_file.readline() <del> line = prior_file.readline() <del> previous_alias = None <del> total_count = 0 <del> counts = [] <del> entities = [] <del> while line: <del> splits = line.replace("\n", "").split(sep="|") <del> new_alias = splits[0] <del> count = int(splits[1]) <del> entity = splits[2] <del> <del> if new_alias != previous_alias and previous_alias: <del> # done reading the previous alias --> output <del> if len(entities) > 0: <del> selected_entities = [] <del> prior_probs = [] <del> for ent_count, ent_string in zip(counts, entities): <del> if ent_string in wp_titles: <del> wd_id = title_to_id[ent_string] <del> p_entity_givenalias = ent_count / total_count <del> selected_entities.append(wd_id) <del> prior_probs.append(p_entity_givenalias) <del> <del> if selected_entities: <del> try: <del> kb.add_alias( <del> alias=previous_alias, <del> entities=selected_entities, <del> probabilities=prior_probs, <del> ) <del> except ValueError as e: <del> logger.error(e) <del> total_count = 0 <del> counts = [] <del> entities = [] <del> <del> total_count += count <del> <del> if len(entities) < max_entities_per_alias and count >= min_occ: <del> counts.append(count) <del> entities.append(entity) <del> previous_alias = new_alias <del> <del> line = prior_file.readline() <del> <del> <del>def read_kb(nlp, kb_file): <del> kb = KnowledgeBase(vocab=nlp.vocab) <del> kb.load_bulk(kb_file) <del> return kb <ide><path>bin/wiki_entity_linking/train_descriptions.py <del># coding: utf-8 <del>from random import shuffle <del> <del>import logging <del>import numpy as np <del> <del>from spacy._ml import zero_init, create_default_optimizer <del>from spacy.cli.pretrain import get_cossim_loss <del> <del>from thinc.v2v import Model <del>from thinc.api import chain <del>from thinc.neural._classes.affine import Affine <del> <del>logger = logging.getLogger(__name__) <del> <del> <del>class EntityEncoder: <del> """ <del> Train the embeddings of entity descriptions to fit a fixed-size entity vector (e.g. 64D). <del> This entity vector will be stored in the KB, for further downstream use in the entity model. <del> """ <del> <del> DROP = 0 <del> BATCH_SIZE = 1000 <del> <del> # Set min. acceptable loss to avoid a 'mean of empty slice' warning by numpy <del> MIN_LOSS = 0.01 <del> <del> # Reasonable default to stop training when things are not improving <del> MAX_NO_IMPROVEMENT = 20 <del> <del> def __init__(self, nlp, input_dim, desc_width, epochs=5): <del> self.nlp = nlp <del> self.input_dim = input_dim <del> self.desc_width = desc_width <del> self.epochs = epochs <del> <del> def apply_encoder(self, description_list): <del> if self.encoder is None: <del> raise ValueError("Can not apply encoder before training it") <del> <del> batch_size = 100000 <del> <del> start = 0 <del> stop = min(batch_size, len(description_list)) <del> encodings = [] <del> <del> while start < len(description_list): <del> docs = list(self.nlp.pipe(description_list[start:stop])) <del> doc_embeddings = [self._get_doc_embedding(doc) for doc in docs] <del> enc = self.encoder(np.asarray(doc_embeddings)) <del> encodings.extend(enc.tolist()) <del> <del> start = start + batch_size <del> stop = min(stop + batch_size, len(description_list)) <del> logger.info("Encoded: {} entities".format(stop)) <del> <del> return encodings <del> <del> def train(self, description_list, to_print=False): <del> processed, loss = self._train_model(description_list) <del> if to_print: <del> logger.info( <del> "Trained entity descriptions on {} ".format(processed) + <del> "(non-unique) descriptions across {} ".format(self.epochs) + <del> "epochs" <del> ) <del> logger.info("Final loss: {}".format(loss)) <del> <del> def _train_model(self, description_list): <del> best_loss = 1.0 <del> iter_since_best = 0 <del> self._build_network(self.input_dim, self.desc_width) <del> <del> processed = 0 <del> loss = 1 <del> # copy this list so that shuffling does not affect other functions <del> descriptions = description_list.copy() <del> to_continue = True <del> <del> for i in range(self.epochs): <del> shuffle(descriptions) <del> <del> batch_nr = 0 <del> start = 0 <del> stop = min(self.BATCH_SIZE, len(descriptions)) <del> <del> while to_continue and start < len(descriptions): <del> batch = [] <del> for descr in descriptions[start:stop]: <del> doc = self.nlp(descr) <del> doc_vector = self._get_doc_embedding(doc) <del> batch.append(doc_vector) <del> <del> loss = self._update(batch) <del> if batch_nr % 25 == 0: <del> logger.info("loss: {} ".format(loss)) <del> processed += len(batch) <del> <del> # in general, continue training if we haven't reached our ideal min yet <del> to_continue = loss > self.MIN_LOSS <del> <del> # store the best loss and track how long it's been <del> if loss < best_loss: <del> best_loss = loss <del> iter_since_best = 0 <del> else: <del> iter_since_best += 1 <del> <del> # stop learning if we haven't seen improvement since the last few iterations <del> if iter_since_best > self.MAX_NO_IMPROVEMENT: <del> to_continue = False <del> <del> batch_nr += 1 <del> start = start + self.BATCH_SIZE <del> stop = min(stop + self.BATCH_SIZE, len(descriptions)) <del> <del> return processed, loss <del> <del> @staticmethod <del> def _get_doc_embedding(doc): <del> indices = np.zeros((len(doc),), dtype="i") <del> for i, word in enumerate(doc): <del> if word.orth in doc.vocab.vectors.key2row: <del> indices[i] = doc.vocab.vectors.key2row[word.orth] <del> else: <del> indices[i] = 0 <del> word_vectors = doc.vocab.vectors.data[indices] <del> doc_vector = np.mean(word_vectors, axis=0) <del> return doc_vector <del> <del> def _build_network(self, orig_width, hidden_with): <del> with Model.define_operators({">>": chain}): <del> # very simple encoder-decoder model <del> self.encoder = Affine(hidden_with, orig_width) <del> self.model = self.encoder >> zero_init( <del> Affine(orig_width, hidden_with, drop_factor=0.0) <del> ) <del> self.sgd = create_default_optimizer(self.model.ops) <del> <del> def _update(self, vectors): <del> predictions, bp_model = self.model.begin_update( <del> np.asarray(vectors), drop=self.DROP <del> ) <del> loss, d_scores = self._get_loss(scores=predictions, golds=np.asarray(vectors)) <del> bp_model(d_scores, sgd=self.sgd) <del> return loss / len(vectors) <del> <del> @staticmethod <del> def _get_loss(golds, scores): <del> loss, gradients = get_cossim_loss(scores, golds) <del> return loss, gradients <ide><path>bin/wiki_entity_linking/wiki_io.py <del># coding: utf-8 <del>from __future__ import unicode_literals <del> <del>import sys <del>import csv <del> <del># min() needed to prevent error on windows, cf https://stackoverflow.com/questions/52404416/ <del>csv.field_size_limit(min(sys.maxsize, 2147483646)) <del> <del>""" This class provides reading/writing methods for temp files """ <del> <del> <del># Entity definition: WP title -> WD ID # <del>def write_title_to_id(entity_def_output, title_to_id): <del> with entity_def_output.open("w", encoding="utf8") as id_file: <del> id_file.write("WP_title" + "|" + "WD_id" + "\n") <del> for title, qid in title_to_id.items(): <del> id_file.write(title + "|" + str(qid) + "\n") <del> <del> <del>def read_title_to_id(entity_def_output): <del> title_to_id = dict() <del> with entity_def_output.open("r", encoding="utf8") as id_file: <del> csvreader = csv.reader(id_file, delimiter="|") <del> # skip header <del> next(csvreader) <del> for row in csvreader: <del> title_to_id[row[0]] = row[1] <del> return title_to_id <del> <del> <del># Entity aliases from WD: WD ID -> WD alias # <del>def write_id_to_alias(entity_alias_path, id_to_alias): <del> with entity_alias_path.open("w", encoding="utf8") as alias_file: <del> alias_file.write("WD_id" + "|" + "alias" + "\n") <del> for qid, alias_list in id_to_alias.items(): <del> for alias in alias_list: <del> alias_file.write(str(qid) + "|" + alias + "\n") <del> <del> <del>def read_id_to_alias(entity_alias_path): <del> id_to_alias = dict() <del> with entity_alias_path.open("r", encoding="utf8") as alias_file: <del> csvreader = csv.reader(alias_file, delimiter="|") <del> # skip header <del> next(csvreader) <del> for row in csvreader: <del> qid = row[0] <del> alias = row[1] <del> alias_list = id_to_alias.get(qid, []) <del> alias_list.append(alias) <del> id_to_alias[qid] = alias_list <del> return id_to_alias <del> <del> <del>def read_alias_to_id_generator(entity_alias_path): <del> """ Read (aliases, qid) tuples """ <del> <del> with entity_alias_path.open("r", encoding="utf8") as alias_file: <del> csvreader = csv.reader(alias_file, delimiter="|") <del> # skip header <del> next(csvreader) <del> for row in csvreader: <del> qid = row[0] <del> alias = row[1] <del> yield alias, qid <del> <del> <del># Entity descriptions from WD: WD ID -> WD alias # <del>def write_id_to_descr(entity_descr_output, id_to_descr): <del> with entity_descr_output.open("w", encoding="utf8") as descr_file: <del> descr_file.write("WD_id" + "|" + "description" + "\n") <del> for qid, descr in id_to_descr.items(): <del> descr_file.write(str(qid) + "|" + descr + "\n") <del> <del> <del>def read_id_to_descr(entity_desc_path): <del> id_to_desc = dict() <del> with entity_desc_path.open("r", encoding="utf8") as descr_file: <del> csvreader = csv.reader(descr_file, delimiter="|") <del> # skip header <del> next(csvreader) <del> for row in csvreader: <del> id_to_desc[row[0]] = row[1] <del> return id_to_desc <del> <del> <del># Entity counts from WP: WP title -> count # <del>def write_entity_to_count(prior_prob_input, count_output): <del> # Write entity counts for quick access later <del> entity_to_count = dict() <del> total_count = 0 <del> <del> with prior_prob_input.open("r", encoding="utf8") as prior_file: <del> # skip header <del> prior_file.readline() <del> line = prior_file.readline() <del> <del> while line: <del> splits = line.replace("\n", "").split(sep="|") <del> # alias = splits[0] <del> count = int(splits[1]) <del> entity = splits[2] <del> <del> current_count = entity_to_count.get(entity, 0) <del> entity_to_count[entity] = current_count + count <del> <del> total_count += count <del> <del> line = prior_file.readline() <del> <del> with count_output.open("w", encoding="utf8") as entity_file: <del> entity_file.write("entity" + "|" + "count" + "\n") <del> for entity, count in entity_to_count.items(): <del> entity_file.write(entity + "|" + str(count) + "\n") <del> <del> <del>def read_entity_to_count(count_input): <del> entity_to_count = dict() <del> with count_input.open("r", encoding="utf8") as csvfile: <del> csvreader = csv.reader(csvfile, delimiter="|") <del> # skip header <del> next(csvreader) <del> for row in csvreader: <del> entity_to_count[row[0]] = int(row[1]) <del> <del> return entity_to_count <ide><path>bin/wiki_entity_linking/wiki_namespaces.py <del># coding: utf8 <del>from __future__ import unicode_literals <del> <del># List of meta pages in Wikidata, should be kept out of the Knowledge base <del>WD_META_ITEMS = [ <del> "Q163875", <del> "Q191780", <del> "Q224414", <del> "Q4167836", <del> "Q4167410", <del> "Q4663903", <del> "Q11266439", <del> "Q13406463", <del> "Q15407973", <del> "Q18616576", <del> "Q19887878", <del> "Q22808320", <del> "Q23894233", <del> "Q33120876", <del> "Q42104522", <del> "Q47460393", <del> "Q64875536", <del> "Q66480449", <del>] <del> <del> <del># TODO: add more cases from non-English WP's <del> <del># List of prefixes that refer to Wikipedia "file" pages <del>WP_FILE_NAMESPACE = ["Bestand", "File"] <del> <del># List of prefixes that refer to Wikipedia "category" pages <del>WP_CATEGORY_NAMESPACE = ["Kategori", "Category", "Categorie"] <del> <del># List of prefixes that refer to Wikipedia "meta" pages <del># these will/should be matched ignoring case <del>WP_META_NAMESPACE = ( <del> WP_FILE_NAMESPACE <del> + WP_CATEGORY_NAMESPACE <del> + [ <del> "b", <del> "betawikiversity", <del> "Book", <del> "c", <del> "Commons", <del> "d", <del> "dbdump", <del> "download", <del> "Draft", <del> "Education", <del> "Foundation", <del> "Gadget", <del> "Gadget definition", <del> "Gebruiker", <del> "gerrit", <del> "Help", <del> "Image", <del> "Incubator", <del> "m", <del> "mail", <del> "mailarchive", <del> "media", <del> "MediaWiki", <del> "MediaWiki talk", <del> "Mediawikiwiki", <del> "MediaZilla", <del> "Meta", <del> "Metawikipedia", <del> "Module", <del> "mw", <del> "n", <del> "nost", <del> "oldwikisource", <del> "otrs", <del> "OTRSwiki", <del> "Overleg gebruiker", <del> "outreach", <del> "outreachwiki", <del> "Portal", <del> "phab", <del> "Phabricator", <del> "Project", <del> "q", <del> "quality", <del> "rev", <del> "s", <del> "spcom", <del> "Special", <del> "species", <del> "Strategy", <del> "sulutil", <del> "svn", <del> "Talk", <del> "Template", <del> "Template talk", <del> "Testwiki", <del> "ticket", <del> "TimedText", <del> "Toollabs", <del> "tools", <del> "tswiki", <del> "User", <del> "User talk", <del> "v", <del> "voy", <del> "w", <del> "Wikibooks", <del> "Wikidata", <del> "wikiHow", <del> "Wikinvest", <del> "wikilivres", <del> "Wikimedia", <del> "Wikinews", <del> "Wikipedia", <del> "Wikipedia talk", <del> "Wikiquote", <del> "Wikisource", <del> "Wikispecies", <del> "Wikitech", <del> "Wikiversity", <del> "Wikivoyage", <del> "wikt", <del> "wiktionary", <del> "wmf", <del> "wmania", <del> "WP", <del> ] <del>) <ide><path>bin/wiki_entity_linking/wikidata_pretrain_kb.py <del># coding: utf-8 <del>"""Script to process Wikipedia and Wikidata dumps and create a knowledge base (KB) <del>with specific parameters. Intermediate files are written to disk. <del> <del>Running the full pipeline on a standard laptop, may take up to 13 hours of processing. <del>Use the -p, -d and -s options to speed up processing using the intermediate files <del>from a previous run. <del> <del>For the Wikidata dump: get the latest-all.json.bz2 from https://dumps.wikimedia.org/wikidatawiki/entities/ <del>For the Wikipedia dump: get enwiki-latest-pages-articles-multistream.xml.bz2 <del>from https://dumps.wikimedia.org/enwiki/latest/ <del> <del>""" <del>from __future__ import unicode_literals <del> <del>import logging <del>from pathlib import Path <del>import plac <del> <del>from bin.wiki_entity_linking import wikipedia_processor as wp, wikidata_processor as wd <del>from bin.wiki_entity_linking import wiki_io as io <del>from bin.wiki_entity_linking import kb_creator <del>from bin.wiki_entity_linking import TRAINING_DATA_FILE, KB_FILE, ENTITY_DESCR_PATH, KB_MODEL_DIR, LOG_FORMAT <del>from bin.wiki_entity_linking import ENTITY_FREQ_PATH, PRIOR_PROB_PATH, ENTITY_DEFS_PATH, ENTITY_ALIAS_PATH <del>import spacy <del>from bin.wiki_entity_linking.kb_creator import read_kb <del> <del>logger = logging.getLogger(__name__) <del> <del> <del>@plac.annotations( <del> wd_json=("Path to the downloaded WikiData JSON dump.", "positional", None, Path), <del> wp_xml=("Path to the downloaded Wikipedia XML dump.", "positional", None, Path), <del> output_dir=("Output directory", "positional", None, Path), <del> model=("Model name or path, should include pretrained vectors.", "positional", None, str), <del> max_per_alias=("Max. # entities per alias (default 10)", "option", "a", int), <del> min_freq=("Min. count of an entity in the corpus (default 20)", "option", "f", int), <del> min_pair=("Min. count of entity-alias pairs (default 5)", "option", "c", int), <del> entity_vector_length=("Length of entity vectors (default 64)", "option", "v", int), <del> loc_prior_prob=("Location to file with prior probabilities", "option", "p", Path), <del> loc_entity_defs=("Location to file with entity definitions", "option", "d", Path), <del> loc_entity_desc=("Location to file with entity descriptions", "option", "s", Path), <del> descr_from_wp=("Flag for using descriptions from WP instead of WD (default False)", "flag", "wp"), <del> limit_prior=("Threshold to limit lines read from WP for prior probabilities", "option", "lp", int), <del> limit_train=("Threshold to limit lines read from WP for training set", "option", "lt", int), <del> limit_wd=("Threshold to limit lines read from WD", "option", "lw", int), <del> lang=("Optional language for which to get Wikidata titles. Defaults to 'en'", "option", "la", str), <del>) <del>def main( <del> wd_json, <del> wp_xml, <del> output_dir, <del> model, <del> max_per_alias=10, <del> min_freq=20, <del> min_pair=5, <del> entity_vector_length=64, <del> loc_prior_prob=None, <del> loc_entity_defs=None, <del> loc_entity_alias=None, <del> loc_entity_desc=None, <del> descr_from_wp=False, <del> limit_prior=None, <del> limit_train=None, <del> limit_wd=None, <del> lang="en", <del>): <del> entity_defs_path = loc_entity_defs if loc_entity_defs else output_dir / ENTITY_DEFS_PATH <del> entity_alias_path = loc_entity_alias if loc_entity_alias else output_dir / ENTITY_ALIAS_PATH <del> entity_descr_path = loc_entity_desc if loc_entity_desc else output_dir / ENTITY_DESCR_PATH <del> entity_freq_path = output_dir / ENTITY_FREQ_PATH <del> prior_prob_path = loc_prior_prob if loc_prior_prob else output_dir / PRIOR_PROB_PATH <del> training_entities_path = output_dir / TRAINING_DATA_FILE <del> kb_path = output_dir / KB_FILE <del> <del> logger.info("Creating KB with Wikipedia and WikiData") <del> <del> # STEP 0: set up IO <del> if not output_dir.exists(): <del> output_dir.mkdir(parents=True) <del> <del> # STEP 1: Load the NLP object <del> logger.info("STEP 1: Loading NLP model {}".format(model)) <del> nlp = spacy.load(model) <del> <del> # check the length of the nlp vectors <del> if "vectors" not in nlp.meta or not nlp.vocab.vectors.size: <del> raise ValueError( <del> "The `nlp` object should have access to pretrained word vectors, " <del> " cf. https://spacy.io/usage/models#languages." <del> ) <del> <del> # STEP 2: create prior probabilities from WP <del> if not prior_prob_path.exists(): <del> # It takes about 2h to process 1000M lines of Wikipedia XML dump <del> logger.info("STEP 2: Writing prior probabilities to {}".format(prior_prob_path)) <del> if limit_prior is not None: <del> logger.warning("Warning: reading only {} lines of Wikipedia dump".format(limit_prior)) <del> wp.read_prior_probs(wp_xml, prior_prob_path, limit=limit_prior) <del> else: <del> logger.info("STEP 2: Reading prior probabilities from {}".format(prior_prob_path)) <del> <del> # STEP 3: calculate entity frequencies <del> if not entity_freq_path.exists(): <del> logger.info("STEP 3: Calculating and writing entity frequencies to {}".format(entity_freq_path)) <del> io.write_entity_to_count(prior_prob_path, entity_freq_path) <del> else: <del> logger.info("STEP 3: Reading entity frequencies from {}".format(entity_freq_path)) <del> <del> # STEP 4: reading definitions and (possibly) descriptions from WikiData or from file <del> if (not entity_defs_path.exists()) or (not descr_from_wp and not entity_descr_path.exists()): <del> # It takes about 10h to process 55M lines of Wikidata JSON dump <del> logger.info("STEP 4: Parsing and writing Wikidata entity definitions to {}".format(entity_defs_path)) <del> if limit_wd is not None: <del> logger.warning("Warning: reading only {} lines of Wikidata dump".format(limit_wd)) <del> title_to_id, id_to_descr, id_to_alias = wd.read_wikidata_entities_json( <del> wd_json, <del> limit_wd, <del> to_print=False, <del> lang=lang, <del> parse_descr=(not descr_from_wp), <del> ) <del> io.write_title_to_id(entity_defs_path, title_to_id) <del> <del> logger.info("STEP 4b: Writing Wikidata entity aliases to {}".format(entity_alias_path)) <del> io.write_id_to_alias(entity_alias_path, id_to_alias) <del> <del> if not descr_from_wp: <del> logger.info("STEP 4c: Writing Wikidata entity descriptions to {}".format(entity_descr_path)) <del> io.write_id_to_descr(entity_descr_path, id_to_descr) <del> else: <del> logger.info("STEP 4: Reading entity definitions from {}".format(entity_defs_path)) <del> logger.info("STEP 4b: Reading entity aliases from {}".format(entity_alias_path)) <del> if not descr_from_wp: <del> logger.info("STEP 4c: Reading entity descriptions from {}".format(entity_descr_path)) <del> <del> # STEP 5: Getting gold entities from Wikipedia <del> if (not training_entities_path.exists()) or (descr_from_wp and not entity_descr_path.exists()): <del> logger.info("STEP 5: Parsing and writing Wikipedia gold entities to {}".format(training_entities_path)) <del> if limit_train is not None: <del> logger.warning("Warning: reading only {} lines of Wikipedia dump".format(limit_train)) <del> wp.create_training_and_desc(wp_xml, entity_defs_path, entity_descr_path, <del> training_entities_path, descr_from_wp, limit_train) <del> if descr_from_wp: <del> logger.info("STEP 5b: Parsing and writing Wikipedia descriptions to {}".format(entity_descr_path)) <del> else: <del> logger.info("STEP 5: Reading gold entities from {}".format(training_entities_path)) <del> if descr_from_wp: <del> logger.info("STEP 5b: Reading entity descriptions from {}".format(entity_descr_path)) <del> <del> # STEP 6: creating the actual KB <del> # It takes ca. 30 minutes to pretrain the entity embeddings <del> if not kb_path.exists(): <del> logger.info("STEP 6: Creating the KB at {}".format(kb_path)) <del> kb = kb_creator.create_kb( <del> nlp=nlp, <del> max_entities_per_alias=max_per_alias, <del> min_entity_freq=min_freq, <del> min_occ=min_pair, <del> entity_def_path=entity_defs_path, <del> entity_descr_path=entity_descr_path, <del> entity_alias_path=entity_alias_path, <del> entity_freq_path=entity_freq_path, <del> prior_prob_path=prior_prob_path, <del> entity_vector_length=entity_vector_length, <del> ) <del> kb.dump(kb_path) <del> logger.info("kb entities: {}".format(kb.get_size_entities())) <del> logger.info("kb aliases: {}".format(kb.get_size_aliases())) <del> nlp.to_disk(output_dir / KB_MODEL_DIR) <del> else: <del> logger.info("STEP 6: KB already exists at {}".format(kb_path)) <del> <del> logger.info("Done!") <del> <del> <del>if __name__ == "__main__": <del> logging.basicConfig(level=logging.INFO, format=LOG_FORMAT) <del> plac.call(main) <ide><path>bin/wiki_entity_linking/wikidata_processor.py <del># coding: utf-8 <del>from __future__ import unicode_literals <del> <del>import bz2 <del>import json <del>import logging <del> <del>from bin.wiki_entity_linking.wiki_namespaces import WD_META_ITEMS <del> <del>logger = logging.getLogger(__name__) <del> <del> <del>def read_wikidata_entities_json(wikidata_file, limit=None, to_print=False, lang="en", parse_descr=True): <del> # Read the JSON wiki data and parse out the entities. Takes about 7-10h to parse 55M lines. <del> # get latest-all.json.bz2 from https://dumps.wikimedia.org/wikidatawiki/entities/ <del> <del> site_filter = '{}wiki'.format(lang) <del> <del> # filter: currently defined as OR: one hit suffices to be removed from further processing <del> exclude_list = WD_META_ITEMS <del> <del> # punctuation <del> exclude_list.extend(["Q1383557", "Q10617810"]) <del> <del> # letters etc <del> exclude_list.extend(["Q188725", "Q19776628", "Q3841820", "Q17907810", "Q9788", "Q9398093"]) <del> <del> neg_prop_filter = { <del> 'P31': exclude_list, # instance of <del> 'P279': exclude_list # subclass <del> } <del> <del> title_to_id = dict() <del> id_to_descr = dict() <del> id_to_alias = dict() <del> <del> # parse appropriate fields - depending on what we need in the KB <del> parse_properties = False <del> parse_sitelinks = True <del> parse_labels = False <del> parse_aliases = True <del> parse_claims = True <del> <del> with bz2.open(wikidata_file, mode='rb') as file: <del> for cnt, line in enumerate(file): <del> if limit and cnt >= limit: <del> break <del> if cnt % 500000 == 0 and cnt > 0: <del> logger.info("processed {} lines of WikiData JSON dump".format(cnt)) <del> clean_line = line.strip() <del> if clean_line.endswith(b","): <del> clean_line = clean_line[:-1] <del> if len(clean_line) > 1: <del> obj = json.loads(clean_line) <del> entry_type = obj["type"] <del> <del> if entry_type == "item": <del> keep = True <del> <del> claims = obj["claims"] <del> if parse_claims: <del> for prop, value_set in neg_prop_filter.items(): <del> claim_property = claims.get(prop, None) <del> if claim_property: <del> for cp in claim_property: <del> cp_id = ( <del> cp["mainsnak"] <del> .get("datavalue", {}) <del> .get("value", {}) <del> .get("id") <del> ) <del> cp_rank = cp["rank"] <del> if cp_rank != "deprecated" and cp_id in value_set: <del> keep = False <del> <del> if keep: <del> unique_id = obj["id"] <del> <del> if to_print: <del> print("ID:", unique_id) <del> print("type:", entry_type) <del> <del> # parsing all properties that refer to other entities <del> if parse_properties: <del> for prop, claim_property in claims.items(): <del> cp_dicts = [ <del> cp["mainsnak"]["datavalue"].get("value") <del> for cp in claim_property <del> if cp["mainsnak"].get("datavalue") <del> ] <del> cp_values = [ <del> cp_dict.get("id") <del> for cp_dict in cp_dicts <del> if isinstance(cp_dict, dict) <del> if cp_dict.get("id") is not None <del> ] <del> if cp_values: <del> if to_print: <del> print("prop:", prop, cp_values) <del> <del> found_link = False <del> if parse_sitelinks: <del> site_value = obj["sitelinks"].get(site_filter, None) <del> if site_value: <del> site = site_value["title"] <del> if to_print: <del> print(site_filter, ":", site) <del> title_to_id[site] = unique_id <del> found_link = True <del> <del> if parse_labels: <del> labels = obj["labels"] <del> if labels: <del> lang_label = labels.get(lang, None) <del> if lang_label: <del> if to_print: <del> print( <del> "label (" + lang + "):", lang_label["value"] <del> ) <del> <del> if found_link and parse_descr: <del> descriptions = obj["descriptions"] <del> if descriptions: <del> lang_descr = descriptions.get(lang, None) <del> if lang_descr: <del> if to_print: <del> print( <del> "description (" + lang + "):", <del> lang_descr["value"], <del> ) <del> id_to_descr[unique_id] = lang_descr["value"] <del> <del> if parse_aliases: <del> aliases = obj["aliases"] <del> if aliases: <del> lang_aliases = aliases.get(lang, None) <del> if lang_aliases: <del> for item in lang_aliases: <del> if to_print: <del> print( <del> "alias (" + lang + "):", item["value"] <del> ) <del> alias_list = id_to_alias.get(unique_id, []) <del> alias_list.append(item["value"]) <del> id_to_alias[unique_id] = alias_list <del> <del> if to_print: <del> print() <del> <del> # log final number of lines processed <del> logger.info("Finished. Processed {} lines of WikiData JSON dump".format(cnt)) <del> return title_to_id, id_to_descr, id_to_alias <del> <del> <ide><path>bin/wiki_entity_linking/wikidata_train_entity_linker.py <del># coding: utf-8 <del>"""Script that takes a previously created Knowledge Base and trains an entity linking <del>pipeline. The provided KB directory should hold the kb, the original nlp object and <del>its vocab used to create the KB, and a few auxiliary files such as the entity definitions, <del>as created by the script `wikidata_create_kb`. <del> <del>For the Wikipedia dump: get enwiki-latest-pages-articles-multistream.xml.bz2 <del>from https://dumps.wikimedia.org/enwiki/latest/ <del>""" <del>from __future__ import unicode_literals <del> <del>import random <del>import logging <del>import spacy <del>from pathlib import Path <del>import plac <del>from tqdm import tqdm <del> <del>from bin.wiki_entity_linking import wikipedia_processor <del>from bin.wiki_entity_linking import TRAINING_DATA_FILE, KB_MODEL_DIR, KB_FILE, LOG_FORMAT, OUTPUT_MODEL_DIR <del>from bin.wiki_entity_linking.entity_linker_evaluation import measure_performance <del>from bin.wiki_entity_linking.kb_creator import read_kb <del> <del>from spacy.util import minibatch, compounding <del> <del>logger = logging.getLogger(__name__) <del> <del> <del>@plac.annotations( <del> dir_kb=("Directory with KB, NLP and related files", "positional", None, Path), <del> output_dir=("Output directory", "option", "o", Path), <del> loc_training=("Location to training data", "option", "k", Path), <del> epochs=("Number of training iterations (default 10)", "option", "e", int), <del> dropout=("Dropout to prevent overfitting (default 0.5)", "option", "p", float), <del> lr=("Learning rate (default 0.005)", "option", "n", float), <del> l2=("L2 regularization", "option", "r", float), <del> train_articles=("# training articles (default 90% of all)", "option", "t", int), <del> dev_articles=("# dev test articles (default 10% of all)", "option", "d", int), <del> labels_discard=("NER labels to discard (default None)", "option", "l", str), <del>) <del>def main( <del> dir_kb, <del> output_dir=None, <del> loc_training=None, <del> epochs=10, <del> dropout=0.5, <del> lr=0.005, <del> l2=1e-6, <del> train_articles=None, <del> dev_articles=None, <del> labels_discard=None <del>): <del> if not output_dir: <del> logger.warning("No output dir specified so no results will be written, are you sure about this ?") <del> <del> logger.info("Creating Entity Linker with Wikipedia and WikiData") <del> <del> output_dir = Path(output_dir) if output_dir else dir_kb <del> training_path = loc_training if loc_training else dir_kb / TRAINING_DATA_FILE <del> nlp_dir = dir_kb / KB_MODEL_DIR <del> kb_path = dir_kb / KB_FILE <del> nlp_output_dir = output_dir / OUTPUT_MODEL_DIR <del> <del> # STEP 0: set up IO <del> if not output_dir.exists(): <del> output_dir.mkdir() <del> <del> # STEP 1 : load the NLP object <del> logger.info("STEP 1a: Loading model from {}".format(nlp_dir)) <del> nlp = spacy.load(nlp_dir) <del> logger.info("Original NLP pipeline has following pipeline components: {}".format(nlp.pipe_names)) <del> <del> # check that there is a NER component in the pipeline <del> if "ner" not in nlp.pipe_names: <del> raise ValueError("The `nlp` object should have a pretrained `ner` component.") <del> <del> logger.info("STEP 1b: Loading KB from {}".format(kb_path)) <del> kb = read_kb(nlp, kb_path) <del> <del> # STEP 2: read the training dataset previously created from WP <del> logger.info("STEP 2: Reading training & dev dataset from {}".format(training_path)) <del> train_indices, dev_indices = wikipedia_processor.read_training_indices(training_path) <del> logger.info("Training set has {} articles, limit set to roughly {} articles per epoch" <del> .format(len(train_indices), train_articles if train_articles else "all")) <del> logger.info("Dev set has {} articles, limit set to rougly {} articles for evaluation" <del> .format(len(dev_indices), dev_articles if dev_articles else "all")) <del> if dev_articles: <del> dev_indices = dev_indices[0:dev_articles] <del> <del> # STEP 3: create and train an entity linking pipe <del> logger.info("STEP 3: Creating and training an Entity Linking pipe for {} epochs".format(epochs)) <del> if labels_discard: <del> labels_discard = [x.strip() for x in labels_discard.split(",")] <del> logger.info("Discarding {} NER types: {}".format(len(labels_discard), labels_discard)) <del> else: <del> labels_discard = [] <del> <del> el_pipe = nlp.create_pipe( <del> name="entity_linker", config={"pretrained_vectors": nlp.vocab.vectors.name, <del> "labels_discard": labels_discard} <del> ) <del> el_pipe.set_kb(kb) <del> nlp.add_pipe(el_pipe, last=True) <del> <del> other_pipes = [pipe for pipe in nlp.pipe_names if pipe != "entity_linker"] <del> with nlp.disable_pipes(*other_pipes): # only train Entity Linking <del> optimizer = nlp.begin_training() <del> optimizer.learn_rate = lr <del> optimizer.L2 = l2 <del> <del> logger.info("Dev Baseline Accuracies:") <del> dev_data = wikipedia_processor.read_el_docs_golds(nlp=nlp, entity_file_path=training_path, <del> dev=True, line_ids=dev_indices, <del> kb=kb, labels_discard=labels_discard) <del> <del> measure_performance(dev_data, kb, el_pipe, baseline=True, context=False, dev_limit=len(dev_indices)) <del> <del> for itn in range(epochs): <del> random.shuffle(train_indices) <del> losses = {} <del> batches = minibatch(train_indices, size=compounding(8.0, 128.0, 1.001)) <del> batchnr = 0 <del> articles_processed = 0 <del> <del> # we either process the whole training file, or just a part each epoch <del> bar_total = len(train_indices) <del> if train_articles: <del> bar_total = train_articles <del> <del> with tqdm(total=bar_total, leave=False, desc='Epoch ' + str(itn)) as pbar: <del> for batch in batches: <del> if not train_articles or articles_processed < train_articles: <del> with nlp.disable_pipes("entity_linker"): <del> train_batch = wikipedia_processor.read_el_docs_golds(nlp=nlp, entity_file_path=training_path, <del> dev=False, line_ids=batch, <del> kb=kb, labels_discard=labels_discard) <del> docs, golds = zip(*train_batch) <del> try: <del> with nlp.disable_pipes(*other_pipes): <del> nlp.update( <del> docs=docs, <del> golds=golds, <del> sgd=optimizer, <del> drop=dropout, <del> losses=losses, <del> ) <del> batchnr += 1 <del> articles_processed += len(docs) <del> pbar.update(len(docs)) <del> except Exception as e: <del> logger.error("Error updating batch:" + str(e)) <del> if batchnr > 0: <del> logging.info("Epoch {} trained on {} articles, train loss {}" <del> .format(itn, articles_processed, round(losses["entity_linker"] / batchnr, 2))) <del> # re-read the dev_data (data is returned as a generator) <del> dev_data = wikipedia_processor.read_el_docs_golds(nlp=nlp, entity_file_path=training_path, <del> dev=True, line_ids=dev_indices, <del> kb=kb, labels_discard=labels_discard) <del> measure_performance(dev_data, kb, el_pipe, baseline=False, context=True, dev_limit=len(dev_indices)) <del> <del> if output_dir: <del> # STEP 4: write the NLP pipeline (now including an EL model) to file <del> logger.info("Final NLP pipeline has following pipeline components: {}".format(nlp.pipe_names)) <del> logger.info("STEP 4: Writing trained NLP to {}".format(nlp_output_dir)) <del> nlp.to_disk(nlp_output_dir) <del> <del> logger.info("Done!") <del> <del> <del>if __name__ == "__main__": <del> logging.basicConfig(level=logging.INFO, format=LOG_FORMAT) <del> plac.call(main) <ide><path>bin/wiki_entity_linking/wikipedia_processor.py <del># coding: utf-8 <del>from __future__ import unicode_literals <del> <del>import re <del>import bz2 <del>import logging <del>import random <del>import json <del> <del>from spacy.gold import GoldParse <del>from bin.wiki_entity_linking import wiki_io as io <del>from bin.wiki_entity_linking.wiki_namespaces import ( <del> WP_META_NAMESPACE, <del> WP_FILE_NAMESPACE, <del> WP_CATEGORY_NAMESPACE, <del>) <del> <del>""" <del>Process a Wikipedia dump to calculate entity frequencies and prior probabilities in combination with certain mentions. <del>Write these results to file for downstream KB and training data generation. <del> <del>Process Wikipedia interlinks to generate a training dataset for the EL algorithm. <del>""" <del> <del>ENTITY_FILE = "gold_entities.csv" <del> <del>map_alias_to_link = dict() <del> <del>logger = logging.getLogger(__name__) <del> <del>title_regex = re.compile(r"(?<=<title>).*(?=</title>)") <del>id_regex = re.compile(r"(?<=<id>)\d*(?=</id>)") <del>text_regex = re.compile(r"(?<=<text xml:space=\"preserve\">).*(?=</text)") <del>info_regex = re.compile(r"{[^{]*?}") <del>html_regex = re.compile(r"&lt;!--[^-]*--&gt;") <del>ref_regex = re.compile(r"&lt;ref.*?&gt;") # non-greedy <del>ref_2_regex = re.compile(r"&lt;/ref.*?&gt;") # non-greedy <del> <del># find the links <del>link_regex = re.compile(r"\[\[[^\[\]]*\]\]") <del> <del># match on interwiki links, e.g. `en:` or `:fr:` <del>ns_regex = r":?" + "[a-z][a-z]" + ":" <del># match on Namespace: optionally preceded by a : <del>for ns in WP_META_NAMESPACE: <del> ns_regex += "|" + ":?" + ns + ":" <del>ns_regex = re.compile(ns_regex, re.IGNORECASE) <del> <del>files = r"" <del>for f in WP_FILE_NAMESPACE: <del> files += "\[\[" + f + ":[^[\]]+]]" + "|" <del>files = files[0 : len(files) - 1] <del>file_regex = re.compile(files) <del> <del>cats = r"" <del>for c in WP_CATEGORY_NAMESPACE: <del> cats += "\[\[" + c + ":[^\[]*]]" + "|" <del>cats = cats[0 : len(cats) - 1] <del>category_regex = re.compile(cats) <del> <del> <del>def read_prior_probs(wikipedia_input, prior_prob_output, limit=None): <del> """ <del> Read the XML wikipedia data and parse out intra-wiki links to estimate prior probabilities. <del> The full file takes about 2-3h to parse 1100M lines. <del> It works relatively fast because it runs line by line, irrelevant of which article the intrawiki is from, <del> though dev test articles are excluded in order not to get an artificially strong baseline. <del> """ <del> cnt = 0 <del> read_id = False <del> current_article_id = None <del> with bz2.open(wikipedia_input, mode="rb") as file: <del> line = file.readline() <del> while line and (not limit or cnt < limit): <del> if cnt % 25000000 == 0 and cnt > 0: <del> logger.info("processed {} lines of Wikipedia XML dump".format(cnt)) <del> clean_line = line.strip().decode("utf-8") <del> <del> # we attempt at reading the article's ID (but not the revision or contributor ID) <del> if "<revision>" in clean_line or "<contributor>" in clean_line: <del> read_id = False <del> if "<page>" in clean_line: <del> read_id = True <del> <del> if read_id: <del> ids = id_regex.search(clean_line) <del> if ids: <del> current_article_id = ids[0] <del> <del> # only processing prior probabilities from true training (non-dev) articles <del> if not is_dev(current_article_id): <del> aliases, entities, normalizations = get_wp_links(clean_line) <del> for alias, entity, norm in zip(aliases, entities, normalizations): <del> _store_alias( <del> alias, entity, normalize_alias=norm, normalize_entity=True <del> ) <del> <del> line = file.readline() <del> cnt += 1 <del> logger.info("processed {} lines of Wikipedia XML dump".format(cnt)) <del> logger.info("Finished. processed {} lines of Wikipedia XML dump".format(cnt)) <del> <del> # write all aliases and their entities and count occurrences to file <del> with prior_prob_output.open("w", encoding="utf8") as outputfile: <del> outputfile.write("alias" + "|" + "count" + "|" + "entity" + "\n") <del> for alias, alias_dict in sorted(map_alias_to_link.items(), key=lambda x: x[0]): <del> s_dict = sorted(alias_dict.items(), key=lambda x: x[1], reverse=True) <del> for entity, count in s_dict: <del> outputfile.write(alias + "|" + str(count) + "|" + entity + "\n") <del> <del> <del>def _store_alias(alias, entity, normalize_alias=False, normalize_entity=True): <del> alias = alias.strip() <del> entity = entity.strip() <del> <del> # remove everything after # as this is not part of the title but refers to a specific paragraph <del> if normalize_entity: <del> # wikipedia titles are always capitalized <del> entity = _capitalize_first(entity.split("#")[0]) <del> if normalize_alias: <del> alias = alias.split("#")[0] <del> <del> if alias and entity: <del> alias_dict = map_alias_to_link.get(alias, dict()) <del> entity_count = alias_dict.get(entity, 0) <del> alias_dict[entity] = entity_count + 1 <del> map_alias_to_link[alias] = alias_dict <del> <del> <del>def get_wp_links(text): <del> aliases = [] <del> entities = [] <del> normalizations = [] <del> <del> matches = link_regex.findall(text) <del> for match in matches: <del> match = match[2:][:-2].replace("_", " ").strip() <del> <del> if ns_regex.match(match): <del> pass # ignore the entity if it points to a "meta" page <del> <del> # this is a simple [[link]], with the alias the same as the mention <del> elif "|" not in match: <del> aliases.append(match) <del> entities.append(match) <del> normalizations.append(True) <del> <del> # in wiki format, the link is written as [[entity|alias]] <del> else: <del> splits = match.split("|") <del> entity = splits[0].strip() <del> alias = splits[1].strip() <del> # specific wiki format [[alias (specification)|]] <del> if len(alias) == 0 and "(" in entity: <del> alias = entity.split("(")[0] <del> aliases.append(alias) <del> entities.append(entity) <del> normalizations.append(False) <del> else: <del> aliases.append(alias) <del> entities.append(entity) <del> normalizations.append(False) <del> <del> return aliases, entities, normalizations <del> <del> <del>def _capitalize_first(text): <del> if not text: <del> return None <del> result = text[0].capitalize() <del> if len(result) > 0: <del> result += text[1:] <del> return result <del> <del> <del>def create_training_and_desc( <del> wp_input, def_input, desc_output, training_output, parse_desc, limit=None <del>): <del> wp_to_id = io.read_title_to_id(def_input) <del> _process_wikipedia_texts( <del> wp_input, wp_to_id, desc_output, training_output, parse_desc, limit <del> ) <del> <del> <del>def _process_wikipedia_texts( <del> wikipedia_input, wp_to_id, output, training_output, parse_descriptions, limit=None <del>): <del> """ <del> Read the XML wikipedia data to parse out training data: <del> raw text data + positive instances <del> """ <del> <del> read_ids = set() <del> <del> with output.open("a", encoding="utf8") as descr_file, training_output.open( <del> "w", encoding="utf8" <del> ) as entity_file: <del> if parse_descriptions: <del> _write_training_description(descr_file, "WD_id", "description") <del> with bz2.open(wikipedia_input, mode="rb") as file: <del> article_count = 0 <del> article_text = "" <del> article_title = None <del> article_id = None <del> reading_text = False <del> reading_revision = False <del> <del> for line in file: <del> clean_line = line.strip().decode("utf-8") <del> <del> if clean_line == "<revision>": <del> reading_revision = True <del> elif clean_line == "</revision>": <del> reading_revision = False <del> <del> # Start reading new page <del> if clean_line == "<page>": <del> article_text = "" <del> article_title = None <del> article_id = None <del> # finished reading this page <del> elif clean_line == "</page>": <del> if article_id: <del> clean_text, entities = _process_wp_text( <del> article_title, article_text, wp_to_id <del> ) <del> if clean_text is not None and entities is not None: <del> _write_training_entities( <del> entity_file, article_id, clean_text, entities <del> ) <del> <del> if article_title in wp_to_id and parse_descriptions: <del> description = " ".join( <del> clean_text[:1000].split(" ")[:-1] <del> ) <del> _write_training_description( <del> descr_file, wp_to_id[article_title], description <del> ) <del> article_count += 1 <del> if article_count % 10000 == 0 and article_count > 0: <del> logger.info( <del> "Processed {} articles".format(article_count) <del> ) <del> if limit and article_count >= limit: <del> break <del> article_text = "" <del> article_title = None <del> article_id = None <del> reading_text = False <del> reading_revision = False <del> <del> # start reading text within a page <del> if "<text" in clean_line: <del> reading_text = True <del> <del> if reading_text: <del> article_text += " " + clean_line <del> <del> # stop reading text within a page (we assume a new page doesn't start on the same line) <del> if "</text" in clean_line: <del> reading_text = False <del> <del> # read the ID of this article (outside the revision portion of the document) <del> if not reading_revision: <del> ids = id_regex.search(clean_line) <del> if ids: <del> article_id = ids[0] <del> if article_id in read_ids: <del> logger.info( <del> "Found duplicate article ID", article_id, clean_line <del> ) # This should never happen ... <del> read_ids.add(article_id) <del> <del> # read the title of this article (outside the revision portion of the document) <del> if not reading_revision: <del> titles = title_regex.search(clean_line) <del> if titles: <del> article_title = titles[0].strip() <del> logger.info("Finished. Processed {} articles".format(article_count)) <del> <del> <del>def _process_wp_text(article_title, article_text, wp_to_id): <del> # ignore meta Wikipedia pages <del> if ns_regex.match(article_title): <del> return None, None <del> <del> # remove the text tags <del> text_search = text_regex.search(article_text) <del> if text_search is None: <del> return None, None <del> text = text_search.group(0) <del> <del> # stop processing if this is a redirect page <del> if text.startswith("#REDIRECT"): <del> return None, None <del> <del> # get the raw text without markup etc, keeping only interwiki links <del> clean_text, entities = _remove_links(_get_clean_wp_text(text), wp_to_id) <del> return clean_text, entities <del> <del> <del>def _get_clean_wp_text(article_text): <del> clean_text = article_text.strip() <del> <del> # remove bolding & italic markup <del> clean_text = clean_text.replace("'''", "") <del> clean_text = clean_text.replace("''", "") <del> <del> # remove nested {{info}} statements by removing the inner/smallest ones first and iterating <del> try_again = True <del> previous_length = len(clean_text) <del> while try_again: <del> clean_text = info_regex.sub( <del> "", clean_text <del> ) # non-greedy match excluding a nested { <del> if len(clean_text) < previous_length: <del> try_again = True <del> else: <del> try_again = False <del> previous_length = len(clean_text) <del> <del> # remove HTML comments <del> clean_text = html_regex.sub("", clean_text) <del> <del> # remove Category and File statements <del> clean_text = category_regex.sub("", clean_text) <del> clean_text = file_regex.sub("", clean_text) <del> <del> # remove multiple = <del> while "==" in clean_text: <del> clean_text = clean_text.replace("==", "=") <del> <del> clean_text = clean_text.replace(". =", ".") <del> clean_text = clean_text.replace(" = ", ". ") <del> clean_text = clean_text.replace("= ", ".") <del> clean_text = clean_text.replace(" =", "") <del> <del> # remove refs (non-greedy match) <del> clean_text = ref_regex.sub("", clean_text) <del> clean_text = ref_2_regex.sub("", clean_text) <del> <del> # remove additional wikiformatting <del> clean_text = re.sub(r"&lt;blockquote&gt;", "", clean_text) <del> clean_text = re.sub(r"&lt;/blockquote&gt;", "", clean_text) <del> <del> # change special characters back to normal ones <del> clean_text = clean_text.replace(r"&lt;", "<") <del> clean_text = clean_text.replace(r"&gt;", ">") <del> clean_text = clean_text.replace(r"&quot;", '"') <del> clean_text = clean_text.replace(r"&amp;nbsp;", " ") <del> clean_text = clean_text.replace(r"&amp;", "&") <del> <del> # remove multiple spaces <del> while " " in clean_text: <del> clean_text = clean_text.replace(" ", " ") <del> <del> return clean_text.strip() <del> <del> <del>def _remove_links(clean_text, wp_to_id): <del> # read the text char by char to get the right offsets for the interwiki links <del> entities = [] <del> final_text = "" <del> open_read = 0 <del> reading_text = True <del> reading_entity = False <del> reading_mention = False <del> reading_special_case = False <del> entity_buffer = "" <del> mention_buffer = "" <del> for index, letter in enumerate(clean_text): <del> if letter == "[": <del> open_read += 1 <del> elif letter == "]": <del> open_read -= 1 <del> elif letter == "|": <del> if reading_text: <del> final_text += letter <del> # switch from reading entity to mention in the [[entity|mention]] pattern <del> elif reading_entity: <del> reading_text = False <del> reading_entity = False <del> reading_mention = True <del> else: <del> reading_special_case = True <del> else: <del> if reading_entity: <del> entity_buffer += letter <del> elif reading_mention: <del> mention_buffer += letter <del> elif reading_text: <del> final_text += letter <del> else: <del> raise ValueError("Not sure at point", clean_text[index - 2 : index + 2]) <del> <del> if open_read > 2: <del> reading_special_case = True <del> <del> if open_read == 2 and reading_text: <del> reading_text = False <del> reading_entity = True <del> reading_mention = False <del> <del> # we just finished reading an entity <del> if open_read == 0 and not reading_text: <del> if "#" in entity_buffer or entity_buffer.startswith(":"): <del> reading_special_case = True <del> # Ignore cases with nested structures like File: handles etc <del> if not reading_special_case: <del> if not mention_buffer: <del> mention_buffer = entity_buffer <del> start = len(final_text) <del> end = start + len(mention_buffer) <del> qid = wp_to_id.get(entity_buffer, None) <del> if qid: <del> entities.append((mention_buffer, qid, start, end)) <del> final_text += mention_buffer <del> <del> entity_buffer = "" <del> mention_buffer = "" <del> <del> reading_text = True <del> reading_entity = False <del> reading_mention = False <del> reading_special_case = False <del> return final_text, entities <del> <del> <del>def _write_training_description(outputfile, qid, description): <del> if description is not None: <del> line = str(qid) + "|" + description + "\n" <del> outputfile.write(line) <del> <del> <del>def _write_training_entities(outputfile, article_id, clean_text, entities): <del> entities_data = [ <del> {"alias": ent[0], "entity": ent[1], "start": ent[2], "end": ent[3]} <del> for ent in entities <del> ] <del> line = ( <del> json.dumps( <del> { <del> "article_id": article_id, <del> "clean_text": clean_text, <del> "entities": entities_data, <del> }, <del> ensure_ascii=False, <del> ) <del> + "\n" <del> ) <del> outputfile.write(line) <del> <del> <del>def read_training_indices(entity_file_path): <del> """ This method creates two lists of indices into the training file: one with indices for the <del> training examples, and one for the dev examples.""" <del> train_indices = [] <del> dev_indices = [] <del> <del> with entity_file_path.open("r", encoding="utf8") as file: <del> for i, line in enumerate(file): <del> example = json.loads(line) <del> article_id = example["article_id"] <del> clean_text = example["clean_text"] <del> <del> if is_valid_article(clean_text): <del> if is_dev(article_id): <del> dev_indices.append(i) <del> else: <del> train_indices.append(i) <del> <del> return train_indices, dev_indices <del> <del> <del>def read_el_docs_golds(nlp, entity_file_path, dev, line_ids, kb, labels_discard=None): <del> """ This method provides training/dev examples that correspond to the entity annotations found by the nlp object. <del> For training, it will include both positive and negative examples by using the candidate generator from the kb. <del> For testing (kb=None), it will include all positive examples only.""" <del> if not labels_discard: <del> labels_discard = [] <del> <del> texts = [] <del> entities_list = [] <del> <del> with entity_file_path.open("r", encoding="utf8") as file: <del> for i, line in enumerate(file): <del> if i in line_ids: <del> example = json.loads(line) <del> article_id = example["article_id"] <del> clean_text = example["clean_text"] <del> entities = example["entities"] <del> <del> if dev != is_dev(article_id) or not is_valid_article(clean_text): <del> continue <del> <del> texts.append(clean_text) <del> entities_list.append(entities) <del> <del> docs = nlp.pipe(texts, batch_size=50) <del> <del> for doc, entities in zip(docs, entities_list): <del> gold = _get_gold_parse(doc, entities, dev=dev, kb=kb, labels_discard=labels_discard) <del> if gold and len(gold.links) > 0: <del> yield doc, gold <del> <del> <del>def _get_gold_parse(doc, entities, dev, kb, labels_discard): <del> gold_entities = {} <del> tagged_ent_positions = { <del> (ent.start_char, ent.end_char): ent <del> for ent in doc.ents <del> if ent.label_ not in labels_discard <del> } <del> <del> for entity in entities: <del> entity_id = entity["entity"] <del> alias = entity["alias"] <del> start = entity["start"] <del> end = entity["end"] <del> <del> candidate_ids = [] <del> if kb and not dev: <del> candidates = kb.get_candidates(alias) <del> candidate_ids = [cand.entity_ for cand in candidates] <del> <del> tagged_ent = tagged_ent_positions.get((start, end), None) <del> if tagged_ent: <del> # TODO: check that alias == doc.text[start:end] <del> should_add_ent = (dev or entity_id in candidate_ids) and is_valid_sentence( <del> tagged_ent.sent.text <del> ) <del> <del> if should_add_ent: <del> value_by_id = {entity_id: 1.0} <del> if not dev: <del> random.shuffle(candidate_ids) <del> value_by_id.update( <del> {kb_id: 0.0 for kb_id in candidate_ids if kb_id != entity_id} <del> ) <del> gold_entities[(start, end)] = value_by_id <del> <del> return GoldParse(doc, links=gold_entities) <del> <del> <del>def is_dev(article_id): <del> if not article_id: <del> return False <del> return article_id.endswith("3") <del> <del> <del>def is_valid_article(doc_text): <del> # custom length cut-off <del> return 10 < len(doc_text) < 30000 <del> <del> <del>def is_valid_sentence(sent_text): <del> if not 10 < len(sent_text) < 3000: <del> # custom length cut-off <del> return False <del> <del> if sent_text.strip().startswith("*") or sent_text.strip().startswith("#"): <del> # remove 'enumeration' sentences (occurs often on Wikipedia) <del> return False <del> <del> return True <add><path>examples/training/create_kb.py <del><path>examples/training/pretrain_kb.py <ide> #!/usr/bin/env python <ide> # coding: utf8 <ide> <del>"""Example of defining and (pre)training spaCy's knowledge base, <add>"""Example of defining a knowledge base in spaCy, <ide> which is needed to implement entity linking functionality. <ide> <ide> For more details, see the documentation: <ide> * Knowledge base: https://spacy.io/api/kb <ide> * Entity Linking: https://spacy.io/usage/linguistic-features#entity-linking <ide> <del>Compatible with: spaCy v2.2.3 <del>Last tested with: v2.2.3 <add>Compatible with: spaCy v2.2.4 <add>Last tested with: v2.2.4 <ide> """ <ide> from __future__ import unicode_literals, print_function <ide> <ide> import spacy <ide> from spacy.kb import KnowledgeBase <ide> <del>from bin.wiki_entity_linking.train_descriptions import EntityEncoder <del> <ide> <ide> # Q2146908 (Russ Cochran): American golfer <ide> # Q7381115 (Russ Cochran): publisher <ide> ENTITIES = {"Q2146908": ("American golfer", 342), "Q7381115": ("publisher", 17)} <ide> <del>INPUT_DIM = 300 # dimension of pretrained input vectors <del>DESC_WIDTH = 64 # dimension of output entity vectors <del> <ide> <ide> @plac.annotations( <ide> model=("Model name, should have pretrained word embeddings", "positional", None, str), <ide> output_dir=("Optional output directory", "option", "o", Path), <del> n_iter=("Number of training iterations", "option", "n", int), <ide> ) <del>def main(model=None, output_dir=None, n_iter=50): <del> """Load the model, create the KB and pretrain the entity encodings. <add>def main(model=None, output_dir=None): <add> """Load the model and create the KB with pre-defined entity encodings. <ide> If an output_dir is provided, the KB will be stored there in a file 'kb'. <ide> The updated vocab will also be written to a directory in the output_dir.""" <ide> <ide> def main(model=None, output_dir=None, n_iter=50): <ide> " cf. https://spacy.io/usage/models#languages." <ide> ) <ide> <del> kb = KnowledgeBase(vocab=nlp.vocab) <add> # You can change the dimension of vectors in your KB by using an encoder that changes the dimensionality. <add> # For simplicity, we'll just use the original vector dimension here instead. <add> vectors_dim = nlp.vocab.vectors.shape[1] <add> kb = KnowledgeBase(vocab=nlp.vocab, entity_vector_length=vectors_dim) <ide> <ide> # set up the data <ide> entity_ids = [] <del> descriptions = [] <add> descr_embeddings = [] <ide> freqs = [] <ide> for key, value in ENTITIES.items(): <ide> desc, freq = value <ide> entity_ids.append(key) <del> descriptions.append(desc) <add> descr_embeddings.append(nlp(desc).vector) <ide> freqs.append(freq) <ide> <del> # training entity description encodings <del> # this part can easily be replaced with a custom entity encoder <del> encoder = EntityEncoder( <del> nlp=nlp, <del> input_dim=INPUT_DIM, <del> desc_width=DESC_WIDTH, <del> epochs=n_iter, <del> ) <del> encoder.train(description_list=descriptions, to_print=True) <del> <del> # get the pretrained entity vectors <del> embeddings = encoder.apply_encoder(descriptions) <del> <ide> # set the entities, can also be done by calling `kb.add_entity` for each entity <del> kb.set_entities(entity_list=entity_ids, freq_list=freqs, vector_list=embeddings) <add> kb.set_entities(entity_list=entity_ids, freq_list=freqs, vector_list=descr_embeddings) <ide> <ide> # adding aliases, the entities need to be defined in the KB beforehand <ide> kb.add_alias( <ide> def main(model=None, output_dir=None, n_iter=50): <ide> vocab2 = Vocab().from_disk(vocab_path) <ide> kb2 = KnowledgeBase(vocab=vocab2) <ide> kb2.load_bulk(kb_path) <del> _print_kb(kb2) <ide> print() <add> _print_kb(kb2) <ide> <ide> <ide> def _print_kb(kb): <ide> def _print_kb(kb): <ide> plac.call(main) <ide> <ide> # Expected output: <del> <ide> # 2 kb entities: ['Q2146908', 'Q7381115'] <ide> # 1 kb aliases: ['Russ Cochran'] <ide><path>examples/training/train_entity_linker.py <ide> #!/usr/bin/env python <ide> # coding: utf8 <ide> <del>"""Example of training spaCy's entity linker, starting off with an <del>existing model and a pre-defined knowledge base. <add>"""Example of training spaCy's entity linker, starting off with a predefined <add>knowledge base and corresponding vocab, and a blank English model. <ide> <ide> For more details, see the documentation: <ide> * Training: https://spacy.io/usage/training <ide> * Entity Linking: https://spacy.io/usage/linguistic-features#entity-linking <ide> <del>Compatible with: spaCy v2.2.3 <del>Last tested with: v2.2.3 <add>Compatible with: spaCy v2.2.4 <add>Last tested with: v2.2.4 <ide> """ <ide> from __future__ import unicode_literals, print_function <ide> <ide> import plac <ide> import random <ide> from pathlib import Path <ide> <del>from spacy.symbols import PERSON <ide> from spacy.vocab import Vocab <ide> <ide> import spacy <ide> from spacy.kb import KnowledgeBase <ide> from spacy.pipeline import EntityRuler <del>from spacy.tokens import Span <ide> from spacy.util import minibatch, compounding <ide> <ide> <ide><path>website/docs/usage/examples.md <ide> start. <ide> https://github.com/explosion/spaCy/tree/master/examples/training/train_new_entity_type.py <ide> ``` <ide> <add>### Creating a Knowledge Base for Named Entity Linking {#kb} <add> <add>This example shows how to create a knowledge base in spaCy, <add>which is needed to implement entity linking functionality. <add>It requires as input a spaCy model with pretrained word vectors, <add>and it stores the KB to file (if an `output_dir` is provided). <add> <add>```python <add>https://github.com/explosion/spaCy/tree/master/examples/training/create_kb.py <add>``` <add> <add>### Training spaCy's Named Entity Linker {#nel} <add> <add>This example shows how to train spaCy's entity linker with your own custom <add>examples, starting off with a predefined knowledge base and its vocab, <add>and using a blank `English` class. <add> <add>```python <add>https://github.com/explosion/spaCy/tree/master/examples/training/train_entity_linker.py <add>``` <add> <ide> ### Training spaCy's Dependency Parser {#parser} <ide> <ide> This example shows how to update spaCy's dependency parser, starting off with an <ide><path>website/docs/usage/linguistic-features.md <ide> import DisplacyEntHtml from 'images/displacy-ent2.html' <ide> <ide> To ground the named entities into the "real world", spaCy provides functionality <ide> to perform entity linking, which resolves a textual entity to a unique <del>identifier from a knowledge base (KB). The <del>[processing scripts](https://github.com/explosion/spaCy/tree/master/bin/wiki_entity_linking) <del>we provide use WikiData identifiers, but you can create your own <add>identifier from a knowledge base (KB). You can create your own <ide> [`KnowledgeBase`](/api/kb) and <ide> [train a new Entity Linking model](/usage/training#entity-linker) using that <ide> custom-made KB. <ide><path>website/docs/usage/training.md <ide> your data** to find a solution that works best for you. <ide> ### Updating the Named Entity Recognizer {#example-train-ner} <ide> <ide> This example shows how to update spaCy's entity recognizer with your own <del>examples, starting off with an existing, pretrained model, or from scratch <del>using a blank `Language` class. To do this, you'll need **example texts** and <del>the **character offsets** and **labels** of each entity contained in the texts. <add>examples, starting off with an existing, pretrained model, or from scratch using <add>a blank `Language` class. To do this, you'll need **example texts** and the <add>**character offsets** and **labels** of each entity contained in the texts. <ide> <ide> ```python <ide> https://github.com/explosion/spaCy/tree/master/examples/training/train_ner.py <ide> https://github.com/explosion/spaCy/tree/master/examples/training/train_parser.py <ide> training the parser. <ide> 2. **Add the dependency labels** to the parser using the <ide> [`add_label`](/api/dependencyparser#add_label) method. If you're starting off <del> with a pretrained spaCy model, this is usually not necessary – but it <del> doesn't hurt either, just to be safe. <add> with a pretrained spaCy model, this is usually not necessary – but it doesn't <add> hurt either, just to be safe. <ide> 3. **Shuffle and loop over** the examples. For each example, **update the <ide> model** by calling [`nlp.update`](/api/language#update), which steps through <ide> the words of the input. At each word, it makes a **prediction**. It then <ide> To train an entity linking model, you first need to define a knowledge base <ide> <ide> A KB consists of a list of entities with unique identifiers. Each such entity <ide> has an entity vector that will be used to measure similarity with the context in <del>which an entity is used. These vectors are pretrained and stored in the KB <del>before the entity linking model will be trained. <add>which an entity is used. These vectors have a fixed length and are stored in the <add>KB. <ide> <ide> The following example shows how to build a knowledge base from scratch, given a <del>list of entities and potential aliases. The script further demonstrates how to <del>pretrain and store the entity vectors. To run this example, the script needs <del>access to a `vocab` instance or an `nlp` model with pretrained word embeddings. <add>list of entities and potential aliases. The script requires an `nlp` model with <add>pretrained word vectors to obtain an encoding of an entity's description as its <add>vector. <ide> <ide> ```python <del>https://github.com/explosion/spaCy/tree/master/examples/training/pretrain_kb.py <add>https://github.com/explosion/spaCy/tree/master/examples/training/create_kb.py <ide> ``` <ide> <ide> #### Step by step guide {#step-by-step-kb}
16
Ruby
Ruby
fix spaced paths with brew bottle
55aa2a296be215716466016bfff3fc8116881328
<ide><path>Library/Contributions/examples/brew-bottle.rb <ide> HOMEBREW_CELLAR.cd do <ide> # Use gzip, much faster than bzip2 and hardly any file size difference <ide> # when compressing binaries. <del> safe_system "tar czf #{destination}/#{filename} #{formula}/#{version}" <add> safe_system 'tar', 'czf', "#{destination}/#{filename}", "#{formula}/#{version}" <ide> end <ide> ohai "Bottled #{filename}" <ide> end <ide>\ No newline at end of file
1
Javascript
Javascript
fix ci problems
c3691df74064ec2a591b3c0beefe3565f84cb71b
<ide><path>test/configCases/container/0-container-full/test.config.js <ide> module.exports = { <ide> findBundle: function (i, options) { <del> return i === 0 ? "./main.js" : "./module/main.mjs"; <add> // In node 10 the ESM part of the test doesn't work <add> return i === 0 || process.version.startsWith("v10.") <add> ? "./main.js" <add> : "./module/main.mjs"; <ide> } <ide> }; <ide><path>test/configCases/container/0-container-full/webpack.config.js <ide> const { ModuleFederationPlugin } = require("../../../../").container; <ide> <add>/** @type {ConstructorParameters<typeof ModuleFederationPlugin>[0]} */ <ide> const common = { <ide> name: "container", <ide> exposes: { <ide><path>test/configCases/container/1-container-full/test.config.js <ide> module.exports = { <ide> findBundle: function (i, options) { <del> return i === 0 ? "./main.js" : "./module/main.mjs"; <add> // In node 10 the ESM part of the test doesn't work <add> return i === 0 || process.version.startsWith("v10.") <add> ? "./main.js" <add> : "./module/main.mjs"; <ide> } <ide> }; <ide><path>test/configCases/container/1-container-full/webpack.config.js <ide> const common = { <ide> runtimeChunk: "single" <ide> } <ide> }; <add> <add>/** @type {ConstructorParameters<typeof ModuleFederationPlugin>[0]} */ <ide> const commonMF = { <ide> runtime: false, <ide> exposes: {
4
Java
Java
add accessors for expirationtime in flashmap
83ff0adc2ece396b21561c3a76c47d2413a818c8
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/FlashMap.java <ide> /* <del> * Copyright 2002-2014 the original author or authors. <add> * Copyright 2002-2015 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> import org.springframework.util.ObjectUtils; <ide> import org.springframework.util.StringUtils; <ide> <add> <ide> /** <ide> * A FlashMap provides a way for one request to store attributes intended for <ide> * use in another. This is most commonly needed when redirecting from one URL <ide> public final class FlashMap extends HashMap<String, Object> implements Comparabl <ide> <ide> private String targetRequestPath; <ide> <del> private final MultiValueMap<String, String> targetRequestParams = new LinkedMultiValueMap<String, String>(); <del> <del> private long expirationStartTime; <add> private final MultiValueMap<String, String> targetRequestParams = new LinkedMultiValueMap<String, String>(4); <ide> <del> private int timeToLive; <add> private long expirationTime = -1; <ide> <ide> <ide> /** <ide> public MultiValueMap<String, String> getTargetRequestParams() { <ide> * @param timeToLive the number of seconds before expiration <ide> */ <ide> public void startExpirationPeriod(int timeToLive) { <del> this.expirationStartTime = System.currentTimeMillis(); <del> this.timeToLive = timeToLive; <add> this.expirationTime = System.currentTimeMillis() + timeToLive * 1000; <add> } <add> <add> /** <add> * Set the expiration time for the FlashMap. This is provided for serialization <add> * purposes but can also be used instead {@link #startExpirationPeriod(int)}. <add> * @since 4.2 <add> */ <add> public void setExpirationTime(long expirationTime) { <add> this.expirationTime = expirationTime; <add> } <add> <add> /** <add> * Return the expiration time for the FlashMap or -1 if the expiration <add> * period has not started. <add> * @since 4.2 <add> */ <add> public long getExpirationTime() { <add> return this.expirationTime; <ide> } <ide> <ide> /** <ide> * Return whether this instance has expired depending on the amount of <ide> * elapsed time since the call to {@link #startExpirationPeriod}. <ide> */ <ide> public boolean isExpired() { <del> return (this.expirationStartTime != 0 && <del> (System.currentTimeMillis() - this.expirationStartTime > this.timeToLive * 1000)); <add> return (this.expirationTime != -1 && System.currentTimeMillis() > this.expirationTime); <ide> } <ide> <ide> <ide> public int hashCode() { <ide> <ide> @Override <ide> public String toString() { <del> StringBuilder sb = new StringBuilder(); <del> sb.append("FlashMap [attributes=").append(super.toString()); <del> sb.append(", targetRequestPath=").append(this.targetRequestPath); <del> sb.append(", targetRequestParams=").append(this.targetRequestParams).append("]"); <del> return sb.toString(); <add> return "FlashMap [attributes=" + super.toString() + ", targetRequestPath=" + <add> this.targetRequestPath + ", targetRequestParams=" + this.targetRequestParams + "]"; <ide> } <ide> <ide> }
1
Javascript
Javascript
remove redundant validateuint32 argument
64ee64d3afc837350ee39058cef9179e92f3554c
<ide><path>lib/internal/crypto/pbkdf2.js <ide> function check(password, salt, iterations, keylen, digest) { <ide> <ide> password = getArrayBufferView(password, 'password'); <ide> salt = getArrayBufferView(salt, 'salt'); <del> validateUint32(iterations, 'iterations', 0); <del> validateUint32(keylen, 'keylen', 0); <add> validateUint32(iterations, 'iterations'); <add> validateUint32(keylen, 'keylen'); <ide> <ide> return { password, salt, iterations, keylen, digest }; <ide> }
1
Text
Text
add text "данная команда перечислит"
4f56f7238c9e75e3eae2167cdd585663ca5d16f2
<ide><path>guide/russian/git/git-status/index.md <ide> git status <ide> ``` <ide> <ide> Отображает, какие файлы проиндексированные, непроиндексированные и неотслеживаемые. <add>
1
Javascript
Javascript
remove unnecessary conditions
28288c82bd7e485831eb85a2bb9475cf1da88def
<ide><path>lib/EvalSourceMapDevToolModuleTemplatePlugin.js <ide> class EvalSourceMapDevToolModuleTemplatePlugin { <ide> return filename; <ide> }); <ide> sourceMap.sources = moduleFilenames; <del> if(sourceMap.sourcesContent) { <del> sourceMap.sourcesContent = sourceMap.sourcesContent.map(content => typeof content === "string" ? content : null); <del> } <ide> sourceMap.sourceRoot = options.sourceRoot || ""; <ide> sourceMap.file = `${module.id}.js`; <ide> <ide><path>lib/SourceMapDevToolPlugin.js <ide> class SourceMapDevToolPlugin { <ide> const modules = task.modules; <ide> const moduleFilenames = modules.map(m => moduleToSourceNameMapping.get(m)); <ide> sourceMap.sources = moduleFilenames; <del> if(sourceMap.sourcesContent && !options.noSources) { <del> sourceMap.sourcesContent = sourceMap.sourcesContent.map((content) => typeof content === "string" ? content : null); <del> } else { <add> if(options.noSources) { <ide> sourceMap.sourcesContent = undefined; <ide> } <ide> sourceMap.sourceRoot = options.sourceRoot || "";
2
Javascript
Javascript
fix hover animations and optimize pivot()
86ed35446d394ec505d879e79fd29e6ecb199b87
<ide><path>src/core/core.element.js <ide> helpers.extend(Element.prototype, { <ide> pivot: function() { <ide> var me = this; <ide> if (!me._view) { <del> me._view = helpers.clone(me._model); <add> me._view = helpers.extend({}, me._model); <ide> } <ide> me._start = {}; <ide> return me; <ide> helpers.extend(Element.prototype, { <ide> <ide> // No animation -> No Transition <ide> if (!model || ease === 1) { <del> me._view = model; <add> me._view = helpers.extend({}, model); <ide> me._start = null; <ide> return me; <ide> } <ide><path>test/specs/core.element.tests.js <ide> describe('Core element tests', function() { <ide> element.transition(0.25); <ide> <ide> expect(element._view).toEqual(element._model); <add> expect(element._view).not.toBe(element._model); <ide> expect(element._view.objectProp).toBe(element._model.objectProp); // not cloned <ide> <ide> element._model.numberProp = 100; <ide> describe('Core element tests', function() { <ide> }, <ide> colorProp: 'rgb(64, 64, 0)', <ide> }); <add> <add> // Final transition clones model into view <add> element.transition(1); <add> <add> expect(element._view).toEqual(element._model); <add> expect(element._view).not.toBe(element._model); <ide> }); <ide> }); <ide><path>test/specs/core.tooltip.tests.js <ide> describe('Core.Tooltip', function() { <ide> footer: [], <ide> caretPadding: 2, <ide> labelColors: [{ <del> borderColor: 'rgb(255, 0, 0)', <del> backgroundColor: 'rgb(0, 255, 0)' <add> borderColor: globalDefaults.defaultColor, <add> backgroundColor: globalDefaults.defaultColor <ide> }, { <del> borderColor: 'rgb(0, 0, 255)', <del> backgroundColor: 'rgb(0, 255, 255)' <add> borderColor: globalDefaults.defaultColor, <add> backgroundColor: globalDefaults.defaultColor <ide> }] <ide> })); <ide> <ide> describe('Core.Tooltip', function() { <ide> caretPadding: 2, <ide> labelTextColors: ['#fff'], <ide> labelColors: [{ <del> borderColor: 'rgb(255, 0, 0)', <del> backgroundColor: 'rgb(0, 255, 0)' <add> borderColor: globalDefaults.defaultColor, <add> backgroundColor: globalDefaults.defaultColor <ide> }] <ide> })); <ide> <ide> describe('Core.Tooltip', function() { <ide> caretPadding: 2, <ide> labelTextColors: ['labelTextColor', 'labelTextColor'], <ide> labelColors: [{ <del> borderColor: 'rgb(255, 0, 0)', <del> backgroundColor: 'rgb(0, 255, 0)' <add> borderColor: globalDefaults.defaultColor, <add> backgroundColor: globalDefaults.defaultColor <ide> }, { <del> borderColor: 'rgb(0, 0, 255)', <del> backgroundColor: 'rgb(0, 255, 255)' <add> borderColor: globalDefaults.defaultColor, <add> backgroundColor: globalDefaults.defaultColor <ide> }] <ide> })); <ide> <ide> describe('Core.Tooltip', function() { <ide> <ide> // Check and see if tooltip was displayed <ide> var tooltip = chart.tooltip; <add> var globalDefaults = Chart.defaults.global; <ide> <ide> expect(tooltip._view).toEqual(jasmine.objectContaining({ <ide> // Positioning <ide> describe('Core.Tooltip', function() { <ide> afterBody: [], <ide> footer: [], <ide> labelColors: [{ <del> borderColor: 'rgb(0, 0, 255)', <del> backgroundColor: 'rgb(0, 255, 255)' <add> borderColor: globalDefaults.defaultColor, <add> backgroundColor: globalDefaults.defaultColor <ide> }, { <del> borderColor: 'rgb(255, 0, 0)', <del> backgroundColor: 'rgb(0, 255, 0)' <add> borderColor: globalDefaults.defaultColor, <add> backgroundColor: globalDefaults.defaultColor <ide> }] <ide> })); <ide> <ide> describe('Core.Tooltip', function() { <ide> <ide> // Check and see if tooltip was displayed <ide> var tooltip = chart.tooltip; <add> var globalDefaults = Chart.defaults.global; <ide> <ide> expect(tooltip._view).toEqual(jasmine.objectContaining({ <ide> // Positioning <ide> describe('Core.Tooltip', function() { <ide> afterBody: [], <ide> footer: [], <ide> labelColors: [{ <del> borderColor: 'rgb(0, 0, 255)', <del> backgroundColor: 'rgb(0, 255, 255)' <add> borderColor: globalDefaults.defaultColor, <add> backgroundColor: globalDefaults.defaultColor <ide> }] <ide> })); <ide> }); <ide> describe('Core.Tooltip', function() { <ide> caretPadding: 2, <ide> labelTextColors: ['labelTextColor', 'labelTextColor'], <ide> labelColors: [{ <del> borderColor: 'rgb(255, 0, 0)', <del> backgroundColor: 'rgb(0, 255, 0)' <add> borderColor: globalDefaults.defaultColor, <add> backgroundColor: globalDefaults.defaultColor <ide> }, { <del> borderColor: 'rgb(0, 0, 255)', <del> backgroundColor: 'rgb(0, 255, 255)' <add> borderColor: globalDefaults.defaultColor, <add> backgroundColor: globalDefaults.defaultColor <ide> }] <ide> })); <ide> });
3
PHP
PHP
allow disabling of specific middleware in tests
3879cb699f26136e227f61595c631112a050438b
<ide><path>src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php <ide> <ide> namespace Illuminate\Foundation\Testing\Concerns; <ide> <add>use Illuminate\Http\Testing\NullMiddleware; <ide> use Illuminate\Support\Str; <ide> use Illuminate\Http\Request; <ide> use Illuminate\Foundation\Testing\TestResponse; <ide> protected function withServerVariables(array $server) <ide> /** <ide> * Disable middleware for the test. <ide> * <add> * @param string|array $middleware <ide> * @return $this <ide> */ <del> public function withoutMiddleware() <add> public function withoutMiddleware($middleware = null) <ide> { <del> $this->app->instance('middleware.disable', true); <add> if (is_null($middleware)) { <add> $this->app->instance('middleware.disable', true); <add> <add> return $this; <add> } <add> <add> $nullMiddleware = new class { <add> public function handle($request, $next) { <add> return $next($request); <add> } <add> }; <add> <add> foreach ((array) $middleware as $abstract) { <add> $this->app->instance($abstract, $nullMiddleware); <add> } <ide> <ide> return $this; <ide> }
1
Java
Java
fix compose generics
4a593af2b18af11ad7f326890a13a301629302d4
<ide><path>src/main/java/rx/Observable.java <ide> public void call(Subscriber<? super R> o) { <ide> * @return the source Observable, transformed by the transformer function <ide> * @see <a href="https://github.com/ReactiveX/RxJava/wiki/Implementing-Your-Own-Operators">RxJava wiki: Implementing Your Own Operators</a> <ide> */ <del> public <R> Observable<R> compose(Transformer<? super T, R> transformer) { <del> return transformer.call(this); <add> @SuppressWarnings("unchecked") <add> public <R> Observable<R> compose(Transformer<? super T, ? extends R> transformer) { <add> // Casting to Observable<R> is type-safe because we know Observable is covariant. <add> return (Observable<R>) transformer.call(this); <ide> } <ide> <ide> /** <ide> * Transformer function used by {@link #compose}. <ide> * @warn more complete description needed <ide> */ <del> public static interface Transformer<T, R> extends Func1<Observable<? extends T>, Observable<R>> { <add> public static interface Transformer<T, R> extends Func1<Observable<? extends T>, Observable<? extends R>> { <ide> // cover for generics insanity <ide> } <ide> <ide><path>src/test/java/rx/CovarianceTest.java <ide> import org.junit.Test; <ide> <ide> import rx.Observable.Transformer; <add>import rx.functions.Func1; <ide> import rx.functions.Func2; <ide> <ide> /** <ide> * Test super/extends of generics. <ide> * <del> * See https://github.com/ReactiveX/RxJava/pull/331 <add> * See https://github.com/Netflix/RxJava/pull/331 <ide> */ <ide> public class CovarianceTest { <ide> <ide> public Integer call(Media t1, Media t2) { <ide> <ide> @Test <ide> public void testCovarianceOfCompose() { <del> Observable<HorrorMovie> movie = Observable.<HorrorMovie> just(new HorrorMovie()); <add> Observable<HorrorMovie> movie = Observable.just(new HorrorMovie()); <ide> Observable<Movie> movie2 = movie.compose(new Transformer<Movie, Movie>() { <ide> <ide> @Override <del> public Observable<Movie> call(Observable<? extends Movie> t1) { <add> public Observable<? extends Movie> call(Observable<? extends Movie> t1) { <ide> return Observable.just(new Movie()); <ide> } <ide> <ide> public void testCovarianceOfCompose2() { <ide> Observable<Movie> movie = Observable.<Movie> just(new HorrorMovie()); <ide> Observable<HorrorMovie> movie2 = movie.compose(new Transformer<Movie, HorrorMovie>() { <ide> @Override <del> public Observable<HorrorMovie> call(Observable<? extends Movie> t1) { <add> public Observable<? extends HorrorMovie> call(Observable<? extends Movie> t1) { <ide> return Observable.just(new HorrorMovie()); <ide> } <ide> }); <ide> } <del> <add> <add> @Test <add> public void testCovarianceOfCompose3() { <add> Observable<Movie> movie = Observable.<Movie>just(new HorrorMovie()); <add> Observable<HorrorMovie> movie2 = movie.compose(new Transformer<Movie, HorrorMovie>() { <add> @Override <add> public Observable<? extends HorrorMovie> call(Observable<? extends Movie> t1) { <add> return Observable.just(new HorrorMovie()).map(new Func1<HorrorMovie, HorrorMovie>() { <add> <add> @Override <add> public HorrorMovie call(HorrorMovie horrorMovie) { <add> return horrorMovie; <add> } <add> }); <add> } <add> }); <add> } <add> <add> @Test <add> public void testCovarianceOfCompose4() { <add> Observable<HorrorMovie> movie = Observable.just(new HorrorMovie()); <add> Observable<HorrorMovie> movie2 = movie.compose(new Transformer<HorrorMovie, HorrorMovie>() { <add> @Override <add> public Observable<? extends HorrorMovie> call(Observable<? extends HorrorMovie> t1) { <add> return t1.map(new Func1<HorrorMovie, HorrorMovie>() { <add> <add> @Override <add> public HorrorMovie call(HorrorMovie horrorMovie) { <add> return horrorMovie; <add> } <add> }); <add> } <add> }); <add> } <ide> <ide> /* <ide> * Most tests are moved into their applicable classes such as [Operator]Tests.java
2
Python
Python
remove print in __init__.py
91495a3352d9a35174c3ec711161010c14be1952
<ide><path>glances/__init__.py <ide> def main(): <ide> from glances.server import GlancesServer <ide> <ide> args = core.get_args() <del> print args.cached_time <ide> <ide> server = GlancesServer(cached_time=args.cached_time, <ide> config=core.get_config(),
1
Ruby
Ruby
remove extra whitespace
3adb01ed769fa19c9b7460c22cf1f766194e7c9f
<ide><path>actionpack/lib/action_dispatch.rb <ide> module Http <ide> end <ide> <ide> module Session <del> autoload :AbstractStore, 'action_dispatch/middleware/session/abstract_store' <del> autoload :CookieStore, 'action_dispatch/middleware/session/cookie_store' <del> autoload :MemCacheStore, 'action_dispatch/middleware/session/mem_cache_store' <del> autoload :CacheStore, 'action_dispatch/middleware/session/cache_store' <add> autoload :AbstractStore, 'action_dispatch/middleware/session/abstract_store' <add> autoload :CookieStore, 'action_dispatch/middleware/session/cookie_store' <add> autoload :MemCacheStore, 'action_dispatch/middleware/session/mem_cache_store' <add> autoload :CacheStore, 'action_dispatch/middleware/session/cache_store' <ide> end <ide> <ide> mattr_accessor :test_app
1
Python
Python
provide a __repr__ for nodeimage and node size
f4ef11abeb07dbfa1df569a8456ec0554043ead0
<ide><path>libcloud/base.py <ide> def destroy(self): <ide> return self.driver.destroy_node(self) <ide> <ide> def __repr__(self): <del> return (('<Node: uuid=%s, name=%s, provider=%s ...>') <del> % (self.uuid, self.name, self.driver.name)) <add> return (('<Node: uuid=%s, name=%s, state=%s, public_ip=%s, provider=%s ...>') <add> % (self.uuid, self.name, self.state, self.public_ip, self.driver.name)) <ide> <ide> <ide> class NodeSize(object): <ide> def __init__(self, id, name, ram, disk, bandwidth, price, driver): <ide> self.bandwidth = bandwidth <ide> self.price = price <ide> self.driver = driver <add> def __repr__(self): <add> return (('<NodeSize: id=%s, name=%s, ram=%s disk=%s bandwidth=%s price=%s driver=%s ...>') <add> % (self.id, self.name, self.ram, self.disk, self.bandwidth, self.price, self.driver.name)) <ide> <ide> <ide> class NodeImage(object): <ide> def __init__(self, id, name, driver): <ide> self.id = id <ide> self.name = name <ide> self.driver = driver <add> def __repr__(self): <add> return (('<NodeImage: id=%s, name=%s, driver=%s ...>') <add> % (self.id, self.name, self.driver.name)) <ide> <ide> <ide> class Response(object):
1
Ruby
Ruby
use 1.9 syntax
1a8ca9fc35083b51c48ddddb6b5b73af2046778c
<ide><path>actionmailer/test/assert_select_email_test.rb <ide> class AssertSelectEmailTest < ActionMailer::TestCase <ide> <ide> class AssertSelectMailer < ActionMailer::Base <ide> def test(html) <del> mail :body => html, :content_type => "text/html", <del> :subject => "Test e-mail", :from => "test@test.host", :to => "test <test@test.host>" <add> mail body: html, content_type: "text/html", <add> subject: "Test e-mail", from: "test@test.host", to: "test <test@test.host>" <ide> end <ide> end <ide> <ide> class AssertMultipartSelectMailer < ActionMailer::Base <ide> def test(options) <del> mail :subject => "Test e-mail", :from => "test@test.host", :to => "test <test@test.host>" do |format| <del> format.text { render :text => options[:text] } <del> format.html { render :text => options[:html] } <add> mail subject: "Test e-mail", from: "test@test.host", to: "test <test@test.host>" do |format| <add> format.text { render text: options[:text] } <add> format.html { render text: options[:html] } <ide> end <ide> end <ide> end <ide> def test_assert_select_email <ide> end <ide> <ide> def test_assert_select_email_multipart <del> AssertMultipartSelectMailer.test(:html => "<div><p>foo</p><p>bar</p></div>", :text => 'foo bar').deliver <add> AssertMultipartSelectMailer.test(html: "<div><p>foo</p><p>bar</p></div>", text: 'foo bar').deliver <ide> assert_select_email do <ide> assert_select "div:root" do <ide> assert_select "p:first-child", "foo"
1
Ruby
Ruby
return an array from options
f2e018d747a79056fb618c12d5ed922574e249fd
<ide><path>Library/Homebrew/formula.rb <ide> def cached_download <ide> def caveats; nil end <ide> <ide> # any e.g. configure options for this package <del> def options; end <add> def options; [] end <ide> <ide> # patches are automatically applied after extracting the tarball <ide> # return an array of strings, or if you need a patch level other than -p1
1
Javascript
Javascript
replace assert.throws w/ common.expectserror
eae0c05697121aaae4b097f34d30a259c8591af1
<ide><path>test/parallel/test-http2-compat-serverresponse-headers.js <ide> server.listen(0, common.mustCall(function() { <ide> ':path', <ide> ':authority', <ide> ':scheme' <del> ].forEach((header) => assert.throws( <add> ].forEach((header) => common.expectsError( <ide> () => response.setHeader(header, 'foobar'), <del> common.expectsError({ <add> { <ide> code: 'ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED', <ide> type: Error, <ide> message: 'Cannot set HTTP/2 pseudo-headers' <ide> }) <del> )); <del> assert.throws(function() { <add> ); <add> common.expectsError(function() { <ide> response.setHeader(real, null); <del> }, common.expectsError({ <add> }, { <ide> code: 'ERR_HTTP2_INVALID_HEADER_VALUE', <ide> type: TypeError, <ide> message: 'Invalid value "null" for header "foo-bar"' <del> })); <del> assert.throws(function() { <add> }); <add> common.expectsError(function() { <ide> response.setHeader(real, undefined); <del> }, common.expectsError({ <add> }, { <ide> code: 'ERR_HTTP2_INVALID_HEADER_VALUE', <ide> type: TypeError, <ide> message: 'Invalid value "undefined" for header "foo-bar"' <del> })); <add> }); <ide> common.expectsError( <ide> () => response.setHeader(), // header name undefined <ide> { <ide><path>test/parallel/test-http2-compat-serverresponse-statuscode.js <ide> server.listen(0, common.mustCall(function() { <ide> response.statusCode = realStatusCodes.internalServerError; <ide> }); <ide> <del> assert.throws(function() { <add> common.expectsError(function() { <ide> response.statusCode = realStatusCodes.continue; <del> }, common.expectsError({ <add> }, { <ide> code: 'ERR_HTTP2_INFO_STATUS_NOT_ALLOWED', <ide> type: RangeError <del> })); <del> assert.throws(function() { <add> }); <add> common.expectsError(function() { <ide> response.statusCode = fakeStatusCodes.tooLow; <del> }, common.expectsError({ <add> }, { <ide> code: 'ERR_HTTP2_STATUS_INVALID', <ide> type: RangeError <del> })); <del> assert.throws(function() { <add> }); <add> common.expectsError(function() { <ide> response.statusCode = fakeStatusCodes.tooHigh; <del> }, common.expectsError({ <add> }, { <ide> code: 'ERR_HTTP2_STATUS_INVALID', <ide> type: RangeError <del> })); <add> }); <ide> <ide> response.on('finish', common.mustCall(function() { <ide> server.close(); <ide><path>test/parallel/test-http2-getpackedsettings.js <ide> assert.doesNotThrow(() => http2.getPackedSettings({ enablePush: false })); <ide> ['maxHeaderListSize', -1], <ide> ['maxHeaderListSize', 2 ** 32] <ide> ].forEach((i) => { <del> assert.throws(() => { <add> common.expectsError(() => { <ide> http2.getPackedSettings({ [i[0]]: i[1] }); <del> }, common.expectsError({ <add> }, { <ide> code: 'ERR_HTTP2_INVALID_SETTING_VALUE', <ide> type: RangeError, <ide> message: `Invalid value for setting "${i[0]}": ${i[1]}` <del> })); <add> }); <ide> }); <ide> <ide> [ <ide> 1, null, '', Infinity, new Date(), {}, NaN, [false] <ide> ].forEach((i) => { <del> assert.throws(() => { <add> common.expectsError(() => { <ide> http2.getPackedSettings({ enablePush: i }); <del> }, common.expectsError({ <add> }, { <ide> code: 'ERR_HTTP2_INVALID_SETTING_VALUE', <ide> type: TypeError, <ide> message: `Invalid value for setting "enablePush": ${i}` <del> })); <add> }); <ide> }); <ide> <ide> { <ide> assert.doesNotThrow(() => http2.getPackedSettings({ enablePush: false })); <ide> 0x00, 0x02, 0x00, 0x00, 0x00, 0x01]); <ide> <ide> [1, true, '', [], {}, NaN].forEach((i) => { <del> assert.throws(() => { <add> common.expectsError(() => { <ide> http2.getUnpackedSettings(i); <del> }, common.expectsError({ <add> }, { <ide> code: 'ERR_INVALID_ARG_TYPE', <ide> type: TypeError, <ide> message: <ide> 'The "buf" argument must be one of type Buffer, TypedArray, or DataView' <del> })); <add> }); <ide> }); <ide> <del> assert.throws(() => { <add> common.expectsError(() => { <ide> http2.getUnpackedSettings(packed.slice(5)); <del> }, common.expectsError({ <add> }, { <ide> code: 'ERR_HTTP2_INVALID_PACKED_SETTINGS_LENGTH', <ide> type: RangeError, <ide> message: 'Packed settings length must be a multiple of six' <del> })); <add> }); <ide> <ide> const settings = http2.getUnpackedSettings(packed); <ide> <ide> assert.doesNotThrow(() => http2.getPackedSettings({ enablePush: false })); <ide> { <ide> const packed = Buffer.from([0x00, 0x05, 0x01, 0x00, 0x00, 0x00]); <ide> <del> assert.throws(() => { <add> common.expectsError(() => { <ide> http2.getUnpackedSettings(packed, { validate: true }); <del> }, common.expectsError({ <add> }, { <ide> code: 'ERR_HTTP2_INVALID_SETTING_VALUE', <ide> type: RangeError, <ide> message: 'Invalid value for setting "maxFrameSize": 16777216' <del> })); <add> }); <ide> } <ide> <ide> // check for maxConcurrentStreams failing the max number <ide> { <ide> const packed = Buffer.from([0x00, 0x03, 0xFF, 0xFF, 0xFF, 0xFF]); <ide> <del> assert.throws(() => { <add> common.expectsError(() => { <ide> http2.getUnpackedSettings(packed, { validate: true }); <del> }, common.expectsError({ <add> }, { <ide> code: 'ERR_HTTP2_INVALID_SETTING_VALUE', <ide> type: RangeError, <ide> message: 'Invalid value for setting "maxConcurrentStreams": 4294967295' <del> })); <add> }); <ide> } <ide><path>test/parallel/test-http2-info-headers.js <ide> const afterRespondregex = <ide> <ide> function onStream(stream, headers, flags) { <ide> <del> assert.throws(() => stream.additionalHeaders({ ':status': 201 }), <del> common.expectsError({ <del> code: 'ERR_HTTP2_INVALID_INFO_STATUS', <del> type: RangeError, <del> message: /^Invalid informational status code: 201$/ <del> })); <del> <del> assert.throws(() => stream.additionalHeaders({ ':status': 101 }), <del> common.expectsError({ <del> code: 'ERR_HTTP2_STATUS_101', <del> type: Error, <del> message: status101regex <del> })); <add> common.expectsError(() => stream.additionalHeaders({ ':status': 201 }), <add> { <add> code: 'ERR_HTTP2_INVALID_INFO_STATUS', <add> type: RangeError, <add> message: /^Invalid informational status code: 201$/ <add> }); <add> <add> common.expectsError(() => stream.additionalHeaders({ ':status': 101 }), <add> { <add> code: 'ERR_HTTP2_STATUS_101', <add> type: Error, <add> message: status101regex <add> }); <ide> <ide> common.expectsError( <ide> () => stream.additionalHeaders({ ':method': 'POST' }), <ide> function onStream(stream, headers, flags) { <ide> ':status': 200 <ide> }); <ide> <del> assert.throws(() => stream.additionalHeaders({ abc: 123 }), <del> common.expectsError({ <del> code: 'ERR_HTTP2_HEADERS_AFTER_RESPOND', <del> type: Error, <del> message: afterRespondregex <del> })); <add> common.expectsError(() => stream.additionalHeaders({ abc: 123 }), <add> { <add> code: 'ERR_HTTP2_HEADERS_AFTER_RESPOND', <add> type: Error, <add> message: afterRespondregex <add> }); <ide> <ide> stream.end('hello world'); <ide> } <ide><path>test/parallel/test-http2-misused-pseudoheaders.js <ide> const common = require('../common'); <ide> if (!common.hasCrypto) <ide> common.skip('missing crypto'); <del>const assert = require('assert'); <ide> const h2 = require('http2'); <ide> <ide> const server = h2.createServer(); <ide> function onStream(stream, headers, flags) { <ide> ':method', <ide> ':scheme' <ide> ].forEach((i) => { <del> assert.throws(() => stream.respond({ [i]: '/' }), <del> common.expectsError({ <del> code: 'ERR_HTTP2_INVALID_PSEUDOHEADER' <del> })); <add> common.expectsError(() => stream.respond({ [i]: '/' }), <add> { <add> code: 'ERR_HTTP2_INVALID_PSEUDOHEADER' <add> }); <ide> }); <ide> <ide> stream.respond({ <ide><path>test/parallel/test-http2-too-many-settings.js <ide> let clients = 2; <ide> function doTest(session) { <ide> for (let n = 0; n < maxPendingAck; n++) <ide> assert.doesNotThrow(() => session.settings({ enablePush: false })); <del> assert.throws(() => session.settings({ enablePush: false }), <del> common.expectsError({ <del> code: 'ERR_HTTP2_MAX_PENDING_SETTINGS_ACK', <del> type: Error <del> })); <add> common.expectsError(() => session.settings({ enablePush: false }), <add> { <add> code: 'ERR_HTTP2_MAX_PENDING_SETTINGS_ACK', <add> type: Error <add> }); <ide> } <ide> <ide> server.on('stream', common.mustNotCall()); <ide><path>test/parallel/test-http2-util-asserts.js <ide> const { <ide> [], <ide> [{}] <ide> ].forEach((i) => { <del> assert.throws(() => assertIsObject(i, 'foo', 'Object'), <del> common.expectsError({ <del> code: 'ERR_INVALID_ARG_TYPE', <del> message: /^The "foo" argument must be of type Object$/ <del> })); <add> common.expectsError(() => assertIsObject(i, 'foo', 'Object'), <add> { <add> code: 'ERR_INVALID_ARG_TYPE', <add> message: /^The "foo" argument must be of type Object$/ <add> }); <ide> }); <ide> <ide> assert.doesNotThrow(() => assertWithinRange('foo', 1, 0, 2)); <ide> <del>assert.throws(() => assertWithinRange('foo', 1, 2, 3), <del> common.expectsError({ <del> code: 'ERR_HTTP2_INVALID_SETTING_VALUE', <del> message: /^Invalid value for setting "foo": 1$/ <del> })); <add>common.expectsError(() => assertWithinRange('foo', 1, 2, 3), <add> { <add> code: 'ERR_HTTP2_INVALID_SETTING_VALUE', <add> message: /^Invalid value for setting "foo": 1$/ <add> }); <ide><path>test/parallel/test-internal-errors.js <ide> errors.E('TEST_ERROR_2', (a, b) => `${a} ${b}`); <ide> assert.strictEqual(err.code, 'TEST_ERROR_1'); <ide> } <ide> <del>assert.throws( <add>common.expectsError( <ide> () => new errors.Error('TEST_FOO_KEY'), <del> common.expectsError({ <add> { <ide> code: 'ERR_ASSERTION', <ide> message: invalidKey('TEST_FOO_KEY') <del> })); <add> }); <ide> // Calling it twice yields same result (using the key does not create it) <del>assert.throws( <add>common.expectsError( <ide> () => new errors.Error('TEST_FOO_KEY'), <del> common.expectsError({ <add> { <ide> code: 'ERR_ASSERTION', <ide> message: invalidKey('TEST_FOO_KEY') <del> })); <del>assert.throws( <add> }); <add>common.expectsError( <ide> () => new errors.Error(1), <del> common.expectsError({ <add> { <ide> code: 'ERR_ASSERTION', <ide> message: invalidKey(1) <del> })); <del>assert.throws( <add> }); <add>common.expectsError( <ide> () => new errors.Error({}), <del> common.expectsError({ <add> { <ide> code: 'ERR_ASSERTION', <ide> message: invalidKey('\\[object Object\\]') <del> })); <del>assert.throws( <add> }); <add>common.expectsError( <ide> () => new errors.Error([]), <del> common.expectsError({ <add> { <ide> code: 'ERR_ASSERTION', <ide> message: invalidKey('') <del> })); <del>assert.throws( <add> }); <add>common.expectsError( <ide> () => new errors.Error(true), <del> common.expectsError({ <add> { <ide> code: 'ERR_ASSERTION', <ide> message: invalidKey('true') <del> })); <del>assert.throws( <add> }); <add>common.expectsError( <ide> () => new errors.TypeError(1), <del> common.expectsError({ <add> { <ide> code: 'ERR_ASSERTION', <ide> message: invalidKey(1) <del> })); <del>assert.throws( <add> }); <add>common.expectsError( <ide> () => new errors.TypeError({}), <del> common.expectsError({ <add> { <ide> code: 'ERR_ASSERTION', <ide> message: invalidKey('\\[object Object\\]') <del> })); <del>assert.throws( <add> }); <add>common.expectsError( <ide> () => new errors.TypeError([]), <del> common.expectsError({ <add> { <ide> code: 'ERR_ASSERTION', <ide> message: invalidKey('') <del> })); <del>assert.throws( <add> }); <add>common.expectsError( <ide> () => new errors.TypeError(true), <del> common.expectsError({ <add> { <ide> code: 'ERR_ASSERTION', <ide> message: invalidKey('true') <del> })); <del>assert.throws( <add> }); <add>common.expectsError( <ide> () => new errors.RangeError(1), <del> common.expectsError({ <add> { <ide> code: 'ERR_ASSERTION', <ide> message: invalidKey(1) <del> })); <del>assert.throws( <add> }); <add>common.expectsError( <ide> () => new errors.RangeError({}), <del> common.expectsError({ <add> { <ide> code: 'ERR_ASSERTION', <ide> message: invalidKey('\\[object Object\\]') <del> })); <del>assert.throws( <add> }); <add>common.expectsError( <ide> () => new errors.RangeError([]), <del> common.expectsError({ <add> { <ide> code: 'ERR_ASSERTION', <ide> message: invalidKey('') <del> })); <del>assert.throws( <add> }); <add>common.expectsError( <ide> () => new errors.RangeError(true), <del> common.expectsError({ <add> { <ide> code: 'ERR_ASSERTION', <ide> message: invalidKey('true') <del> })); <add> }); <ide> <ide> <ide> // Tests for common.expectsError <ide> assert.doesNotThrow(() => { <ide> }, common.expectsError({ code: 'TEST_ERROR_1', type: Error })); <ide> }); <ide> <del>assert.throws(() => { <del> assert.throws(() => { <add>common.expectsError(() => { <add> common.expectsError(() => { <ide> throw new errors.TypeError('TEST_ERROR_1', 'a'); <del> }, common.expectsError({ code: 'TEST_ERROR_1', type: RangeError })); <del>}, common.expectsError({ <add> }, { code: 'TEST_ERROR_1', type: RangeError }); <add>}, { <ide> code: 'ERR_ASSERTION', <ide> message: /^.+ is not instance of \S/ <del>})); <add>}); <ide> <del>assert.throws(() => { <del> assert.throws(() => { <add>common.expectsError(() => { <add> common.expectsError(() => { <ide> throw new errors.TypeError('TEST_ERROR_1', 'a'); <del> }, common.expectsError({ code: 'TEST_ERROR_1', <del> type: TypeError, <del> message: /^Error for testing 2/ })); <del>}, common.expectsError({ <add> }, { code: 'TEST_ERROR_1', <add> type: TypeError, <add> message: /^Error for testing 2/ }); <add>}, { <ide> code: 'ERR_ASSERTION', <ide> message: /.+ does not match \S/ <del>})); <add>}); <ide> <ide> // // Test ERR_INVALID_ARG_TYPE <ide> assert.strictEqual(errors.message('ERR_INVALID_ARG_TYPE', ['a', 'b']), <ide> assert.strictEqual(errors.message('ERR_INVALID_URL_SCHEME', [['http', 'ftp']]), <ide> 'The URL must be one of scheme http or ftp'); <ide> assert.strictEqual(errors.message('ERR_INVALID_URL_SCHEME', [['a', 'b', 'c']]), <ide> 'The URL must be one of scheme a, b, or c'); <del>assert.throws( <add>common.expectsError( <ide> () => errors.message('ERR_INVALID_URL_SCHEME', [[]]), <del> common.expectsError({ <add> { <ide> code: 'ERR_ASSERTION', <ide> message: /^At least one expected value needs to be specified$/ <del> })); <add> }); <ide> <ide> // Test ERR_MISSING_ARGS <ide> assert.strictEqual(errors.message('ERR_MISSING_ARGS', ['name']), <ide> assert.strictEqual(errors.message('ERR_MISSING_ARGS', ['name', 'value']), <ide> 'The "name" and "value" arguments must be specified'); <ide> assert.strictEqual(errors.message('ERR_MISSING_ARGS', ['a', 'b', 'c']), <ide> 'The "a", "b", and "c" arguments must be specified'); <del>assert.throws( <add>common.expectsError( <ide> () => errors.message('ERR_MISSING_ARGS'), <del> common.expectsError({ <add> { <ide> code: 'ERR_ASSERTION', <ide> message: /^At least one arg needs to be specified$/ <del> })); <add> }); <ide> <ide> // Test ERR_SOCKET_BAD_PORT <ide> assert.strictEqual( <ide><path>test/parallel/test-module-loading-error.js <ide> assert.throws( <ide> } <ide> ); <ide> <del>assert.throws( <add>common.expectsError( <ide> require, <del> common.expectsError({ <add> { <ide> code: 'ERR_ASSERTION', <ide> message: /^missing path$/ <del> })); <add> }); <ide> <del>assert.throws( <add>common.expectsError( <ide> () => { require({}); }, <del> common.expectsError({ <add> { <ide> code: 'ERR_ASSERTION', <ide> message: /^path must be a string$/ <del> })); <add> }); <ide><path>test/parallel/test-net-better-error-messages-path.js <ide> 'use strict'; <ide> const common = require('../common'); <ide> const net = require('net'); <del>const assert = require('assert'); <ide> <ide> { <ide> const fp = '/tmp/fadagagsdfgsdf'; <ide> const assert = require('assert'); <ide> } <ide> <ide> { <del> assert.throws( <add> common.expectsError( <ide> () => net.createConnection({ path: {} }), <del> common.expectsError({ code: 'ERR_INVALID_ARG_TYPE' }) <add> { code: 'ERR_INVALID_ARG_TYPE' } <ide> ); <ide> } <ide><path>test/parallel/test-net-connect-options-port.js <ide> const net = require('net'); <ide> const hintOptBlocks = doConnect([{ hints: hints }], <ide> () => common.mustNotCall()); <ide> for (const block of hintOptBlocks) { <del> assert.throws(block, common.expectsError({ <add> common.expectsError(block, { <ide> code: 'ERR_INVALID_OPT_VALUE', <ide> type: TypeError, <ide> message: /The value "\d+" is invalid for option "hints"/ <del> })); <add> }); <ide> } <ide> } <ide> <ide><path>test/parallel/test-net-options-lookup.js <ide> function connectThrows(input) { <ide> lookup: input <ide> }; <ide> <del> assert.throws(() => { <add> common.expectsError(() => { <ide> net.connect(opts); <del> }, common.expectsError({ <add> }, { <ide> code: 'ERR_INVALID_ARG_TYPE', <ide> type: TypeError <del> })); <add> }); <ide> } <ide> <ide> connectDoesNotThrow(() => {}); <ide><path>test/parallel/test-net-server-listen-options.js <ide> const listenOnPort = [ <ide> const block = () => { <ide> net.createServer().listen(options, common.mustNotCall()); <ide> }; <del> assert.throws(block, <del> common.expectsError({ <del> code: 'ERR_INVALID_OPT_VALUE', <del> type: Error, <del> message: /^The value "{.*}" is invalid for option "options"$/ <del> })); <add> common.expectsError(block, <add> { <add> code: 'ERR_INVALID_OPT_VALUE', <add> type: Error, <add> message: /^The value "{.*}" is invalid for option "options"$/ <add> }); <ide> } <ide> <ide> shouldFailToListen(false, { port: false }); <ide><path>test/parallel/test-net-server-options.js <ide> 'use strict'; <ide> const common = require('../common'); <del>const assert = require('assert'); <ide> const net = require('net'); <ide> <del>assert.throws(function() { net.createServer('path'); }, <del> common.expectsError({ <del> code: 'ERR_INVALID_ARG_TYPE', <del> type: TypeError <del> })); <add>common.expectsError(function() { net.createServer('path'); }, <add> { <add> code: 'ERR_INVALID_ARG_TYPE', <add> type: TypeError <add> }); <ide> <del>assert.throws(function() { net.createServer(0); }, <del> common.expectsError({ <del> code: 'ERR_INVALID_ARG_TYPE', <del> type: TypeError <del> })); <add>common.expectsError(function() { net.createServer(0); }, <add> { <add> code: 'ERR_INVALID_ARG_TYPE', <add> type: TypeError <add> }); <ide><path>test/parallel/test-net-socket-write-error.js <ide> 'use strict'; <ide> <ide> const common = require('../common'); <del>const assert = require('assert'); <ide> const net = require('net'); <ide> <ide> const server = net.createServer().listen(0, connectToServer); <ide> <ide> function connectToServer() { <ide> const client = net.createConnection(this.address().port, () => { <del> assert.throws(() => client.write(1337), <del> common.expectsError({ <del> code: 'ERR_INVALID_ARG_TYPE', <del> type: TypeError <del> })); <add> common.expectsError(() => client.write(1337), <add> { <add> code: 'ERR_INVALID_ARG_TYPE', <add> type: TypeError <add> }); <ide> <ide> client.end(); <ide> }) <ide><path>test/parallel/test-path-parse-format.js <ide> function checkFormat(path, testCases) { <ide> } <ide> <ide> [null, undefined, 1, true, false, 'string'].forEach((pathObject) => { <del> assert.throws(() => { <add> common.expectsError(() => { <ide> path.format(pathObject); <del> }, common.expectsError({ <add> }, { <ide> code: 'ERR_INVALID_ARG_TYPE', <ide> type: TypeError, <ide> message: 'The "pathObject" argument must be of type Object. ' + <ide> `Received type ${typeName(pathObject)}` <del> })); <add> }); <ide> }); <ide> } <ide><path>test/parallel/test-path.js <ide> const typeErrorTests = [true, false, 7, null, {}, undefined, [], NaN]; <ide> function fail(fn) { <ide> const args = Array.from(arguments).slice(1); <ide> <del> assert.throws(() => { <add> common.expectsError(() => { <ide> fn.apply(null, args); <del> }, common.expectsError({ code: 'ERR_INVALID_ARG_TYPE', type: TypeError })); <add> }, { code: 'ERR_INVALID_ARG_TYPE', type: TypeError }); <ide> } <ide> <ide> typeErrorTests.forEach((test) => { <ide><path>test/parallel/test-performance-function.js <ide> const { <ide> <ide> { <ide> [1, {}, [], null, undefined, Infinity].forEach((i) => { <del> assert.throws(() => performance.timerify(i), <del> common.expectsError({ <del> code: 'ERR_INVALID_ARG_TYPE', <del> type: TypeError, <del> message: 'The "fn" argument must be of type Function' <del> })); <add> common.expectsError(() => performance.timerify(i), <add> { <add> code: 'ERR_INVALID_ARG_TYPE', <add> type: TypeError, <add> message: 'The "fn" argument must be of type Function' <add> }); <ide> }); <ide> } <ide> <ide><path>test/parallel/test-process-assert.js <ide> const common = require('../common'); <ide> const assert = require('assert'); <ide> <ide> assert.strictEqual(process.assert(1, 'error'), undefined); <del>assert.throws(() => { <add>common.expectsError(() => { <ide> process.assert(undefined, 'errorMessage'); <del>}, common.expectsError({ <add>}, { <ide> code: 'ERR_ASSERTION', <ide> type: Error, <ide> message: 'errorMessage' <del>}) <add>} <ide> ); <del>assert.throws(() => { <add>common.expectsError(() => { <ide> process.assert(false); <del>}, common.expectsError({ <add>}, { <ide> code: 'ERR_ASSERTION', <ide> type: Error, <ide> message: 'assertion error' <del>}) <add>} <ide> ); <ide><path>test/parallel/test-process-hrtime.js <ide> validateTuple(tuple); <ide> validateTuple(process.hrtime(tuple)); <ide> <ide> // test that only an Array may be passed to process.hrtime() <del>assert.throws(() => { <add>common.expectsError(() => { <ide> process.hrtime(1); <del>}, common.expectsError({ <add>}, { <ide> code: 'ERR_INVALID_ARG_TYPE', <ide> type: TypeError, <ide> message: 'The "time" argument must be of type Array. Received type number' <del>})); <del>assert.throws(() => { <add>}); <add>common.expectsError(() => { <ide> process.hrtime([]); <del>}, common.expectsError({ <add>}, { <ide> code: 'ERR_INVALID_ARRAY_LENGTH', <ide> type: TypeError, <ide> message: 'The array "time" (length 0) must be of length 2.' <del>})); <del>assert.throws(() => { <add>}); <add>common.expectsError(() => { <ide> process.hrtime([1]); <del>}, common.expectsError({ <add>}, { <ide> code: 'ERR_INVALID_ARRAY_LENGTH', <ide> type: TypeError, <ide> message: 'The array "time" (length 1) must be of length 2.' <del>})); <del>assert.throws(() => { <add>}); <add>common.expectsError(() => { <ide> process.hrtime([1, 2, 3]); <del>}, common.expectsError({ <add>}, { <ide> code: 'ERR_INVALID_ARRAY_LENGTH', <ide> type: TypeError, <ide> message: 'The array "time" (length 3) must be of length 2.' <del>})); <add>}); <ide> <ide> function validateTuple(tuple) { <ide> assert(Array.isArray(tuple)); <ide><path>test/parallel/test-process-next-tick.js <ide> <ide> 'use strict'; <ide> const common = require('../common'); <del>const assert = require('assert'); <ide> const N = 2; <ide> <ide> function cb() { <ide> process.on('exit', function() { <ide> }); <ide> <ide> [null, 1, 'test', {}, [], Infinity, true].forEach((i) => { <del> assert.throws(() => process.nextTick(i), <del> common.expectsError({ <del> code: 'ERR_INVALID_CALLBACK', <del> type: TypeError, <del> message: 'Callback must be a function' <del> })); <add> common.expectsError(() => process.nextTick(i), <add> { <add> code: 'ERR_INVALID_CALLBACK', <add> type: TypeError, <add> message: 'Callback must be a function' <add> }); <ide> }); <ide><path>test/parallel/test-readline-csi.js <ide> assert.doesNotThrow(() => readline.cursorTo(writable, 'a', 'b')); <ide> assert.strictEqual(writable.data, ''); <ide> <ide> writable.data = ''; <del>assert.throws( <add>common.expectsError( <ide> () => readline.cursorTo(writable, 'a', 1), <del> common.expectsError({ <add> { <ide> type: Error, <ide> code: 'ERR_INVALID_CURSOR_POS', <ide> message: 'Cannot set cursor row without setting its column' <del> })); <add> }); <ide> assert.strictEqual(writable.data, ''); <ide> <ide> writable.data = ''; <ide><path>test/parallel/test-regress-GH-5727.js <ide> net.Server().listen(0, function() { <ide> }); <ide> <ide> // The first argument is a configuration object <del>assert.throws(() => { <add>common.expectsError(() => { <ide> net.Server().listen({ port: invalidPort }, common.mustNotCall()); <del>}, common.expectsError({ <add>}, { <ide> code: 'ERR_SOCKET_BAD_PORT', <ide> type: RangeError <del>})); <add>}); <ide> <ide> // The first argument is the port, no IP given. <del>assert.throws(() => { <add>common.expectsError(() => { <ide> net.Server().listen(invalidPort, common.mustNotCall()); <del>}, common.expectsError({ <add>}, { <ide> code: 'ERR_SOCKET_BAD_PORT', <ide> type: RangeError <del>})); <add>}); <ide> <ide> // The first argument is the port, the second an IP. <del>assert.throws(() => { <add>common.expectsError(() => { <ide> net.Server().listen(invalidPort, '0.0.0.0', common.mustNotCall()); <del>}, common.expectsError({ <add>}, { <ide> code: 'ERR_SOCKET_BAD_PORT', <ide> type: RangeError <del>})); <add>}); <ide><path>test/parallel/test-require-invalid-package.js <ide> 'use strict'; <ide> <ide> const common = require('../common'); <del>const assert = require('assert'); <ide> <ide> // Should be an invalid package path. <del>assert.throws(() => require('package.json'), <del> common.expectsError({ code: 'MODULE_NOT_FOUND' }) <add>common.expectsError(() => require('package.json'), <add> { code: 'MODULE_NOT_FOUND' } <ide> ); <ide><path>test/parallel/test-stream-readable-with-unimplemented-_read.js <ide> 'use strict'; <ide> const common = require('../common'); <ide> const stream = require('stream'); <del>const assert = require('assert'); <ide> <ide> const readable = new stream.Readable(); <ide> <del>assert.throws(() => readable.read(), common.expectsError({ <add>common.expectsError(() => readable.read(), { <ide> code: 'ERR_STREAM_READ_NOT_IMPLEMENTED', <ide> type: Error, <ide> message: '_read() is not implemented' <del>})); <add>}); <ide><path>test/parallel/test-stream-unshift-read-race.js <ide> r._read = function(n) { <ide> }; <ide> <ide> function pushError() { <del> assert.throws(function() { <add> common.expectsError(function() { <ide> r.push(Buffer.allocUnsafe(1)); <del> }, common.expectsError({ <add> }, { <ide> code: 'ERR_STREAM_PUSH_AFTER_EOF', <ide> type: Error, <ide> message: 'stream.push() after EOF' <del> })); <add> }); <ide> } <ide> <ide> <ide> w._write = function(chunk, encoding, cb) { <ide> }; <ide> <ide> r.on('end', common.mustCall(function() { <del> assert.throws(function() { <add> common.expectsError(function() { <ide> r.unshift(Buffer.allocUnsafe(1)); <del> }, common.expectsError({ <add> }, { <ide> code: 'ERR_STREAM_UNSHIFT_AFTER_END_EVENT', <ide> type: Error, <ide> message: 'stream.unshift() after end event' <del> })); <add> }); <ide> w.end(); <ide> })); <ide> <ide><path>test/parallel/test-timers-enroll-invalid-msecs.js <ide> <ide> const common = require('../common'); <ide> const timers = require('timers'); <del>const assert = require('assert'); <ide> <ide> [ <ide> {}, <ide> const assert = require('assert'); <ide> () => { }, <ide> Symbol('foo') <ide> ].forEach((val) => { <del> assert.throws( <add> common.expectsError( <ide> () => timers.enroll({}, val), <del> common.expectsError({ <add> { <ide> code: 'ERR_INVALID_ARG_TYPE', <ide> type: TypeError <del> }) <add> } <ide> ); <ide> }); <ide> <ide> const assert = require('assert'); <ide> Infinity, <ide> NaN <ide> ].forEach((val) => { <del> assert.throws( <add> common.expectsError( <ide> () => timers.enroll({}, val), <del> common.expectsError({ <add> { <ide> code: 'ERR_VALUE_OUT_OF_RANGE', <ide> type: RangeError, <ide> message: 'The value of "msecs" must be a non-negative ' + <ide> `finite number. Received "${val}"` <del> }) <add> } <ide> ); <ide> }); <ide><path>test/parallel/test-tls-basic-validations.js <ide> assert.throws(() => tls.createServer({ key: 'dummykey', passphrase: 1 }), <ide> assert.throws(() => tls.createServer({ ecdhCurve: 1 }), <ide> /TypeError: ECDH curve name must be a string/); <ide> <del>assert.throws(() => tls.createServer({ handshakeTimeout: 'abcd' }), <del> common.expectsError({ <del> code: 'ERR_INVALID_ARG_TYPE', <del> type: TypeError, <del> message: 'The "timeout" argument must be of type number' <del> }) <add>common.expectsError(() => tls.createServer({ handshakeTimeout: 'abcd' }), <add> { <add> code: 'ERR_INVALID_ARG_TYPE', <add> type: TypeError, <add> message: 'The "timeout" argument must be of type number' <add> } <ide> ); <ide> <ide> assert.throws(() => tls.createServer({ sessionTimeout: 'abcd' }), <ide><path>test/parallel/test-tls-clientcertengine-invalid-arg-type.js <ide> const common = require('../common'); <ide> if (!common.hasCrypto) <ide> common.skip('missing crypto'); <ide> <del>const assert = require('assert'); <ide> const tls = require('tls'); <ide> <ide> { <del> assert.throws( <add> common.expectsError( <ide> () => { tls.createSecureContext({ clientCertEngine: 0 }); }, <del> common.expectsError({ code: 'ERR_INVALID_ARG_TYPE', <del> message: / Received type number$/ })); <add> { code: 'ERR_INVALID_ARG_TYPE', <add> message: / Received type number$/ }); <ide> } <ide><path>test/parallel/test-tls-clientcertengine-unsupported.js <ide> binding.SecureContext = function() { <ide> return rv; <ide> }; <ide> <del>const assert = require('assert'); <ide> const tls = require('tls'); <ide> <ide> { <del> assert.throws( <add> common.expectsError( <ide> () => { tls.createSecureContext({ clientCertEngine: 'Cannonmouth' }); }, <del> common.expectsError({ <add> { <ide> code: 'ERR_CRYPTO_CUSTOM_ENGINE_NOT_SUPPORTED', <ide> message: 'Custom engines not supported by this OpenSSL' <del> }) <add> } <ide> ); <ide> } <ide><path>test/parallel/test-tls-no-cert-required.js <ide> tls.createServer(assert.fail) <ide> tls.createServer({}) <ide> .listen(0, common.mustCall(close)); <ide> <del>assert.throws(() => tls.createServer('this is not valid'), <del> common.expectsError({ <del> code: 'ERR_INVALID_ARG_TYPE', <del> type: TypeError, <del> message: 'The "options" argument must be of type Object' <del> }) <add>common.expectsError(() => tls.createServer('this is not valid'), <add> { <add> code: 'ERR_INVALID_ARG_TYPE', <add> type: TypeError, <add> message: 'The "options" argument must be of type Object' <add> } <ide> ); <ide> <ide> tls.createServer() <ide><path>test/parallel/test-tls-options-boolean-check.js <ide> const invalidCertRE = /^The "cert" argument must be one of type string, Buffer, <ide> [[keyStr, keyStr2], true, invalidCertRE], <ide> [true, [certBuff, certBuff2], invalidKeyRE] <ide> ].map(([key, cert, message]) => { <del> assert.throws(() => { <add> common.expectsError(() => { <ide> tls.createServer({ key, cert }); <del> }, common.expectsError({ <add> }, { <ide> code: 'ERR_INVALID_ARG_TYPE', <ide> type: TypeError, <ide> message <del> })); <add> }); <ide> }); <ide> <ide> // Checks to ensure tls.createServer works with the CA parameter <ide> const invalidCertRE = /^The "cert" argument must be one of type string, Buffer, <ide> [keyBuff, certBuff, true], <ide> [keyBuff, certBuff, [caCert, true]] <ide> ].map(([key, cert, ca]) => { <del> assert.throws(() => { <add> common.expectsError(() => { <ide> tls.createServer({ key, cert, ca }); <del> }, common.expectsError({ <add> }, { <ide> code: 'ERR_INVALID_ARG_TYPE', <ide> type: TypeError, <ide> message: /^The "ca" argument must be one of type string, Buffer, TypedArray, or DataView$/ <del> })); <add> }); <ide> }); <ide> <ide> // Checks to ensure tls.createServer throws an error for CA assignment <ide> const invalidCertRE = /^The "cert" argument must be one of type string, Buffer, <ide> [keyBuff, certBuff, true], <ide> [keyBuff, certBuff, [caCert, true]] <ide> ].map(([key, cert, ca]) => { <del> assert.throws(() => { <add> common.expectsError(() => { <ide> tls.createServer({ key, cert, ca }); <del> }, common.expectsError({ <add> }, { <ide> code: 'ERR_INVALID_ARG_TYPE', <ide> type: TypeError, <ide> message: /^The "ca" argument must be one of type string, Buffer, TypedArray, or DataView$/ <del> })); <add> }); <ide> }); <ide> <ide> // Checks to ensure tls.createSecureContext works with false-y input <ide><path>test/parallel/test-util-callbackify.js <ide> const values = [ <ide> { <ide> // Verify that non-function inputs throw. <ide> ['foo', null, undefined, false, 0, {}, Symbol(), []].forEach((value) => { <del> assert.throws(() => { <add> common.expectsError(() => { <ide> callbackify(value); <del> }, common.expectsError({ <add> }, { <ide> code: 'ERR_INVALID_ARG_TYPE', <ide> type: TypeError, <ide> message: 'The "original" argument must be of type Function' <del> })); <add> }); <ide> }); <ide> } <ide> <ide> const values = [ <ide> // Verify that the last argument to the callbackified function is a function. <ide> ['foo', null, undefined, false, 0, {}, Symbol(), []].forEach((value) => { <ide> args.push(value); <del> assert.throws(() => { <add> common.expectsError(() => { <ide> cb(...args); <del> }, common.expectsError({ <add> }, { <ide> code: 'ERR_INVALID_ARG_TYPE', <ide> type: TypeError, <ide> message: 'The last argument must be of type Function' <del> })); <add> }); <ide> }); <ide> } <ide><path>test/parallel/test-util-inherits.js <ide> assert.strictEqual(e.e(), 'e'); <ide> assert.strictEqual(e.constructor, E); <ide> <ide> // should throw with invalid arguments <del>assert.throws(function() { <add>common.expectsError(function() { <ide> inherits(A, {}); <del>}, common.expectsError({ <add>}, { <ide> code: 'ERR_INVALID_ARG_TYPE', <ide> type: TypeError, <ide> message: 'The "superCtor.prototype" property must be of type Function' <del>}) <add>} <ide> ); <ide> assert.throws(function() { <ide> inherits(A, null); <ide> }, errCheck); <del>assert.throws(function() { <add>common.expectsError(function() { <ide> inherits(null, A); <del>}, common.expectsError({ <add>}, { <ide> code: 'ERR_INVALID_ARG_TYPE', <ide> type: TypeError, <ide> message: 'The "ctor" argument must be of type Function' <del>}) <add>} <ide> ); <ide><path>test/parallel/test-util-inspect.js <ide> if (typeof Symbol !== 'undefined') { <ide> JSON.stringify(oldOptions) <ide> ); <ide> <del> assert.throws(() => { <add> common.expectsError(() => { <ide> util.inspect.defaultOptions = null; <del> }, common.expectsError({ <add> }, { <ide> code: 'ERR_INVALID_ARG_TYPE', <ide> type: TypeError, <ide> message: 'The "options" argument must be of type Object' <del> }) <add> } <ide> ); <ide> <del> assert.throws(() => { <add> common.expectsError(() => { <ide> util.inspect.defaultOptions = 'bad'; <del> }, common.expectsError({ <add> }, { <ide> code: 'ERR_INVALID_ARG_TYPE', <ide> type: TypeError, <ide> message: 'The "options" argument must be of type Object' <del> }) <add> } <ide> ); <ide> } <ide> <ide><path>test/parallel/test-whatwg-encoding-textdecoder.js <ide> assert(TextDecoder); <ide> if (common.hasIntl) { <ide> ['unicode-1-1-utf-8', 'utf8', 'utf-8'].forEach((i) => { <ide> const dec = new TextDecoder(i, { fatal: true }); <del> assert.throws(() => dec.decode(buf.slice(0, 8)), <del> common.expectsError({ <del> code: 'ERR_ENCODING_INVALID_ENCODED_DATA', <del> type: TypeError, <del> message: 'The encoded data was not valid for encoding utf-8' <del> })); <add> common.expectsError(() => dec.decode(buf.slice(0, 8)), <add> { <add> code: 'ERR_ENCODING_INVALID_ENCODED_DATA', <add> type: TypeError, <add> message: 'The encoded data was not valid ' + <add> 'for encoding utf-8' <add> }); <ide> }); <ide> <ide> ['unicode-1-1-utf-8', 'utf8', 'utf-8'].forEach((i) => { <ide> if (common.hasIntl) { <ide> assert.doesNotThrow(() => dec.decode(buf.slice(8))); <ide> }); <ide> } else { <del> assert.throws( <add> common.expectsError( <ide> () => new TextDecoder('utf-8', { fatal: true }), <del> common.expectsError({ <add> { <ide> code: 'ERR_NO_ICU', <ide> type: TypeError, <ide> message: '"fatal" option is not supported on Node.js compiled without ICU' <del> })); <add> }); <ide> } <ide> <ide> // Test TextDecoder, UTF-16le <ide> if (common.hasIntl) { <ide> }); <ide> <ide> [{}, [], true, 1, '', new TextEncoder()].forEach((i) => { <del> assert.throws(() => fn.call(i, Infinity, {}), <del> common.expectsError({ <del> code: 'ERR_INVALID_THIS', <del> type: TypeError, <del> message: 'Value of "this" must be of type TextDecoder' <del> })); <add> common.expectsError(() => fn.call(i, Infinity, {}), <add> { <add> code: 'ERR_INVALID_THIS', <add> type: TypeError, <add> message: 'Value of "this" must be of type TextDecoder' <add> }); <ide> }); <ide> } <ide> <ide><path>test/parallel/test-whatwg-encoding-textencoder.js <ide> assert(TextEncoder); <ide> }); <ide> <ide> [{}, [], true, 1, '', new TextDecoder()].forEach((i) => { <del> assert.throws(() => fn.call(i, Infinity, {}), <del> common.expectsError({ <del> code: 'ERR_INVALID_THIS', <del> type: TypeError, <del> message: 'Value of "this" must be of type TextEncoder' <del> })); <add> common.expectsError(() => fn.call(i, Infinity, {}), <add> { <add> code: 'ERR_INVALID_THIS', <add> type: TypeError, <add> message: 'Value of "this" must be of type TextEncoder' <add> }); <ide> }); <ide> } <ide><path>test/parallel/test-whatwg-url-searchparams-append.js <ide> test(function() { <ide> // Tests below are not from WPT. <ide> { <ide> const params = new URLSearchParams(); <del> assert.throws(() => { <add> common.expectsError(() => { <ide> params.append.call(undefined); <del> }, common.expectsError({ <add> }, { <ide> code: 'ERR_INVALID_THIS', <ide> type: TypeError, <ide> message: 'Value of "this" must be of type URLSearchParams' <del> })); <del> assert.throws(() => { <add> }); <add> common.expectsError(() => { <ide> params.append('a'); <del> }, common.expectsError({ <add> }, { <ide> code: 'ERR_MISSING_ARGS', <ide> type: TypeError, <ide> message: 'The "name" and "value" arguments must be specified' <del> })); <add> }); <ide> <ide> const obj = { <ide> toString() { throw new Error('toString'); }, <ide><path>test/parallel/test-whatwg-url-searchparams-delete.js <ide> test(function() { <ide> // Tests below are not from WPT. <ide> { <ide> const params = new URLSearchParams(); <del> assert.throws(() => { <add> common.expectsError(() => { <ide> params.delete.call(undefined); <del> }, common.expectsError({ <add> }, { <ide> code: 'ERR_INVALID_THIS', <ide> type: TypeError, <ide> message: 'Value of "this" must be of type URLSearchParams' <del> })); <del> assert.throws(() => { <add> }); <add> common.expectsError(() => { <ide> params.delete(); <del> }, common.expectsError({ <add> }, { <ide> code: 'ERR_MISSING_ARGS', <ide> type: TypeError, <ide> message: 'The "name" argument must be specified' <del> })); <add> }); <ide> <ide> const obj = { <ide> toString() { throw new Error('toString'); }, <ide><path>test/parallel/test-whatwg-url-searchparams-entries.js <ide> assert.deepStrictEqual(entries.next(), { <ide> done: true <ide> }); <ide> <del>assert.throws(() => { <add>common.expectsError(() => { <ide> entries.next.call(undefined); <del>}, common.expectsError({ <add>}, { <ide> code: 'ERR_INVALID_THIS', <ide> type: TypeError, <ide> message: 'Value of "this" must be of type URLSearchParamsIterator' <del>})); <del>assert.throws(() => { <add>}); <add>common.expectsError(() => { <ide> params.entries.call(undefined); <del>}, common.expectsError({ <add>}, { <ide> code: 'ERR_INVALID_THIS', <ide> type: TypeError, <ide> message: 'Value of "this" must be of type URLSearchParams' <del>})); <add>}); <ide><path>test/parallel/test-whatwg-url-searchparams-foreach.js <ide> 'use strict'; <ide> <ide> const common = require('../common'); <del>const assert = require('assert'); <ide> const { URL, URLSearchParams } = require('url'); <ide> const { test, assert_array_equals, assert_unreached } = <ide> require('../common/wpt'); <ide> test(function() { <ide> // Tests below are not from WPT. <ide> { <ide> const params = new URLSearchParams(); <del> assert.throws(() => { <add> common.expectsError(() => { <ide> params.forEach.call(undefined); <del> }, common.expectsError({ <add> }, { <ide> code: 'ERR_INVALID_THIS', <ide> type: TypeError, <ide> message: 'Value of "this" must be of type URLSearchParams' <del> })); <add> }); <ide> } <ide><path>test/parallel/test-whatwg-url-searchparams-get.js <ide> test(function() { <ide> // Tests below are not from WPT. <ide> { <ide> const params = new URLSearchParams(); <del> assert.throws(() => { <add> common.expectsError(() => { <ide> params.get.call(undefined); <del> }, common.expectsError({ <add> }, { <ide> code: 'ERR_INVALID_THIS', <ide> type: TypeError, <ide> message: 'Value of "this" must be of type URLSearchParams' <del> })); <del> assert.throws(() => { <add> }); <add> common.expectsError(() => { <ide> params.get(); <del> }, common.expectsError({ <add> }, { <ide> code: 'ERR_MISSING_ARGS', <ide> type: TypeError, <ide> message: 'The "name" argument must be specified' <del> })); <add> }); <ide> <ide> const obj = { <ide> toString() { throw new Error('toString'); }, <ide><path>test/parallel/test-whatwg-url-searchparams-getall.js <ide> test(function() { <ide> // Tests below are not from WPT. <ide> { <ide> const params = new URLSearchParams(); <del> assert.throws(() => { <add> common.expectsError(() => { <ide> params.getAll.call(undefined); <del> }, common.expectsError({ <add> }, { <ide> code: 'ERR_INVALID_THIS', <ide> type: TypeError, <ide> message: 'Value of "this" must be of type URLSearchParams' <del> })); <del> assert.throws(() => { <add> }); <add> common.expectsError(() => { <ide> params.getAll(); <del> }, common.expectsError({ <add> }, { <ide> code: 'ERR_MISSING_ARGS', <ide> type: TypeError, <ide> message: 'The "name" argument must be specified' <del> })); <add> }); <ide> <ide> const obj = { <ide> toString() { throw new Error('toString'); }, <ide><path>test/parallel/test-whatwg-url-searchparams-has.js <ide> test(function() { <ide> // Tests below are not from WPT. <ide> { <ide> const params = new URLSearchParams(); <del> assert.throws(() => { <add> common.expectsError(() => { <ide> params.has.call(undefined); <del> }, common.expectsError({ <add> }, { <ide> code: 'ERR_INVALID_THIS', <ide> type: TypeError, <ide> message: 'Value of "this" must be of type URLSearchParams' <del> })); <del> assert.throws(() => { <add> }); <add> common.expectsError(() => { <ide> params.has(); <del> }, common.expectsError({ <add> }, { <ide> code: 'ERR_MISSING_ARGS', <ide> type: TypeError, <ide> message: 'The "name" argument must be specified' <del> })); <add> }); <ide> <ide> const obj = { <ide> toString() { throw new Error('toString'); }, <ide><path>test/parallel/test-whatwg-url-searchparams-keys.js <ide> assert.deepStrictEqual(keys.next(), { <ide> done: true <ide> }); <ide> <del>assert.throws(() => { <add>common.expectsError(() => { <ide> keys.next.call(undefined); <del>}, common.expectsError({ <add>}, { <ide> code: 'ERR_INVALID_THIS', <ide> type: TypeError, <ide> message: 'Value of "this" must be of type URLSearchParamsIterator' <del>})); <del>assert.throws(() => { <add>}); <add>common.expectsError(() => { <ide> params.keys.call(undefined); <del>}, common.expectsError({ <add>}, { <ide> code: 'ERR_INVALID_THIS', <ide> type: TypeError, <ide> message: 'Value of "this" must be of type URLSearchParams' <del>})); <add>}); <ide><path>test/parallel/test-whatwg-url-searchparams-set.js <ide> test(function() { <ide> // Tests below are not from WPT. <ide> { <ide> const params = new URLSearchParams(); <del> assert.throws(() => { <add> common.expectsError(() => { <ide> params.set.call(undefined); <del> }, common.expectsError({ <add> }, { <ide> code: 'ERR_INVALID_THIS', <ide> type: TypeError, <ide> message: 'Value of "this" must be of type URLSearchParams' <del> })); <del> assert.throws(() => { <add> }); <add> common.expectsError(() => { <ide> params.set('a'); <del> }, common.expectsError({ <add> }, { <ide> code: 'ERR_MISSING_ARGS', <ide> type: TypeError, <ide> message: 'The "name" and "value" arguments must be specified' <del> })); <add> }); <ide> <ide> const obj = { <ide> toString() { throw new Error('toString'); }, <ide><path>test/parallel/test-whatwg-url-searchparams-stringifier.js <ide> 'use strict'; <ide> <ide> const common = require('../common'); <del>const assert = require('assert'); <ide> const URLSearchParams = require('url').URLSearchParams; <ide> const { test, assert_equals } = require('../common/wpt'); <ide> <ide> test(function() { <ide> // Tests below are not from WPT. <ide> { <ide> const params = new URLSearchParams(); <del> assert.throws(() => { <add> common.expectsError(() => { <ide> params.toString.call(undefined); <del> }, common.expectsError({ <add> }, { <ide> code: 'ERR_INVALID_THIS', <ide> type: TypeError, <ide> message: 'Value of "this" must be of type URLSearchParams' <del> })); <add> }); <ide> } <ide><path>test/parallel/test-whatwg-url-searchparams-values.js <ide> assert.deepStrictEqual(values.next(), { <ide> done: true <ide> }); <ide> <del>assert.throws(() => { <add>common.expectsError(() => { <ide> values.next.call(undefined); <del>}, common.expectsError({ <add>}, { <ide> code: 'ERR_INVALID_THIS', <ide> type: TypeError, <ide> message: 'Value of "this" must be of type URLSearchParamsIterator' <del>})); <del>assert.throws(() => { <add>}); <add>common.expectsError(() => { <ide> params.values.call(undefined); <del>}, common.expectsError({ <add>}, { <ide> code: 'ERR_INVALID_THIS', <ide> type: TypeError, <ide> message: 'Value of "this" must be of type URLSearchParams' <del>})); <add>});
48
Python
Python
add hebrew to init and setup.py
7e4befec8820371930d9815c0f1c880e2c1d2196
<ide><path>setup.py <ide> 'spacy.sv', <ide> 'spacy.fi', <ide> 'spacy.bn', <add> 'spacy.he', <ide> 'spacy.en.lemmatizer', <ide> 'spacy.language_data', <ide> 'spacy.serialize', <ide><path>spacy/__init__.py <ide> from . import sv <ide> from . import fi <ide> from . import bn <add>from . import he <ide> <ide> from .about import * <ide> <ide> set_lang_class(sv.Swedish.lang, sv.Swedish) <ide> set_lang_class(fi.Finnish.lang, fi.Finnish) <ide> set_lang_class(bn.Bengali.lang, bn.Bengali) <add>set_lang_class(he.Hebrew.lang, he.Hebrew) <ide> <ide> <ide> def load(name, **overrides):
2
Text
Text
fix volume binding in fluentd container example
c450e608b9b1f79f474dbfb468ab26ae0f741868
<ide><path>docs/admin/logging/fluentd.md <ide> aggregate store. <ide> <ide> 2. Launch Fluentd container with this configuration file: <ide> <del> $ docker run -it -p 24224:24224 -v /path/to/conf/test.conf:/fluentd/etc -e FLUENTD_CONF=test.conf fluent/fluentd:latest <add> $ docker run -it -p 24224:24224 -v /path/to/conf/test.conf:/fluentd/etc/test.conf -e FLUENTD_CONF=test.conf fluent/fluentd:latest <ide> <ide> 3. Start one or more containers with the `fluentd` logging driver: <ide>
1
Ruby
Ruby
take advantage of inheritence for easier codes
56f2de870a7279e11575f6d0c6f2f9eea1374407
<ide><path>lib/arel/algebra/relations/writes.rb <ide> module Arel <del> class Deletion < Compound <del> attributes :relation <del> deriving :initialize, :== <add> class Action < Compound <add> def == other <add> super || self.class === other && @relation == other.relation <add> end <add> end <ide> <add> class Deletion < Action <ide> def call <ide> engine.delete(self) <ide> end <ide> end <ide> <del> class Insert < Compound <del> attributes :relation, :record <del> deriving :== <add> class Insert < Action <add> attr_reader :record <ide> <ide> def initialize(relation, record) <del> @relation, @record = relation, record.bind(relation) <add> super(relation) <add> @record = record.bind(relation) <ide> end <ide> <ide> def call <ide> engine.create(self) <ide> end <del> end <ide> <del> class Update < Compound <del> attributes :relation, :assignments <del> deriving :== <del> <del> def initialize(relation, assignments) <del> @relation, @assignments = relation, assignments.bind(relation) <add> def == other <add> super && @record == other.record <ide> end <add> end <add> <add> class Update < Insert <add> alias :assignments :record <ide> <ide> def call <ide> engine.update(self) <ide><path>lib/arel/engines/memory/relations/writes.rb <ide> module Arel <del> class Insert < Compound <add> class Insert < Action <ide> def eval <ide> unoperated_rows + [Row.new(self, record.values.collect(&:value))] <ide> end <ide><path>lib/arel/engines/sql/relations/writes.rb <ide> module Arel <del> class Deletion < Compound <add> class Deletion < Action <ide> def to_sql <ide> compiler.delete_sql <ide> end <ide> end <ide> <del> class Insert < Compound <add> class Insert < Action <ide> def to_sql(include_returning = true) <ide> compiler.insert_sql(include_returning) <ide> end <ide> end <ide> <del> class Update < Compound <add> class Update < Insert <ide> def to_sql <ide> compiler.update_sql <ide> end
3
PHP
PHP
create tests for assertnotfound
c9c5513bb0dcc94a118c4fe86348c02b2b0fded9
<ide><path>tests/Foundation/FoundationTestResponseTest.php <ide> public function testAssertSeeTextInOrderCanFail2() <ide> $response->assertSeeTextInOrder(['foobar', 'qux', 'baz']); <ide> } <ide> <add> public function testAssertNotFound() <add> { <add> $statusCode = 500; <add> <add> $this->expectException(AssertionFailedError::class); <add> $this->expectExceptionMessage('Response status code ['.$statusCode.'] is not a not found status code.'); <add> <add> $baseResponse = tap(new Response, function ($response) use ($statusCode) { <add> $response->setStatusCode($statusCode); <add> }); <add> <add> $response = TestResponse::fromBaseResponse($baseResponse); <add> $response->assertNotFound(); <add> } <add> <ide> public function testAssertHeader() <ide> { <ide> $this->expectException(AssertionFailedError::class);
1
Python
Python
unskip test on win32
af6e61668ac3598daca111e7ed81bcca5e910735
<ide><path>numpy/random/_examples/cython/setup.py <ide> from distutils.core import setup <ide> from Cython.Build import cythonize <ide> from setuptools.extension import Extension <del>from os.path import join, abspath, dirname <add>from os.path import join, dirname <ide> <del>path = abspath(dirname(__file__)) <add>path = dirname(__file__) <ide> defs = [('NPY_NO_DEPRECATED_API', 0)] <ide> <ide> extending = Extension("extending", <ide><path>numpy/random/tests/test_extending.py <ide> <ide> @pytest.mark.skipif(cython is None, reason="requires cython") <ide> @pytest.mark.slow <del>@pytest.mark.skipif(sys.platform == 'win32', reason="cmd too long on CI") <ide> def test_cython(tmp_path): <ide> examples = os.path.join(os.path.dirname(__file__), '..', '_examples') <ide> base = os.path.dirname(examples)
2
Ruby
Ruby
show help text for tapped external command
5b393cb049edbc4d85356896883bf5e85d913acc
<ide><path>Library/Homebrew/brew.rb <ide> class MissingEnvironmentVariables < RuntimeError; end <ide> safe_system(*tap_commands) <ide> end <ide> <add> ARGV << "--help" if help_flag <ide> exec HOMEBREW_BREW_FILE, cmd, *ARGV <ide> end <ide> rescue UsageError => e
1
Python
Python
fix conv reccurent test
84ceb94055b831c486dbf4955fdf1ba0f63320d1
<ide><path>tests/keras/layers/convolutional_recurrent_test.py <ide> def test_convolutional_recurrent(): <ide> for return_sequences in [True, False]: <ide> <ide> # test for return state: <del> inputs = Input(batch_shape=inputs.shape) <add> x = Input(batch_shape=inputs.shape) <ide> kwargs = {'data_format': data_format, <ide> 'return_sequences': return_sequences, <ide> 'return_state': True, <ide> def test_convolutional_recurrent(): <ide> 'padding': 'valid'} <ide> layer = convolutional_recurrent.ConvLSTM2D(**kwargs) <ide> layer.build(inputs.shape) <del> outputs = layer(inputs) <add> outputs = layer(x) <ide> output, states = outputs[0], outputs[1:] <ide> assert len(states) == 2 <del> model = Model(inputs, states[0]) <add> model = Model(x, states[0]) <ide> state = model.predict(inputs) <ide> np.testing.assert_allclose( <ide> K.eval(layer.states[0]), state, atol=1e-4)
1
Text
Text
add note about nghttp2 hd pair size
91cc4fa32d98952312b5bc543b4f0cd43246112b
<ide><path>doc/api/http2.md <ide> changes: <ide> serialized, compressed block of headers. Attempts to send headers that <ide> exceed this limit will result in a `'frameError'` event being emitted <ide> and the stream being closed and destroyed. <add> While this sets the maximum allowed size to the entire block of headers, <add> `nghttp2` (the internal http2 library) has a limit of `65536` <add> for each decompressed key/value pair. <ide> * `paddingStrategy` {number} The strategy used for determining the amount of <ide> padding to use for `HEADERS` and `DATA` frames. **Default:** <ide> `http2.constants.PADDING_STRATEGY_NONE`. Value may be one of:
1
PHP
PHP
fix model typo in eloquent/model.php
a83c3f2f471b9ba78e3f9500caf1673cac7f413d
<ide><path>src/Illuminate/Database/Eloquent/Model.php <ide> public static function hasGlobalScope($scope) <ide> } <ide> <ide> /** <del> * Get a global scope registered with the modal. <add> * Get a global scope registered with the model. <ide> * <ide> * @param \Illuminate\Database\Eloquent\ScopeInterface $scope <ide> * @return \Illuminate\Database\Eloquent\ScopeInterface|null
1
PHP
PHP
use hash instead of set class
ad5e62515fd824210d1ca0c67b33b5c372f0f63c
<ide><path>lib/Cake/View/XmlView.php <ide> <ide> App::uses('View', 'View'); <ide> App::uses('Xml', 'Utility'); <add>App::uses('Hash', 'Utility'); <ide> <ide> /** <ide> * A view class that is used for creating XML responses. <ide> protected function _serialize($serialize) { <ide> } <ide> } else { <ide> $data = isset($this->viewVars[$serialize]) ? $this->viewVars[$serialize] : null; <del> if (is_array($data) && Set::numeric(array_keys($data))) { <add> if (is_array($data) && Hash::numeric(array_keys($data))) { <ide> $data = array($rootNode => array($serialize => $data)); <ide> } <ide> }
1
Ruby
Ruby
remove unused require
9d700ad6259a459f8b0c25ebaad49a095f36a814
<ide><path>railties/lib/rails/commands/dbconsole/dbconsole_command.rb <del>require "erb" <del>require "yaml" <del> <ide> require "rails/command/environment_argument" <ide> <ide> module Rails
1
Javascript
Javascript
add unc support to url.pathtofileurl()
7b8c6b0c00f5e321e431047794fde8b84d0c4c3f
<ide><path>lib/internal/url.js <ide> const { getConstructorOf, removeColors } = require('internal/util'); <ide> const { <ide> ERR_ARG_NOT_ITERABLE, <ide> ERR_INVALID_ARG_TYPE, <add> ERR_INVALID_ARG_VALUE, <ide> ERR_INVALID_CALLBACK, <ide> ERR_INVALID_FILE_URL_HOST, <ide> ERR_INVALID_FILE_URL_PATH, <ide> const backslashRegEx = /\\/g; <ide> const newlineRegEx = /\n/g; <ide> const carriageReturnRegEx = /\r/g; <ide> const tabRegEx = /\t/g; <add> <add>function encodePathChars(filepath) { <add> if (filepath.includes('%')) <add> filepath = filepath.replace(percentRegEx, '%25'); <add> // In posix, backslash is a valid character in paths: <add> if (!isWindows && filepath.includes('\\')) <add> filepath = filepath.replace(backslashRegEx, '%5C'); <add> if (filepath.includes('\n')) <add> filepath = filepath.replace(newlineRegEx, '%0A'); <add> if (filepath.includes('\r')) <add> filepath = filepath.replace(carriageReturnRegEx, '%0D'); <add> if (filepath.includes('\t')) <add> filepath = filepath.replace(tabRegEx, '%09'); <add> return filepath; <add>} <add> <ide> function pathToFileURL(filepath) { <del> let resolved = path.resolve(filepath); <del> // path.resolve strips trailing slashes so we must add them back <del> const filePathLast = filepath.charCodeAt(filepath.length - 1); <del> if ((filePathLast === CHAR_FORWARD_SLASH || <del> (isWindows && filePathLast === CHAR_BACKWARD_SLASH)) && <del> resolved[resolved.length - 1] !== path.sep) <del> resolved += '/'; <ide> const outURL = new URL('file://'); <del> if (resolved.includes('%')) <del> resolved = resolved.replace(percentRegEx, '%25'); <del> // In posix, "/" is a valid character in paths <del> if (!isWindows && resolved.includes('\\')) <del> resolved = resolved.replace(backslashRegEx, '%5C'); <del> if (resolved.includes('\n')) <del> resolved = resolved.replace(newlineRegEx, '%0A'); <del> if (resolved.includes('\r')) <del> resolved = resolved.replace(carriageReturnRegEx, '%0D'); <del> if (resolved.includes('\t')) <del> resolved = resolved.replace(tabRegEx, '%09'); <del> outURL.pathname = resolved; <add> if (isWindows && filepath.startsWith('\\\\')) { <add> // UNC path format: \\server\share\resource <add> const paths = filepath.split('\\'); <add> if (paths.length <= 3) { <add> throw new ERR_INVALID_ARG_VALUE( <add> 'filepath', <add> filepath, <add> 'Missing UNC resource path' <add> ); <add> } <add> const hostname = paths[2]; <add> if (hostname.length === 0) { <add> throw new ERR_INVALID_ARG_VALUE( <add> 'filepath', <add> filepath, <add> 'Empty UNC servername' <add> ); <add> } <add> outURL.hostname = domainToASCII(hostname); <add> outURL.pathname = encodePathChars(paths.slice(3).join('/')); <add> } else { <add> let resolved = path.resolve(filepath); <add> // path.resolve strips trailing slashes so we must add them back <add> const filePathLast = filepath.charCodeAt(filepath.length - 1); <add> if ((filePathLast === CHAR_FORWARD_SLASH || <add> (isWindows && filePathLast === CHAR_BACKWARD_SLASH)) && <add> resolved[resolved.length - 1] !== path.sep) <add> resolved += '/'; <add> outURL.pathname = encodePathChars(resolved); <add> } <ide> return outURL; <ide> } <ide> <ide><path>test/parallel/test-url-fileurltopath.js <ide> assert.throws(() => url.fileURLToPath('https://a/b/c'), { <ide> // Euro sign (BMP code point) <ide> { path: 'C:\\€', fileURL: 'file:///C:/%E2%82%AC' }, <ide> // Rocket emoji (non-BMP code point) <del> { path: 'C:\\🚀', fileURL: 'file:///C:/%F0%9F%9A%80' } <add> { path: 'C:\\🚀', fileURL: 'file:///C:/%F0%9F%9A%80' }, <add> // UNC path (see https://docs.microsoft.com/en-us/archive/blogs/ie/file-uris-in-windows) <add> { path: '\\\\nas\\My Docs\\File.doc', fileURL: 'file://nas/My%20Docs/File.doc' }, <ide> ]; <ide> } else { <ide> testCases = [ <ide><path>test/parallel/test-url-pathtofileurl.js <ide> const url = require('url'); <ide> assert.ok(fileURL.includes('%25')); <ide> } <ide> <add>{ <add> if (isWindows) { <add> // UNC path: \\server\share\resource <add> <add> // Missing server: <add> assert.throws(() => url.pathToFileURL('\\\\\\no-server'), { <add> code: 'ERR_INVALID_ARG_VALUE' <add> }); <add> <add> // Missing share or resource: <add> assert.throws(() => url.pathToFileURL('\\\\host'), { <add> code: 'ERR_INVALID_ARG_VALUE' <add> }); <add> } else { <add> // UNC paths on posix are considered a single path that has backslashes: <add> const fileURL = url.pathToFileURL('\\\\nas\\share\\path.txt').href; <add> assert.match(fileURL, /file:\/\/.+%5C%5Cnas%5Cshare%5Cpath\.txt$/); <add> } <add>} <add> <ide> { <ide> let testCases; <ide> if (isWindows) { <ide> const url = require('url'); <ide> // Euro sign (BMP code point) <ide> { path: 'C:\\€', expected: 'file:///C:/%E2%82%AC' }, <ide> // Rocket emoji (non-BMP code point) <del> { path: 'C:\\🚀', expected: 'file:///C:/%F0%9F%9A%80' } <add> { path: 'C:\\🚀', expected: 'file:///C:/%F0%9F%9A%80' }, <add> // UNC path (see https://docs.microsoft.com/en-us/archive/blogs/ie/file-uris-in-windows) <add> { path: '\\\\nas\\My Docs\\File.doc', expected: 'file://nas/My%20Docs/File.doc' } <ide> ]; <ide> } else { <ide> testCases = [
3
Python
Python
add juggler sequence
b33ea81a7437eaf7d048d92a9b75330c9d9e165e
<ide><path>maths/juggler_sequence.py <add>""" <add>== Juggler Sequence == <add>Juggler sequence start with any positive integer n. The next term is <add>obtained as follows: <add> If n term is even, the next term is floor value of square root of n . <add> If n is odd, the next term is floor value of 3 time the square root of n. <add> <add>https://en.wikipedia.org/wiki/Juggler_sequence <add>""" <add> <add># Author : Akshay Dubey (https://github.com/itsAkshayDubey) <add>import math <add> <add> <add>def juggler_sequence(number: int) -> list[int]: <add> """ <add> >>> juggler_sequence(0) <add> Traceback (most recent call last): <add> ... <add> ValueError: Input value of [number=0] must be a positive integer <add> >>> juggler_sequence(1) <add> [1] <add> >>> juggler_sequence(2) <add> [2, 1] <add> >>> juggler_sequence(3) <add> [3, 5, 11, 36, 6, 2, 1] <add> >>> juggler_sequence(5) <add> [5, 11, 36, 6, 2, 1] <add> >>> juggler_sequence(10) <add> [10, 3, 5, 11, 36, 6, 2, 1] <add> >>> juggler_sequence(25) <add> [25, 125, 1397, 52214, 228, 15, 58, 7, 18, 4, 2, 1] <add> >>> juggler_sequence(6.0) <add> Traceback (most recent call last): <add> ... <add> TypeError: Input value of [number=6.0] must be an integer <add> >>> juggler_sequence(-1) <add> Traceback (most recent call last): <add> ... <add> ValueError: Input value of [number=-1] must be a positive integer <add> """ <add> if not isinstance(number, int): <add> raise TypeError(f"Input value of [number={number}] must be an integer") <add> if number < 1: <add> raise ValueError(f"Input value of [number={number}] must be a positive integer") <add> sequence = [number] <add> while number != 1: <add> if number % 2 == 0: <add> number = math.floor(math.sqrt(number)) <add> else: <add> number = math.floor( <add> math.sqrt(number) * math.sqrt(number) * math.sqrt(number) <add> ) <add> sequence.append(number) <add> return sequence <add> <add> <add>if __name__ == "__main__": <add> import doctest <add> <add> doctest.testmod()
1
PHP
PHP
fix storeas array issue
37a9617da416d8aec68d01a206c0453f0288c159
<ide><path>src/Illuminate/Http/UploadedFile.php <ide> public function storePubliclyAs($path, $name, $options = []) <ide> */ <ide> public function storeAs($path, $name, $options = []) <ide> { <add> $options = $this->parseOptions($options); <add> <ide> $disk = Arr::pull($options, 'disk'); <ide> <ide> return Container::getInstance()->make(FilesystemFactory::class)->disk($disk)->putFileAs(
1
Javascript
Javascript
expose the serialization api
e06a8087638284d4def981e396feaead7b207c17
<ide><path>lib/cache/FileCachePlugin.js <ide> const path = require("path"); <ide> const createHash = require("../util/createHash"); <ide> const makeSerializable = require("../util/makeSerializable"); <del>const serializer = require("../util/serializer"); <add>const { serializer } = require("../util/serialization"); <ide> <ide> /** @typedef {import("webpack-sources").Source} Source */ <ide> /** @typedef {import("../../declarations/WebpackOptions").FileCacheOptions} FileCacheOptions */ <ide><path>lib/index.js <ide> exportPlugins((exports.debug = {}), { <ide> <ide> exportPlugins((exports.util = {}), { <ide> createHash: () => require("./util/createHash"), <del> comparators: () => require("./util/comparators") <add> comparators: () => require("./util/comparators"), <add> serialization: () => require("./util/serialization") <ide> }); <ide><path>lib/util/serialization.js <add>/* <add> MIT License http://www.opensource.org/licenses/mit-license.php <add>*/ <add> <add>"use strict"; <add> <add>const ObjectMiddleware = require("../serialization/ObjectMiddleware"); <add> <add>exports.serializer = require("./serializer"); <add> <add>exports.register = ObjectMiddleware.register; <add>exports.registerLoader = ObjectMiddleware.registerLoader; <add>exports.registerNotSerializable = ObjectMiddleware.registerNotSerializable;
3
Text
Text
add notes on how to exit the debugger [ci-skip]
14e8939e2861f69505c0810caf63b5c0579a7ed1
<ide><path>guides/source/debugging_rails_applications.md <ide> Processing by PostsController#index as HTML <ide> (rdbg) <ide> ``` <ide> <add>You can exit the debugging session at any time and continue your application execution with the `continue` (or `c`) command. Or, to exit both the debugging session and your application, use the `quit` (or `q`) command. <add> <ide> ### The Context <ide> <ide> After entering the debugging session, you can type in Ruby code as you're in a Rails console or IRB.
1
Python
Python
fix double-wrapping of object scalars
fa56437c4eb4ca0c2a97597700a3fc6ad36963fa
<ide><path>numpy/lib/shape_base.py <ide> def apply_along_axis(func1d, axis, arr, *args, **kwargs): <ide> in_dims = list(range(nd)) <ide> inarr_view = transpose(arr, in_dims[:axis] + in_dims[axis+1:] + [axis]) <ide> <del> # compute indices for the iteration axes <add> # compute indices for the iteration axes, and append a trailing ellipsis to <add> # prevent 0d arrays decaying to scalars, which fixes gh-8642 <ide> inds = ndindex(inarr_view.shape[:-1]) <add> inds = (ind + (Ellipsis,) for ind in inds) <ide> <ide> # invoke the function on the first item <ide> try: <ide><path>numpy/lib/tests/test_shape_base.py <ide> def empty_to_1(x): <ide> assert_equal(actual, np.ones(10)) <ide> assert_raises(ValueError, np.apply_along_axis, empty_to_1, 0, a) <ide> <add> def test_with_iterable_object(self): <add> # from issue 5248 <add> d = np.array([ <add> [set([1, 11]), set([2, 22]), set([3, 33])], <add> [set([4, 44]), set([5, 55]), set([6, 66])] <add> ]) <add> actual = np.apply_along_axis(lambda a: set.union(*a), 0, d) <add> expected = np.array([{1, 11, 4, 44}, {2, 22, 5, 55}, {3, 33, 6, 66}]) <add> <add> assert_equal(actual, expected) <add> <add> # issue 8642 - assert_equal doesn't detect this! <add> for i in np.ndindex(actual.shape): <add> assert_equal(type(actual[i]), type(expected[i])) <add> <ide> <ide> class TestApplyOverAxes(TestCase): <ide> def test_simple(self):
2
Ruby
Ruby
set correct compiler symbol for gcc 4.0
bdd2e71b3a66f9f4a434110ec7501d87cf7b256d
<ide><path>Library/Homebrew/extend/ENV/std.rb <ide> def gcc_4_0_1 <ide> self.cxx = "#{MacOS.dev_tools_path}/g++-4.0" <ide> replace_in_cflags '-O4', '-O3' <ide> set_cpu_cflags '-march=nocona -mssse3' <del> @compiler = :gcc <add> @compiler = :gcc_4_0 <ide> end <ide> alias_method :gcc_4_0, :gcc_4_0_1 <ide>
1
Javascript
Javascript
throw error if interpolation is used in expression
cd21602d5b1650d8be373618cb7320d697e32c4d
<ide><path>src/ng/directive/ngBind.js <ide> var ngBindHtmlDirective = ['$sce', '$parse', '$compile', function($sce, $parse, <ide> return { <ide> restrict: 'A', <ide> compile: function ngBindHtmlCompile(tElement, tAttrs) { <add> var ngBindHtmlGetter = $parse(tAttrs.ngBindHtml); <add> var ngBindHtmlWatch = $parse(tAttrs.ngBindHtml, function getStringValue(value) { <add> return (value || '').toString(); <add> }); <ide> $compile.$$addBindingClass(tElement); <ide> <ide> return function ngBindHtmlLink(scope, element, attr) { <ide> $compile.$$addBindingInfo(element, attr.ngBindHtml); <del> var ngBindHtmlGetter = $parse(attr.ngBindHtml); <del> var ngBindHtmlWatch = $parse(attr.ngBindHtml, function getStringValue(value) { <del> return (value || '').toString(); <del> }); <ide> <ide> scope.$watch(ngBindHtmlWatch, function ngBindHtmlWatchAction() { <ide> // we re-evaluate the expr because we want a TrustedValueHolderType <ide><path>test/ng/directive/ngBindSpec.js <ide> describe('ngBind*', function() { <ide> <ide> describe('ngBindHtml', function() { <ide> <add> it('should complain about accidental use of interpolation', inject(function($compile) { <add> expect(function() { <add> $compile('<div ng-bind-html="{{myHtml}}"></div>'); <add> }).toThrowMinErr('$parse', 'syntax', "Syntax Error: Token 'myHtml' is unexpected, " + <add> "expecting [:] at column 3 of the expression [{{myHtml}}] starting at [myHtml}}]."); <add> })); <add> <add> <ide> describe('SCE disabled', function() { <ide> beforeEach(function() { <ide> module(function($sceProvider) { $sceProvider.enabled(false); });
2
PHP
PHP
update deprecation notice
1d374307beabdb45a3e79d8f57433a2ed3e09e6e
<ide><path>src/Validation/Validator.php <ide> protected function _convertValidatorToArray($fieldName, $defaults = [], $setting <ide> * Because this and `allowEmpty()` modify the same internal state, the last <ide> * method called will take precedence. <ide> * <del> * @deprecated 3.7.0 Use allowEmptyString(), allowEmptyArray(), allowEmptyFile(), <del> * allowEmptyDate(), allowEmptyTime() or allowEmptyDateTime() with reversed <del> * conditions instead. <add> * @deprecated 3.7.0 Use notEmptyString(), notEmptyArray(), notEmptyFile(), <add> * notEmptyDate(), notEmptyTime() or notEmptyDateTime() instead. <ide> * @param string|array $field the name of the field or list of fields <ide> * @param string|null $message The message to show if the field is not <ide> * @param bool|string|callable $when Indicates when the field is not allowed
1
Ruby
Ruby
add mktemp function
bb1bb5130908381e91106ae1312d4dced780a011
<ide><path>Library/Homebrew/requirement.rb <ide> def display_s <ide> name <ide> end <ide> <add> def mktemp <add> Mktemp.new(name).run do |staging| <add> yield staging <add> end <add> end <add> <ide> private <ide> <ide> def infer_name
1
Java
Java
expose js source location to js
3a0a1a41222f327beb607fd7994e1b273532dbf4
<ide><path>ReactAndroid/src/main/java/com/facebook/react/CoreModulesPackage.java <ide> public List<NativeModule> createNativeModules( <ide> new ExceptionsManagerModule(mReactInstanceManager.getDevSupportManager()), <ide> new Timing(catalystApplicationContext), <ide> new SourceCodeModule( <del> mReactInstanceManager.getDevSupportManager().getSourceUrl(), <add> mReactInstanceManager.getSourceUrl(), <ide> mReactInstanceManager.getDevSupportManager().getSourceMapUrl()), <ide> new UIManagerModule( <ide> catalystApplicationContext, <ide><path>ReactAndroid/src/main/java/com/facebook/react/ReactInstanceManager.java <ide> public class ReactInstanceManager { <ide> private @Nullable volatile ReactContext mCurrentReactContext; <ide> private final Context mApplicationContext; <ide> private @Nullable DefaultHardwareBackBtnHandler mDefaultBackButtonImpl; <add> private String mSourceUrl; <ide> <ide> private final ReactInstanceDevCommandsHandler mDevInterface = <ide> new ReactInstanceDevCommandsHandler() { <ide> public void showDevOptionsDialog() { <ide> mDevSupportManager.showDevOptionsDialog(); <ide> } <ide> <add> /** <add> * Get the URL where the last bundle was loaded from. <add> */ <add> public String getSourceUrl() { <add> return Assertions.assertNotNull(mSourceUrl); <add> } <add> <ide> /** <ide> * Attach given {@param rootView} to a catalyst instance manager and start JS application using <ide> * JS module provided by {@link ReactRootView#getJSModuleName}. If the react context is currently <ide> private ReactApplicationContext createReactContext( <ide> JavaScriptExecutor jsExecutor, <ide> JSBundleLoader jsBundleLoader) { <ide> FLog.i(ReactConstants.TAG, "Creating react context."); <add> mSourceUrl = jsBundleLoader.getSourceUrl(); <ide> NativeModuleRegistry.Builder nativeRegistryBuilder = new NativeModuleRegistry.Builder(); <ide> JavaScriptModulesConfig.Builder jsModulesBuilder = new JavaScriptModulesConfig.Builder(); <ide> <ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/JSBundleLoader.java <ide> public static JSBundleLoader createAssetLoader( <ide> public void loadScript(ReactBridge bridge) { <ide> bridge.loadScriptFromAssets(assetManager, assetFileName); <ide> } <add> <add> @Override <add> public String getSourceUrl() { <add> return "file:///android_asset/" + assetFileName; <add> } <ide> }; <ide> } <ide> <ide> public static JSBundleLoader createCachedBundleFromNetworkLoader( <ide> public void loadScript(ReactBridge bridge) { <ide> bridge.loadScriptFromNetworkCached(sourceURL, cachedFileLocation); <ide> } <add> <add> @Override <add> public String getSourceUrl() { <add> return sourceURL; <add> } <ide> }; <ide> } <ide> <ide> public static JSBundleLoader createRemoteDebuggerBundleLoader( <ide> public void loadScript(ReactBridge bridge) { <ide> bridge.loadScriptFromNetworkCached(sourceURL, null); <ide> } <add> <add> @Override <add> public String getSourceUrl() { <add> return sourceURL; <add> } <ide> }; <ide> } <ide> <ide> public abstract void loadScript(ReactBridge bridge); <add> public abstract String getSourceUrl(); <ide> }
3
Javascript
Javascript
fix length judgment in minchunksizeplugin
d8a495c357a907279a91fdfc26180dc176c8c87f
<ide><path>lib/optimize/MinChunkSizePlugin.js <ide> MinChunkSizePlugin.prototype.apply = function(compiler) { <ide> return pair[0].size(equalOptions) < minChunkSize || pair[1].size(equalOptions) < minChunkSize; <ide> }); <ide> <del> if(combinations.length === 0) return; <del> <ide> combinations.forEach(function(pair) { <ide> var a = pair[0].size(options); <ide> var b = pair[1].size(options); <ide> MinChunkSizePlugin.prototype.apply = function(compiler) { <ide> combinations = combinations.filter(function(pair) { <ide> return pair[1] !== false; <ide> }); <add> <add> if(combinations.length === 0) return; <ide> <ide> combinations.sort(function(a,b) { <ide> var diff = b[0] - a[0];
1
Text
Text
update all pypi.python.org urls to pypi.org
8c47a875ec526192550f4b5c1a7f22a3b8dd095d
<ide><path>README.md <ide> Send a description of the issue via email to [rest-framework-security@googlegrou <ide> [coverage-status-image]: https://img.shields.io/codecov/c/github/encode/django-rest-framework/master.svg <ide> [codecov]: https://codecov.io/github/encode/django-rest-framework?branch=master <ide> [pypi-version]: https://img.shields.io/pypi/v/djangorestframework.svg <del>[pypi]: https://pypi.python.org/pypi/djangorestframework <add>[pypi]: https://pypi.org/project/djangorestframework/ <ide> [twitter]: https://twitter.com/_tomchristie <ide> [group]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework <ide> [sandbox]: https://restframework.herokuapp.com/ <ide><path>docs/index.md <ide> <img src="https://secure.travis-ci.org/encode/django-rest-framework.svg?branch=master" class="status-badge"> <ide> </a> <ide> <del> <a href="https://pypi.python.org/pypi/djangorestframework"> <add> <a href="https://pypi.org/project/djangorestframework/"> <ide> <img src="https://img.shields.io/pypi/v/djangorestframework.svg" class="status-badge"> <ide> </a> <ide> </p> <ide> OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. <ide> [redhat]: https://www.redhat.com/ <ide> [heroku]: https://www.heroku.com/ <ide> [eventbrite]: https://www.eventbrite.co.uk/about/ <del>[coreapi]: https://pypi.python.org/pypi/coreapi/ <del>[markdown]: https://pypi.python.org/pypi/Markdown/ <del>[django-filter]: https://pypi.python.org/pypi/django-filter <add>[coreapi]: https://pypi.org/project/coreapi/ <add>[markdown]: https://pypi.org/project/Markdown/ <add>[django-filter]: https://pypi.org/project/django-filter/ <ide> [django-crispy-forms]: https://github.com/maraujop/django-crispy-forms <ide> [django-guardian]: https://github.com/django-guardian/django-guardian <ide> [index]: . <ide><path>docs/topics/project-management.md <ide> The following issues still need to be addressed: <ide> [bus-factor]: https://en.wikipedia.org/wiki/Bus_factor <ide> [un-triaged]: https://github.com/encode/django-rest-framework/issues?q=is%3Aopen+no%3Alabel <ide> [transifex-project]: https://www.transifex.com/projects/p/django-rest-framework/ <del>[transifex-client]: https://pypi.python.org/pypi/transifex-client <add>[transifex-client]: https://pypi.org/project/transifex-client/ <ide> [translation-memory]: http://docs.transifex.com/guides/tm#let-tm-automatically-populate-translations <ide> [github-org]: https://github.com/encode/django-rest-framework/issues/2162 <ide> [sandbox]: https://restframework.herokuapp.com/
3
PHP
PHP
remove deprecated method
e90b88bccf104aa90c307e0bcac74688365677b9
<ide><path>src/Illuminate/Database/Eloquent/Model.php <ide> public function fill(array $attributes) <ide> $totallyGuarded = $this->totallyGuarded(); <ide> <ide> foreach ($this->fillableFromArray($attributes) as $key => $value) { <del> $key = $this->removeTableFromKey($key); <del> <ide> // The developers may choose to place some attributes in the "fillable" array <ide> // which means only those attributes may be set through mass assignment to <ide> // the model, and all others will just get ignored for security reasons. <ide> public function qualifyColumn($column) <ide> return $this->getTable().'.'.$column; <ide> } <ide> <del> /** <del> * Remove the table name from a given key. <del> * <del> * @param string $key <del> * @return string <del> * <del> * @deprecated This method is deprecated and will be removed in a future Laravel version. <del> */ <del> protected function removeTableFromKey($key) <del> { <del> return $key; <del> } <del> <ide> /** <ide> * Create a new instance of the given model. <ide> *
1
Python
Python
fix typo in comment
f00bceab8d3f74d107396fcfb0a90c8ea54b2264
<ide><path>src/transformers/models/gpt2/modeling_gpt2.py <ide> def forward( <ide> attention_mask = attention_mask.to(dtype=self.dtype) # fp16 compatibility <ide> attention_mask = (1.0 - attention_mask) * -10000.0 <ide> <del> # If a 2D ou 3D attention mask is provided for the cross-attention <add> # If a 2D or 3D attention mask is provided for the cross-attention <ide> # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length] <ide> if self.config.add_cross_attention and encoder_hidden_states is not None: <ide> encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
1
Java
Java
fix checkstyle violation
09db8881bba81cdf7a41565b97f055485ff8e96b
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/view/RedirectView.java <ide> import java.util.Arrays; <ide> import java.util.Collection; <ide> import java.util.Collections; <del>import java.util.Iterator; <ide> import java.util.LinkedHashMap; <ide> import java.util.Map; <ide> import java.util.regex.Matcher;
1
Text
Text
remove unnecessary line break
238f17825762fcb17f3c8670f37614178efb49e6
<ide><path>docs/api/combineReducers.md <ide> <ide> As your app grows more complex, you’ll want to split your [reducing function](../Glossary.md#reducer) into separate functions, each managing independent parts of the [state](../Glossary.md#state). <ide> <del>The `combineReducers` helper function turns an object whose values are different reducing functions into a single <del>reducing function you can pass to [`createStore`](createStore.md). <add>The `combineReducers` helper function turns an object whose values are different reducing functions into a single reducing function you can pass to [`createStore`](createStore.md). <ide> <ide> The resulting reducer calls every child reducer, and gather their results into a single state object. The shape of the state object matches the keys of the passed `reducers`. <ide>
1
Python
Python
detect vendor versions of gnu compilers
ed569bfa689a3f58425af2c5007a6779a7f4c4a7
<ide><path>numpy/distutils/fcompiler/gnu.py <ide> class GnuFCompiler(FCompiler): <ide> <ide> def gnu_version_match(self, version_string): <ide> """Handle the different versions of GNU fortran compilers""" <del> m = re.match(r'GNU Fortran', version_string) <add> m = re.search(r'GNU Fortran', version_string) <ide> if not m: <ide> return None <del> m = re.match(r'GNU Fortran\s+95.*?([0-9-.]+)', version_string) <add> m = re.search(r'GNU Fortran\s+95.*?([0-9-.]+)', version_string) <ide> if m: <ide> return ('gfortran', m.group(1)) <del> m = re.match(r'GNU Fortran.*?\-?([0-9-.]+)', version_string) <add> m = re.search(r'GNU Fortran.*?\-?([0-9-.]+)', version_string) <ide> if m: <ide> v = m.group(1) <ide> if v.startswith('0') or v.startswith('2') or v.startswith('3'):
1
Python
Python
remove more compat code
57d628ca74513480908a63a6b66c1c8b1af896e8
<ide><path>src/flask/cli.py <ide> def convert(self, value, param, ctx): <ide> <ide> obj = import_string(value, silent=True) <ide> <del> if sys.version_info < (2, 7, 9): <del> if obj: <del> return obj <del> else: <del> if isinstance(obj, ssl.SSLContext): <del> return obj <add> if isinstance(obj, ssl.SSLContext): <add> return obj <ide> <ide> raise <ide> <ide><path>src/flask/ctx.py <ide> def __init__(self, app): <ide> def push(self): <ide> """Binds the app context to the current context.""" <ide> self._refcnt += 1 <del> if hasattr(sys, "exc_clear"): <del> sys.exc_clear() <ide> _app_ctx_stack.push(self) <ide> appcontext_pushed.send(self.app) <ide> <ide> def push(self): <ide> else: <ide> self._implicit_app_ctx_stack.append(None) <ide> <del> if hasattr(sys, "exc_clear"): <del> sys.exc_clear() <del> <ide> _request_ctx_stack.push(self) <ide> <ide> # Open the session at the moment that the request context is available. <ide> def pop(self, exc=_sentinel): <ide> Added the `exc` argument. <ide> """ <ide> app_ctx = self._implicit_app_ctx_stack.pop() <add> clear_request = False <ide> <ide> try: <del> clear_request = False <ide> if not self._implicit_app_ctx_stack: <ide> self.preserved = False <ide> self._preserved_exc = None <ide> if exc is _sentinel: <ide> exc = sys.exc_info()[1] <ide> self.app.do_teardown_request(exc) <ide> <del> # If this interpreter supports clearing the exception information <del> # we do that now. This will only go into effect on Python 2.x, <del> # on 3.x it disappears automatically at the end of the exception <del> # stack. <del> if hasattr(sys, "exc_clear"): <del> sys.exc_clear() <del> <ide> request_close = getattr(self.request, "close", None) <ide> if request_close is not None: <ide> request_close() <ide><path>src/flask/helpers.py <ide> def send_file( <ide> mtime = os.path.getmtime(filename) <ide> fsize = os.path.getsize(filename) <ide> elif isinstance(file, io.BytesIO): <del> try: <del> fsize = file.getbuffer().nbytes <del> except AttributeError: <del> # Python 2 doesn't have getbuffer <del> fsize = len(file.getvalue()) <add> fsize = file.getbuffer().nbytes <ide> elif isinstance(file, io.TextIOBase): <ide> raise ValueError("Files must be opened in binary mode or use BytesIO.") <ide> <ide> def get_root_path(import_name): <ide> if loader is None or import_name == "__main__": <ide> return os.getcwd() <ide> <del> # For .egg, zipimporter does not have get_filename until Python 2.7. <del> # Some other loaders might exhibit the same behavior. <ide> if hasattr(loader, "get_filename"): <ide> filepath = loader.get_filename(import_name) <ide> else: <ide> def _matching_loader_thinks_module_is_package(loader, mod_name): <ide> <ide> def _find_package_path(root_mod_name): <ide> """Find the path where the module's root exists in""" <del> if sys.version_info >= (3, 4): <del> import importlib.util <add> import importlib.util <ide> <del> try: <del> spec = importlib.util.find_spec(root_mod_name) <del> if spec is None: <del> raise ValueError("not found") <del> # ImportError: the machinery told us it does not exist <del> # ValueError: <del> # - the module name was invalid <del> # - the module name is __main__ <del> # - *we* raised `ValueError` due to `spec` being `None` <del> except (ImportError, ValueError): <del> pass # handled below <add> try: <add> spec = importlib.util.find_spec(root_mod_name) <add> if spec is None: <add> raise ValueError("not found") <add> # ImportError: the machinery told us it does not exist <add> # ValueError: <add> # - the module name was invalid <add> # - the module name is __main__ <add> # - *we* raised `ValueError` due to `spec` being `None` <add> except (ImportError, ValueError): <add> pass # handled below <add> else: <add> # namespace package <add> if spec.origin in {"namespace", None}: <add> return os.path.dirname(next(iter(spec.submodule_search_locations))) <add> # a package (with __init__.py) <add> elif spec.submodule_search_locations: <add> return os.path.dirname(os.path.dirname(spec.origin)) <add> # just a normal module <ide> else: <del> # namespace package <del> if spec.origin in {"namespace", None}: <del> return os.path.dirname(next(iter(spec.submodule_search_locations))) <del> # a package (with __init__.py) <del> elif spec.submodule_search_locations: <del> return os.path.dirname(os.path.dirname(spec.origin)) <del> # just a normal module <del> else: <del> return os.path.dirname(spec.origin) <add> return os.path.dirname(spec.origin) <ide> <ide> # we were unable to find the `package_path` using PEP 451 loaders <ide> loader = pkgutil.get_loader(root_mod_name) <ide> if loader is None or root_mod_name == "__main__": <ide> # import name is not found, or interactive/main module <ide> return os.getcwd() <ide> else: <del> # For .egg, zipimporter does not have get_filename until Python 2.7. <ide> if hasattr(loader, "get_filename"): <ide> filename = loader.get_filename(root_mod_name) <ide> elif hasattr(loader, "archive"): <ide><path>tests/test_basic.py <ide> def more(): <ide> assert rv.status_code == 405 <ide> assert sorted(rv.allow) == ["GET", "HEAD"] <ide> <del> # Older versions of Werkzeug.test.Client don't have an options method <del> if hasattr(client, "options"): <del> rv = client.options("/") <del> else: <del> rv = client.open("/", method="OPTIONS") <del> <add> rv = client.open("/", method="OPTIONS") <ide> assert rv.status_code == 405 <ide> <ide> rv = client.head("/") <ide> def more(): <ide> assert rv.status_code == 405 <ide> assert sorted(rv.allow) == ["GET", "HEAD", "POST"] <ide> <del> if hasattr(client, "options"): <del> rv = client.options("/more") <del> else: <del> rv = client.open("/more", method="OPTIONS") <del> <add> rv = client.open("/more", method="OPTIONS") <ide> assert rv.status_code == 405 <ide> <ide> <ide><path>tests/test_cli.py <ide> def test_run_cert_import(monkeypatch): <ide> with pytest.raises(click.BadParameter): <ide> run_command.make_context("run", ["--cert", "not_here"]) <ide> <del> # not an SSLContext <del> if sys.version_info >= (2, 7, 9): <del> with pytest.raises(click.BadParameter): <del> run_command.make_context("run", ["--cert", "flask"]) <add> with pytest.raises(click.BadParameter): <add> run_command.make_context("run", ["--cert", "flask"]) <ide> <ide> # SSLContext <del> if sys.version_info < (2, 7, 9): <del> ssl_context = object() <del> else: <del> ssl_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) <add> ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) <ide> <ide> monkeypatch.setitem(sys.modules, "ssl_context", ssl_context) <ide> ctx = run_command.make_context("run", ["--cert", "ssl_context"]) <ide><path>tests/test_helpers.py <ide> class TestJSON(object): <ide> ) <ide> def test_detect_encoding(self, value, encoding): <ide> data = json.dumps(value).encode(encoding) <del> assert json.detect_encoding(data) == encoding <ide> assert json.loads(data) == value <ide> <ide> @pytest.mark.parametrize("debug", (True, False)) <ide> def test_attachment(self, app, req_ctx): <ide> "%C3%91and%C3%BA%EF%BC%8Fping%C3%BCino.txt", <ide> ), <ide> (u"Vögel.txt", "Vogel.txt", "V%C3%B6gel.txt"), <del> # Native string not marked as Unicode on Python 2 <del> ("tést.txt", "test.txt", "t%C3%A9st.txt"), <ide> # ":/" are not safe in filename* value <ide> (u"те:/ст", '":/"', "%D1%82%D0%B5%3A%2F%D1%81%D1%82"), <ide> ), <ide><path>tests/test_regression.py <ide> :license: BSD-3-Clause <ide> """ <ide> import gc <del>import sys <add>import platform <ide> import threading <ide> <ide> import pytest <ide> def __exit__(self, exc_type, exc_value, tb): <ide> gc.enable() <ide> <ide> <add>@pytest.mark.skipif(platform.python_implementation() == "PyPy", reason="CPython only") <ide> def test_memory_consumption(): <ide> app = flask.Flask(__name__) <ide> <ide> def fire(): <ide> # Trigger caches <ide> fire() <ide> <del> # This test only works on CPython 2.7. <del> if sys.version_info >= (2, 7) and not hasattr(sys, "pypy_translation_info"): <del> with assert_no_leak(): <del> for _x in range(10): <del> fire() <add> with assert_no_leak(): <add> for _x in range(10): <add> fire() <ide> <ide> <ide> def test_safe_join_toplevel_pardir(): <ide><path>tests/test_reqctx.py <ide> def get_dynamic_cookie(): <ide> def test_bad_environ_raises_bad_request(): <ide> app = flask.Flask(__name__) <ide> <del> # We cannot use app.test_client() for the Unicode-rich Host header, <del> # because werkzeug enforces latin1 on Python 2. <del> # However it works when actually passed to the server. <del> <ide> from flask.testing import EnvironBuilder <ide> <ide> builder = EnvironBuilder(app) <ide> def test_environ_for_valid_idna_completes(): <ide> def index(): <ide> return "Hello World!" <ide> <del> # We cannot use app.test_client() for the Unicode-rich Host header, <del> # because werkzeug enforces latin1 on Python 2. <del> # However it works when actually passed to the server. <del> <ide> from flask.testing import EnvironBuilder <ide> <ide> builder = EnvironBuilder(app) <ide><path>tests/test_testing.py <ide> def get_session(): <ide> rv = client.get("/") <ide> assert rv.data == b"index" <ide> assert flask.session.get("data") == "foo" <add> <ide> rv = client.post("/", data={}, follow_redirects=True) <ide> assert rv.data == b"foo" <del> <del> # This support requires a new Werkzeug version <del> if not hasattr(client, "redirect_client"): <del> assert flask.session.get("data") == "foo" <add> assert flask.session.get("data") == "foo" <ide> <ide> rv = client.get("/getsession") <ide> assert rv.data == b"foo"
9
Ruby
Ruby
align the gemfileentry api with stable branches
46617f02c6e473b7e695330076d2039de1c9aff2
<ide><path>railties/lib/rails/generators/app_base.rb <ide> def initialize(name, version, comment, options = {}, commented_out = false) <ide> super <ide> end <ide> <del> def self.github(name, github, comment = nil) <del> new(name, nil, comment, github: github) <add> def self.github(name, github, branch = nil, comment = nil) <add> if branch <add> new(name, nil, comment, github: github, branch: branch) <add> else <add> new(name, nil, comment, github: github) <add> end <ide> end <ide> <ide> def self.version(name, version, comment = nil) <ide> def assets_gemfile_entry <ide> <ide> gems = [] <ide> if options.dev? || options.edge? <del> gems << GemfileEntry.github('sass-rails', 'rails/sass-rails', <add> gems << GemfileEntry.github('sass-rails', 'rails/sass-rails', nil, <ide> 'Use SCSS for stylesheets') <ide> else <ide> gems << GemfileEntry.version('sass-rails', '~> 4.0', <ide> def sdoc_gemfile_entry <ide> def console_gemfile_entry <ide> comment = 'Use Rails Console on the Browser' <ide> if options.dev? || options.edge? <del> GemfileEntry.github 'web-console', 'rails/web-console', comment <add> GemfileEntry.github 'web-console', 'rails/web-console', nil, comment <ide> else <ide> [] <ide> end <ide> def console_gemfile_entry <ide> def coffee_gemfile_entry <ide> comment = 'Use CoffeeScript for .coffee assets and views' <ide> if options.dev? || options.edge? <del> GemfileEntry.github 'coffee-rails', 'rails/coffee-rails', comment <add> GemfileEntry.github 'coffee-rails', 'rails/coffee-rails', nil, comment <ide> else <ide> GemfileEntry.version 'coffee-rails', '~> 4.1.0', comment <ide> end
1
Javascript
Javascript
update linkrendernode signature
93d42e327425a9ae776fe200469b3048d47ef63d
<ide><path>packages/ember-htmlbars/lib/hooks/link-render-node.js <ide> import subscribe from "ember-htmlbars/utils/subscribe"; <ide> import shouldDisplay from "ember-views/streams/should_display"; <ide> import { chain, read } from "ember-metal/streams/utils"; <ide> <del>export default function linkRenderNode(renderNode, scope, path, params, hash) { <add>export default function linkRenderNode(renderNode, env, scope, path, params, hash) { <ide> if (renderNode.state.unsubscribers) { <ide> return true; <ide> }
1
Python
Python
update the beta dependencies
d5ce303a3b675886827344e2b85d4a94c7e61242
<ide><path>official/projects/basnet/modeling/basnet_model.py <ide> <ide> from official.modeling import tf_utils <ide> from official.projects.basnet.modeling import nn_blocks <del>from official.vision.beta.modeling.backbones import factory <add>from official.vision.modeling.backbones import factory <ide> <ide> # Specifications for BASNet encoder. <ide> # Each element in the block configuration is in the following format: <ide><path>official/projects/edgetpu/vision/tasks/semantic_segmentation_test.py <ide> import orbit <ide> import tensorflow as tf <ide> <add>from official import vision <ide> from official.core import exp_factory <ide> from official.modeling import optimization <ide> from official.projects.edgetpu.vision.configs import semantic_segmentation_config as seg_cfg <ide> from official.projects.edgetpu.vision.configs import semantic_segmentation_searched_config as autoseg_cfg <ide> from official.projects.edgetpu.vision.tasks import semantic_segmentation as img_seg_task <del>from official.vision import beta <ide> <ide> <ide> # Dummy ADE20K TF dataset. <ide><path>official/projects/teams/teams_experiments_test.py <ide> from absl.testing import parameterized <ide> import tensorflow as tf <ide> <del># pylint: disable=unused-import <del>from official.common import registry_imports <del># pylint: enable=unused-import <add>from official.common import registry_imports # pylint: disable=unused-import <ide> from official.core import config_definitions as cfg <ide> from official.core import exp_factory <ide>
3
PHP
PHP
add support for sha256 hashing on token guard
e2e16744bea55dab43a4b2093f6de67720e6a28d
<ide><path>src/Illuminate/Auth/TokenGuard.php <ide> class TokenGuard implements Guard <ide> */ <ide> protected $storageKey; <ide> <add> /** <add> * Indicates if the API token is hashed in storage. <add> * <add> * @var bool <add> */ <add> protected $hash = false; <add> <ide> /** <ide> * Create a new authentication guard. <ide> * <ide> * @param \Illuminate\Contracts\Auth\UserProvider $provider <ide> * @param \Illuminate\Http\Request $request <ide> * @param string $inputKey <ide> * @param string $storageKey <add> * @param bool $hash <ide> * @return void <ide> */ <del> public function __construct(UserProvider $provider, Request $request, $inputKey = 'api_token', $storageKey = 'api_token') <add> public function __construct( <add> UserProvider $provider, <add> Request $request, <add> $inputKey = 'api_token', <add> $storageKey = 'api_token', <add> $hash = false) <ide> { <add> $this->hash = $hash; <ide> $this->request = $request; <ide> $this->provider = $provider; <ide> $this->inputKey = $inputKey; <ide> public function user() <ide> <ide> if (! empty($token)) { <ide> $user = $this->provider->retrieveByCredentials([ <del> $this->storageKey => $token, <add> $this->storageKey => $this->hash ? hash('sha256', $token) : $token, <ide> ]); <ide> } <ide> <ide><path>tests/Auth/AuthTokenGuardTest.php <ide> public function testUserCanBeRetrievedByQueryStringVariable() <ide> $this->assertEquals(1, $guard->id()); <ide> } <ide> <add> <add> public function testTokenCanBeHashed() <add> { <add> $provider = m::mock(UserProvider::class); <add> $user = new AuthTokenGuardTestUser; <add> $user->id = 1; <add> $provider->shouldReceive('retrieveByCredentials')->once()->with(['api_token' => hash('sha256', 'foo')])->andReturn($user); <add> $request = Request::create('/', 'GET', ['api_token' => 'foo']); <add> <add> $guard = new TokenGuard($provider, $request, 'api_token', 'api_token', $hash = true); <add> <add> $user = $guard->user(); <add> <add> $this->assertEquals(1, $user->id); <add> $this->assertTrue($guard->check()); <add> $this->assertFalse($guard->guest()); <add> $this->assertEquals(1, $guard->id()); <add> } <add> <ide> public function testUserCanBeRetrievedByAuthHeaders() <ide> { <ide> $provider = m::mock(UserProvider::class);
2
Javascript
Javascript
use main entry points only inside ember-views
e9d69fb6fa8cce70d099db09e1a36cf155d693a5
<ide><path>packages/ember-metal/lib/index.js <ide> export { <ide> didRender, <ide> assertNotRendered <ide> } from './transaction'; <add>export { default as descriptor } from './descriptor'; <ide> <ide> <ide> // TODO: this needs to be deleted once we refactor the build tooling <ide><path>packages/ember-views/lib/compat/attrs-proxy.js <del>import { Mixin } from 'ember-metal/mixin'; <del>import symbol from 'ember-metal/symbol'; <del>import { PROPERTY_DID_CHANGE } from 'ember-metal/property_events'; <add>import { <add> Mixin, <add> symbol, <add> PROPERTY_DID_CHANGE <add>} from 'ember-metal'; <ide> <ide> export function deprecation(key) { <ide> return `You tried to look up an attribute directly on the component. This is deprecated. Use attrs.${key} instead.`; <ide><path>packages/ember-views/lib/compat/fallback-view-registry.js <del>import dict from 'ember-metal/dictionary'; <add>import { dictionary } from 'ember-metal'; <ide> <del>export default dict(null); <add>export default dictionary(null); <ide><path>packages/ember-views/lib/component_lookup.js <del>import { assert } from 'ember-metal/debug'; <del>import EmberObject from 'ember-runtime/system/object'; <add>import { assert } from 'ember-metal'; <add>import { Object as EmberObject } from 'ember-runtime'; <ide> <ide> export default EmberObject.extend({ <ide> componentFor(name, owner, options) { <ide><path>packages/ember-views/lib/mixins/action_support.js <ide> @module ember <ide> @submodule ember-views <ide> */ <del>import { Mixin } from 'ember-metal/mixin'; <del>import { get } from 'ember-metal/property_get'; <del>import isNone from 'ember-metal/is_none'; <del>import { assert } from 'ember-metal/debug'; <add>import { <add> Mixin, <add> get, <add> isNone, <add> assert, <add> inspect <add>} from 'ember-metal'; <ide> import { MUTABLE_CELL } from '../compat/attrs-proxy'; <del>import { inspect } from 'ember-metal/utils'; <ide> <ide> function validateAction(component, actionName) { <ide> if (actionName && actionName[MUTABLE_CELL]) { <ide><path>packages/ember-views/lib/mixins/child_views_support.js <ide> @module ember <ide> @submodule ember-views <ide> */ <del>import { Mixin } from 'ember-metal/mixin'; <add>import { <add> Mixin, <add> descriptor <add>} from 'ember-metal'; <ide> import { getOwner, setOwner } from 'container'; <del>import descriptor from 'ember-metal/descriptor'; <ide> import { initChildViews, getChildViews, addChildView } from '../system/utils'; <ide> <ide> export default Mixin.create({ <ide><path>packages/ember-views/lib/mixins/class_names_support.js <ide> @module ember <ide> @submodule ember-views <ide> */ <del>import { assert } from 'ember-metal/debug'; <del>import { Mixin } from 'ember-metal/mixin'; <add> <add>import { <add> assert, <add> Mixin <add>} from 'ember-metal'; <ide> <ide> const EMPTY_ARRAY = Object.freeze([]); <ide> <ide><path>packages/ember-views/lib/mixins/instrumentation_support.js <ide> @module ember <ide> @submodule ember-views <ide> */ <del>import { Mixin } from 'ember-metal/mixin'; <del>import { get } from 'ember-metal/property_get'; <add>import { <add> Mixin, <add> get <add>} from 'ember-metal'; <ide> <ide> /** <ide> @class InstrumentationSupport <ide><path>packages/ember-views/lib/mixins/template_support.js <del>import EmberError from 'ember-metal/error'; <del>import { computed } from 'ember-metal/computed'; <add>import { <add> Error as EmberError, <add> computed, <add> Mixin, <add> get, <add> assert <add>} from 'ember-metal'; <ide> import { getOwner } from 'container'; <del>import { Mixin } from 'ember-metal/mixin'; <del>import { get } from 'ember-metal/property_get'; <del>import { assert } from 'ember-metal/debug'; <ide> <ide> export default Mixin.create({ <ide> /** <ide><path>packages/ember-views/lib/mixins/text_support.js <ide> @submodule ember-views <ide> */ <ide> <del>import { get } from 'ember-metal/property_get'; <del>import { set } from 'ember-metal/property_set'; <del>import { Mixin } from 'ember-metal/mixin'; <del>import TargetActionSupport from 'ember-runtime/mixins/target_action_support'; <add>import { <add> get, <add> set, <add> Mixin <add>} from 'ember-metal'; <add>import { TargetActionSupport } from 'ember-runtime'; <ide> <ide> const KEY_EVENTS = { <ide> 13: 'insertNewline', <ide><path>packages/ember-views/lib/mixins/view_state_support.js <ide> @module ember <ide> @submodule ember-views <ide> */ <del>import { Mixin } from 'ember-metal/mixin'; <add>import { Mixin } from 'ember-metal'; <ide> <ide> export default Mixin.create({ <ide> _transitionTo(state) { <ide><path>packages/ember-views/lib/mixins/view_support.js <del>import { assert, deprecate } from 'ember-metal/debug'; <del>import run from 'ember-metal/run_loop'; <del>import { guidFor } from 'ember-metal/utils'; <del>import { Mixin } from 'ember-metal/mixin'; <del>import { POST_INIT } from 'ember-runtime/system/core_object'; <del>import symbol from 'ember-metal/symbol'; <add>import { <add> assert, <add> deprecate, <add> run, <add> guidFor, <add> Mixin, <add> symbol <add>} from 'ember-metal'; <add>import { POST_INIT } from 'ember-runtime'; <ide> import { environment } from 'ember-environment'; <ide> import { matches } from '../system/utils'; <ide> <ide><path>packages/ember-views/lib/mixins/visibility_support.js <ide> */ <ide> import { <ide> Mixin, <del> observer <del>} from 'ember-metal/mixin'; <del>import { get } from 'ember-metal/property_get'; <del>import run from 'ember-metal/run_loop'; <add> observer, <add> get, <add> run <add>} from 'ember-metal'; <ide> <ide> function K() { return this; } <ide> <ide><path>packages/ember-views/lib/system/event_dispatcher.js <ide> @submodule ember-views <ide> */ <ide> <del>import { assert } from 'ember-metal/debug'; <del>import { get } from 'ember-metal/property_get'; <del>import { set } from 'ember-metal/property_set'; <del>import isNone from 'ember-metal/is_none'; <del>import run from 'ember-metal/run_loop'; <del>import EmberObject from 'ember-runtime/system/object'; <add>import { <add> assert, <add> get, <add> set, <add> isNone, <add> run, <add> assign <add>} from 'ember-metal'; <add>import { Object as EmberObject } from 'ember-runtime'; <ide> import jQuery from './jquery'; <ide> import ActionManager from './action_manager'; <del>import assign from 'ember-metal/assign'; <ide> import { getOwner } from 'container'; <ide> import { environment } from 'ember-environment'; <ide> import fallbackViewRegistry from '../compat/fallback-view-registry'; <ide><path>packages/ember-views/lib/system/ext.js <ide> @submodule ember-views <ide> */ <ide> <del>import run from 'ember-metal/run_loop'; <add>import { run } from 'ember-metal'; <ide> <ide> // Add a new named queue for rendering views that happens <ide> // after bindings have synced, and a queue for scheduling actions <ide><path>packages/ember-views/lib/system/lookup_partial.js <del>import { assert } from 'ember-metal/debug'; <del>import EmberError from 'ember-metal/error'; <add>import { <add> assert, <add> Error as EmberError <add>} from 'ember-metal'; <ide> <ide> function parseUnderscoredName(templateName) { <ide> let nameParts = templateName.split('/'); <ide><path>packages/ember-views/lib/system/utils.js <ide> /* globals Element */ <ide> <del>import { guidFor } from 'ember-metal/utils'; <add>import { guidFor, symbol } from 'ember-metal'; <ide> import { getOwner } from 'container'; <del>import symbol from 'ember-metal/symbol'; <ide> <ide> /** <ide> @module ember <ide><path>packages/ember-views/lib/views/core_view.js <del>import { get } from 'ember-metal/property_get'; <del> <del>import EmberObject from 'ember-runtime/system/object'; <del>import Evented from 'ember-runtime/mixins/evented'; <del>import ActionHandler, { deprecateUnderscoreActions } from 'ember-runtime/mixins/action_handler'; <del>import { typeOf } from 'ember-runtime/utils'; <add>import { get } from 'ember-metal'; <add> <add>import { <add> Object as EmberObject, <add> Evented, <add> ActionHandler, <add> deprecateUnderscoreActions, <add> typeOf <add>} from 'ember-runtime'; <ide> import { cloneStates, states } from './states'; <ide> <ide> /** <ide><path>packages/ember-views/lib/views/states.js <del>import assign from 'ember-metal/assign'; <add>import { assign } from 'ember-metal'; <ide> import _default from './states/default'; <ide> import preRender from './states/pre_render'; <ide> import hasElement from './states/has_element'; <ide><path>packages/ember-views/lib/views/states/default.js <del>import EmberError from 'ember-metal/error'; <del>import { get } from 'ember-metal/property_get'; <add>import { <add> Error as EmberError, <add> get <add>} from 'ember-metal'; <ide> import { MUTABLE_CELL } from '../../compat/attrs-proxy'; <ide> <ide> /** <ide><path>packages/ember-views/lib/views/states/destroying.js <del>import assign from 'ember-metal/assign'; <add>import { assign, Error as EmberError } from 'ember-metal'; <ide> import _default from './default'; <del>import EmberError from 'ember-metal/error'; <ide> /** <ide> @module ember <ide> @submodule ember-views <ide><path>packages/ember-views/lib/views/states/has_element.js <ide> import _default from './default'; <del>import assign from 'ember-metal/assign'; <add>import { <add> assign, <add> run, <add> flaggedInstrument, <add> get <add>} from 'ember-metal'; <ide> import jQuery from '../../system/jquery'; <del>import run from 'ember-metal/run_loop'; <del>import { flaggedInstrument } from 'ember-metal/instrumentation'; <del> <del>/** <del>@module ember <del>@submodule ember-views <del>*/ <del> <del>import { get } from 'ember-metal/property_get'; <ide> <ide> const hasElement = Object.create(_default); <ide> <ide><path>packages/ember-views/lib/views/states/in_dom.js <del>import { runInDebug } from 'ember-metal/debug'; <del>import assign from 'ember-metal/assign'; <del>import EmberError from 'ember-metal/error'; <del>import { _addBeforeObserver } from 'ember-metal/observer'; <add>import { <add> runInDebug, <add> assign, <add> Error as EmberError, <add> _addBeforeObserver <add>} from 'ember-metal'; <ide> <ide> import hasElement from './has_element'; <ide> /** <ide><path>packages/ember-views/lib/views/states/pre_render.js <ide> import _default from './default'; <del>import assign from 'ember-metal/assign'; <add>import { assign } from 'ember-metal'; <ide> <ide> /** <ide> @module ember
24