content_type
stringclasses
8 values
main_lang
stringclasses
7 values
message
stringlengths
1
50
sha
stringlengths
40
40
patch
stringlengths
52
962k
file_count
int64
1
300
Javascript
Javascript
add some tests for dynamic rendering
753113bb9cbd10b9dc49770744e8d85d41788cbb
<ide><path>test/integration/basic/components/hello1.js <add>export default () => ( <add> <p>Hello World 1</p> <add>) <ide><path>test/integration/basic/pages/dynamic/no-ssr-custom-loading.js <add>import dynamic from 'next/dynamic' <add> <add>const Hello = dynamic(import('../../components/hello1'), { <add> ssr: false, <add> loading: () => (<p>LOADING</p>) <add>}) <add> <add>export default Hello <ide><path>test/integration/basic/pages/dynamic/no-ssr.js <add>import dynamic from 'next/dynamic' <add> <add>const Hello = dynamic(import('../../components/hello1'), { ssr: false }) <add> <add>export default Hello <ide><path>test/integration/basic/pages/dynamic/ssr.js <add>import dynamic from 'next/dynamic' <add> <add>const Hello = dynamic(import('../../components/hello1')) <add> <add>export default Hello <ide><path>test/integration/basic/test/rendering.js <ide> export default function ({ app }, suiteName, render) { <ide> expect($('h1').text()).toBe('404') <ide> expect($('h2').text()).toBe('This page could not be found.') <ide> }) <add> <add> test('render dynmaic import components via SSR', async () => { <add> const $ = await get$('/dynamic/ssr') <add> expect($('p').text()).toBe('Hello World 1') <add> }) <add> <add> test('stop render dynmaic import components in SSR', async () => { <add> const $ = await get$('/dynamic/no-ssr') <add> expect($('p').text()).toBe('loading...') <add> }) <add> <add> test('stop render dynmaic import components in SSR with custom loading', async () => { <add> const $ = await get$('/dynamic/no-ssr-custom-loading') <add> expect($('p').text()).toBe('LOADING') <add> }) <ide> }) <ide> }
5
Ruby
Ruby
add another file check to check_for_macgpg2
e750242b73d3dba199fd7491972854ca6b48ea38
<ide><path>Library/Homebrew/brew_doctor.rb <ide> def is_prefix? prefix, longer_string <ide> # Installing MacGPG2 interferes with Homebrew in a big way <ide> # http://sourceforge.net/projects/macgpg2/files/ <ide> def check_for_macgpg2 <del> if File.exist? "/Applications/start-gpg-agent.app" <add> if File.exist? "/Applications/start-gpg-agent.app" or <add> File.exist? "/Library/Receipts/libiconv1.pkg" <ide> puts <<-EOS.undent <ide> If you have installed MacGPG2 via the package installer, several other <ide> checks in this script will turn up problems, such as stray .dylibs in
1
Mixed
Ruby
add inline failure reporting to test runner
64a3b09b408400c94fd25f22c2ce791a8d90b5cb
<ide><path>railties/CHANGELOG.md <add>* Add inline output to `bin/rails test` <add> <add> Any failures or errors (and skips if running in verbose mode) are output <add> during a test run: <add> <add> ``` <add> # Running: <add> <add> .....S..........................................F <add> <add> This failed <add> <add> bin/rails test test/models/bunny_test.rb:14 <add> <add> .................................E <add> <add> ArgumentError: Wups! Bet you didn't expect this! <add> test/models/bunny_test.rb:19:in `block in <class:BunnyTest>' <add> <add> bin/rails test test/models/bunny_test.rb:18 <add> <add> .................... <add> <add> Finished in 0.069708s, 1477.6019 runs/s, 1448.9106 assertions/s. <add> ``` <add> <add> Output can be deferred to after a run with the `--defer-output` option. <add> <add> *Kasper Timm Hansen* <add> <ide> * Fix displaying mailer previews on non local requests when config <ide> `action_mailer.show_previews` is set <ide> <ide><path>railties/lib/rails/test_unit/minitest_plugin.rb <ide> def self.plugin_rails_options(opts, options) <ide> opts.separator "" <ide> opts.separator " bin/rails test test/controllers test/integration/login_test.rb" <ide> opts.separator "" <add> opts.separator "By default test failures and errors are reported inline during a run." <add> opts.separator "" <ide> <ide> opts.separator "Rails options:" <ide> opts.on("-e", "--environment ENV", <ide> def self.plugin_rails_options(opts, options) <ide> options[:full_backtrace] = true <ide> end <ide> <add> opts.on("-d", "--defer-output", <add> "Output test failures and errors after the test run") do <add> options[:output_inline] = false <add> end <add> <ide> options[:patterns] = opts.order! <ide> end <ide> <ide><path>railties/lib/rails/test_unit/reporter.rb <ide> class TestUnitReporter < Minitest::StatisticsReporter <ide> class_attribute :executable <ide> self.executable = "bin/rails test" <ide> <add> def record(result) <add> super <add> <add> if output_inline? && result.failure && (!result.skipped? || options[:verbose]) <add> io.puts <add> io.puts <add> io.puts result.failures.map(&:message) <add> io.puts <add> io.puts format_rerun_snippet(result) <add> io.puts <add> end <add> end <add> <ide> def report <del> return if filtered_results.empty? <add> return if output_inline? || filtered_results.empty? <ide> io.puts <ide> io.puts "Failed tests:" <ide> io.puts <ide> io.puts aggregated_results <ide> end <ide> <ide> def aggregated_results # :nodoc: <del> filtered_results.map do |result| <del> location, line = result.method(result.name).source_location <del> "#{self.executable} #{relative_path_for(location)}:#{line}" <del> end.join "\n" <add> filtered_results.map { |result| format_rerun_snippet(result) }.join "\n" <ide> end <ide> <ide> def filtered_results <ide> def filtered_results <ide> def relative_path_for(file) <ide> file.sub(/^#{Rails.root}\/?/, '') <ide> end <add> <add> private <add> def output_inline? <add> options.fetch(:output_inline, true) <add> end <add> <add> def format_rerun_snippet(result) <add> location, line = result.method(result.name).source_location <add> "#{self.executable} #{relative_path_for(location)}:#{line}" <add> end <ide> end <ide> end <ide><path>railties/test/application/test_runner_test.rb <ide> def test_run_app_without_rails_loaded <ide> assert_match '0 runs, 0 assertions', run_test_command('') <ide> end <ide> <add> def test_output_inline_by_default <add> app_file 'test/models/post_test.rb', <<-RUBY <add> require 'test_helper' <add> <add> class PostTest < ActiveSupport::TestCase <add> def test_post <add> assert false, 'wups!' <add> end <add> end <add> RUBY <add> <add> output = run_test_command('test/models/post_test.rb') <add> assert_match %r{Running:\n\nF\n\nwups!\n\nbin/rails test test/models/post_test.rb:4}, output <add> end <add> <ide> def test_raise_error_when_specified_file_does_not_exist <ide> error = capture(:stderr) { run_test_command('test/not_exists.rb') } <ide> assert_match(%r{cannot load such file.+test/not_exists\.rb}, error) <ide><path>railties/test/test_unit/reporter_test.rb <ide> def woot; end <ide> end <ide> end <ide> <add> test "outputs failures inline" do <add> @reporter.record(failed_test) <add> @reporter.report <add> <add> assert_match %r{\A\n\nboo\n\nbin/rails test .*test/test_unit/reporter_test.rb:6\n\n\z}, @output.string <add> end <add> <add> test "outputs errors inline" do <add> @reporter.record(errored_test) <add> @reporter.report <add> <add> assert_match %r{\A\n\nArgumentError: wups\n No backtrace\n\nbin/rails test .*test/test_unit/reporter_test.rb:6\n\n\z}, @output.string <add> end <add> <add> test "outputs skipped tests inline if verbose" do <add> verbose = Rails::TestUnitReporter.new @output, verbose: true <add> verbose.record(skipped_test) <add> verbose.report <add> <add> assert_match %r{\A\n\nskipchurches, misstemples\n\nbin/rails test .*test/test_unit/reporter_test.rb:6\n\n\z}, @output.string <add> end <add> <add> test "does not output rerun snippets after run" do <add> @reporter.record(failed_test) <add> @reporter.report <add> <add> assert_no_match 'Failed tests:', @output.string <add> end <add> <ide> private <ide> def assert_rerun_snippet_count(snippet_count) <ide> assert_equal snippet_count, @output.string.scan(%r{^bin/rails test }).size <ide> def failed_test <ide> ft <ide> end <ide> <add> def errored_test <add> et = ExampleTest.new(:woot) <add> et.failures << Minitest::UnexpectedError.new(ArgumentError.new("wups")) <add> et <add> end <add> <ide> def passing_test <ide> ExampleTest.new(:woot) <ide> end <ide> <ide> def skipped_test <ide> st = ExampleTest.new(:woot) <ide> st.failures << begin <del> raise Minitest::Skip <add> raise Minitest::Skip, "skipchurches, misstemples" <ide> rescue Minitest::Assertion => e <ide> e <ide> end
5
Text
Text
add teletype highlights from the past week
4fbad81a7cd2f2e3925d7e920086bc1ebf2fe210
<ide><path>docs/focus/2018-04-23.md <ide> - Code cleanup: replace ObserveModelDecorator with ObserveModel render-prop [atom/github#1393](https://github.com/atom/github/pull/1393) <ide> - Document our [long-term visions](https://github.com/atom/github/tree/master/docs/vision) for the GitHub package. <ide> - Teletype <add> - Shipped [Teletype 0.13.0](https://github.com/atom/teletype/releases/tag/v0.13.0) with improved ability to tell which cursor belongs to which collaborator ([atom/teletype#338](https://github.com/atom/teletype/issues/338)) <add> - Published RFC-004 with proposed approach for more quickly collaborating with coworkers and friends ([atom/teletype#344](https://github.com/atom/teletype/pull/344)) <ide> - Xray <ide> - Shared workspaces merged <ide> - [Detailed update](https://github.com/atom/xray/blob/master/docs/updates/2018_04_23.md) <ide> - GitHub Package <ide> - :notebook: Planning, roadmapping, prioritizing, scheming <ide> - Teletype <add> - :bug: Improve handling of scenario where guest puts their computer to sleep while participating in a portal ([atom/teletype#354](https://github.com/atom/teletype/issues/354)) <ide> - Tree-sitter <ide> - Xray <ide><path>docs/focus/README.md <ide> Near-term goal: Encourage more collaboration by reducing barriers to entry. <ide> <ide> Longer-term goal: Provide the world's fastest transition from "I want to collaborate" to "I am collaborating." 🚀 <ide> <del>- [ ] Publish RFC (including a request for review from GitHub's Community and Safety team) <add>- [x] Publish RFC (including a request for review from GitHub's Community and Safety team) ([RFC-003](https://github.com/atom/teletype/blob/v0.13.0/doc/rfcs/003-share-and-join-a-portal-via-url.md), [RFC-004](https://github.com/atom/teletype/blob/v0.13.0/doc/rfcs/004-quickly-collaborate-with-coworkers-and-friends.md)) <ide> - [x] Host can share a URL for the portal, and guests can follow the URL to instantly join the portal (https://github.com/atom/teletype/issues/109) <ide> - [ ] Quickly collaborate with coworkers and friends (https://github.com/atom/teletype/issues/213, https://github.com/atom/teletype/issues/284) <ide> - You can view a list of past collaborators (i.e., a ["buddy list"](https://github.com/atom/teletype/issues/22) of sorts). <ide> - You can choose any online person in the buddy list and invite them to join your portal. They get a notification (or similar) informing them of the invitation, and they can choose to join the portal or not. <ide> - To prevent abuse/harassment, each time you join a portal via a URL or portal ID, Teletype adds the collaborators to your buddy list. You can directly invite anyone in your buddy list to join your portal, and anyone in your buddy list can invite you to a portal. You can remove anyone from your buddy list, at which point they can no longer _directly_ invite you to a portal. <ide> <del>##### 3. Nice bang-for-the-buck refinements <add>##### 3. ✅ Nice bang-for-the-buck refinements <ide> <del>- [ ] Add a colored border around avatars that matches the cursor when that participant's tether is not retracted (https://github.com/atom/teletype/issues/338) <add>- [x] Add a colored border around avatars that matches the cursor when that participant's tether is not retracted (https://github.com/atom/teletype/issues/338) <ide> <del>##### 4. Prioritized bugs <add>##### 4. ✅ Prioritized bugs <ide> <ide> - [x] Uncaught TypeError: Cannot match against 'undefined' or 'null' (https://github.com/atom/teletype/issues/233) <ide>
2
PHP
PHP
resolve default driver in shoulduse
997c74052c860a5e41e833a4079d4aeb5c48046d
<ide><path>src/Illuminate/Auth/AuthManager.php <ide> public function getDefaultDriver() <ide> */ <ide> public function shouldUse($name) <ide> { <add> $name = $name ?: $this->getDefaultDriver(); <add> <ide> $this->setDefaultDriver($name); <ide> <ide> $this->userResolver = function ($name = null) {
1
Java
Java
remove unnecessary null check in sysenvpropsource
009d2a5efd456a37c29fd984be3087f09082c325
<ide><path>spring-core/src/main/java/org/springframework/core/env/SystemEnvironmentPropertySource.java <ide> public boolean containsProperty(String name) { <ide> public Object getProperty(String name) { <ide> Assert.notNull(name, "property name must not be null"); <ide> String actualName = resolvePropertyName(name); <del> if (actualName == null) { <del> // at this point we know the property does not exist <del> return null; <del> } <ide> if (logger.isDebugEnabled() && !name.equals(actualName)) { <ide> logger.debug(String.format( <ide> "PropertySource [%s] does not contain '%s', but found equivalent '%s'",
1
Go
Go
add testcase of expose 5678/udp
0552f1a0caf8f8e57736d05c2ed42f82e97df5f6
<ide><path>integration-cli/docker_cli_build_test.go <ide> func TestBuildExposeOrder(t *testing.T) { <ide> logDone("build - expose order") <ide> } <ide> <add>func TestBuildExposeUpperCaseProto(t *testing.T) { <add> name := "testbuildexposeuppercaseproto" <add> expected := "map[5678/udp:map[]]" <add> defer deleteImages(name) <add> _, err := buildImage(name, <add> `FROM scratch <add> EXPOSE 5678/UDP`, <add> true) <add> if err != nil { <add> t.Fatal(err) <add> } <add> res, err := inspectField(name, "Config.ExposedPorts") <add> if err != nil { <add> t.Fatal(err) <add> } <add> if res != expected { <add> t.Fatalf("Exposed ports %s, expected %s", res, expected) <add> } <add> logDone("build - expose port with upper case proto") <add>} <add> <ide> func TestBuildEmptyEntrypointInheritance(t *testing.T) { <ide> name := "testbuildentrypointinheritance" <ide> name2 := "testbuildentrypointinheritance2"
1
Text
Text
unify more headings
6e869be104374a2970a60de8bfccce9f6197af31
<ide><path>doc/api/async_hooks.md <ide> function destroy(asyncId) { } <ide> function promiseResolve(asyncId) { } <ide> ``` <ide> <del>#### `async_hooks.createHook(callbacks)` <add>#### async_hooks.createHook(callbacks) <ide> <ide> <!-- YAML <ide> added: v8.1.0 <ide> provided by AsyncHooks itself. The logging should then be skipped when <ide> it was the logging itself that caused AsyncHooks callback to call. By <ide> doing this the otherwise infinite recursion is broken. <ide> <del>#### `asyncHook.enable()` <add>#### asyncHook.enable() <ide> <ide> * Returns: {AsyncHook} A reference to `asyncHook`. <ide> <ide> const async_hooks = require('async_hooks'); <ide> const hook = async_hooks.createHook(callbacks).enable(); <ide> ``` <ide> <del>#### `asyncHook.disable()` <add>#### asyncHook.disable() <ide> <ide> * Returns: {AsyncHook} A reference to `asyncHook`. <ide> <ide> Key events in the lifetime of asynchronous events have been categorized into <ide> four areas: instantiation, before/after the callback is called, and when the <ide> instance is destroyed. <ide> <del>##### `init(asyncId, type, triggerAsyncId, resource)` <add>##### init(asyncId, type, triggerAsyncId, resource) <ide> <ide> * `asyncId` {number} A unique ID for the async resource. <ide> * `type` {string} The type of the async resource. <ide> It is possible to have type name collisions. Embedders are encouraged to use <ide> unique prefixes, such as the npm package name, to prevent collisions when <ide> listening to the hooks. <ide> <del>###### `triggerId` <add>###### `triggerAsyncId` <ide> <ide> `triggerAsyncId` is the `asyncId` of the resource that caused (or "triggered") <ide> the new resource to initialize and that caused `init` to call. This is different <ide> The graph only shows *when* a resource was created, not *why*, so to track <ide> the *why* use `triggerAsyncId`. <ide> <ide> <del>##### `before(asyncId)` <add>##### before(asyncId) <ide> <ide> * `asyncId` {number} <ide> <ide> callback multiple times, while other operations like `fs.open()` will call <ide> it only once. <ide> <ide> <del>##### `after(asyncId)` <add>##### after(asyncId) <ide> <ide> * `asyncId` {number} <ide> <ide> will run *after* the `'uncaughtException'` event is emitted or a `domain`'s <ide> handler runs. <ide> <ide> <del>##### `destroy(asyncId)` <add>##### destroy(asyncId) <ide> <ide> * `asyncId` {number} <ide> <ide> made to the `resource` object passed to `init` it is possible that `destroy` <ide> will never be called, causing a memory leak in the application. If the resource <ide> does not depend on garbage collection, then this will not be an issue. <ide> <del>##### `promiseResolve(asyncId)` <add>##### promiseResolve(asyncId) <ide> <ide> * `asyncId` {number} <ide> <ide> init for PROMISE with id 6, trigger id: 5 # the Promise returned by then() <ide> after 6 <ide> ``` <ide> <del>#### `async_hooks.executionAsyncId()` <add>#### async_hooks.executionAsyncId() <ide> <ide> <!-- YAML <ide> added: v8.1.0 <ide> const server = net.createServer(function onConnection(conn) { <ide> Note that promise contexts may not get precise executionAsyncIds by default. <ide> See the section on [promise execution tracking][]. <ide> <del>#### `async_hooks.triggerAsyncId()` <add>#### async_hooks.triggerAsyncId() <ide> <ide> * Returns: {number} The ID of the resource responsible for calling the callback <ide> that is currently being executed. <ide> Library developers that handle their own asynchronous resources performing tasks <ide> like I/O, connection pooling, or managing callback queues may use the <ide> `AsyncWrap` JavaScript API so that all the appropriate callbacks are called. <ide> <del>### `class AsyncResource()` <add>### Class: AsyncResource <ide> <ide> The class `AsyncResource` is designed to be extended by the embedder's async <ide> resources. Using this, users can easily trigger the lifetime events of their <ide> asyncResource.emitBefore(); <ide> asyncResource.emitAfter(); <ide> ``` <ide> <del>#### `AsyncResource(type[, options])` <add>#### new AsyncResource(type[, options]) <ide> <ide> * `type` {string} The type of async event. <ide> * `options` {Object} <ide> class DBQuery extends AsyncResource { <ide> } <ide> ``` <ide> <del>#### `asyncResource.runInAsyncScope(fn[, thisArg, ...args])` <add>#### asyncResource.runInAsyncScope(fn[, thisArg, ...args]) <ide> <!-- YAML <ide> added: v9.6.0 <ide> --> <ide> of the async resource. This will establish the context, trigger the AsyncHooks <ide> before callbacks, call the function, trigger the AsyncHooks after callbacks, and <ide> then restore the original execution context. <ide> <del>#### `asyncResource.emitBefore()` <add>#### asyncResource.emitBefore() <ide> <!-- YAML <ide> deprecated: v9.6.0 <ide> --> <ide> will abort. For this reason, the `emitBefore` and `emitAfter` APIs are <ide> considered deprecated. Please use `runInAsyncScope`, as it provides a much safer <ide> alternative. <ide> <del>#### `asyncResource.emitAfter()` <add>#### asyncResource.emitAfter() <ide> <!-- YAML <ide> deprecated: v9.6.0 <ide> --> <ide> will abort. For this reason, the `emitBefore` and `emitAfter` APIs are <ide> considered deprecated. Please use `runInAsyncScope`, as it provides a much safer <ide> alternative. <ide> <del>#### `asyncResource.emitDestroy()` <add>#### asyncResource.emitDestroy() <ide> <ide> Call all `destroy` hooks. This should only ever be called once. An error will <ide> be thrown if it is called more than once. This **must** be manually called. If <ide> the resource is left to be collected by the GC then the `destroy` hooks will <ide> never be called. <ide> <del>#### `asyncResource.asyncId()` <add>#### asyncResource.asyncId() <ide> <ide> * Returns: {number} The unique `asyncId` assigned to the resource. <ide> <del>#### `asyncResource.triggerAsyncId()` <add>#### asyncResource.triggerAsyncId() <ide> <ide> * Returns: {number} The same `triggerAsyncId` that is passed to the <ide> `AsyncResource` constructor. <ide><path>doc/api/dns.md <ide> dns.resolve4('archive.org', (err, addresses) => { <ide> There are subtle consequences in choosing one over the other, please consult <ide> the [Implementation considerations section][] for more information. <ide> <del>## Class dns.Resolver <add>## Class: dns.Resolver <ide> <!-- YAML <ide> added: v8.3.0 <ide> --> <ide><path>doc/api/esm.md <ide> Only the CLI argument for the main entry point to the program can be an entry <ide> point into an ESM graph. Dynamic import can also be used to create entry points <ide> into ESM graphs at runtime. <ide> <del>#### `import.meta` <add>#### import.meta <add> <add>* {Object} <ide> <ide> The `import.meta` metaproperty is an `Object` that contains the following <ide> property: <del>* `url` {string} The absolute `file:` URL of the module <add> <add>* `url` {string} The absolute `file:` URL of the module. <ide> <ide> ### Unsupported <ide>
3
Ruby
Ruby
remove special cases in build-time dep audit
6c3ee52d14e54f5cb23438c3ec4a1b57a1e60e80
<ide><path>Library/Homebrew/cmd/audit.rb <ide> def audit_deps <ide> <ide> case dep.name <ide> when *BUILD_TIME_DEPS <del> next if dep.build? <del> next if dep.name == 'autoconf' && f.name =~ /automake/ <del> next if dep.name == 'libtool' && %w{imagemagick libgphoto2 libp11 libextractor}.any? { |n| f.name == n } <del> next if dep.name =~ /autoconf|pkg-config/ && f.name == 'ruby-build' <del> <add> next if dep.build? or dep.run? <ide> problem %{#{dep} dependency should be "depends_on '#{dep}' => :build"} <ide> when "git", "ruby", "emacs", "mercurial" <ide> problem <<-EOS.undent <ide><path>Library/Homebrew/dependency_collector.rb <ide> def x11_dep(spec, tags) <ide> end <ide> <ide> def autotools_dep(spec, tags) <del> unless MacOS::Xcode.provides_autotools? <del> case spec <del> when :libltdl then spec = :libtool <del> else tags << :build <del> end <add> return if MacOS::Xcode.provides_autotools? <ide> <del> Dependency.new(spec.to_s, tags) <add> if spec == :libltdl <add> spec = :libtool <add> tags << :run <ide> end <add> <add> tags << :build unless tags.include? :run <add> Dependency.new(spec.to_s, tags) <ide> end <ide> <ide> def ant_dep(spec, tags)
2
Ruby
Ruby
fix #480. passing nil to create association works
5fc3564a5021909384d2b762d125e521683403f1
<ide><path>activerecord/lib/active_record/associations/collection_association.rb <ide> def insert_record(record, validate = true) <ide> end <ide> <ide> def build_record(attributes, options) <del> reflection.build_association(scoped.scope_for_create.merge(attributes), options) <add> reflection.build_association(scoped.scope_for_create.merge(attributes || {}), options) <ide> end <ide> <ide> def delete_or_destroy(records, method)
1
Ruby
Ruby
fix pkg-config paths
d7323f30d3ce781519044585fab2b030e29b3efb
<ide><path>Library/Homebrew/extend/os/mac/extend/ENV/std.rb <ide> module Stdenv <ide> undef homebrew_extra_pkg_config_paths <ide> <ide> def homebrew_extra_pkg_config_paths <del> ["#{HOMEBREW_LIBRARY}/Homebrew/os/mac/pkgconfig/#{MacOS.sdk_version}"] <add> ["#{HOMEBREW_LIBRARY}/Homebrew/os/mac/pkgconfig/#{MacOS.version}"] <ide> end <ide> <ide> def setup_build_environment(formula: nil, cc: nil, build_bottle: false, bottle_arch: nil, testing_formula: false) <ide><path>Library/Homebrew/extend/os/mac/extend/ENV/super.rb <ide> def homebrew_extra_paths <ide> # @private <ide> def homebrew_extra_pkg_config_paths <ide> paths = \ <del> ["/usr/lib/pkgconfig", "#{HOMEBREW_LIBRARY}/Homebrew/os/mac/pkgconfig/#{MacOS.sdk_version}"] <add> ["/usr/lib/pkgconfig", "#{HOMEBREW_LIBRARY}/Homebrew/os/mac/pkgconfig/#{MacOS.version}"] <ide> paths << "#{MacOS::XQuartz.lib}/pkgconfig" << "#{MacOS::XQuartz.share}/pkgconfig" if x11? <ide> paths <ide> end
2
Javascript
Javascript
fix physical node material
3ec88490b2293606bb8aad37e4316e83cf523da3
<ide><path>examples/js/nodes/materials/StandardNode.js <ide> THREE.StandardNode.prototype.build = function( builder ) { <ide> <ide> output.push( <ide> environment.code, <del> "RE_IndirectSpecular(" + environment.result + ", geometry, material, reflectedLight );" <add> "RE_IndirectSpecular_Physical(" + environment.result + ", vec3( 0.0 ), geometry, material, reflectedLight );" <ide> ); <ide> <ide> }
1
Python
Python
set version to spacy-nightly rc2
4efaf9306c46c4424e493bf9b75cf838a354d093
<ide><path>spacy/about.py <ide> # https://python-packaging-user-guide.readthedocs.org/en/latest/single_source_version/ <ide> # https://github.com/pypa/warehouse/blob/master/warehouse/__about__.py <ide> <del>__title__ = 'spacy' <del>__version__ = '2.0.0' <add>__title__ = 'spacy-nightly' <add>__version__ = '2.0.0rc2' <ide> __summary__ = 'Industrial-strength Natural Language Processing (NLP) with Python and Cython' <ide> __uri__ = 'https://spacy.io' <ide> __author__ = 'Explosion AI'
1
Python
Python
add conditional version retrieval from setup.
537aba738cf44f471dfc55db2e860d227c58dd55
<ide><path>airflow/version.py <ide> except ImportError: <ide> import importlib_metadata as metadata <ide> <del>version = metadata.version('apache-airflow') <add>try: <add> version = metadata.version('apache-airflow') <add>except metadata.PackageNotFoundError: <add> import logging <add> <add> log = logging.getLogger(__name__) <add> log.warning("Package metadata could not be found. Overriding it with version found in setup.py") <add> from setup import version <ide> <ide> del metadata
1
Ruby
Ruby
fix urlsafe messageverifier not to include padding
08afa160a56809ca5827c559f409bcb89d362af1
<ide><path>activesupport/lib/active_support/message_verifier.rb <ide> def generate(value, expires_at: nil, expires_in: nil, purpose: nil) <ide> <ide> private <ide> def encode(data) <del> @urlsafe ? Base64.urlsafe_encode64(data) : Base64.strict_encode64(data) <add> @urlsafe ? Base64.urlsafe_encode64(data, padding: false) : Base64.strict_encode64(data) <ide> end <ide> <ide> def decode(data) <ide><path>activesupport/test/message_verifier_test.rb <ide> def test_urlsafe <ide> assert_equal message, URI.encode_www_form_component(message) <ide> end <ide> <add> def test_no_padding <add> message = generate("a") <add> assert_not_includes message, "=" <add> end <add> <ide> private <ide> def verifier_options <ide> { urlsafe: true }
2
Python
Python
show the location of an empty list in np.block
6a3a236ca847785657b264576f9b34a20a24e957
<ide><path>numpy/core/shape_base.py <ide> def stack(arrays, axis=0, out=None): <ide> return _nx.concatenate(expanded_arrays, axis=axis, out=out) <ide> <ide> <add>def _block_format_index(index): <add> """ <add> Convert a list of indices ``[0, 1, 2]`` into ``"arrays[0][1][2]"``. <add> """ <add> idx_str = ''.join('[{}]'.format(i) for i in index if i is not None) <add> return 'arrays' + idx_str <add> <add> <ide> def _block_check_depths_match(arrays, parent_index=[]): <ide> """ <ide> Recursive function checking that the depths of nested lists in `arrays` <ide> def _block_check_depths_match(arrays, parent_index=[]): <ide> Returns <ide> ------- <ide> first_index : list of int <del> The full index of the first element from the bottom of the nesting in <del> `arrays`. An empty list at the bottom of the nesting is represented by <del> a `None` index. <add> The full index of an element from the bottom of the nesting in <add> `arrays`. If any element at the bottom is an empty list, this will <add> refer to it, and the last index along the empty axis will be `None`. <ide> max_arr_ndim : int <ide> The maximum of the ndims of the arrays nested in `arrays`. <ide> """ <del> def format_index(index): <del> idx_str = ''.join('[{}]'.format(i) for i in index if i is not None) <del> return 'arrays' + idx_str <ide> if type(arrays) is tuple: <ide> # not strictly necessary, but saves us from: <ide> # - more than one way to do things - no point treating tuples like <ide> def format_index(index): <ide> '{} is a tuple. ' <ide> 'Only lists can be used to arrange blocks, and np.block does ' <ide> 'not allow implicit conversion from tuple to ndarray.'.format( <del> format_index(parent_index) <add> _block_format_index(parent_index) <ide> ) <ide> ) <ide> elif type(arrays) is list and len(arrays) > 0: <ide> def format_index(index): <ide> "{}, but there is an element at depth {} ({})".format( <ide> len(first_index), <ide> len(index), <del> format_index(index) <add> _block_format_index(index) <ide> ) <ide> ) <add> # propagate our flag that indicates an empty list at the bottom <add> if index[-1] is None: <add> first_index = index <ide> return first_index, max_arr_ndim <ide> elif type(arrays) is list and len(arrays) == 0: <ide> # We've 'bottomed out' on an empty list <ide> def atleast_nd(a, ndim): <ide> @recursive <ide> def block_recursion(self, arrays, depth=0): <ide> if depth < max_depth: <del> if len(arrays) == 0: <del> raise ValueError('Lists cannot be empty') <ide> arrs = [self(arr, depth+1) for arr in arrays] <ide> return _nx.concatenate(arrs, axis=-(max_depth-depth)) <ide> else: <ide> def block(arrays): <ide> """ <ide> bottom_index, arr_ndim = _block_check_depths_match(arrays) <ide> list_ndim = len(bottom_index) <add> if bottom_index and bottom_index[-1] is None: <add> raise ValueError( <add> 'List at {} cannot be empty'.format( <add> _block_format_index(bottom_index) <add> ) <add> ) <ide> return _block(arrays, list_ndim, max(arr_ndim, list_ndim))
1
Python
Python
move quote_parameter off of operations and rename
42607a9e33e63639d1da2166b9a2f85c691e07ae
<ide><path>django/db/backends/__init__.py <ide> def quote_name(self, name): <ide> """ <ide> raise NotImplementedError('subclasses of BaseDatabaseOperations may require a quote_name() method') <ide> <del> def quote_parameter(self, value): <del> """ <del> Returns a quoted version of the value so it's safe to use in an SQL <del> string. This should NOT be used to prepare SQL statements to send to <del> the database; it is meant for outputting SQL statements to a file <del> or the console for later execution by a developer/DBA. <del> """ <del> raise NotImplementedError() <del> <ide> def random_function_sql(self): <ide> """ <ide> Returns an SQL expression that returns a random value. <ide><path>django/db/backends/mysql/base.py <ide> def quote_name(self, name): <ide> return name # Quoting once is enough. <ide> return "`%s`" % name <ide> <del> def quote_parameter(self, value): <del> # Inner import to allow module to fail to load gracefully <del> import MySQLdb.converters <del> return MySQLdb.escape(value, MySQLdb.converters.conversions) <del> <ide> def random_function_sql(self): <ide> return 'RAND()' <ide> <ide><path>django/db/backends/mysql/schema.py <ide> class DatabaseSchemaEditor(BaseDatabaseSchemaEditor): <ide> <ide> sql_create_pk = "ALTER TABLE %(table)s ADD CONSTRAINT %(name)s PRIMARY KEY (%(columns)s)" <ide> sql_delete_pk = "ALTER TABLE %(table)s DROP PRIMARY KEY" <add> <add> def quote_value(self, value): <add> # Inner import to allow module to fail to load gracefully <add> import MySQLdb.converters <add> return MySQLdb.escape(value, MySQLdb.converters.conversions) <ide><path>django/db/backends/oracle/base.py <ide> def quote_name(self, name): <ide> name = name.replace('%', '%%') <ide> return name.upper() <ide> <del> def quote_parameter(self, value): <del> if isinstance(value, (datetime.date, datetime.time, datetime.datetime)): <del> return "'%s'" % value <del> elif isinstance(value, six.string_types): <del> return repr(value) <del> elif isinstance(value, bool): <del> return "1" if value else "0" <del> else: <del> return str(value) <del> <ide> def random_function_sql(self): <ide> return "DBMS_RANDOM.RANDOM" <ide> <ide><path>django/db/backends/oracle/schema.py <ide> import copy <add>import datetime <ide> <add>from django.utils import six <ide> from django.db.backends.schema import BaseDatabaseSchemaEditor <ide> from django.db.utils import DatabaseError <ide> <ide> class DatabaseSchemaEditor(BaseDatabaseSchemaEditor): <ide> sql_delete_column = "ALTER TABLE %(table)s DROP COLUMN %(column)s" <ide> sql_delete_table = "DROP TABLE %(table)s CASCADE CONSTRAINTS" <ide> <add> def quote_value(self, value): <add> if isinstance(value, (datetime.date, datetime.time, datetime.datetime)): <add> return "'%s'" % value <add> elif isinstance(value, six.string_types): <add> return repr(value) <add> elif isinstance(value, bool): <add> return "1" if value else "0" <add> else: <add> return str(value) <add> <ide> def delete_model(self, model): <ide> # Run superclass action <ide> super(DatabaseSchemaEditor, self).delete_model(model) <ide> def _generate_temp_name(self, for_name): <ide> return self.normalize_name(for_name + "_" + suffix) <ide> <ide> def prepare_default(self, value): <del> return self.connection.ops.quote_parameter(value) <add> return self.quote_value(value) <ide><path>django/db/backends/postgresql_psycopg2/operations.py <ide> def quote_name(self, name): <ide> return name # Quoting once is enough. <ide> return '"%s"' % name <ide> <del> def quote_parameter(self, value): <del> # Inner import so backend fails nicely if it's not present <del> import psycopg2 <del> return psycopg2.extensions.adapt(value) <del> <ide> def set_time_zone_sql(self): <ide> return "SET TIME ZONE %s" <ide> <ide><path>django/db/backends/postgresql_psycopg2/schema.py <ide> class DatabaseSchemaEditor(BaseDatabaseSchemaEditor): <ide> sql_delete_sequence = "DROP SEQUENCE IF EXISTS %(sequence)s CASCADE" <ide> sql_set_sequence_max = "SELECT setval('%(sequence)s', MAX(%(column)s)) FROM %(table)s" <ide> <add> def quote_value(self, value): <add> # Inner import so backend fails nicely if it's not present <add> import psycopg2 <add> return psycopg2.extensions.adapt(value) <add> <ide> def _alter_column_type_sql(self, table, column, type): <ide> """ <ide> Makes ALTER TYPE with SERIAL make sense. <ide><path>django/db/backends/schema.py <ide> def execute(self, sql, params=[]): <ide> # Log the command we're running, then run it <ide> logger.debug("%s; (params %r)" % (sql, params)) <ide> if self.collect_sql: <del> self.collected_sql.append((sql % tuple(map(self.connection.ops.quote_parameter, params))) + ";") <add> self.collected_sql.append((sql % tuple(map(self.quote_value, params))) + ";") <ide> else: <ide> with self.connection.cursor() as cursor: <ide> cursor.execute(sql, params) <ide> def effective_default(self, field): <ide> default = default() <ide> return default <ide> <add> def quote_value(self, value): <add> """ <add> Returns a quoted version of the value so it's safe to use in an SQL <add> string. This is not safe against injection from user code; it is <add> intended only for use in making SQL scripts or preparing default values <add> for particularly tricky backends (defaults are not user-defined, though, <add> so this is safe). <add> """ <add> raise NotImplementedError() <add> <ide> # Actions <ide> <ide> def create_model(self, model): <ide><path>django/db/backends/sqlite3/base.py <ide> def quote_name(self, name): <ide> return name # Quoting once is enough. <ide> return '"%s"' % name <ide> <del> def quote_parameter(self, value): <del> # Inner import to allow nice failure for backend if not present <del> import _sqlite3 <del> try: <del> value = _sqlite3.adapt(value) <del> except _sqlite3.ProgrammingError: <del> pass <del> # Manual emulation of SQLite parameter quoting <del> if isinstance(value, type(True)): <del> return str(int(value)) <del> elif isinstance(value, six.integer_types): <del> return str(value) <del> elif isinstance(value, six.string_types): <del> return '"%s"' % six.text_type(value) <del> elif value is None: <del> return "NULL" <del> else: <del> raise ValueError("Cannot quote parameter value %r" % value) <del> <ide> def no_limit_value(self): <ide> return -1 <ide> <ide><path>django/db/backends/sqlite3/schema.py <add>from django.utils import six <ide> from django.apps.registry import Apps <ide> from django.db.backends.schema import BaseDatabaseSchemaEditor <ide> from django.db.models.fields.related import ManyToManyField <ide> class DatabaseSchemaEditor(BaseDatabaseSchemaEditor): <ide> sql_delete_table = "DROP TABLE %(table)s" <ide> sql_create_inline_fk = "REFERENCES %(to_table)s (%(to_column)s)" <ide> <add> def quote_value(self, value): <add> # Inner import to allow nice failure for backend if not present <add> import _sqlite3 <add> try: <add> value = _sqlite3.adapt(value) <add> except _sqlite3.ProgrammingError: <add> pass <add> # Manual emulation of SQLite parameter quoting <add> if isinstance(value, type(True)): <add> return str(int(value)) <add> elif isinstance(value, six.integer_types): <add> return str(value) <add> elif isinstance(value, six.string_types): <add> return '"%s"' % six.text_type(value) <add> elif value is None: <add> return "NULL" <add> else: <add> raise ValueError("Cannot quote parameter value %r" % value) <add> <ide> def _remake_table(self, model, create_fields=[], delete_fields=[], alter_fields=[], rename_fields=[], override_uniques=None): <ide> """ <ide> Shortcut to transform a model from old_model into new_model <ide> def _remake_table(self, model, create_fields=[], delete_fields=[], alter_fields= <ide> body[field.name] = field <ide> # If there's a default, insert it into the copy map <ide> if field.has_default(): <del> mapping[field.column] = self.connection.ops.quote_parameter( <add> mapping[field.column] = self.quote_value( <ide> field.get_default() <ide> ) <ide> # Add in any altered fields
10
Ruby
Ruby
remove unused method
c8aea8653abcbb89a1334b173511b39e8588825a
<ide><path>Library/Homebrew/utils/bottles.rb <ide> def extname_tag_rebuild(filename) <ide> HOMEBREW_BOTTLES_EXTNAME_REGEX.match(filename).to_a <ide> end <ide> <del> # TODO: remove when removed from brew-test-bot <del> sig { returns(Regexp) } <del> def native_regex <del> /(\.#{Regexp.escape(tag.to_s)}\.bottle\.(\d+\.)?tar\.gz)$/o <del> end <del> <ide> def receipt_path(bottle_file) <ide> path = Utils.popen_read("tar", "-tzf", bottle_file).lines.map(&:chomp).find do |line| <ide> line =~ %r{.+/.+/INSTALL_RECEIPT.json}
1
Java
Java
mark the thread as interrupted again
4880e34a45bea09828ce3419919d5fd3336f54f3
<ide><path>rxjava-core/src/main/java/rx/Observable.java <ide> public void onNext(T args) { <ide> try { <ide> latch.await(); <ide> } catch (InterruptedException e) { <add> // set the interrupted flag again so callers can still get it <add> // for more information see https://github.com/Netflix/RxJava/pull/147#issuecomment-13624780 <add> Thread.currentThread().interrupt(); <add> // using Runtime so it is not checked <ide> throw new RuntimeException("Interrupted while waiting for subscription to complete.", e); <ide> } <ide>
1
Ruby
Ruby
use canonical_name in the exception message
70f22fc31e8aea5cd3c05f5a9cde54896814099f
<ide><path>Library/Homebrew/extend/ARGV.rb <ide> def kegs <ide> elsif (prefix = Formulary.factory(canonical_name).prefix).directory? <ide> Keg.new(prefix) <ide> else <del> raise MultipleVersionsInstalledError.new(name) <add> raise MultipleVersionsInstalledError.new(canonical_name) <ide> end <ide> rescue FormulaUnavailableError <ide> raise <<-EOS.undent
1
PHP
PHP
use real command name
313abe624db65237d4bacc5fa3dd93e651c05ab9
<ide><path>app/Console/Kernel.php <ide> class Kernel extends ConsoleKernel { <ide> */ <ide> protected function schedule(Schedule $schedule) <ide> { <del> $schedule->artisan('foo') <add> $schedule->artisan('inspire'); <ide> ->hourly(); <ide> } <ide>
1
Ruby
Ruby
remove unnecessary require and extend
e3fc35b5d68b66d5fa165baf69bf76c1110bb512
<ide><path>railties/test/railties/engine_test.rb <ide> def boot_rails <ide> add_to_env_config "development", "config.assets.digest = false" <ide> <ide> boot_rails <del> require 'rack/test' <del> extend Rack::Test::Methods <ide> <ide> get "/assets/engine.js" <ide> assert_match "alert()", last_response.body <ide> def self.call(env) <ide> RUBY <ide> <ide> boot_rails <del> require 'rack/test' <del> extend Rack::Test::Methods <ide> <ide> get "/sprokkit" <ide> assert_equal "I am a Sprokkit", last_response.body <ide> def index <ide> RUBY <ide> <ide> boot_rails <del> require 'rack/test' <del> extend Rack::Test::Methods <ide> <ide> get '/foo' <ide> assert_equal 'foo', last_response.body <ide> def index <ide> RUBY <ide> <ide> boot_rails <del> require 'rack/test' <del> extend Rack::Test::Methods <ide> <ide> get "/admin/foo/bar" <ide> assert_equal 200, last_response.status
1
Javascript
Javascript
modify key events for horizontal scrolling
eaf14e5d47a0ef7fcf5186d5babf1c73b48ec662
<ide><path>web/app.js <ide> function webViewerKeyDown(evt) { <ide> } <ide> <ide> if (cmd === 0) { // no control key pressed at all. <add> let turnPage = 0, turnOnlyIfPageFit = false; <ide> switch (evt.keyCode) { <ide> case 38: // up arrow <ide> case 33: // pg up <add> // vertical scrolling using arrow/pg keys <add> if (pdfViewer.isVerticalScrollbarEnabled) { <add> turnOnlyIfPageFit = true; <add> } <add> turnPage = -1; <add> break; <ide> case 8: // backspace <del> if (!isViewerInPresentationMode && <del> pdfViewer.currentScaleValue !== 'page-fit') { <del> break; <add> if (!isViewerInPresentationMode) { <add> turnOnlyIfPageFit = true; <ide> } <del> /* in presentation mode */ <del> /* falls through */ <add> turnPage = -1; <add> break; <ide> case 37: // left arrow <ide> // horizontal scrolling using arrow keys <ide> if (pdfViewer.isHorizontalScrollbarEnabled) { <del> break; <add> turnOnlyIfPageFit = true; <ide> } <ide> /* falls through */ <ide> case 75: // 'k' <ide> case 80: // 'p' <del> if (PDFViewerApplication.page > 1) { <del> PDFViewerApplication.page--; <del> } <del> handled = true; <add> turnPage = -1; <ide> break; <ide> case 27: // esc key <ide> if (PDFViewerApplication.secondaryToolbar.isOpen) { <ide> function webViewerKeyDown(evt) { <ide> handled = true; <ide> } <ide> break; <del> case 13: // enter key <ide> case 40: // down arrow <ide> case 34: // pg down <add> // vertical scrolling using arrow/pg keys <add> if (pdfViewer.isVerticalScrollbarEnabled) { <add> turnOnlyIfPageFit = true; <add> } <add> turnPage = 1; <add> break; <add> case 13: // enter key <ide> case 32: // spacebar <del> if (!isViewerInPresentationMode && <del> pdfViewer.currentScaleValue !== 'page-fit') { <del> break; <add> if (!isViewerInPresentationMode) { <add> turnOnlyIfPageFit = true; <ide> } <del> /* falls through */ <add> turnPage = 1; <add> break; <ide> case 39: // right arrow <ide> // horizontal scrolling using arrow keys <ide> if (pdfViewer.isHorizontalScrollbarEnabled) { <del> break; <add> turnOnlyIfPageFit = true; <ide> } <ide> /* falls through */ <ide> case 74: // 'j' <ide> case 78: // 'n' <del> if (PDFViewerApplication.page < PDFViewerApplication.pagesCount) { <del> PDFViewerApplication.page++; <del> } <del> handled = true; <add> turnPage = 1; <ide> break; <ide> <ide> case 36: // home <ide> function webViewerKeyDown(evt) { <ide> PDFViewerApplication.rotatePages(90); <ide> break; <ide> } <add> <add> if (turnPage !== 0 && <add> (!turnOnlyIfPageFit || pdfViewer.currentScaleValue === 'page-fit')) { <add> if (turnPage > 0) { <add> if (PDFViewerApplication.page < PDFViewerApplication.pagesCount) { <add> PDFViewerApplication.page++; <add> } <add> } else { <add> if (PDFViewerApplication.page > 1) { <add> PDFViewerApplication.page--; <add> } <add> } <add> handled = true; <add> } <ide> } <ide> <ide> if (cmd === 4) { // shift-key <ide><path>web/base_viewer.js <ide> class BaseViewer { <ide> false : (this.container.scrollWidth > this.container.clientWidth)); <ide> } <ide> <add> get isVerticalScrollbarEnabled() { <add> return (this.isInPresentationMode ? <add> false : (this.container.scrollHeight > this.container.clientHeight)); <add> } <add> <ide> _getVisiblePages() { <ide> throw new Error('Not implemented: _getVisiblePages'); <ide> }
2
Text
Text
remove conflict comment
1adbc22fdeb6dce5a6628fd7cb4a7dc2883e25fc
<ide><path>docs/docs/02.1-jsx-in-depth.md <ide> var content = ( <ide> <ide> > NOTE: <ide> > <del>> JSX is similar to HTML, but not exactly the same. See [JSX gotchas](/react/docs/jsx-gotchas.html) for some key differences. <del>>>>>>>> master <add>> JSX is similar to HTML, but not exactly the same. See [JSX gotchas](/react/docs/jsx-gotchas.html) for some key differences. <ide>\ No newline at end of file
1
PHP
PHP
fix config option in listen command
a597ed29dc35444f63c8b53273133b3838e3ea29
<ide><path>src/Illuminate/Queue/Console/ListenCommand.php <ide> public function fire() <ide> */ <ide> protected function getQueue($connection) <ide> { <del> $queue = $this->laravel['config']->get("queue.{$connection}.queue", 'default'); <add> $queue = $this->laravel['config']->get("queue.connections.{$connection}.queue", 'default'); <ide> <ide> return $this->input->getOption('queue') ?: $queue; <ide> }
1
Javascript
Javascript
add test for noassert option in buf.read*()
c8ed5f29ca877e8baddea2f04483f19d5c872832
<ide><path>test/parallel/test-buffer-read-noassert.js <add>'use strict'; <add>require('../common'); <add>const assert = require('assert'); <add> <add>// testing basic buffer read functions <add>const buf = Buffer.from([0xa4, 0xfd, 0x48, 0xea, 0xcf, 0xff, 0xd9, 0x01, 0xde]); <add> <add>function read(buff, funx, args, expected) { <add> <add> assert.strictEqual(buff[funx](...args), expected); <add> assert.throws( <add> () => buff[funx](-1), <add> /^RangeError: Index out of range$/ <add> ); <add> <add> assert.doesNotThrow( <add> () => assert.strictEqual(buff[funx](...args, true), expected), <add> 'noAssert does not change return value for valid ranges' <add>); <add> <add>} <add> <add>// testing basic functionality of readDoubleBE() and readDOubleLE() <add>read(buf, 'readDoubleBE', [1], -3.1827727774563287e+295); <add>read(buf, 'readDoubleLE', [1], -6.966010051009108e+144); <add> <add>// testing basic functionality of readFLoatBE() and readFloatLE() <add>read(buf, 'readFloatBE', [1], -1.6691549692541768e+37); <add>read(buf, 'readFloatLE', [1], -7861303808); <add> <add>// testing basic functionality of readInt8() <add>read(buf, 'readInt8', [1], -3); <add> <add>// testing basic functionality of readInt16BE() and readInt16LE() <add>read(buf, 'readInt16BE', [1], -696); <add>read(buf, 'readInt16LE', [1], 0x48fd); <add> <add>// testing basic functionality of readInt32BE() and readInt32LE() <add>read(buf, 'readInt32BE', [1], -45552945); <add>read(buf, 'readInt32LE', [1], -806729475); <add> <add>// testing basic functionality of readIntBE() and readIntLE() <add>read(buf, 'readIntBE', [1, 1], -3); <add>read(buf, 'readIntLE', [2, 1], 0x48); <add> <add>// testing basic functionality of readUInt8() <add>read(buf, 'readUInt8', [1], 0xfd); <add> <add>// testing basic functionality of readUInt16BE() and readUInt16LE() <add>read(buf, 'readUInt16BE', [2], 0x48ea); <add>read(buf, 'readUInt16LE', [2], 0xea48); <add> <add>// testing basic functionality of readUInt32BE() and readUInt32LE() <add>read(buf, 'readUInt32BE', [1], 0xfd48eacf); <add>read(buf, 'readUInt32LE', [1], 0xcfea48fd); <add> <add>// testing basic functionality of readUIntBE() and readUIntLE() <add>read(buf, 'readUIntBE', [2, 0], 0xfd); <add>read(buf, 'readUIntLE', [2, 0], 0x48);
1
Ruby
Ruby
fix wrong require
b11645eb2b8617ebf9feb1128dc16072922580ee
<ide><path>activerecord/lib/active_record/encryption/encryptor.rb <ide> # frozen_string_literal: true <ide> <ide> require "openssl" <del>require "zip" <add>require "zlib" <ide> require "active_support/core_ext/numeric" <ide> <ide> module ActiveRecord
1
Java
Java
make javadoc for zip() variants more precise
1ea6d157d71000a563ec90db548907f3afbb8412
<ide><path>src/main/java/rx/Observable.java <ide> public final static <T, Resource> Observable<T> using( <ide> } <ide> <ide> /** <del> * Returns an Observable that emits the results of a function of your choosing applied to combinations of <add> * Returns an Observable that emits the results of a specified combiner function applied to combinations of <ide> * items emitted, in sequence, by an Iterable of other Observables. <ide> * <p> <ide> * {@code zip} applies this function in strict sequence, so the first item emitted by the new Observable <ide> public final static <R> Observable<R> zip(Iterable<? extends Observable<?>> ws, <ide> } <ide> <ide> /** <del> * Returns an Observable that emits the results of a function of your choosing applied to combinations of <add> * Returns an Observable that emits the results of a specified combiner function applied to combinations of <ide> * <i>n</i> items emitted, in sequence, by the <i>n</i> Observables emitted by a specified Observable. <ide> * <p> <ide> * {@code zip} applies this function in strict sequence, so the first item emitted by the new Observable <ide> public Observable<?>[] call(List<? extends Observable<?>> o) { <ide> } <ide> <ide> /** <del> * Returns an Observable that emits the results of a function of your choosing applied to combinations of <add> * Returns an Observable that emits the results of a specified combiner function applied to combinations of <ide> * two items emitted, in sequence, by two other Observables. <ide> * <p> <ide> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/zip.png" alt=""> <ide> public final static <T1, T2, R> Observable<R> zip(Observable<? extends T1> o1, O <ide> } <ide> <ide> /** <del> * Returns an Observable that emits the results of a function of your choosing applied to combinations of <add> * Returns an Observable that emits the results of a specified combiner function applied to combinations of <ide> * three items emitted, in sequence, by three other Observables. <ide> * <p> <ide> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/zip.png" alt=""> <ide> public final static <T1, T2, T3, R> Observable<R> zip(Observable<? extends T1> o <ide> } <ide> <ide> /** <del> * Returns an Observable that emits the results of a function of your choosing applied to combinations of <add> * Returns an Observable that emits the results of a specified combiner function applied to combinations of <ide> * four items emitted, in sequence, by four other Observables. <ide> * <p> <ide> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/zip.png" alt=""> <ide> public final static <T1, T2, T3, T4, R> Observable<R> zip(Observable<? extends T <ide> } <ide> <ide> /** <del> * Returns an Observable that emits the results of a function of your choosing applied to combinations of <add> * Returns an Observable that emits the results of a specified combiner function applied to combinations of <ide> * five items emitted, in sequence, by five other Observables. <ide> * <p> <ide> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/zip.png" alt=""> <ide> public final static <T1, T2, T3, T4, T5, R> Observable<R> zip(Observable<? exten <ide> } <ide> <ide> /** <del> * Returns an Observable that emits the results of a function of your choosing applied to combinations of <add> * Returns an Observable that emits the results of a specified combiner function applied to combinations of <ide> * six items emitted, in sequence, by six other Observables. <ide> * <p> <ide> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/zip.png" alt=""> <ide> public final static <T1, T2, T3, T4, T5, T6, R> Observable<R> zip(Observable<? e <ide> } <ide> <ide> /** <del> * Returns an Observable that emits the results of a function of your choosing applied to combinations of <add> * Returns an Observable that emits the results of a specified combiner function applied to combinations of <ide> * seven items emitted, in sequence, by seven other Observables. <ide> * <p> <ide> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/zip.png" alt=""> <ide> public final static <T1, T2, T3, T4, T5, T6, T7, R> Observable<R> zip(Observable <ide> } <ide> <ide> /** <del> * Returns an Observable that emits the results of a function of your choosing applied to combinations of <add> * Returns an Observable that emits the results of a specified combiner function applied to combinations of <ide> * eight items emitted, in sequence, by eight other Observables. <ide> * <p> <ide> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/zip.png" alt=""> <ide> public final static <T1, T2, T3, T4, T5, T6, T7, T8, R> Observable<R> zip(Observ <ide> } <ide> <ide> /** <del> * Returns an Observable that emits the results of a function of your choosing applied to combinations of <add> * Returns an Observable that emits the results of a specified combiner function applied to combinations of <ide> * nine items emitted, in sequence, by nine other Observables. <ide> * <p> <ide> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/zip.png" alt="">
1
Ruby
Ruby
include missing module in tag_helper
05fde24e1ef8c3b225eea8c51cbc05418620ae4a
<ide><path>actionview/lib/action_view/helpers/tag_helper.rb <ide> module Helpers #:nodoc: <ide> module TagHelper <ide> extend ActiveSupport::Concern <ide> include CaptureHelper <add> include OutputSafetyHelper <ide> <ide> BOOLEAN_ATTRIBUTES = %w(disabled readonly multiple checked autobuffer <ide> autoplay controls loop selected hidden scoped async
1
Javascript
Javascript
increase lint compliance
1d96d7da7331619ee99066451f6bcf1b5a7f3953
<ide><path>benchmark/napi/function_args/index.js <ide> let napi; <ide> try { <ide> v8 = require('./build/Release/binding'); <ide> } catch (err) { <del> // eslint-disable-next-line no-path-concat <del> console.error(__filename + ': V8 Binding failed to load'); <add> console.error(`${__filename}: V8 Binding failed to load`); <ide> process.exit(0); <ide> } <ide> <ide> try { <ide> napi = require('./build/Release/napi_binding'); <ide> } catch (err) { <del> // eslint-disable-next-line no-path-concat <del> console.error(__filename + ': NAPI-Binding failed to load'); <add> console.error(`${__filename}: NAPI-Binding failed to load`); <ide> process.exit(0); <ide> } <ide>
1
Javascript
Javascript
add tests for console.log arguments handling
bedca2e7a9714ad97bc12e1228ff08075fd25556
<ide><path>test/simple/test-console.js <add>common = require("../common"); <add>assert = common.assert; <add> <add>var stdout_write = global.process.stdout.write; <add>var strings = []; <add>global.process.stdout.write = function(string) { <add> strings.push(string); <add>}; <add> <add>console.log('foo'); <add>console.log('foo', 'bar'); <add>console.log('%s %s', 'foo', 'bar', 'hop'); <add> <add>global.process.stdout.write = stdout_write; <add>assert.equal('foo\n', strings.shift()); <add>assert.equal('foo bar\n', strings.shift()); <add>assert.equal('foo bar hop\n', strings.shift());
1
Text
Text
add french translation
dad28cd65720293e613cef6ae335c984b4ab53d5
<ide><path>threejs/lessons/fr/threejs-cameras.md <add>Title: Caméras dans Three.js <add>Description: Comment utiliser les Cameras dans Three.js <add>TOC: Cameras <add> <add>Cet article fait partie d'une série consacrée à Three.js. <add>Le premier article s'intitule [Principes de base](threejs-fundamentals.html). <add>Si vous ne l'avez pas encore lu, vous voudriez peut-être commencer par là. <add> <add>Parlons des caméras dans Three.js. Nous en avons déjà parlé dans [le premier article](threejs-fundamentals.html) mais ici nous allons entrer dans le détail. <add> <add>La caméra la plus courante dans Three.js et celle que nous avons utilisée jusqu'à présent, la [`PerspectiveCamera`](https://threejs.org/docs/#api/en/cameras/PerspectiveCamera). Elle donne une vue 3D où les choses lointaines semblent plus petites que les plus proches. <add> <add>La `PerspectiveCamera` définit un *frustum*. [Un frustum (tronc) est une forme pyramidale solide dont la pointe est coupée](https://fr.wikipedia.org/wiki/Tronc_(g%C3%A9om%C3%A9trie)). Par nom de solide, j'entends par exemple un cube, un cône, une sphère, un cylindre et un frustum sont tous des noms de différents types de solides. <add> <add><div class="spread"> <add> <div><div data-diagram="shapeCube"></div><div>cube</div></div> <add> <div><div data-diagram="shapeCone"></div><div>cone</div></div> <add> <div><div data-diagram="shapeSphere"></div><div>sphere</div></div> <add> <div><div data-diagram="shapeCylinder"></div><div>cylinder</div></div> <add> <div><div data-diagram="shapeFrustum"></div><div>frustum</div></div> <add></div> <add> <add>Je le signale seulement parce que je ne le savais pas. Et quand je voyais le mot *frustum* dans un livre mes yeux buggaient. Comprendre que c'est le nom d'un type de forme solide a rendu ces descriptions soudainement plus logiques &#128517; <add> <add>Une `PerspectiveCamera` définit son frustum selon 4 propriétés. `near` définit l'endroit où commence l'avant du frustum. `far` où il finit. `fov`, le champ de vision, définit la hauteur de l'avant et de l'arrière du tronc en fonction de la propriété `near`. L'`aspect` se rapporte à la largeur de l'avant et de l'arrière du tronc. La largeur du tronc est juste la hauteur multipliée par l'aspect. <add> <add><img src="resources/frustum-3d.svg" width="500" class="threejs_center"/> <add> <add>Utilisons la scène de [l'article précédent](threejs-lights.html) avec son plan, sa sphère et son cube, et faisons en sorte que nous puissions ajuster les paramètres de la caméra. <add> <add>Pour ce faire, nous allons créer un `MinMaxGUIHelper` pour les paramètres `near` et `far` où `far` <add>est toujours supérieur `near`. Il aura des propriétés `min` et `max` que dat.GUI <add>pourra ajuster. Une fois ajustés, ils définiront les 2 propriétés que nous spécifions. <add> <add>```js <add>class MinMaxGUIHelper { <add> constructor(obj, minProp, maxProp, minDif) { <add> this.obj = obj; <add> this.minProp = minProp; <add> this.maxProp = maxProp; <add> this.minDif = minDif; <add> } <add> get min() { <add> return this.obj[this.minProp]; <add> } <add> set min(v) { <add> this.obj[this.minProp] = v; <add> this.obj[this.maxProp] = Math.max(this.obj[this.maxProp], v + this.minDif); <add> } <add> get max() { <add> return this.obj[this.maxProp]; <add> } <add> set max(v) { <add> this.obj[this.maxProp] = v; <add> this.min = this.min; // this will call the min setter <add> } <add>} <add>``` <add> <add>Maintenant, nous pouvons configurer dat.GUI comme ça <add> <add>```js <add>function updateCamera() { <add> camera.updateProjectionMatrix(); <add>} <add> <add>const gui = new GUI(); <add>gui.add(camera, 'fov', 1, 180).onChange(updateCamera); <add>const minMaxGUIHelper = new MinMaxGUIHelper(camera, 'near', 'far', 0.1); <add>gui.add(minMaxGUIHelper, 'min', 0.1, 50, 0.1).name('near').onChange(updateCamera); <add>gui.add(minMaxGUIHelper, 'max', 0.1, 50, 0.1).name('far').onChange(updateCamera); <add>``` <add> <add>Chaque fois que les paramètres de la caméra changent, il faut appeler la fonction <add>[`updateProjectionMatrix`](PerspectiveCamera.updateProjectionMatrix). Nous avons donc créé une fonction `updateCamera` transmise à dat.GUI pour l'appeler lorsque les choses changent. <add> <add>{{{example url="../threejs-cameras-perspective.html" }}} <add> <add>Vous pouvez ajuster les valeurs et voir comment elles fonctionnent. Notez que nous n'avons pas rendu `aspect` réglable car il est pris à partir de la taille de la fenêtre, donc si vous souhaitez ajuster l'aspect, ouvrez l'exemple dans une nouvelle fenêtre, puis redimensionnez la fenêtre. <add> <add>Néanmoins, je pense que c'est un peu difficile à voir, alors modifions l'exemple pour qu'il ait 2 caméras. L'un montrera notre scène telle que nous la voyons ci-dessus, l'autre montrera une autre caméra regardant la scène que la première caméra dessine et montrant le frustum de cette caméra. <add> <add>Pour ce faire, nous pouvons utiliser la fonction ciseaux de three.js. Modifions-le pour dessiner 2 scènes avec 2 caméras côte à côte en utilisant la fonction ciseaux. <add> <add>Tout d'abord, utilisons du HTML et du CSS pour définir 2 éléments côte à côte. Cela nous aidera également avec les événements afin que les deux caméras puissent facilement avoir leurs propres `OrbitControls`. <add> <add>```html <add><body> <add> <canvas id="c"></canvas> <add>+ <div class="split"> <add>+ <div id="view1" tabindex="1"></div> <add>+ <div id="view2" tabindex="2"></div> <add>+ </div> <add></body> <add>``` <add> <add>Et le CSS qui fera apparaître ces 2 vues côte à côte sur le canevas <add> <add>```css <add>.split { <add> position: absolute; <add> left: 0; <add> top: 0; <add> width: 100%; <add> height: 100%; <add> display: flex; <add>} <add>.split>div { <add> width: 100%; <add> height: 100%; <add>} <add>``` <add> <add>Ensuite, ajoutons un `CameraHelper`. Un `CameraHelper` dessine le frustum d'une `Camera`. <add> <add>```js <add>const cameraHelper = new THREE.CameraHelper(camera); <add> <add>... <add> <add>scene.add(cameraHelper); <add>``` <add> <add>Récupérons maintenant nos 2 éléments. <add> <add>```js <add>const view1Elem = document.querySelector('#view1'); <add>const view2Elem = document.querySelector('#view2'); <add>``` <add> <add>Et nous allons configurer nos `OrbitControls` pour qu'ils répondent uniquement au premier élément. <add> <add>```js <add>-const controls = new OrbitControls(camera, canvas); <add>+const controls = new OrbitControls(camera, view1Elem); <add>``` <add> <add>Ajoutons une nouvelle `PerspectiveCamera` et un second `OrbitControls`. <add>Le deuxième `OrbitControls` est lié à la deuxième caméra et reçoit view2Elem en paramètre. <add> <add>```js <add>const camera2 = new THREE.PerspectiveCamera( <add> 60, // fov <add> 2, // aspect <add> 0.1, // near <add> 500, // far <add>); <add>camera2.position.set(40, 10, 30); <add>camera2.lookAt(0, 5, 0); <add> <add>const controls2 = new OrbitControls(camera2, view2Elem); <add>controls2.target.set(0, 5, 0); <add>controls2.update(); <add>``` <add> <add>Enfin, nous devons rendre la scène du point de vue de chaque caméra en utilisant la fonction `setScissor` pour ne rendre qu'une partie du canvas. <add> <add>Voici une fonction qui, étant donné un élément, calculera le rectangle de cet élément qui chevauche le canvas. Il définira ensuite les ciseaux et la fenêtre sur ce rectangle et renverra l'aspect pour cette taille. <add> <add>```js <add>function setScissorForElement(elem) { <add> const canvasRect = canvas.getBoundingClientRect(); <add> const elemRect = elem.getBoundingClientRect(); <add> <add> // calculer un rectangle relatif au canvas <add> const right = Math.min(elemRect.right, canvasRect.right) - canvasRect.left; <add> const left = Math.max(0, elemRect.left - canvasRect.left); <add> const bottom = Math.min(elemRect.bottom, canvasRect.bottom) - canvasRect.top; <add> const top = Math.max(0, elemRect.top - canvasRect.top); <add> <add> const width = Math.min(canvasRect.width, right - left); <add> const height = Math.min(canvasRect.height, bottom - top); <add> <add> // configurer les ciseaux pour ne rendre que cette partie du canvas <add> const positiveYUpBottom = canvasRect.height - bottom; <add> renderer.setScissor(left, positiveYUpBottom, width, height); <add> renderer.setViewport(left, positiveYUpBottom, width, height); <add> <add> // retourne aspect <add> return width / height; <add>} <add>``` <add> <add>Et maintenant, nous pouvons utiliser cette fonction pour dessiner la scène deux fois dans notre fonction `render` <add> <add>```js <add> function render() { <add> <add>- if (resizeRendererToDisplaySize(renderer)) { <add>- const canvas = renderer.domElement; <add>- camera.aspect = canvas.clientWidth / canvas.clientHeight; <add>- camera.updateProjectionMatrix(); <add>- } <add> <add>+ resizeRendererToDisplaySize(renderer); <add>+ <add>+ // déclenche la fonction setScissorTest <add>+ renderer.setScissorTest(true); <add>+ <add>+ // rend la vue originelle <add>+ { <add>+ const aspect = setScissorForElement(view1Elem); <add>+ <add>+ // adjuste la caméra pour cet aspect <add>+ camera.aspect = aspect; <add>+ camera.updateProjectionMatrix(); <add>+ cameraHelper.update(); <add>+ <add>+ // ne pas ajouter le camera helper dans la vue originelle <add>+ cameraHelper.visible = false; <add>+ <add>+ scene.background.set(0x000000); <add>+ <add>+ // rendu <add>+ renderer.render(scene, camera); <add>+ } <add>+ <add>+ // rendu de la 2e caméra <add>+ { <add>+ const aspect = setScissorForElement(view2Elem); <add>+ <add>+ // adjuste la caméra <add>+ camera2.aspect = aspect; <add>+ camera2.updateProjectionMatrix(); <add>+ <add>+ // camera helper dans la 2e vue <add>+ cameraHelper.visible = true; <add>+ <add>+ scene.background.set(0x000040); <add>+ <add>+ renderer.render(scene, camera2); <add>+ } <add> <add>- renderer.render(scene, camera); <add> <add> requestAnimationFrame(render); <add> } <add> <add> requestAnimationFrame(render); <add>} <add>``` <add> <add>Le code ci-dessus définit la couleur d'arrière-plan de la scène lors du rendu de la deuxième vue en bleu foncé juste pour faciliter la distinction des deux vues. <add> <add>Nous pouvons également supprimer notre code `updateCamera` puisque nous mettons tout à jour dans la fonction `render`. <add> <add>```js <add>-function updateCamera() { <add>- camera.updateProjectionMatrix(); <add>-} <add> <add>const gui = new GUI(); <add>-gui.add(camera, 'fov', 1, 180).onChange(updateCamera); <add>+gui.add(camera, 'fov', 1, 180); <add>const minMaxGUIHelper = new MinMaxGUIHelper(camera, 'near', 'far', 0.1); <add>-gui.add(minMaxGUIHelper, 'min', 0.1, 50, 0.1).name('near').onChange(updateCamera); <add>-gui.add(minMaxGUIHelper, 'max', 0.1, 50, 0.1).name('far').onChange(updateCamera); <add>+gui.add(minMaxGUIHelper, 'min', 0.1, 50, 0.1).name('near'); <add>+gui.add(minMaxGUIHelper, 'max', 0.1, 50, 0.1).name('far'); <add>``` <add> <add>Et maintenant, vous pouvez utiliser une vue pour voir le frustum de l'autre. <add> <add>{{{example url="../threejs-cameras-perspective-2-scenes.html" }}} <add> <add>Sur la gauche, vous pouvez voir la vue d'origine et sur la droite, vous pouvez voir une vue montrant le frustum sur la gauche. Lorsque vous ajustez `near`, `far`, `fov` et déplacez la caméra avec la souris, vous pouvez voir que seul ce qui se trouve à l'intérieur du frustum montré à droite apparaît dans la scène à gauche. <add> <add>Ajustez `near` d'environ 20 et vous verrez facilement le devant des objets disparaître car ils ne sont plus dans le tronc. Ajustez `far` en dessous de 35 et vous commencerez à voir le plan de masse disparaître car il n'est plus dans le tronc. <add> <add>Cela soulève la question, pourquoi ne pas simplement définir `near` de 0,0000000001 et `far` de 100000000000000 ou quelque chose comme ça pour que vous puissiez tout voir? Parce que votre GPU n'a qu'une précision limitée pour décider si quelque chose est devant ou derrière quelque chose d'autre. Cette précision se répartit entre `near` et `far`. Pire, par défaut la précision au plus près de la caméra est précise tandis que celle la plus lointaine de la caméra est grossière. Les unités commencent par `near` et s'étendent lentement à mesure qu'elles s'approchent de `far`. <add> <add>En commençant par l'exemple du haut, modifions le code pour insérer 20 sphères d'affilée. <add> <add>```js <add>{ <add> const sphereRadius = 3; <add> const sphereWidthDivisions = 32; <add> const sphereHeightDivisions = 16; <add> const sphereGeo = new THREE.SphereGeometry(sphereRadius, sphereWidthDivisions, sphereHeightDivisions); <add> const numSpheres = 20; <add> for (let i = 0; i < numSpheres; ++i) { <add> const sphereMat = new THREE.MeshPhongMaterial(); <add> sphereMat.color.setHSL(i * .73, 1, 0.5); <add> const mesh = new THREE.Mesh(sphereGeo, sphereMat); <add> mesh.position.set(-sphereRadius - 1, sphereRadius + 2, i * sphereRadius * -2.2); <add> scene.add(mesh); <add> } <add>} <add>``` <add> <add>et définissons `near` à 0.00001 <add> <add>```js <add>const fov = 45; <add>const aspect = 2; // valeur par défaut <add>-const near = 0.1; <add>+const near = 0.00001; <add>const far = 100; <add>const camera = new THREE.PerspectiveCamera(fov, aspect, near, far); <add>``` <add> <add>Nous devons également modifier un peu le code de dat.GUI pour autoriser 0,00001 si la valeur est modifiée. <add> <add>```js <add>-gui.add(minMaxGUIHelper, 'min', 0.1, 50, 0.1).name('near').onChange(updateCamera); <add>+gui.add(minMaxGUIHelper, 'min', 0.00001, 50, 0.00001).name('near').onChange(updateCamera); <add>``` <add> <add>Que pensez-vous qu'il va se passer ? <add> <add>{{{example url="../threejs-cameras-z-fighting.html" }}} <add> <add>Ceci est un exemple de *z fighting* où le GPU de votre ordinateur n'a pas assez de précision pour décider quels pixels sont devant et quels pixels sont derrière. <add> <add>Juste au cas où le problème ne s'afficherait pas sur votre machine, voici ce que je vois sur la mienne. <add> <add><div class="threejs_center"><img src="resources/images/z-fighting.png" style="width: 570px;"></div> <add> <add>Une solution consiste à indiquer à Three.js d'utiliser une méthode différente pour calculer quels pixels sont devant et lesquels sont derrière. Nous pouvons le faire en activant `logarithmicDepthBuffer` lorsque nous créons le [`WebGLRenderer`](https://threejs.org/docs/#api/en/renderers/WebGLRenderer) <add> <add>```js <add>-const renderer = new THREE.WebGLRenderer({canvas}); <add>+const renderer = new THREE.WebGLRenderer({ <add>+ canvas, <add>+ logarithmicDepthBuffer: true, <add>+}); <add>``` <add> <add>et avec ça, ça devrait marcher. <add> <add>{{{example url="../threejs-cameras-logarithmic-depth-buffer.html" }}} <add> <add>Si cela n'a pas résolu le problème pour vous, vous avez rencontré une raison pour laquelle vous ne pouvez pas toujours utiliser cette solution. Cette raison est due au fait que seuls certains GPU le prennent en charge. En septembre 2018, presque aucun appareil mobile ne prenait en charge cette solution, contrairement à la plupart des ordinateurs de bureau. <add> <add>Une autre raison de ne pas choisir cette solution est qu'elle peut être nettement plus lente que la solution standard. <add> <add>Même avec cette solution, la résolution est encore limitée. Rendez `near` encore plus petit ou `far` plus grand et vous finirez par rencontrer les mêmes problèmes. <add> <add>Cela signifie que vous devez toujours faire un effort pour choisir un paramètre `near` et `far` qui correspond à votre cas d'utilisation. Placez `near` aussi loin que possible de la caméra et rien ne disparaîtra. Placez `far` aussi près que possible de la caméra et, de même, tout restera visible. Si vous essayez de dessiner une scène géante et de montrer en gros plan un visage de façon à voir ses cils, tandis qu'en arrière-plan il possible de voir les montagnes à 50 kilomètres de distance, vous devrez en trouver d'autres solutions créatives, nous-y reviendrons peut-être plus tard. Pour l'instant, sachez que vous devez prendre soin de choisir des valeurs proches et éloignées appropriées à vos besoins. <add> <add>La deuxième caméra la plus courante est l'[`OrthographicCamera`](https://threejs.org/docs/#api/en/cameras/OrthographicCamera). Plutôt que de définir un frustum, il spécifie une boîte avec les paramètres `left`, `right`, `top`, `bottom`, `near` et `far`. Comme elle projette une boîte, il n'y a pas de perspective. <add> <add>Changeons notre exemple précédent pour utiliser une `OrthographicCamera` dans la première vue. <add> <add>D'abord, paramétrons notre `OrthographicCamera`. <add> <add>```js <add>const left = -1; <add>const right = 1; <add>const top = 1; <add>const bottom = -1; <add>const near = 5; <add>const far = 50; <add>const camera = new THREE.OrthographicCamera(left, right, top, bottom, near, far); <add>camera.zoom = 0.2; <add>``` <add> <add>Définissons `left` and `bottom` à -1 et `right` et `top` à 1. On devrait obtenir une boîte de 2 unités de large et 2 unités de haut, mais nous allons ajuster `left` et `top` en fonction de l'aspect du rectangle sur lequel nous dessinons. Nous utiliserons la propriété `zoom` pour faciliter le réglage du nombre d'unités réellement affichées par la caméra. <add> <add>Ajoutons un nouveau paramètre à dat.GUI pour le `zoom`. <add> <add>```js <add>const gui = new GUI(); <add>+gui.add(camera, 'zoom', 0.01, 1, 0.01).listen(); <add>``` <add> <add>L'appel à `listen` dit à dat.GUI de surveiller les changements. Il faut faire cela parce que `OrbitControls` peut contrôler le zoom. Par exemple, la molette de défilement d'une souris zoomera via les `OrbitControls`. <add> <add>Enfin, nous avons juste besoin de changer la partie qui rend le côté gauche pour mettre à jour la `OrthographicCamera`. <add> <add>```js <add>{ <add> const aspect = setScissorForElement(view1Elem); <add> <add> // mettre à jour la caméra pour cet aspect <add>- camera.aspect = aspect; <add>+ camera.left = -aspect; <add>+ camera.right = aspect; <add> camera.updateProjectionMatrix(); <add> cameraHelper.update(); <add> <add> // ne pas dessiner le camera helper dans la vue d'origine <add> cameraHelper.visible = false; <add> <add> scene.background.set(0x000000); <add> renderer.render(scene, camera); <add>} <add>``` <add> <add>et maintenant vous pouvez voir une `OrthographicCamera` au boulot. <add> <add>{{{example url="../threejs-cameras-orthographic-2-scenes.html" }}} <add> <add>Une `OrthographicCamera` est souvent utilisée pour dessiner des objets en 2D. Il faut décider du nombre d'unités que la caméra doit afficher. Par exemple, si vous voulez qu'un pixel du canvas corresponde à une unité de l'appareil photo, vous pouvez faire quelque chose comme. <add> <add> <add>Pour mettre l'origine au centre et avoir 1 pixel = 1 unité three.js quelque chose comme <add> <add>```js <add>camera.left = -canvas.width / 2; <add>camera.right = canvas.width / 2; <add>camera.top = canvas.height / 2; <add>camera.bottom = -canvas.height / 2; <add>camera.near = -1; <add>camera.far = 1; <add>camera.zoom = 1; <add>``` <add> <add>Ou si nous voulions que l'origine soit en haut à gauche comme un canvas 2D, nous pourrions utiliser ceci <add> <add>```js <add>camera.left = 0; <add>camera.right = canvas.width; <add>camera.top = 0; <add>camera.bottom = canvas.height; <add>camera.near = -1; <add>camera.far = 1; <add>camera.zoom = 1; <add>``` <add> <add>Dans ce cas, le coin supérieur gauche serait à 0,0 tout comme un canvas 2D. <add> <add>Essayons! Commençons par installer la caméra. <add> <add>```js <add>const left = 0; <add>const right = 300; // taille par défaut <add>const top = 0; <add>const bottom = 150; // taille par défaut <add>const near = -1; <add>const far = 1; <add>const camera = new THREE.OrthographicCamera(left, right, top, bottom, near, far); <add>camera.zoom = 1; <add>``` <add> <add>Chargeons ensuite 6 textures et créons 6 plans, un pour chaque texture. Nous allons associer chaque plan à un `THREE.Object3D` pour faciliter le décalage du plan afin que son centre semble être dans son coin supérieur gauche. <add> <add>Pour travailler en local sur votre machine, vous aurez besoin d'une [configuration spécifique](threejs-setup.html). <add>Vous voudrez peut-être en savoir plus sur [l'utilisation des textures](threejs-textures.html). <add> <add>```js <add>const loader = new THREE.TextureLoader(); <add>const textures = [ <add> loader.load('resources/images/flower-1.jpg'), <add> loader.load('resources/images/flower-2.jpg'), <add> loader.load('resources/images/flower-3.jpg'), <add> loader.load('resources/images/flower-4.jpg'), <add> loader.load('resources/images/flower-5.jpg'), <add> loader.load('resources/images/flower-6.jpg'), <add>]; <add>const planeSize = 256; <add>const planeGeo = new THREE.PlaneGeometry(planeSize, planeSize); <add>const planes = textures.map((texture) => { <add> const planePivot = new THREE.Object3D(); <add> scene.add(planePivot); <add> texture.magFilter = THREE.NearestFilter; <add> const planeMat = new THREE.MeshBasicMaterial({ <add> map: texture, <add> side: THREE.DoubleSide, <add> }); <add> const mesh = new THREE.Mesh(planeGeo, planeMat); <add> planePivot.add(mesh); <add> // déplacer le plan pour que le coin supérieur gauche soit l'origine <add> mesh.position.set(planeSize / 2, planeSize / 2, 0); <add> return planePivot; <add>}); <add>``` <add> <add>et nous devons mettre à jour la caméra si la taille de la toile change. <add> <add>```js <add>function render() { <add> <add> if (resizeRendererToDisplaySize(renderer)) { <add> camera.right = canvas.width; <add> camera.bottom = canvas.height; <add> camera.updateProjectionMatrix(); <add> } <add> <add> ... <add>``` <add> <add>`planes` est un tableau de `THREE.Mesh`. <add>Déplaçons-les en fonction du temps. <add> <add>```js <add>function render(time) { <add> time *= 0.001; // convertir en secondes; <add> <add> ... <add> <add> const distAcross = Math.max(20, canvas.width - planeSize); <add> const distDown = Math.max(20, canvas.height - planeSize); <add> <add> // distance totale à parcourir <add> const xRange = distAcross * 2; <add> const yRange = distDown * 2; <add> const speed = 180; <add> <add> planes.forEach((plane, ndx) => { <add> // calculer un temps unique pour chaque plan <add> const t = time * speed + ndx * 300; <add> <add> // définir une valeur entre 0 et une plage <add> const xt = t % xRange; <add> const yt = t % yRange; <add> <add> // définit notre position en avant si 0 à la moitié de la plage <add> // et vers l'arrière si la moitié de la plage à la plage <add> const x = xt < distAcross ? xt : xRange - xt; <add> const y = yt < distDown ? yt : yRange - yt; <add> <add> plane.position.set(x, y, 0); <add> }); <add> <add> renderer.render(scene, camera); <add>``` <add> <add>Et vous pouvez voir les images rebondir parfaitement sur les bords de la toile en utilisant les mathématiques des pixels, tout comme une toile 2D. <add> <add>{{{example url="../threejs-cameras-orthographic-canvas-top-left-origin.html" }}} <add> <add>Une autre utilisation courante d'une caméra orthographique est de dessiner les vues haut, bas, gauche, droite, avant et arrière d'un programme de modélisation 3D ou d'un éditeur de moteur de jeu. <add> <add><div class="threejs_center"><img src="resources/images/quad-viewport.png" style="width: 574px;"></div> <add> <add>Dans la capture d'écran ci-dessus, vous pouvez voir que 1 vue est une vue en perspective et 3 vues sont des vues orthogonales. <add> <add>C'est la base des caméras. Nous aborderons quelques façons courantes de déplacer les caméras dans d'autres articles. Pour l'instant passons aux [ombres](threejs-shadows.html). <add> <add><canvas id="c"></canvas> <add><script type="module" src="resources/threejs-cameras.js"></script>
1
PHP
PHP
bootstrap the application when testing
f66122149a5d9b3a685f48f33302279b222ab309
<ide><path>tests/TestCase.php <ide> class TestCase extends Illuminate\Foundation\Testing\TestCase { <ide> */ <ide> public function createApplication() <ide> { <del> return require __DIR__.'/../bootstrap/app.php'; <add> $app = require __DIR__.'/../bootstrap/app.php'; <add> <add> $app->make('Illuminate\Contracts\Http\Kernel')->bootstrap(); <add> <add> return $app; <ide> } <ide> <ide> }
1
Python
Python
fix vcloud driver so it works with 2.5
eef29109f995de68ee3494e9e68949e7b6616d01
<ide><path>libcloud/compute/drivers/vcloud.py <ide> from libcloud.utils.py3 import httplib <ide> from libcloud.utils.py3 import urlparse <ide> from libcloud.utils.py3 import b <add>from libcloud.utils.py3 import next <ide> <ide> urlparse = urlparse.urlparse <ide>
1
PHP
PHP
list command
d13803151750232417c5ad2e749dd440e6f3cfce
<ide><path>src/Illuminate/Foundation/Console/RouteListCommand.php <ide> class RouteListCommand extends Command <ide> protected $description = 'List all registered routes'; <ide> <ide> /** <del> * An array of all the registered routes. <add> * The router instance. <ide> * <del> * @var \Illuminate\Routing\RouteCollection <add> * @var \Illuminate\Routing\Router <ide> */ <del> protected $routes; <add> protected $router; <ide> <ide> /** <ide> * The table headers for the command.
1
Javascript
Javascript
remove excessive instrumentation
50cfa59755418192c7f17a2564c7bea72c66811a
<ide><path>packages/ember-handlebars/lib/helpers/binding.js <ide> function bind(property, options, preserveContext, shouldDisplay, valueNormalizer <ide> fn = options.fn, <ide> inverse = options.inverse, <ide> view = data.view, <del> instrumentName = view.instrumentName, <ide> currentContext = this, <ide> pathRoot, path, normalized, <ide> observer; <ide> function bind(property, options, preserveContext, shouldDisplay, valueNormalizer <ide> <ide> template(context, { data: options.data }); <ide> } else { <del> var bindView = Ember.instrument('bind-view.' + instrumentName, <del> { object: view.toString() }, <del> function() { <del> // Create the view that will wrap the output of this template/property <del> // and add it to the nearest view's childViews array. <del> // See the documentation of Ember._HandlebarsBoundView for more. <del> var bindView = view.createChildView(Ember._HandlebarsBoundView, { <del> preserveContext: preserveContext, <del> shouldDisplayFunc: shouldDisplay, <del> valueNormalizerFunc: valueNormalizer, <del> displayTemplate: fn, <del> inverseTemplate: inverse, <del> path: path, <del> pathRoot: pathRoot, <del> previousContext: currentContext, <del> isEscaped: !options.hash.unescaped, <del> templateData: options.data <del> }); <del> <del> view.appendChild(bindView); <del> return bindView; <del> }); <add> // Create the view that will wrap the output of this template/property <add> // and add it to the nearest view's childViews array. <add> // See the documentation of Ember._HandlebarsBoundView for more. <add> var bindView = view.createChildView(Ember._HandlebarsBoundView, { <add> preserveContext: preserveContext, <add> shouldDisplayFunc: shouldDisplay, <add> valueNormalizerFunc: valueNormalizer, <add> displayTemplate: fn, <add> inverseTemplate: inverse, <add> path: path, <add> pathRoot: pathRoot, <add> previousContext: currentContext, <add> isEscaped: !options.hash.unescaped, <add> templateData: options.data <add> }); <add> <add> view.appendChild(bindView); <ide> <ide> /** @private */ <ide> observer = function() { <ide> function bind(property, options, preserveContext, shouldDisplay, valueNormalizer <ide> function simpleBind(property, options) { <ide> var data = options.data, <ide> view = data.view, <del> instrumentName = view.instrumentName, <ide> currentContext = this, <ide> pathRoot, path, normalized, <ide> observer; <ide> function simpleBind(property, options) { <ide> if (result === null || result === undefined) { result = ""; } <ide> data.buffer.push(result); <ide> } else { <del> var bindView = Ember.instrument('simple-bind-view.' + instrumentName, <del> { object: view.toString() }, <del> function() { <del> var bindView = new Ember._SimpleHandlebarsView( <del> path, pathRoot, !options.hash.unescaped, options.data <del> ); <del> <del> bindView._parentView = view; <del> view.appendChild(bindView); <del> return bindView; <del> }); <add> var bindView = new Ember._SimpleHandlebarsView( <add> path, pathRoot, !options.hash.unescaped, options.data <add> ); <add> <add> bindView._parentView = view; <add> view.appendChild(bindView); <ide> <ide> observer = function() { <ide> Ember.run.scheduleOnce('render', bindView, 'rerender'); <ide> EmberHandlebars.registerHelper('bindAttr', function(options) { <ide> <ide> Ember.assert("You must specify at least one hash argument to bindAttr", !!Ember.keys(attrs).length); <ide> <del> var view = options.data.view, instrumentName = view.instrumentName; <add> var view = options.data.view; <ide> var ret = []; <ide> var ctx = this; <ide> <ide> EmberHandlebars.registerHelper('bindAttr', function(options) { <ide> // Handle classes differently, as we can bind multiple classes <ide> var classBindings = attrs['class']; <ide> if (classBindings !== null && classBindings !== undefined) { <del> var classResults = Ember.instrument('class-bindings.' + instrumentName, <del> { object: view.toString() }, <del> function() { <del> return EmberHandlebars.bindClasses(this, classBindings, view, dataId, options); <del> }, this); <add> var classResults = EmberHandlebars.bindClasses(this, classBindings, view, dataId, options); <ide> <ide> ret.push('class="' + Handlebars.Utils.escapeExpression(classResults.join(' ')) + '"'); <ide> delete attrs['class']; <ide><path>packages/ember-handlebars/lib/helpers/collection.js <ide> Ember.Handlebars.registerHelper('collection', function(path, options) { <ide> var data = options.data; <ide> var inverse = options.inverse; <ide> var view = options.data.view; <del> var instrumentName = view.instrumentName; <ide> <ide> // If passed a path string, convert that into an object. <ide> // Otherwise, just default to the standard class. <ide> Ember.Handlebars.registerHelper('collection', function(path, options) { <ide> <ide> var viewString = view.toString(); <ide> <del> Ember.instrument('collection-setup.' + instrumentName, <del> { object: viewString }, <del> function() { <del> var viewOptions = Ember.Handlebars.ViewHelper.propertiesFromHTMLOptions({ data: data, hash: itemHash }, this); <del> viewOptions._anonymous = true; <del> hash.itemViewClass = itemViewClass.extend(viewOptions); <del> }); <add> var viewOptions = Ember.Handlebars.ViewHelper.propertiesFromHTMLOptions({ data: data, hash: itemHash }, this); <add> hash.itemViewClass = itemViewClass.extend(viewOptions); <ide> <del> return Ember.instrument('collection-view.' + instrumentName, <del> { object: viewString }, <del> function() { <del> return Ember.Handlebars.helpers.view.call(this, collectionClass, options); <del> }, this); <add> return Ember.Handlebars.helpers.view.call(this, collectionClass, options); <ide> }); <ide> <ide><path>packages/ember-handlebars/lib/views/handlebars_bound_view.js <ide> SimpleHandlebarsView.prototype = { <ide> return result; <ide> }, <ide> <del> renderToBuffer: function(parentBuffer) { <del> var name = 'render-to-buffer.simpleHandlebars', <del> details = { object: '<Ember._SimpleHandlebarsView>' }; <del> <del> return Ember.instrument(name, details, function() { <del> return this._renderToBuffer(parentBuffer); <del> }, this); <del> }, <del> <del> _renderToBuffer: function(buffer) { <add> renderToBuffer: function(buffer) { <ide> var string = ''; <ide> <ide> string += this.morph.startTag(); <ide><path>packages/ember-views/lib/views/view.js <ide> Ember.CoreView = Ember.Object.extend(Ember.Evented, { <ide> be used. <ide> */ <ide> renderToBuffer: function(parentBuffer, bufferOperation) { <del> var name = 'render-to-buffer.' + this.instrumentName, <add> var name = 'render.' + this.instrumentName, <ide> details = {}; <ide> <ide> this.instrumentDetails(details); <ide> Ember.View = Ember.CoreView.extend( <ide> Ember.assert('template must be a function. Did you mean to call Ember.Handlebars.compile("...") or specify templateName instead?', typeof template === 'function'); <ide> // The template should write directly to the render buffer instead <ide> // of returning a string. <del> Ember.instrument('template.' + this.instrumentName, <del> { object: this.toString() }, <del> function() { output = template(context, { data: data }); }); <add> output = template(context, { data: data }); <ide> <ide> // If the template returned a string instead of writing to the buffer, <ide> // push the string onto the buffer.
4
Ruby
Ruby
remove with_git_env method
19e61355b38b8ba96db0ca71849bb536af0490bf
<ide><path>Library/Homebrew/dev-cmd/tests.rb <ide> def tests <ide> %w[AUTHOR COMMITTER].each do |role| <ide> ENV["GIT_#{role}_NAME"] = "brew tests" <ide> ENV["GIT_#{role}_EMAIL"] = "brew-tests@localhost" <add> ENV["GIT_#{role}_DATE"] = "Sun Jan 22 19:59:13 2017 +0000" <ide> end <ide> <ide> Homebrew.install_gem_setup_path! "bundler" <ide><path>Library/Homebrew/test/download_strategies_test.rb <ide> def git_commit_all <ide> end <ide> <ide> def setup_git_repo <del> using_git_env do <del> @cached_location.cd do <del> shutup do <del> system "git", "init" <del> system "git", "remote", "add", "origin", "https://github.com/Homebrew/homebrew-foo" <del> end <del> touch "README" <del> git_commit_all <add> @cached_location.cd do <add> shutup do <add> system "git", "init" <add> system "git", "remote", "add", "origin", "https://github.com/Homebrew/homebrew-foo" <ide> end <add> touch "README" <add> git_commit_all <ide> end <ide> end <ide> <ide> def test_source_modified_time <ide> <ide> def test_last_commit <ide> setup_git_repo <del> using_git_env do <del> @cached_location.cd do <del> touch "LICENSE" <del> git_commit_all <del> end <add> @cached_location.cd do <add> touch "LICENSE" <add> git_commit_all <ide> end <ide> assert_equal "f68266e", @strategy.last_commit <ide> end <ide> def test_fetch_last_commit <ide> resource.instance_variable_set(:@version, Version.create("HEAD")) <ide> @strategy = GitDownloadStrategy.new("baz", resource) <ide> <del> using_git_env do <del> remote_repo.cd do <del> shutup do <del> system "git", "init" <del> system "git", "remote", "add", "origin", "https://github.com/Homebrew/homebrew-foo" <del> end <del> touch "README" <del> git_commit_all <del> touch "LICENSE" <del> git_commit_all <add> remote_repo.cd do <add> shutup do <add> system "git", "init" <add> system "git", "remote", "add", "origin", "https://github.com/Homebrew/homebrew-foo" <ide> end <add> touch "README" <add> git_commit_all <add> touch "LICENSE" <add> git_commit_all <ide> end <ide> <ide> @strategy.shutup! <ide><path>Library/Homebrew/test/formula_test.rb <ide> def test_update_head_version <ide> cached_location = f.head.downloader.cached_location <ide> cached_location.mkpath <ide> <del> using_git_env do <del> cached_location.cd do <del> FileUtils.touch "LICENSE" <del> shutup do <del> system "git", "init" <del> system "git", "add", "--all" <del> system "git", "commit", "-m", "Initial commit" <del> end <add> cached_location.cd do <add> FileUtils.touch "LICENSE" <add> shutup do <add> system "git", "init" <add> system "git", "add", "--all" <add> system "git", "commit", "-m", "Initial commit" <ide> end <ide> end <ide> <ide> def test_outdated_fetch_head <ide> head "file://#{testball_repo}", using: :git <ide> end <ide> <del> using_git_env do <del> testball_repo.cd do <del> FileUtils.touch "LICENSE" <del> shutup do <del> system "git", "init" <del> system "git", "add", "--all" <del> system "git", "commit", "-m", "Initial commit" <del> end <add> testball_repo.cd do <add> FileUtils.touch "LICENSE" <add> shutup do <add> system "git", "init" <add> system "git", "add", "--all" <add> system "git", "commit", "-m", "Initial commit" <ide> end <ide> end <ide> <ide><path>Library/Homebrew/test/install_test.rb <ide> def test_install_head_installed <ide> repo_path = HOMEBREW_CACHE.join("repo") <ide> repo_path.join("bin").mkpath <ide> <del> using_git_env do <del> repo_path.cd do <del> shutup do <del> system "git", "init" <del> system "git", "remote", "add", "origin", "https://github.com/Homebrew/homebrew-foo" <del> FileUtils.touch "bin/something.bin" <del> FileUtils.touch "README" <del> system "git", "add", "--all" <del> system "git", "commit", "-m", "Initial repo commit" <del> end <add> repo_path.cd do <add> shutup do <add> system "git", "init" <add> system "git", "remote", "add", "origin", "https://github.com/Homebrew/homebrew-foo" <add> FileUtils.touch "bin/something.bin" <add> FileUtils.touch "README" <add> system "git", "add", "--all" <add> system "git", "commit", "-m", "Initial repo commit" <ide> end <ide> end <ide> <ide><path>Library/Homebrew/test/support/helper/env.rb <ide> def with_environment(partial_env) <ide> ensure <ide> restore_env old <ide> end <del> <del> def using_git_env <del> git_env = ["AUTHOR", "COMMITTER"].each_with_object({}) do |role, env| <del> env["GIT_#{role}_NAME"] = "brew tests" <del> env["GIT_#{role}_EMAIL"] = "brew-tests@localhost" <del> env["GIT_#{role}_DATE"] = "Sun Jan 22 19:59:13 2017 +0000" <del> end <del> <del> with_environment(git_env) do <del> yield <del> end <del> end <ide> end <ide> end <ide> end <ide><path>Library/Homebrew/test/tap_test.rb <ide> class Foo < Formula <ide> end <ide> <ide> def setup_git_repo <del> using_git_env do <del> @path.cd do <del> shutup do <del> system "git", "init" <del> system "git", "remote", "add", "origin", "https://github.com/Homebrew/homebrew-foo" <del> system "git", "add", "--all" <del> system "git", "commit", "-m", "init" <del> end <add> @path.cd do <add> shutup do <add> system "git", "init" <add> system "git", "remote", "add", "origin", "https://github.com/Homebrew/homebrew-foo" <add> system "git", "add", "--all" <add> system "git", "commit", "-m", "init" <ide> end <ide> end <ide> end
6
Python
Python
add new recfunctions to __all__
e28cd9e215d3cd8976c37f97c12d2aea971adb27
<ide><path>numpy/lib/recfunctions.py <ide> <ide> <ide> __all__ = [ <del> 'append_fields', 'drop_fields', 'find_duplicates', <del> 'get_fieldstructure', 'join_by', 'merge_arrays', <del> 'rec_append_fields', 'rec_drop_fields', 'rec_join', <del> 'recursive_fill_fields', 'rename_fields', 'stack_arrays', <add> 'append_fields', 'apply_along_fields', 'assign_fields_by_name', <add> 'drop_fields', 'find_duplicates', 'get_fieldstructure', <add> 'join_by', 'merge_arrays', 'rec_append_fields', <add> 'rec_drop_fields', 'rec_join', 'recursive_fill_fields', <add> 'rename_fields', 'require_fields', 'stack_arrays', <add> 'structured_to_unstructured', <ide> ] <ide> <ide> <ide> def structured_to_unstructured(arr, dtype=None, copy=False, casting='unsafe'): <ide> Examples <ide> -------- <ide> <add> >>> from numpy.lib import recfunctions as rfn <ide> >>> a = np.zeros(4, dtype=[('a', 'i4'), ('b', 'f4,u2'), ('c', 'f4', 2)]) <ide> >>> a <ide> array([(0, (0., 0), [0., 0.]), (0, (0., 0), [0., 0.]), <ide> (0, (0., 0), [0., 0.]), (0, (0., 0), [0., 0.])], <ide> dtype=[('a', '<i4'), ('b', [('f0', '<f4'), ('f1', '<u2')]), ('c', '<f4', (2,))]) <del> >>> structured_to_unstructured(arr) <add> >>> rfn.structured_to_unstructured(a) <ide> array([[0., 0., 0., 0., 0.], <ide> [0., 0., 0., 0., 0.], <ide> [0., 0., 0., 0., 0.], <ide> [0., 0., 0., 0., 0.]]) <ide> <ide> >>> b = np.array([(1, 2, 5), (4, 5, 7), (7, 8 ,11), (10, 11, 12)], <ide> ... dtype=[('x', 'i4'), ('y', 'f4'), ('z', 'f8')]) <del> >>> np.mean(structured_to_unstructured(b[['x', 'z']]), axis=-1) <add> >>> np.mean(rfn.structured_to_unstructured(b[['x', 'z']]), axis=-1) <ide> array([ 3. , 5.5, 9. , 11. ]) <ide> <ide> """ <ide> def apply_along_fields(func, arr): <ide> Examples <ide> -------- <ide> <add> >>> from numpy.lib import recfunctions as rfn <ide> >>> b = np.array([(1, 2, 5), (4, 5, 7), (7, 8 ,11), (10, 11, 12)], <ide> ... dtype=[('x', 'i4'), ('y', 'f4'), ('z', 'f8')]) <del> >>> apply_along_fields(np.mean, b) <add> >>> rfn.apply_along_fields(np.mean, b) <ide> array([ 2.66666667, 5.33333333, 8.66666667, 11. ]) <del> >>> apply_along_fields(np.mean, b[['x', 'z']]) <add> >>> rfn.apply_along_fields(np.mean, b[['x', 'z']]) <ide> array([ 3. , 5.5, 9. , 11. ]) <ide> <ide> """ <ide> def require_fields(array, required_dtype): <ide> Examples <ide> -------- <ide> <add> >>> from numpy.lib import recfunctions as rfn <ide> >>> a = np.ones(4, dtype=[('a', 'i4'), ('b', 'f8'), ('c', 'u1')]) <del> >>> require_fields(a, [('b', 'f4'), ('c', 'u1')]) <add> >>> rfn.require_fields(a, [('b', 'f4'), ('c', 'u1')]) <ide> array([(1., 1), (1., 1), (1., 1), (1., 1)], <ide> dtype=[('b', '<f4'), ('c', 'u1')]) <del> >>> require_fields(a, [('b', 'f4'), ('newf', 'u1')]) <add> >>> rfn.require_fields(a, [('b', 'f4'), ('newf', 'u1')]) <ide> array([(1., 0), (1., 0), (1., 0), (1., 0)], <ide> dtype=[('b', '<f4'), ('newf', 'u1')]) <del> <add> <ide> """ <ide> out = np.empty(array.shape, dtype=required_dtype) <ide> assign_fields_by_name(out, array)
1
PHP
PHP
add basic tests for cleancopy()
8887c4aa280a24cbd8d6afd427f41493b14ceeac
<ide><path>tests/TestCase/ORM/QueryTest.php <ide> public function testAutoFieldsCount() { <ide> $this->assertEquals(3, $result); <ide> } <ide> <add>/** <add> * test that cleanCopy makes a cleaned up clone. <add> * <add> * @return void <add> */ <add> public function testCleanCopy() { <add> $table = TableRegistry::get('Articles'); <add> $table->hasMany('Comments'); <add> <add> $query = $table->find(); <add> $query->offset(10) <add> ->limit(1) <add> ->order(['Articles.id' => 'DESC']) <add> ->contain(['Comments']); <add> $copy = $query->cleanCopy(); <add> <add> $this->assertNotSame($copy, $query); <add> $this->assertNull($copy->clause('offset')); <add> $this->assertNull($copy->clause('limit')); <add> $this->assertNull($copy->clause('order')); <add> } <add> <ide> }
1
Go
Go
fix the compare of restart policy
e721ed9b5319e8e7c1daf87c34690f8a4e62c9e3
<ide><path>daemon/monitor.go <ide> func (m *containerMonitor) shouldRestart(exitCode int) bool { <ide> return true <ide> case "on-failure": <ide> // the default value of 0 for MaximumRetryCount means that we will not enforce a maximum count <del> if max := m.restartPolicy.MaximumRetryCount; max != 0 && m.failureCount >= max { <add> if max := m.restartPolicy.MaximumRetryCount; max != 0 && m.failureCount > max { <ide> log.Debugf("stopping restart of container %s because maximum failure could of %d has been reached", <ide> utils.TruncateID(m.container.ID), max) <ide> return false
1
Python
Python
fix mypy issues in ``tests/executors``
e3c6fc51257d6364e4ebf3ade5d0ff4d71eaf3fb
<ide><path>airflow/executors/base_executor.py <ide> class BaseExecutor(LoggingMixin): <ide> ``0`` for infinity <ide> """ <ide> <del> job_id: Optional[int] = None <add> job_id: Optional[str] = None <ide> <ide> def __init__(self, parallelism: int = PARALLELISM): <ide> super().__init__()
1
Javascript
Javascript
remove unreachable code
524dd469cefb63c9963a9c7a99197df857888f1a
<ide><path>lib/buffer.js <ide> Buffer.prototype.write = function write(string, offset, length, encoding) { <ide> <ide> // Buffer#write(string, offset[, length][, encoding]) <ide> } else { <del> if (offset === undefined) { <del> offset = 0; <del> } else { <del> validateInt32(offset, 'offset', 0, this.length); <del> } <add> validateInt32(offset, 'offset', 0, this.length); <ide> <ide> const remaining = this.length - offset; <ide>
1
Javascript
Javascript
improve isnumeric logic and test coverage
7103d8ef47e04a4cf373abee0e8bfa9062fd616f
<ide><path>src/core.js <ide> jQuery.extend( { <ide> // that can be coerced to finite numbers (gh-2662) <ide> var type = jQuery.type( obj ); <ide> return ( type === "number" || type === "string" ) && <del> ( obj - parseFloat( obj ) + 1 ) >= 0; <add> <add> // parseFloat NaNs numeric-cast false positives ("") <add> // ...but misinterprets leading-number strings, particularly hex literals ("0x...") <add> // subtraction forces infinities to NaN <add> !isNaN( obj - parseFloat( obj ) ); <ide> }, <ide> <ide> isPlainObject: function( obj ) { <ide><path>test/unit/core.js <ide> QUnit.test( "isFunction", function( assert ) { <ide> } ); <ide> <ide> QUnit.test( "isNumeric", function( assert ) { <del> assert.expect( 38 ); <add> assert.expect( 41 ); <ide> <ide> var t = jQuery.isNumeric, <ide> ToString = function( value ) { <ide> QUnit.test( "isNumeric", function( assert ) { <ide> assert.ok( t( -16 ), "Negative integer number" ); <ide> assert.ok( t( 0 ), "Zero integer number" ); <ide> assert.ok( t( 32 ), "Positive integer number" ); <add> <add> if ( +"0b1" === 1 ) { <add> assert.ok( t( "0b111110" ), "Binary integer literal string" ); // jshint ignore:line <add> } else { <add> assert.ok( true, "Browser does not support binary integer literal" ); <add> } <add> <ide> assert.ok( t( "040" ), "Octal integer literal string" ); <add> <ide> assert.ok( t( "0xFF" ), "Hexadecimal integer literal string" ); <add> <add> if ( +"0b1" === 1 ) { <add> assert.ok( t( 0b111110 ), "Binary integer literal" ); // jshint ignore:line <add> } else { <add> assert.ok( true, "Browser does not support binary integer literal" ); <add> } <add> <add> if ( +"0o1" === 1 ) { <add> assert.ok( t( 0o76 ), "Octal integer literal" ); // jshint ignore:line <add> } else { <add> assert.ok( true, "Browser does not support octal integer literal" ); <add> } <add> <ide> assert.ok( t( 0xFFF ), "Hexadecimal integer literal" ); <ide> assert.ok( t( "-1.6" ), "Negative floating point string" ); <ide> assert.ok( t( "4.536" ), "Positive floating point string" ); <ide> QUnit.test( "isNumeric", function( assert ) { <ide> assert.ok( t( 8e5 ), "Exponential notation" ); <ide> assert.ok( t( "123e-2" ), "Exponential notation string" ); <ide> <del> assert.equal( t( new ToString( "42" ) ), false, "Custom .toString returning number" ); <add> assert.equal( t( new ToString( "42" ) ), false, "Only limited to strings and numbers" ); <ide> assert.equal( t( "" ), false, "Empty string" ); <ide> assert.equal( t( " " ), false, "Whitespace characters string" ); <ide> assert.equal( t( "\t\t" ), false, "Tab characters string" );
2
Java
Java
improve documentation for tx support in the tcf
b16e6cc44e2fbc92ad7c648b052e4f11d2b3f674
<ide><path>spring-test/src/main/java/org/springframework/test/context/transaction/TestTransaction.java <ide> * {@code TestTransaction} provides a collection of static utility methods for <ide> * programmatic interaction with <em>test-managed transactions</em>. <ide> * <del> * <p>Test-managed transactions are transactions that are managed by the <em>Spring TestContext Framework</em>. <add> * <p>Test-managed transactions are transactions that are managed by the <add> * <em>Spring TestContext Framework</em>. <ide> * <ide> * <p>Support for {@code TestTransaction} is automatically available whenever <ide> * the {@link TransactionalTestExecutionListener} is enabled. Note that the <ide><path>spring-test/src/main/java/org/springframework/test/context/transaction/TransactionalTestExecutionListener.java <ide> import org.springframework.beans.BeansException; <ide> import org.springframework.beans.factory.BeanFactory; <ide> import org.springframework.beans.factory.annotation.BeanFactoryAnnotationUtils; <del>import org.springframework.context.ApplicationContext; <ide> import org.springframework.core.annotation.AnnotatedElementUtils; <ide> import org.springframework.core.annotation.AnnotationAttributes; <ide> import org.springframework.test.annotation.Rollback; <ide> import org.springframework.transaction.TransactionDefinition; <ide> import org.springframework.transaction.TransactionStatus; <ide> import org.springframework.transaction.annotation.AnnotationTransactionAttributeSource; <del>import org.springframework.transaction.annotation.TransactionManagementConfigurer; <ide> import org.springframework.transaction.interceptor.TransactionAttribute; <ide> import org.springframework.transaction.interceptor.TransactionAttributeSource; <ide> import org.springframework.util.Assert; <ide> <ide> /** <ide> * {@code TestExecutionListener} that provides support for executing tests <del> * within transactions by honoring the <add> * within <em>test-managed transactions</em> by honoring Spring's <ide> * {@link org.springframework.transaction.annotation.Transactional @Transactional} <del> * annotation. Expects a {@link PlatformTransactionManager} bean to be defined in the <del> * Spring {@link ApplicationContext} for the test. <add> * annotation. <ide> * <del> * <p>Changes to the database during a test that is run with {@code @Transactional} <del> * will be run within a transaction that will, by default, be automatically <del> * <em>rolled back</em> after completion of the test. Test methods that are <add> * <h3>Test-managed Transactions</h3> <add> * <p><em>Test-managed transactions</em> are transactions that are managed <add> * by this listener. Such transactions should not be confused with <add> * <em>Spring-managed transactions</em> (i.e., those managed directly <add> * by Spring within the {@code ApplicationContext} loaded for tests) or <add> * <em>application-managed transactions</em> (i.e., those managed <add> * programmatically within application code that is invoked via tests). <add> * Spring-managed transactions and application-managed transactions will <add> * typically participate in test-managed transactions; however, caution <add> * should be taken if Spring-managed transactions or application-managed <add> * transactions are configured with any propagation type other than <add> * {@link org.springframework.transaction.annotation.Propagation#REQUIRED REQUIRED} <add> * or {@link org.springframework.transaction.annotation.Propagation#SUPPORTS SUPPORTS}. <add> * <add> * <h3>Enabling and Disabling Transactions</h3> <add> * <p>Annotating a test method with {@code @Transactional} causes the test <add> * to be run within a transaction that will, by default, be automatically <add> * <em>rolled back</em> after completion of the test. If a test class is <add> * annotated with {@code @Transactional}, each test method within that class <add> * hierarchy will be run within a transaction. Test methods that are <ide> * <em>not</em> annotated with {@code @Transactional} (at the class or method <ide> * level) will not be run within a transaction. Furthermore, test methods <ide> * that <em>are</em> annotated with {@code @Transactional} but have the <ide> * {@link org.springframework.transaction.annotation.Propagation#NOT_SUPPORTED NOT_SUPPORTED} <ide> * will not be run within a transaction. <ide> * <del> * <p>Transactional commit and rollback behavior can be configured via the <del> * class-level {@link TransactionConfiguration @TransactionConfiguration} and <del> * method-level {@link Rollback @Rollback} annotations. <add> * <h3>Declarative Rollback and Commit Behavior</h3> <add> * <p>By default, test transactions will be automatically <em>rolled back</em> <add> * after completion of the test; however, transactional commit and rollback <add> * behavior can be configured declaratively via the class-level <add> * {@link TransactionConfiguration @TransactionConfiguration} and method-level <add> * {@link Rollback @Rollback} annotations. <ide> * <del> * <p>In case there are multiple instances of {@code PlatformTransactionManager} <del> * within the test's {@code ApplicationContext}, {@code @TransactionConfiguration} <del> * supports configuring the bean name of the {@code PlatformTransactionManager} <del> * that should be used to drive transactions. Alternatively, a <em>qualifier</em> <del> * may be declared via {@link Transactional#value} or <del> * {@link TransactionManagementConfigurer} can be implemented by an <del> * {@link org.springframework.context.annotation.Configuration @Configuration} <del> * class. See {@link TestContextTransactionUtils#retrieveTransactionManager()} <del> * for details on the algorithm used to look up a transaction manager in <del> * the test's {@code ApplicationContext}. <add> * <h3>Programmatic Transaction Management</h3> <add> * <p>As of Spring Framework 4.1, it is possible to interact with test-managed <add> * transactions programmatically via the static methods in {@link TestTransaction}. <add> * {@code TestTransaction} may be used within <em>test</em> methods, <add> * <em>before</em> methods, and <em>after</em> methods. <ide> * <add> * <h3>Executing Code outside of a Transaction</h3> <ide> * <p>When executing transactional tests, it is sometimes useful to be able to <ide> * execute certain <em>set up</em> or <em>tear down</em> code outside of a <ide> * transaction. {@code TransactionalTestExecutionListener} provides such <ide> * support for methods annotated with <del> * {@link BeforeTransaction @BeforeTransaction} and <add> * {@link BeforeTransaction @BeforeTransaction} or <ide> * {@link AfterTransaction @AfterTransaction}. <ide> * <add> * <h3>Configuring a Transaction Manager</h3> <add> * <p>{@code TransactionalTestExecutionListener} expects a <add> * {@link PlatformTransactionManager} bean to be defined in the Spring <add> * {@code ApplicationContext} for the test. In case there are multiple <add> * instances of {@code PlatformTransactionManager} within the test's <add> * {@code ApplicationContext}, {@code @TransactionConfiguration} supports <add> * configuring the bean name of the {@code PlatformTransactionManager} that <add> * should be used to drive transactions. Alternatively, a <em>qualifier</em> <add> * may be declared via <add> * {@link org.springframework.transaction.annotation.Transactional#value @Transactional("myQualifier")}, or <add> * {@link org.springframework.transaction.annotation.TransactionManagementConfigurer TransactionManagementConfigurer} <add> * can be implemented by an <add> * {@link org.springframework.context.annotation.Configuration @Configuration} <add> * class. See {@link TestContextTransactionUtils#retrieveTransactionManager()} <add> * for details on the algorithm used to look up a transaction manager in <add> * the test's {@code ApplicationContext}. <add> * <ide> * @author Sam Brannen <ide> * @author Juergen Hoeller <ide> * @since 2.5 <ide> * @see TransactionConfiguration <del> * @see TransactionManagementConfigurer <add> * @see org.springframework.transaction.annotation.TransactionManagementConfigurer <ide> * @see org.springframework.transaction.annotation.Transactional <ide> * @see org.springframework.test.annotation.Rollback <ide> * @see BeforeTransaction
2
Java
Java
add tests for spr-12738
b94c6fdf7ae1305516166db710070acf4f967f21
<ide><path>spring-core/src/test/java/org/springframework/core/annotation/AnnotatedElementUtilsTests.java <ide> import java.lang.annotation.Retention; <ide> import java.lang.annotation.RetentionPolicy; <ide> import java.lang.annotation.Target; <add>import java.lang.reflect.Method; <ide> import java.util.Arrays; <ide> <add>import org.junit.Ignore; <ide> import org.junit.Test; <ide> <ide> import org.springframework.util.MultiValueMap; <ide> public void getAnnotationAttributesFavorsInheritedComposedAnnotationsOverMoreLoc <ide> attributes.getBoolean("readOnly")); <ide> } <ide> <add> // SPR-12738 <add> <add> @Test <add> public void getAnnotationAttributesInheritedFromInterface() { <add> String name = Transactional.class.getName(); <add> AnnotationAttributes attributes = getAnnotationAttributes(ConcreteClassWithInheritedAnnotation.class, name); <add>// assertNotNull(attributes); <add> } <add> <add> // SPR-12738 <add> <add> @Test <add> public void getAnnotationAttributesInheritedFromAbstractMethod() throws NoSuchMethodException { <add> String name = Transactional.class.getName(); <add> Method method = ConcreteClassWithInheritedAnnotation.class.getMethod("handle"); <add> AnnotationAttributes attributes = getAnnotationAttributes(method, name); <add>// assertNotNull(attributes); <add> } <add> <add> // SPR-12738 <add> <add> @Test <add> public void getAnnotationAttributesInheritedFromParameterizedMethod() throws NoSuchMethodException { <add> String name = Transactional.class.getName(); <add> Method method = ConcreteClassWithInheritedAnnotation.class.getMethod("handleParameterized", String.class); <add> AnnotationAttributes attributes = getAnnotationAttributes(ConcreteClassWithInheritedAnnotation.class, name); <add>// assertNotNull(attributes); <add> } <add> <ide> <ide> // ------------------------------------------------------------------------- <ide> <ide> static class MetaCycleAnnotatedClass { <ide> // ------------------------------------------------------------------------- <ide> <ide> @Retention(RetentionPolicy.RUNTIME) <del> @Target(ElementType.TYPE) <add> @Target({ElementType.TYPE, ElementType.METHOD}) <ide> @Documented <ide> @Inherited <ide> @interface Transactional { <ide> static class DerivedTxConfig extends TxConfig { <ide> static class TxFromMultipleComposedAnnotations { <ide> } <ide> <add> @Transactional <add> static interface InterfaceWithInheritedAnnotation { <add> } <add> <add> static abstract class AbstractClassWithInheritedAnnotation<T> implements InterfaceWithInheritedAnnotation { <add> <add> @Transactional <add> public abstract void handle(); <add> <add> @Transactional <add> public void handleParameterized(T t) { <add> } <add> } <add> <add> static class ConcreteClassWithInheritedAnnotation extends AbstractClassWithInheritedAnnotation<String> { <add> <add> @Override <add> public void handle() { <add> } <add> <add> @Override <add> public void handleParameterized(String s) { <add> } <add> } <add> <ide> }
1
Javascript
Javascript
upgrade tapable for multicompiler
0ccc0374d7d0e3b1ddf368b874ed561aa3c17147
<ide><path>lib/MultiCompiler.js <ide> */ <ide> "use strict"; <ide> <del>const Tapable = require("tapable-old"); <add>const Tapable = require("tapable").Tapable; <add>const SyncHook = require("tapable").SyncHook; <ide> const asyncLib = require("async"); <ide> const MultiWatching = require("./MultiWatching"); <ide> const MultiStats = require("./MultiStats"); <ide> <ide> module.exports = class MultiCompiler extends Tapable { <ide> constructor(compilers) { <ide> super(); <add> this.hooks = { <add> done: new SyncHook(["stats"]), <add> invalid: new SyncHook([]) <add> }; <ide> if(!Array.isArray(compilers)) { <ide> compilers = Object.keys(compilers).map((name) => { <ide> compilers[name].name = name; <ide> module.exports = class MultiCompiler extends Tapable { <ide> } <ide> compilerStats[idx] = stats; <ide> if(doneCompilers === this.compilers.length) { <del> this.applyPlugins("done", new MultiStats(compilerStats)); <add> this.hooks.done.call(new MultiStats(compilerStats)); <ide> } <ide> }); <ide> compiler.plugin("invalid", () => { <ide> if(compilerDone) { <ide> compilerDone = false; <ide> doneCompilers--; <ide> } <del> this.applyPlugins("invalid"); <add> this.hooks.invalid.call(); <ide> }); <ide> }); <ide> } <ide><path>test/MultiCompiler.unittest.js <ide> describe("MultiCompiler", () => { <ide> }); <ide> <ide> it("returns a multi-watching object", () => { <del> const result = JSON.stringify(env.result); <del> result.should.be.exactly("{\"watchings\":[\"compiler1\",\"compiler2\"],\"compiler\":{\"_plugins\":{},\"compilers\":[{\"name\":\"compiler1\"},{\"name\":\"compiler2\"}]}}"); <add> const result = env.result; <add> result.constructor.name.should.be.exactly("MultiWatching"); <ide> }); <ide> <ide> it("calls watch on each compiler with original options", () => {
2
Java
Java
create new feature flag to eager initialize fabric
aba321b4fb4e539cbf6a6a9a53de9b70e1cc9497
<ide><path>ReactAndroid/src/main/java/com/facebook/react/config/ReactFeatureFlags.java <ide> public class ReactFeatureFlags { <ide> * remove this when bug is fixed <ide> */ <ide> public static boolean enableTransitionLayoutOnlyViewCleanup = false; <add> <add> /** Feature flag to configure eager initialization of Fabric */ <add> public static boolean eagerInitializeFabric = false; <ide> }
1
Python
Python
apply nonzero fixer
54ca3f28ada715a0c84686f74f3b5a7ba4aa2c95
<ide><path>numpy/oldnumeric/ma.py <ide> def __nonzero__(self): <ide> return bool(m is not nomask and m.any() <ide> or d is not nomask and d.any()) <ide> <add> def __bool__(self): <add> """returns true if any element is non-zero or masked <add> <add> """ <add> # XXX: This changes bool conversion logic from MA. <add> # XXX: In MA bool(a) == len(a) != 0, but in numpy <add> # XXX: scalars do not have len <add> m = self._mask <add> d = self._data <add> return bool(m is not nomask and m.any() <add> or d is not nomask and d.any()) <add> <ide> def __len__ (self): <ide> """Return length of first dimension. This is weird but Python's <ide> slicing behavior depends on it.""" <ide> def asarray(data, dtype=None): <ide> # XXX: I is better to to change the masked_*_operation adaptors <ide> # XXX: to wrap ndarray methods directly to create ma.array methods. <ide> from types import MethodType <add> <ide> def _m(f): <ide> return MethodType(f, None, array) <add> <ide> def not_implemented(*args, **kwds): <ide> raise NotImplementedError("not yet implemented for numpy.ma arrays") <add> <ide> array.all = _m(alltrue) <ide> array.any = _m(sometrue) <ide> array.argmax = _m(argmax) <ide><path>tools/py3tool.py <ide> 'methodattrs', <ide> 'ne', <ide> # 'next', <del># 'nonzero', <add> 'nonzero', <ide> 'numliterals', <ide> 'operator', <ide> 'paren',
2
Ruby
Ruby
improve performance for contextual validations
0fb166e81cfd331222c7dbb0c7cd9213878e49ee
<ide><path>activemodel/lib/active_model/validations.rb <ide> def validate(*args, &block) <ide> end <ide> <ide> if options.key?(:on) <del> options = options.dup <del> options[:on] = Array(options[:on]) <del> options[:if] = [ <del> ->(o) { !(options[:on] & Array(o.validation_context)).empty? }, <del> *options[:if] <del> ] <add> options = options.merge(if: [predicate_for_validation_context(options[:on]), *options[:if]]) <ide> end <ide> <ide> set_callback(:validate, *args, options, &block) <ide> def inherited(base) # :nodoc: <ide> base._validators = dup.each { |k, v| dup[k] = v.dup } <ide> super <ide> end <add> <add> private <add> @@predicates_for_validation_contexts = {} <add> <add> def predicate_for_validation_context(context) <add> context = context.is_a?(Array) ? context.sort : Array(context) <add> <add> @@predicates_for_validation_contexts[context] ||= -> (model) do <add> if model.validation_context.is_a?(Array) <add> model.validation_context.any? { |model_context| context.include?(model_context) } <add> else <add> context.include?(model.validation_context) <add> end <add> end <add> end <ide> end <ide> <ide> # Clean the +Errors+ object if instance is duped.
1
Text
Text
add changelog for 2.12.0-beta.3 [ci skip]
b93b1ab39df3c3344649eb2d9130907cfbe17d33
<ide><path>CHANGELOG.md <ide> # Ember Changelog <ide> <add>### 2.12.0-beta.3 (March 8, 2017) <add> <add>- [#14987](https://github.com/emberjs/ember.js/pull/14987) [BUGFIX] Fix a memory leak when components are destroyed. <add>- [#14986](https://github.com/emberjs/ember.js/pull/14986) [BUGFIX] Fix a memory leak in RSVP.js. <add>- [#14985](https://github.com/emberjs/ember.js/pull/14985) [BUGFIX] Fix a bug that added babel helpers to the global scope. <add>- [#14898](https://github.com/emberjs/ember.js/pull/14898) [BUGFIX] Fix an issue where errors in tests sometimes do not cause a failure. <add>- [#14707](https://github.com/emberjs/ember.js/pull/14707) [BUGFIX] Improve deprecation message for unsafe `style` attribute bindings. <add> <ide> ### 2.12.0-beta.2 (February 16, 2017) <ide> <ide> - [#14872](https://github.com/emberjs/ember.js/pull/14872) / [#14871](https://github.com/emberjs/ember.js/pull/14871) / [#14883](https://github.com/emberjs/ember.js/pull/14883) [PERF] Simplify action event handler
1
Python
Python
modify code to suit multiscale anchor generator
90106a40ae1765be80ba14ba49db7772b3b17ecd
<ide><path>research/object_detection/meta_architectures/faster_rcnn_meta_arch.py <ide> def __init__(self, <ide> # in the future. <ide> super(FasterRCNNMetaArch, self).__init__(num_classes=num_classes) <ide> <del> if not isinstance(first_stage_anchor_generator, <del> grid_anchor_generator.GridAnchorGenerator): <del> raise ValueError('first_stage_anchor_generator must be of type ' <del> 'grid_anchor_generator.GridAnchorGenerator.') <del> <ide> self._is_training = is_training <ide> self._image_resizer_fn = image_resizer_fn <ide> self._resize_masks = resize_masks <ide> def __init__(self, <ide> hyperparams_builder.KerasLayerHyperparams): <ide> num_anchors_per_location = ( <ide> self._first_stage_anchor_generator.num_anchors_per_location()) <del> if len(num_anchors_per_location) != 1: <del> raise ValueError('anchor_generator is expected to generate anchors ' <del> 'corresponding to a single feature map.') <add> <ide> conv_hyperparams = ( <ide> first_stage_box_predictor_arg_scope_fn) <ide> self._first_stage_box_predictor_first_conv = ( <ide> def _extract_rpn_feature_maps(self, preprocessed_inputs): <ide> if not isinstance(rpn_features_to_crop, list): <ide> rpn_features_to_crop = [rpn_features_to_crop] <ide> <add> feature_map_shapes = [] <ide> rpn_box_predictor_features = [] <del> anchors = [] <ide> for single_rpn_features_to_crop in rpn_features_to_crop: <del> feature_map_shape = tf.shape(single_rpn_features_to_crop) <del> level_anchors = box_list_ops.concatenate( <del> self._first_stage_anchor_generator.generate([(feature_map_shape[1], <del> feature_map_shape[2])])) <del> anchors.append(level_anchors) <add> single_shape = tf.shape(single_rpn_features_to_crop) <add> feature_map_shapes.append((single_shape[1], single_shape[2])) <ide> single_rpn_box_predictor_features = ( <del> self._first_stage_box_predictor_first_conv(single_rpn_features_to_crop)) <add> self._first_stage_box_predictor_first_conv(single_rpn_features_to_crop)) <ide> rpn_box_predictor_features.append(single_rpn_box_predictor_features) <del> anchors = box_list_ops.concatenate(anchors) <add> anchors = box_list_ops.concatenate( <add> self._first_stage_anchor_generator.generate(feature_map_shapes)) <ide> return (rpn_box_predictor_features, rpn_features_to_crop, <ide> anchors, image_shape) <ide> <ide> def _predict_rpn_proposals(self, rpn_box_predictor_features): <ide> """ <ide> num_anchors_per_location = ( <ide> self._first_stage_anchor_generator.num_anchors_per_location()) <del> if len(num_anchors_per_location) != 1: <del> raise RuntimeError('anchor_generator is expected to generate anchors ' <del> 'corresponding to a single feature map.') <add> # if len(num_anchors_per_location) != 1: <add> # raise RuntimeError('anchor_generator is expected to generate anchors ' <add> # 'corresponding to a single feature map.') <ide> if self._first_stage_box_predictor.is_keras_model: <ide> box_predictions = self._first_stage_box_predictor( <ide> rpn_box_predictor_features)
1
Text
Text
fix typo in readme link
2715898cb9a2d8d740e7a7d5cde9663f78493f02
<ide><path>README.md <ide> The source for the React Native documentation and website is hosted on a separat <ide> <ide> [docs]: https://facebook.github.io/react-native/docs/getting-started.html <ide> [r-docs]: https://reactjs.org/docs/getting-started.html <del>[repo-website]: (https://github.com/facebook/react-native-website) <add>[repo-website]: https://github.com/facebook/react-native-website <ide> <ide> ## 🚀 Upgrading <ide>
1
PHP
PHP
use isset instead of array_key_exists
3201b00272251c4878b705cddb7d49f736500880
<ide><path>src/Illuminate/Database/Eloquent/Model.php <ide> public function attributesToArray() <ide> // formatting while accessing attributes vs. arraying / JSONing a model. <ide> foreach ($this->getDates() as $key) <ide> { <del> if ( ! array_key_exists($key, $attributes)) continue; <add> if ( ! isset($attributes[$key])) continue; <ide> <ide> $attributes[$key] = (string) $this->asDateTime($attributes[$key]); <ide> }
1
Text
Text
use html for links including closing bracket
179a6512408b6df0722c7d80efc44a9cd06a999e
<ide><path>docs/IntegrationWithExistingApps.md <ide> $ sudo gem install cocoapods <ide> <ide> <block class="objc" /> <ide> <del>Assume the [app for integration](https://github.com/JoelMarcey/iOS-2048) is a [2048](https://en.wikipedia.org/wiki/2048_(video_game)) game. Here is what the main menu of the native application looks like without React Native. <add>Assume the [app for integration](https://github.com/JoelMarcey/iOS-2048) is a <a href="https://en.wikipedia.org/wiki/2048_(video_game)">2048</a> game. Here is what the main menu of the native application looks like without React Native. <ide> <ide> <block class="swift" /> <ide> <del>Assume the [app for integration](https://github.com/JoelMarcey/swift-2048) is a [2048](https://en.wikipedia.org/wiki/2048_(video_game) game. Here is what the main menu of the native application looks like without React Native. <add>Assume the [app for integration](https://github.com/JoelMarcey/swift-2048) is a <a href="https://en.wikipedia.org/wiki/2048_(video_game)">2048</a> game. Here is what the main menu of the native application looks like without React Native. <ide> <ide> <block class="objc swift" /> <ide>
1
Java
Java
fix failing test
b18053f93a2f3b01c53843284627a54e751577cf
<ide><path>spring-web/src/test/java/org/springframework/web/client/AsyncRestTemplateIntegrationTests.java <ide> import java.nio.charset.Charset; <ide> import java.util.EnumSet; <ide> import java.util.Set; <add>import java.util.concurrent.CountDownLatch; <ide> import java.util.concurrent.ExecutionException; <ide> import java.util.concurrent.Future; <add>import java.util.concurrent.TimeUnit; <ide> <ide> import org.junit.Before; <ide> import org.junit.Test; <ide> public void deleteCallbackWithLambdas() throws Exception { <ide> public void identicalExceptionThroughGetAndCallback() throws Exception { <ide> final HttpClientErrorException[] callbackException = new HttpClientErrorException[1]; <ide> <add> final CountDownLatch latch = new CountDownLatch(1); <ide> ListenableFuture<?> future = template.execute(baseUrl + "/status/notfound", HttpMethod.GET, null, null); <ide> future.addCallback(new ListenableFutureCallback<Object>() { <ide> @Override <ide> public void onSuccess(Object result) { <ide> fail("onSuccess not expected"); <ide> } <ide> @Override <del> public void onFailure(Throwable t) { <del> assertTrue(t instanceof HttpClientErrorException); <del> callbackException[0] = (HttpClientErrorException) t; <add> public void onFailure(Throwable ex) { <add> assertTrue(ex instanceof HttpClientErrorException); <add> callbackException[0] = (HttpClientErrorException) ex; <add> latch.countDown(); <ide> } <ide> }); <ide> <ide> public void onFailure(Throwable t) { <ide> catch (ExecutionException ex) { <ide> Throwable cause = ex.getCause(); <ide> assertTrue(cause instanceof HttpClientErrorException); <add> latch.await(5, TimeUnit.SECONDS); <ide> assertSame(callbackException[0], cause); <ide> } <ide> }
1
Ruby
Ruby
explain the possible precautions
cc5a4bb4df2390cb57d5a295a4f4a51572012268
<ide><path>actionpack/lib/action_dispatch/middleware/remote_ip.rb <ide> module ActionDispatch <ide> # IF YOU DON'T USE A PROXY, THIS MAKES YOU VULNERABLE TO IP SPOOFING. <ide> # This middleware assumes that there is at least one proxy sitting around <ide> # and setting headers with the client's remote IP address. If you don't use <del> # a proxy, because you are hosted on e.g. Heroku, any client can claim to <del> # have any IP address by setting the X-Forwarded-For header. If you care <del> # about that, please take precautions. <add> # a proxy, because you are hosted on e.g. Heroku without SSL, any client can <add> # claim to have any IP address by setting the X-Forwarded-For header. If you <add> # care about that, then you need to explicitly drop or ignore those headers <add> # sometime before this middleware runs. <ide> class RemoteIp <ide> class IpSpoofAttackError < StandardError; end <ide>
1
PHP
PHP
fix part of plugin assets tests
95db91c57ad6213baa1fad9dcafd886674591a85
<ide><path>tests/TestCase/Command/PluginAssetsCommandsTest.php <ide> * @since 3.0.0 <ide> * @license https://opensource.org/licenses/mit-license.php MIT License <ide> */ <del>namespace Cake\Test\TestCase\Shell\Task; <add>namespace Cake\Test\TestCase\Command; <ide> <add>use Cake\Console\Command; <ide> use Cake\Core\Configure; <ide> use Cake\Filesystem\Filesystem; <add>use Cake\TestSuite\ConsoleIntegrationTestTrait; <ide> use Cake\TestSuite\TestCase; <ide> <ide> /** <del> * AssetsTaskTest class <add> * PluginAssetsCommandsTest class <ide> */ <del>class AssetsTaskTest extends TestCase <add>class PluginAssetsCommandsTest extends TestCase <ide> { <add> use ConsoleIntegrationTestTrait; <add> <ide> protected $wwwRoot; <ide> <ide> /** <ide> public function setUp(): void <ide> ->disableOriginalConstructor() <ide> ->getMock(); <ide> <del> $this->Task = $this->getMockBuilder('Cake\Shell\Task\AssetsTask') <del> ->setMethods(['in', 'out', 'err', '_stop']) <del> ->setConstructorArgs([$this->io]) <del> ->getMock(); <del> <ide> $this->wwwRoot = TMP . 'assets_task_webroot' . DS; <ide> Configure::write('App.wwwRoot', $this->wwwRoot); <ide> <ide> $this->fs = new Filesystem(); <ide> $this->fs->deleteDir($this->wwwRoot); <ide> $this->fs->copyDir(WWW_ROOT, $this->wwwRoot); <add> <add> $this->useCommandRunner(); <add> $this->setAppNamespace(); <ide> } <ide> <ide> /** <ide> public function setUp(): void <ide> public function tearDown(): void <ide> { <ide> parent::tearDown(); <del> unset($this->Task); <ide> $this->clearPlugins(); <ide> } <ide> <ide> public function tearDown(): void <ide> */ <ide> public function testSymlink() <ide> { <del> $this->loadPlugins(['TestPlugin', 'Company/TestPluginThree']); <add> $this->loadPlugins(['TestPlugin' => ['routes' => false], 'Company/TestPluginThree']); <ide> <del> $this->Task->symlink(); <add> $this->exec('plugin assets symlink'); <add> $this->assertExitCode(Command::CODE_SUCCESS); <ide> <ide> $path = $this->wwwRoot . 'test_plugin'; <ide> $this->assertFileExists($path . DS . 'root.js'); <ide> public function testSymlinkWhenVendorDirectoryExits() <ide> <ide> mkdir($this->wwwRoot . 'company'); <ide> <del> $this->Task->symlink(); <add> $this->exec('plugin assets symlink'); <ide> $path = $this->wwwRoot . 'company' . DS . 'test_plugin_three'; <ide> if (DS === '\\') { <ide> $this->assertDirectoryExits($path); <ide> public function testForPluginWithoutWebroot() <ide> { <ide> $this->loadPlugins(['TestPluginTwo']); <ide> <del> $this->Task->symlink(); <add> $this->exec('plugin assets symlink'); <ide> $this->assertFileNotExists($this->wwwRoot . 'test_plugin_two'); <ide> } <ide> <ide> public function testForPluginWithoutWebroot() <ide> */ <ide> public function testSymlinkingSpecifiedPlugin() <ide> { <del> $this->loadPlugins(['TestPlugin', 'Company/TestPluginThree']); <add> $this->loadPlugins(['TestPlugin' => ['routes' => false], 'Company/TestPluginThree']); <ide> <del> $this->Task->symlink('TestPlugin'); <add> $this->exec('plugin assets symlink', ['TestPlugin']); <ide> <ide> $path = $this->wwwRoot . 'test_plugin'; <ide> $link = new \SplFileInfo($path); <ide> public function testSymlinkingSpecifiedPlugin() <ide> */ <ide> public function testCopy() <ide> { <del> $this->loadPlugins(['TestPlugin', 'Company/TestPluginThree']); <add> $this->loadPlugins(['TestPlugin' => ['routes' => false], 'Company/TestPluginThree']); <ide> <del> $this->Task->copy(); <add> $this->exec('plugin assets copy'); <ide> <ide> $path = $this->wwwRoot . 'test_plugin'; <ide> $this->assertDirectoryExists($path); <ide> public function testCopy() <ide> */ <ide> public function testCopyOverwrite() <ide> { <del> $this->loadPlugins(['TestPlugin']); <add> $this->loadPlugins(['TestPlugin' => ['routes' => false]]); <ide> <del> $this->Task->copy(); <add> $this->exec('plugin assets copy'); <ide> <ide> $pluginPath = TEST_APP . 'Plugin' . DS . 'TestPlugin' . DS . 'webroot'; <ide> <ide> public function testCopyOverwrite() <ide> <ide> file_put_contents($path . DS . 'root.js', 'updated'); <ide> <del> $this->Task->copy(); <add> $this->exec('plugin assets copy'); <ide> <ide> $this->assertFileNotEquals($path . DS . 'root.js', $pluginPath . DS . 'root.js'); <ide> <del> $this->Task->params['overwrite'] = true; <del> $this->Task->copy(); <add> $this->exec('plugin assets copy', ['--overwrite']); <ide> <ide> $this->assertFileEquals($path . DS . 'root.js', $pluginPath . DS . 'root.js'); <ide> } <ide> public function testRemoveSymlink() <ide> ); <ide> } <ide> <del> $this->loadPlugins(['TestPlugin', 'Company/TestPluginThree']); <add> $this->loadPlugins(['TestPlugin' => ['routes' => false], 'Company/TestPluginThree']); <ide> <ide> mkdir($this->wwwRoot . 'company'); <ide> <del> $this->Task->symlink(); <add> $this->exec('plugin assets symlink'); <ide> <ide> $this->assertTrue(is_link($this->wwwRoot . 'test_plugin')); <ide> <ide> $path = $this->wwwRoot . 'company' . DS . 'test_plugin_three'; <ide> $this->assertTrue(is_link($path)); <ide> <del> $this->Task->remove(); <add> $this->exec('plugin assets remove'); <ide> <ide> $this->assertFalse(is_link($this->wwwRoot . 'test_plugin')); <ide> $this->assertFalse(is_link($path)); <ide> public function testRemoveSymlink() <ide> */ <ide> public function testRemoveFolder() <ide> { <del> $this->loadPlugins(['TestPlugin', 'Company/TestPluginThree']); <add> $this->loadPlugins(['TestPlugin' => ['routes' => false], 'Company/TestPluginThree']); <ide> <del> $this->Task->copy(); <add> $this->exec('plugin assets copy'); <ide> <ide> $this->assertTrue(is_dir($this->wwwRoot . 'test_plugin')); <ide> <ide> $this->assertTrue(is_dir($this->wwwRoot . 'company' . DS . 'test_plugin_three')); <ide> <del> $this->Task->remove(); <add> $this->exec('plugin assets remove'); <ide> <ide> $this->assertDirectoryNotExists($this->wwwRoot . 'test_plugin'); <ide> $this->assertDirectoryNotExists($this->wwwRoot . 'company' . DS . 'test_plugin_three'); <ide> public function testRemoveFolder() <ide> */ <ide> public function testOverwrite() <ide> { <del> $this->loadPlugins(['TestPlugin', 'Company/TestPluginThree']); <add> $this->loadPlugins(['TestPlugin' => ['routes' => false], 'Company/TestPluginThree']); <ide> <ide> $path = $this->wwwRoot . 'test_plugin'; <ide> <ide> mkdir($path); <ide> $filectime = filectime($path); <ide> <ide> sleep(1); <del> $this->Task->params['overwrite'] = true; <del> $this->Task->symlink('TestPlugin'); <add> $this->exec('plugin assets symlink', ['TestPlugin', '--overwrite']); <ide> if (DS === '\\') { <ide> $this->assertDirectoryExists($path); <ide> } else { <ide> public function testOverwrite() <ide> $filectime = filectime($path); <ide> <ide> sleep(1); <del> $this->Task->params['overwrite'] = true; <del> $this->Task->copy('Company/TestPluginThree'); <add> $this->exec('plugin assets copy', ['Company/TestPluginThree', '--overwrite']); <ide> <ide> $newfilectime = filectime($path); <ide> $this->assertTrue($newfilectime > $filectime);
1
Mixed
Python
update calback page
73a620b6e875a2f153cb5acea194d89e845dc726
<ide><path>docs/templates/callbacks.md <ide> class LossHistory(keras.callbacks.Callback): <ide> self.losses.append(logs.get('loss')) <ide> <ide> model = Sequential() <del>model.add(Dense(10, input_dim=784, init='uniform')) <add>model.add(Dense(10, input_dim=784, kernel_initializer='uniform')) <ide> model.add(Activation('softmax')) <ide> model.compile(loss='categorical_crossentropy', optimizer='rmsprop') <ide> <ide> print history.losses <ide> from keras.callbacks import ModelCheckpoint <ide> <ide> model = Sequential() <del>model.add(Dense(10, input_dim=784, init='uniform')) <add>model.add(Dense(10, input_dim=784, kernel_initializer='uniform')) <ide> model.add(Activation('softmax')) <ide> model.compile(loss='categorical_crossentropy', optimizer='rmsprop') <ide> <ide><path>keras/callbacks.py <ide> class TensorBoard(Callback): <ide> tensorboard --logdir=/full_path_to_your_logs <ide> ``` <ide> You can find more information about TensorBoard <del> [here](https://www.tensorflow.org/versions/master/how_tos/summaries_and_tensorboard/index.html). <add> [here](https://www.tensorflow.org/get_started/summaries_and_tensorboard). <ide> <ide> # Arguments <ide> log_dir: the path of the directory where to save the log
2
Text
Text
add reformer mlm notebook
306f1a269504b781f886d75105acabf8ae95bd11
<ide><path>notebooks/README.md <ide> Pull Request so it can be included under the Community notebooks. <ide> |[Fine-tune BERT for Multi-label Classification](https://github.com/abhimishra91/transformers-tutorials/blob/master/transformers_multi_label_classification.ipynb)|How to fine-tune BERT for multi-label classification using PyTorch|[Abhishek Kumar Mishra](https://github.com/abhimishra91) |[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/abhimishra91/transformers-tutorials/blob/master/transformers_multi_label_classification.ipynb)| <ide> |[Fine-tune T5 for Summarization](https://github.com/abhimishra91/transformers-tutorials/blob/master/transformers_summarization_wandb.ipynb)|How to fine-tune T5 for summarization in PyTorch and track experiments with WandB|[Abhishek Kumar Mishra](https://github.com/abhimishra91) |[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/abhimishra91/transformers-tutorials/blob/master/transformers_summarization_wandb.ipynb)| <ide> |[Speed up Fine-Tuning in Transformers with Dynamic Padding / Bucketing](https://github.com/ELS-RD/transformers-notebook/blob/master/Divide_Hugging_Face_Transformers_training_time_by_2_or_more.ipynb)|How to speed up fine-tuning by a factor of 2 using dynamic padding / bucketing|[Michael Benesty](https://github.com/pommedeterresautee) |[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1CBfRU1zbfu7-ijiOqAAQUA-RJaxfcJoO?usp=sharing)| <add>|[Pretrain Reformer for Masked Language Modeling](https://github.com/patrickvonplaten/notebooks/blob/master/Reformer_For_Masked_LM.ipynb)| How to train a Reformer model with bi-directional self-attention layers | [Patrick von Platen](https://github.com/patrickvonplaten) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1tzzh0i8PgDQGV3SMFUGxM7_gGae3K-uW?usp=sharing)|
1
PHP
PHP
correct the warning raised
f65df2f0fdf841e4063e73e3f7bcbf89b51005fd
<ide><path>src/Utility/Inflector.php <ide> public static function slug($string, $replacement = '-') <ide> { <ide> deprecationWarning( <ide> 'Inflector::slug() is deprecated. ' . <del> 'Use Text::getSalt()/setSalt() instead.' <add> 'Use Text::slug() instead.' <ide> ); <ide> $quotedReplacement = preg_quote($replacement, '/'); <ide>
1
Ruby
Ruby
fix typo extention -> extension [ci skip]
7bfc79ec9bb054b97b2f961a75f8c789999b68dc
<ide><path>actionview/lib/action_view/helpers/asset_tag_helper.rb <ide> module AssetTagHelper <ide> # When the last parameter is a hash you can add HTML attributes using that <ide> # parameter. The following options are supported: <ide> # <del> # * <tt>:extname</tt> - Append a extention to the generated url unless the extension <add> # * <tt>:extname</tt> - Append an extension to the generated url unless the extension <ide> # already exists. This only applies for relative urls. <ide> # * <tt>:protocol</tt> - Sets the protocol of the generated url, this option only <ide> # applies when a relative url and +host+ options are provided.
1
Mixed
Ruby
allow rescue from parameter parse errors
6b3faf8e502dbd238fe4b4c409e96308638297a1
<ide><path>actionpack/CHANGELOG.md <add>* Allow rescue from parameter parse errors: <add> <add> ``` <add> rescue_from ActionDispatch::Http::Parameters::ParseError do <add> head :unauthorized <add> end <add> ``` <add> <add> *Gannon McGibbon*, *Josh Cheek* <add> <ide> * Reset Capybara sessions if failed system test screenshot raising an exception. <ide> <ide> Reset Capybara sessions if `take_failed_screenshot` raise exception <ide><path>actionpack/lib/action_controller/metal/params_wrapper.rb <ide> def process_action(*args) <ide> # This will display the wrapped hash in the log file. <ide> request.filtered_parameters.merge! wrapped_filtered_hash <ide> end <del> super <add> ensure <add> # NOTE: Rescues all exceptions so they <add> # may be caught in ActionController::Rescue. <add> return super <ide> end <ide> <ide> private <ide><path>actionpack/lib/action_dispatch/http/filter_parameters.rb <ide> def initialize <ide> # Returns a hash of parameters with all sensitive data replaced. <ide> def filtered_parameters <ide> @filtered_parameters ||= parameter_filter.filter(parameters) <add> rescue ActionDispatch::Http::Parameters::ParseError <add> @filtered_parameters = {} <ide> end <ide> <ide> # Returns a hash of request.env with all sensitive data replaced. <ide><path>actionpack/lib/action_dispatch/http/mime_negotiation.rb <ide> module Http <ide> module MimeNegotiation <ide> extend ActiveSupport::Concern <ide> <add> RESCUABLE_MIME_FORMAT_ERRORS = [ <add> ActionController::BadRequest, <add> ActionDispatch::Http::Parameters::ParseError, <add> ] <add> <ide> included do <ide> mattr_accessor :ignore_accept_header, default: false <ide> end <ide> def formats <ide> fetch_header("action_dispatch.request.formats") do |k| <ide> params_readable = begin <ide> parameters[:format] <del> rescue ActionController::BadRequest <add> rescue *RESCUABLE_MIME_FORMAT_ERRORS <ide> false <ide> end <ide> <ide><path>actionpack/lib/action_dispatch/http/parameters.rb <ide> def parse_formatted_parameters(parsers) <ide> begin <ide> strategy.call(raw_post) <ide> rescue # JSON or Ruby code block errors. <del> my_logger = logger || ActiveSupport::Logger.new($stderr) <del> my_logger.debug "Error occurred while parsing request parameters.\nContents:\n\n#{raw_post}" <del> <add> log_parse_error_once <ide> raise ParseError <ide> end <ide> end <ide> <add> def log_parse_error_once <add> @parse_error_logged ||= begin <add> parse_logger = logger || ActiveSupport::Logger.new($stderr) <add> parse_logger.debug <<~MSG.chomp <add> Error occurred while parsing request parameters. <add> Contents: <add> <add> #{raw_post} <add> MSG <add> end <add> end <add> <ide> def params_parsers <ide> ActionDispatch::Request.parameter_parsers <ide> end <ide><path>actionpack/lib/action_dispatch/http/request.rb <ide> def POST <ide> end <ide> self.request_parameters = Request::Utils.normalize_encode_params(pr) <ide> end <del> rescue Http::Parameters::ParseError # one of the parse strategies blew up <del> self.request_parameters = Request::Utils.normalize_encode_params(super || {}) <del> raise <ide> rescue Rack::Utils::ParameterTypeError, Rack::Utils::InvalidParameterError => e <ide> raise ActionController::BadRequest.new("Invalid request parameters: #{e.message}") <ide> end <ide><path>actionpack/test/controller/params_parse_test.rb <add># frozen_string_literal: true <add> <add>require "abstract_unit" <add> <add>class ParamsParseTest < ActionController::TestCase <add> class UsersController < ActionController::Base <add> def create <add> head :ok <add> end <add> end <add> <add> tests UsersController <add> <add> def test_parse_error_logged_once <add> log_output = capture_log_output do <add> post :create, body: "{", as: :json <add> end <add> assert_equal <<~LOG, log_output <add> Error occurred while parsing request parameters. <add> Contents: <add> <add> { <add> LOG <add> end <add> <add> private <add> <add> def capture_log_output <add> output = StringIO.new <add> request.set_header "action_dispatch.logger", ActiveSupport::Logger.new(output) <add> yield <add> output.string <add> end <add>end <ide><path>actionpack/test/controller/rescue_test.rb <ide> class ResourceUnavailableToRescueAsString < StandardError <ide> render plain: "io error" <ide> end <ide> <add> rescue_from ActionDispatch::Http::Parameters::ParseError do <add> render plain: "parse error", status: :bad_request <add> end <add> <ide> before_action(only: :before_action_raises) { raise "umm nice" } <ide> <ide> def before_action_raises <ide> def resource_unavailable_raise_as_string <ide> raise ResourceUnavailableToRescueAsString <ide> end <ide> <add> def arbitrary_action <add> params <add> render plain: "arbitrary action" <add> end <add> <ide> def missing_template <ide> end <ide> <ide> def test_block_rescue_handler_with_argument_as_string <ide> get :exception_with_no_handler_for_wrapper <ide> assert_response :unprocessable_entity <ide> end <add> <add> test "can rescue a ParseError" do <add> capture_log_output do <add> post :arbitrary_action, body: "{", as: :json <add> end <add> assert_response :bad_request <add> assert_equal "parse error", response.body <add> end <add> <add> private <add> <add> def capture_log_output <add> output = StringIO.new <add> request.set_header "action_dispatch.logger", ActiveSupport::Logger.new(output) <add> yield <add> output.string <add> end <ide> end <ide> <ide> class RescueTest < ActionDispatch::IntegrationTest
8
PHP
PHP
add directory visibility
870bc7d6c106a3391da90372d488b89da3bc8236
<ide><path>src/Illuminate/Filesystem/FilesystemManager.php <ide> protected function formatS3Config(array $config) <ide> */ <ide> protected function createFlysystem(FlysystemAdapter $adapter, array $config) <ide> { <del> $config = Arr::only($config, ['visibility', 'disable_asserts', 'url', 'temporary_url']); <del> <del> return new Flysystem($adapter, $config); <add> return new Flysystem($adapter, Arr::only($config, [ <add> 'directory_visibility', <add> 'disable_asserts', <add> 'temporary_url', <add> 'url', <add> 'visibility', <add> ])); <ide> } <ide> <ide> /**
1
PHP
PHP
fix throttlerequestsexception
985b2cf1845b544cdfd744ee68be2dfa95652c51
<ide><path>src/Illuminate/Http/Exceptions/ThrottleRequestsException.php <ide> class ThrottleRequestsException extends TooManyRequestsHttpException <ide> /** <ide> * Create a new throttle requests exception instance. <ide> * <del> * @param string|null $message <add> * @param string $message <ide> * @param \Throwable|null $previous <ide> * @param array $headers <ide> * @param int $code <ide> * @return void <ide> */ <del> public function __construct($message = null, Throwable $previous = null, array $headers = [], $code = 0) <add> public function __construct($message = '', Throwable $previous = null, array $headers = [], $code = 0) <ide> { <ide> parent::__construct(null, $message, $previous, $code, $headers); <ide> }
1
Javascript
Javascript
add {{input action="foo" on="keypress"}}
c48b843265c849e0add3085ea57b97741c60ad64
<ide><path>packages/ember-handlebars/lib/controls.js <ide> Ember.Handlebars.registerHelper('input', function(options) { <ide> <ide> var hash = options.hash, <ide> types = options.hashTypes, <del> inputType = hash.type; <add> inputType = hash.type, <add> onEvent = hash.on; <ide> <ide> delete hash.type; <add> delete hash.on; <add> <add> hash.onEvent = onEvent; <ide> <ide> normalizeHash(hash, types); <ide> <ide> if (inputType === 'checkbox') { <ide> return Ember.Handlebars.helpers.view.call(this, Ember.Checkbox, options); <ide> } else { <add> hash.type = inputType; <ide> return Ember.Handlebars.helpers.view.call(this, Ember.TextField, options); <ide> } <ide> }); <ide>\ No newline at end of file <ide><path>packages/ember-handlebars/lib/controls/text_field.js <ide> Ember.TextField = Ember.View.extend(Ember.TextSupport, <ide> */ <ide> action: null, <ide> <add> /** <add> The event that should send the action. <add> <add> Options are: <add> <add> * `enter`: the user pressed enter <add> * `keypress`: the user pressed a key <add> <add> @property on <add> @type String <add> @default enter <add> */ <add> onEvent: 'enter', <add> <ide> /** <ide> Whether they `keyUp` event that triggers an `action` to be sent continues <ide> propagating to other views. <ide> Ember.TextField = Ember.View.extend(Ember.TextSupport, <ide> bubbles: false, <ide> <ide> insertNewline: function(event) { <del> var controller = get(this, 'controller'), <del> action = get(this, 'action'); <add> sendAction('enter', this, event); <add> }, <ide> <del> if (action) { <del> controller.send(action, get(this, 'value'), this); <add> keyPress: function(event) { <add> sendAction('keyPress', this, event); <add> } <add>}); <add> <add>function sendAction(eventName, view, event) { <add> var action = get(view, 'action'), <add> on = get(view, 'onEvent'); <ide> <del> if (!get(this, 'bubbles')) { <del> event.stopPropagation(); <del> } <add> if (action && on === eventName) { <add> var controller = get(view, 'controller'), <add> value = get(view, 'value'), <add> bubbles = get(view, 'bubbles'); <add> <add> controller.send(action, value, view); <add> <add> if (!bubbles) { <add> event.stopPropagation(); <ide> } <ide> } <del>}); <add>} <ide>\ No newline at end of file <ide><path>packages/ember-handlebars/tests/controls/text_field_test.js <ide> test("should send an action if one is defined when the return key is pressed", f <ide> textField.trigger('keyUp', event); <ide> }); <ide> <add>test("should send an action on keyPress if one is defined with onEvent=keyPress", function() { <add> expect(3); <add> <add> var StubController = Ember.Object.extend({ <add> send: function(actionName, value, sender) { <add> equal(actionName, 'didTriggerAction', "text field sent correct action name"); <add> equal(value, "textFieldValue", "text field sent its current value as first argument"); <add> equal(sender, textField, "text field sent itself as second argument"); <add> } <add> }); <add> <add> textField.set('action', 'didTriggerAction'); <add> textField.set('onEvent', 'keyPress'); <add> textField.set('value', "textFieldValue"); <add> textField.set('controller', StubController.create()); <add> <add> Ember.run(function() { textField.append(); }); <add> <add> var event = { <add> keyCode: 48, <add> stopPropagation: Ember.K <add> }; <add> <add> textField.trigger('keyPress', event); <add>}); <add> <add> <ide> test("bubbling of handled actions can be enabled via bubbles property", function() { <ide> textField.set('bubbles', true); <ide> textField.set('action', 'didTriggerAction');
3
Java
Java
fix flowable.concatmap backpressure w/ scalars
0668d042b47d3585f856af831bd3b1e1742c080f
<ide><path>src/main/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableConcatMap.java <ide> package io.reactivex.rxjava3.internal.operators.flowable; <ide> <ide> import java.util.Objects; <del>import java.util.concurrent.atomic.AtomicInteger; <add>import java.util.concurrent.atomic.*; <ide> <ide> import org.reactivestreams.*; <ide> <ide> void drain() { <ide> continue; <ide> } else { <ide> active = true; <del> inner.setSubscription(new WeakScalarSubscription<>(vr, inner)); <add> inner.setSubscription(new SimpleScalarSubscription<>(vr, inner)); <ide> } <ide> <ide> } else { <ide> void drain() { <ide> } <ide> } <ide> <del> static final class WeakScalarSubscription<T> implements Subscription { <add> static final class SimpleScalarSubscription<T> <add> extends AtomicBoolean <add> implements Subscription { <add> private static final long serialVersionUID = -7606889335172043256L; <add> <ide> final Subscriber<? super T> downstream; <ide> final T value; <del> boolean once; <ide> <del> WeakScalarSubscription(T value, Subscriber<? super T> downstream) { <add> SimpleScalarSubscription(T value, Subscriber<? super T> downstream) { <ide> this.value = value; <ide> this.downstream = downstream; <ide> } <ide> <ide> @Override <ide> public void request(long n) { <del> if (n > 0 && !once) { <del> once = true; <add> if (n > 0L && compareAndSet(false, true)) { <ide> Subscriber<? super T> a = downstream; <ide> a.onNext(value); <ide> a.onComplete(); <ide> void drain() { <ide> continue; <ide> } else { <ide> active = true; <del> inner.setSubscription(new WeakScalarSubscription<>(vr, inner)); <add> inner.setSubscription(new SimpleScalarSubscription<>(vr, inner)); <ide> } <ide> } else { <ide> active = true; <ide><path>src/main/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableConcatMapScheduler.java <ide> public void run() { <ide> continue; <ide> } else { <ide> active = true; <del> inner.setSubscription(new WeakScalarSubscription<>(vr, inner)); <add> inner.setSubscription(new SimpleScalarSubscription<>(vr, inner)); <ide> } <ide> <ide> } else { <ide> public void run() { <ide> continue; <ide> } else { <ide> active = true; <del> inner.setSubscription(new WeakScalarSubscription<>(vr, inner)); <add> inner.setSubscription(new SimpleScalarSubscription<>(vr, inner)); <ide> } <ide> } else { <ide> active = true; <ide><path>src/test/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableConcatMapSchedulerTest.java <ide> public Publisher<? extends Object> apply(String v) <ide> .assertResult("RxSingleScheduler"); <ide> } <ide> <add> @Test <add> public void innerScalarRequestRace() { <add> Flowable<Integer> just = Flowable.just(1); <add> int n = 1000; <add> for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { <add> PublishProcessor<Flowable<Integer>> source = PublishProcessor.create(); <add> <add> TestSubscriber<Integer> ts = source <add> .concatMap(v -> v, n + 1, ImmediateThinScheduler.INSTANCE) <add> .test(1L); <add> <add> TestHelper.race(() -> { <add> for (int j = 0; j < n; j++) { <add> source.onNext(just); <add> } <add> }, () -> { <add> for (int j = 0; j < n; j++) { <add> ts.request(1); <add> } <add> }); <add> <add> ts.assertValueCount(n); <add> } <add> } <add> <add> @Test <add> public void innerScalarRequestRaceDelayError() { <add> Flowable<Integer> just = Flowable.just(1); <add> int n = 1000; <add> for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { <add> PublishProcessor<Flowable<Integer>> source = PublishProcessor.create(); <add> <add> TestSubscriber<Integer> ts = source <add> .concatMapDelayError(v -> v, true, n + 1, ImmediateThinScheduler.INSTANCE) <add> .test(1L); <add> <add> TestHelper.race(() -> { <add> for (int j = 0; j < n; j++) { <add> source.onNext(just); <add> } <add> }, () -> { <add> for (int j = 0; j < n; j++) { <add> ts.request(1); <add> } <add> }); <add> <add> ts.assertValueCount(n); <add> } <add> } <add> <ide> @Test <ide> public void boundaryFusionDelayError() { <ide> Flowable.range(1, 10000) <ide><path>src/test/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableConcatMapTest.java <ide> import io.reactivex.rxjava3.core.*; <ide> import io.reactivex.rxjava3.exceptions.*; <ide> import io.reactivex.rxjava3.functions.*; <del>import io.reactivex.rxjava3.internal.operators.flowable.FlowableConcatMap.WeakScalarSubscription; <del>import io.reactivex.rxjava3.processors.UnicastProcessor; <add>import io.reactivex.rxjava3.internal.operators.flowable.FlowableConcatMap.SimpleScalarSubscription; <add>import io.reactivex.rxjava3.processors.*; <ide> import io.reactivex.rxjava3.schedulers.Schedulers; <ide> import io.reactivex.rxjava3.subscribers.TestSubscriber; <ide> import io.reactivex.rxjava3.testsupport.TestHelper; <ide> <ide> public class FlowableConcatMapTest extends RxJavaTest { <ide> <ide> @Test <del> public void weakSubscriptionRequest() { <add> public void simpleSubscriptionRequest() { <ide> TestSubscriber<Integer> ts = new TestSubscriber<>(0); <del> WeakScalarSubscription<Integer> ws = new WeakScalarSubscription<>(1, ts); <add> SimpleScalarSubscription<Integer> ws = new SimpleScalarSubscription<>(1, ts); <ide> ts.onSubscribe(ws); <ide> <ide> ws.request(0); <ide> public Publisher<? extends Object> apply(String v) <ide> .assertResult("RxSingleScheduler"); <ide> } <ide> <add> @Test <add> public void innerScalarRequestRace() { <add> Flowable<Integer> just = Flowable.just(1); <add> int n = 1000; <add> for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { <add> PublishProcessor<Flowable<Integer>> source = PublishProcessor.create(); <add> <add> TestSubscriber<Integer> ts = source <add> .concatMap(v -> v, n + 1) <add> .test(1L); <add> <add> TestHelper.race(() -> { <add> for (int j = 0; j < n; j++) { <add> source.onNext(just); <add> } <add> }, () -> { <add> for (int j = 0; j < n; j++) { <add> ts.request(1); <add> } <add> }); <add> <add> ts.assertValueCount(n); <add> } <add> } <add> <add> @Test <add> public void innerScalarRequestRaceDelayError() { <add> Flowable<Integer> just = Flowable.just(1); <add> int n = 1000; <add> for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { <add> PublishProcessor<Flowable<Integer>> source = PublishProcessor.create(); <add> <add> TestSubscriber<Integer> ts = source <add> .concatMapDelayError(v -> v, true, n + 1) <add> .test(1L); <add> <add> TestHelper.race(() -> { <add> for (int j = 0; j < n; j++) { <add> source.onNext(just); <add> } <add> }, () -> { <add> for (int j = 0; j < n; j++) { <add> ts.request(1); <add> } <add> }); <add> <add> ts.assertValueCount(n); <add> } <add> } <add> <ide> @Test <ide> public void boundaryFusionDelayError() { <ide> Flowable.range(1, 10000)
4
Python
Python
move matrix class into its own module
fe002b2916a5928463f7c46c5c4875114228bf7f
<ide><path>numpy/__init__.py <ide> def pkgload(*packages, **options): <ide> import random <ide> import ctypeslib <ide> import ma <add> import matrx as _mat <add> from matrx import * <ide> <ide> # Make these accessible from numpy name-space <ide> # but not imported in from numpy import * <ide> def pkgload(*packages, **options): <ide> __all__.extend(['__version__', 'pkgload', 'PackageLoader', <ide> 'show_config']) <ide> __all__.extend(core.__all__) <add> __all__.extend(_mat.__all__) <ide> __all__.extend(lib.__all__) <ide> __all__.extend(['linalg', 'fft', 'random', 'ctypeslib', 'ma']) <ide><path>numpy/core/__init__.py <ide> import _sort <ide> from numeric import * <ide> from fromnumeric import * <del>from defmatrix import * <ide> import defchararray as char <ide> import records as rec <ide> from records import * <ide> __all__ = ['char','rec','memmap'] <ide> __all__ += numeric.__all__ <ide> __all__ += fromnumeric.__all__ <del>__all__ += defmatrix.__all__ <ide> __all__ += rec.__all__ <ide> __all__ += char.__all__ <ide> <ide><path>numpy/core/tests/test_numeric.py <ide> def test_vecvecinner(self): <ide> c2 = dot_(b3, b1) <ide> assert_almost_equal(c1, c2, decimal=self.N) <ide> <del> def test_matscalar(self): <del> b1 = matrix(ones((3,3),dtype=complex)) <del> assert_equal(b1*1.0, b1) <del> <ide> def test_columnvect1(self): <ide> b1 = ones((3,1)) <ide> b2 = [5.3] <ide><path>numpy/lib/index_tricks.py <ide> import math <ide> <ide> import function_base <del>import numpy.core.defmatrix as matrix <add>import numpy.matrx as matrix <ide> from function_base import diff <ide> makemat = matrix.matrix <ide> <ide><path>numpy/lib/tests/test_function_base.py <ide> import numpy.lib <ide> from numpy.lib import * <ide> from numpy.core import * <add>from numpy import matrix, asmatrix <ide> <ide> class TestAny(TestCase): <ide> def test_basic(self): <ide><path>numpy/lib/tests/test_shape_base.py <ide> from numpy.testing import * <ide> from numpy.lib import * <ide> from numpy.core import * <add>from numpy import matrix, asmatrix <ide> <ide> class TestApplyAlongAxis(TestCase): <ide> def test_simple(self): <ide><path>numpy/linalg/linalg.py <ide> isfinite, size <ide> from numpy.lib import triu <ide> from numpy.linalg import lapack_lite <del>from numpy.core.defmatrix import matrix_power <add>from numpy.matrx.defmatrix import matrix_power <ide> <ide> fortran_int = intc <ide> <ide><path>numpy/matrx/__init__.py <add>from defmatrix import * <add> <add>__all__ = defmatrix.__all__ <add> <add>from numpy.testing import Tester <add>test = Tester().test <add>bench = Tester().bench <add><path>numpy/matrx/defmatrix.py <del><path>numpy/core/defmatrix.py <ide> __all__ = ['matrix', 'bmat', 'mat', 'asmatrix'] <ide> <ide> import sys <del>import numeric as N <del>from numeric import concatenate, isscalar, binary_repr, identity, asanyarray <del>from numerictypes import issubdtype <add>import numpy.core.numeric as N <add>from numpy.core.numeric import concatenate, isscalar, binary_repr, identity, asanyarray <add>from numpy.core.numerictypes import issubdtype <ide> <ide> # make translation table <ide> _table = [None]*256 <ide><path>numpy/matrx/setup.py <add>#!/usr/bin/env python <add>import os <add> <add>def configuration(parent_package='', top_path=None): <add> from numpy.distutils.misc_util import Configuration <add> config = Configuration('matrx', parent_package, top_path) <add> config.add_data_dir('tests') <add> return config <add> <add>if __name__ == "__main__": <add> from numpy.distutils.core import setup <add> config = configuration(top_path='').todict() <add> setup(**config) <ide><path>numpy/matrx/setupscons.py <add>#!/usr/bin/env python <add>import os <add> <add>def configuration(parent_package='', top_path=None): <add> from numpy.distutils.misc_util import Configuration <add> config = Configuration('matrx', parent_package, top_path) <add> config.add_data_dir('tests') <add> return config <add> <add>if __name__ == "__main__": <add> from numpy.distutils.core import setup <add> config = configuration(top_path='').todict() <add> setup(**config) <add><path>numpy/matrx/tests/test_defmatrix.py <del><path>numpy/core/tests/test_defmatrix.py <ide> from numpy.testing import * <ide> from numpy.core import * <del>from numpy.core.defmatrix import matrix_power <add>from numpy import matrix, asmatrix, bmat <add>from numpy.matrx.defmatrix import matrix_power <add>from numpy.matrx import mat <ide> import numpy as np <ide> <ide> class TestCtor(TestCase): <ide><path>numpy/matrx/tests/test_numeric.py <add>from numpy.testing import assert_equal, TestCase <add>from numpy.core import ones <add>from numpy import matrix <add> <add>class TestDot(TestCase): <add> def test_matscalar(self): <add> b1 = matrix(ones((3,3),dtype=complex)) <add> assert_equal(b1*1.0, b1) <ide><path>numpy/setup.py <ide> def configuration(parent_package='',top_path=None): <ide> config.add_subpackage('linalg') <ide> config.add_subpackage('random') <ide> config.add_subpackage('ma') <add> config.add_subpackage('matrx') <ide> config.add_subpackage('doc') <ide> config.add_data_dir('doc') <ide> config.add_data_dir('tests') <ide><path>numpy/setupscons.py <ide> def configuration(parent_package='', top_path=None): <ide> config.add_subpackage('linalg') <ide> config.add_subpackage('random') <ide> config.add_subpackage('ma') <add> config.add_subpackage('matrx') <ide> config.add_data_dir('doc') <ide> config.add_data_dir('tests') <ide>
15
Python
Python
add chroot detection
5359c8d0976807a2846949f29e996a2419490b40
<ide><path>setup.py <ide> <ide> from setuptools import setup <ide> <add>is_chroot = os.stat('/').st_ino != 2 <add> <ide> <ide> def get_data_files(): <ide> data_files = [ <ide> def get_data_files(): <ide> ('share/man/man1', ['man/glances.1']) <ide> ] <ide> <del> if os.name == 'posix' and os.getuid() == 0: # Unix-like + root privileges <add> if hasattr(sys, 'real_prefix'): # virtualenv <add> conf_path = os.path.join(sys.prefix, 'etc', 'glances') <add> elif os.name == 'posix' and (os.getuid() == 0 or is_chroot): <add> # Unix-like + root privileges/chroot environment <ide> if 'bsd' in sys.platform: <ide> conf_path = os.path.join(sys.prefix, 'etc', 'glances') <ide> elif 'linux' in sys.platform: <ide> conf_path = os.path.join('/etc', 'glances') <ide> elif 'darwin' in sys.platform: <ide> conf_path = os.path.join('/usr/local', 'etc', 'glances') <del> elif hasattr(sys, 'real_prefix'): # virtualenv <del> conf_path = os.path.join(sys.prefix, 'etc', 'glances') <ide> elif 'win32' in sys.platform: # windows <ide> conf_path = os.path.join(os.environ.get('APPDATA'), 'glances') <ide> else: # Unix-like + per-user install
1
Javascript
Javascript
fix bug where $eval on undefined throws error
9b392eca3597fdc9dab81d88df75bef75f6e678f
<ide><path>src/Scope.js <ide> function createScope(parent, services, existing) { <ide> $set: bind(instance, setter, instance), <ide> <ide> $eval: function $eval(exp) { <del> if (exp === undefined) { <add> var type = typeof exp; <add> if (type == 'undefined') { <ide> for ( var i = 0, iSize = evalLists.sorted.length; i < iSize; i++) { <ide> for ( var queue = evalLists.sorted[i], <ide> jSize = queue.length, <ide> j= 0; j < jSize; j++) { <ide> instance.$tryEval(queue[j].fn, queue[j].handler); <ide> } <ide> } <del> } else if (typeof exp === 'function'){ <add> } else if (type === 'function') { <ide> return exp.call(instance); <del> } else { <add> } else if (type === 'string') { <ide> return expressionCompile(exp).call(instance); <ide> } <ide> }, <ide> <ide> $tryEval: function (expression, exceptionHandler) { <add> var type = typeof expression; <ide> try { <del> if (typeof expression == 'function') { <add> if (type == 'function') { <ide> return expression.call(instance); <del> } else { <add> } else if (type == 'string'){ <ide> return expressionCompile(expression).call(instance); <ide> } <ide> } catch (e) { <ide><path>test/ScopeSpec.js <ide> describe('scope/model', function(){ <ide> }); <ide> <ide> describe('$eval', function(){ <add> var model; <add> <add> beforeEach(function(){model = createScope();}); <add> <ide> it('should eval function with correct this', function(){ <del> var model = createScope(); <ide> model.$eval(function(){ <ide> this.name = 'works'; <ide> }); <ide> expect(model.name).toEqual('works'); <ide> }); <ide> <ide> it('should eval expression with correct this', function(){ <del> var model = createScope(); <ide> model.$eval('name="works"'); <ide> expect(model.name).toEqual('works'); <ide> }); <ide> <ide> it('should do nothing on empty string and not update view', function(){ <del> var model = createScope(); <ide> var onEval = jasmine.createSpy('onEval'); <ide> model.$onEval(onEval); <ide> model.$eval(''); <ide> expect(onEval).wasNotCalled(); <ide> }); <add> <add> it('should ignore none string/function', function(){ <add> model.$eval(null); <add> model.$eval({}); <add> model.$tryEval(null); <add> model.$tryEval({}); <add> }); <add> <ide> }); <ide> <ide> describe('$watch', function(){
2
Javascript
Javascript
handle incorrect sizes
7b6f56ef610bb886c7fb670fd4df1cd5b041e94f
<ide><path>lib/SizeFormatHelpers.js <ide> const SizeFormatHelpers = exports; <ide> <ide> SizeFormatHelpers.formatSize = size => { <add> if (typeof size !== "number" || Number.isNaN(size) === true) { <add> return "unknown size"; <add> } <add> <ide> if (size <= 0) { <ide> return "0 bytes"; <ide> } <ide><path>test/SizeFormatHelpers.unittest.js <ide> describe("SizeFormatHelpers", () => { <ide> "1.2 GiB" <ide> ); <ide> }); <add> <add> it("should handle undefined/NaN", () => { <add> should(SizeFormatHelpers.formatSize(undefined)).be.eql("unknown size"); <add> should(SizeFormatHelpers.formatSize(NaN)).be.eql("unknown size"); <add> }); <ide> }); <ide> });
2
Python
Python
add defaults for _gather_[list/dict]_attr
a9c6f264127bfac5bb9d499b2e7f1308bf0cee3b
<ide><path>keras/models.py <ide> def flattened_layers(self): <ide> def _gather_list_attr(self, attr): <ide> all_attrs = [] <ide> for layer in self.flattened_layers: <del> all_attrs += getattr(layer, attr) <add> all_attrs += getattr(layer, attr, []) <ide> return all_attrs <ide> <ide> def _gather_dict_attr(self, attr): <ide> all_attrs = {} <ide> for layer in self.flattened_layers: <del> layer_dict = getattr(layer, attr) <add> layer_dict = getattr(layer, attr, {}) <ide> all_attrs = dict(list(all_attrs.items()) + <ide> list(layer_dict.items())) <ide> return all_attrs
1
Ruby
Ruby
remove extra space before 'order by'
8572455d4cf7a61462bde7cef2d3724685c1c44c
<ide><path>lib/arel/visitors/to_sql.rb <ide> def visit_Arel_Nodes_SelectStatement o, collector <ide> } <ide> <ide> unless o.orders.empty? <del> collector << SPACE <ide> collector << ORDER_BY <ide> len = o.orders.length - 1 <ide> o.orders.each_with_index { |x, i| <ide><path>test/visitors/test_to_sql.rb <ide> def dispatch <ide> assert_match(/LIMIT 'omg'/, compile(sc)) <ide> end <ide> <add> it "should contain a single space before ORDER BY" do <add> table = Table.new(:users) <add> test = table.order(table[:name]) <add> sql = compile test <add> assert_match(/"users" ORDER BY/, sql) <add> end <add> <ide> it "should quote LIMIT without column type coercion" do <ide> table = Table.new(:users) <ide> sc = table.where(table[:name].eq(0)).take(1).ast <ide> def dispatch <ide> end <ide> <ide> it "should visit_Arel_Nodes_Assignment" do <del> column = @table["id"] <add> column = @table["id"] <ide> node = Nodes::Assignment.new( <ide> Nodes::UnqualifiedColumn.new(column), <ide> Nodes::UnqualifiedColumn.new(column)
2
Javascript
Javascript
add watch for simple copy
84d6c7f553ca60e0ca8591364974f4e92d838a24
<ide><path>Gruntfile.js <ide> module.exports = function(grunt) { <ide> clean: [ <ide> 'out/**/*', <ide> ], <add> watch: { <add> main: { <add> files: [ <add> 'threejs/**', <add> '3rdparty/**', <add> ], <add> tasks: ['copy'], <add> options: { <add> spawn: false, <add> }, <add> }, <add> }, <add> }); <add> <add> let changedFiles = {}; <add> const onChange = grunt.util._.debounce(function() { <add> grunt.config('copy.main.files', Object.keys(changedFiles).filter(noMds).map((file) => { <add> return { <add> src: file, <add> dest: 'out/', <add> }; <add> })); <add> changedFiles = {}; <add> }, 200); <add> grunt.event.on('watch', function(action, filepath) { <add> changedFiles[filepath] = action; <add> onChange(); <ide> }); <ide> <ide> grunt.registerTask('buildlessons', function() {
1
PHP
PHP
apply fixes from styleci
fe928fbc651c2a436346e5b540e6f8fbaf052fa8
<ide><path>src/Illuminate/Console/Scheduling/Event.php <ide> namespace Illuminate\Console\Scheduling; <ide> <ide> use Closure; <del>use DateTime; <ide> use Carbon\Carbon; <ide> use Cron\CronExpression; <ide> use GuzzleHttp\Client as HttpClient;
1
PHP
PHP
fix method order
0730ec587dc7a4071966a1c65f3c978ccc4ad467
<ide><path>src/Illuminate/Filesystem/Filesystem.php <ide> public function isDirectory($directory) <ide> } <ide> <ide> /** <del> * Determine if the given path is writable. <add> * Determine if the given path is readable. <ide> * <ide> * @param string $path <ide> * @return bool <ide> */ <del> public function isWritable($path) <add> public function isReadable($path) <ide> { <del> return is_writable($path); <add> return is_readable($path); <ide> } <ide> <ide> /** <del> * Determine if the given path is readable. <add> * Determine if the given path is writable. <ide> * <ide> * @param string $path <ide> * @return bool <ide> */ <del> public function isReadable($path) <add> public function isWritable($path) <ide> { <del> return is_readable($path); <add> return is_writable($path); <ide> } <ide> <ide> /**
1
Javascript
Javascript
add ability to disable user code on page load
81028fceacccd186b39d216594052a5e572d15c6
<ide><path>client/commonFramework/code-uri.js <ide> window.common = (function(global) { <ide> return decoded <ide> .split('?') <ide> .splice(1) <add> .pop() <add> .split('&') <ide> .reduce(function(found, param) { <ide> var key = param.split('=')[0]; <ide> if (key === 'solution') { <ide> window.common = (function(global) { <ide> codeUri.isInQuery(location.search) || <ide> codeUri.isInQuery(location.hash); <ide> }, <add> getKeyInQuery(query, keyToFind = '') { <add> return query <add> .split('&') <add> .reduce(function(oldValue, param) { <add> var key = param.split('=')[0]; <add> var value = param.split('=')[1]; <add> if (key === keyToFind) { <add> return value; <add> } <add> return oldValue; <add> }, null); <add> }, <add> getSolutionFromQuery(query = '') { <add> return decodeFcc( <add> codeUri.decode(codeUri.getKeyInQuery(query, 'solution')) <add> ); <add> }, <ide> parse: function() { <ide> if (!codeUri.enabled) { <ide> return null; <ide> } <ide> var query; <ide> if (location.search && codeUri.isInQuery(location.search)) { <ide> query = location.search.replace(/^\?/, ''); <add> <ide> if (history && typeof history.replaceState === 'function') { <ide> history.replaceState( <ide> history.state, <ide> window.common = (function(global) { <ide> } else { <ide> query = location.hash.replace(/^\#\?/, ''); <ide> } <add> <ide> if (!query) { <ide> return null; <ide> } <ide> <del> return query <del> .split('&') <del> .reduce(function(solution, param) { <del> var key = param.split('=')[0]; <del> var value = param.split('=')[1]; <del> if (key === 'solution') { <del> return decodeFcc(codeUri.decode(value || '')); <del> } <del> return solution; <del> }, null); <add> return this.getSolutionFromQuery(query); <ide> }, <ide> querify: function(solution) { <ide> if (!codeUri.enabled) { <ide> window.common = (function(global) { <ide> history.replaceState( <ide> history.state, <ide> null, <del> '?solution=' + codeUri.encode(encodeFcc(solution)) <add> '#?solution=' + <add> codeUri.encode(encodeFcc(solution)) + <add> (codeUri.shouldRun() ? '&run=disabled' : '' ) <ide> ); <ide> } else { <ide> location.hash = '?solution=' + <ide> window.common = (function(global) { <ide> <ide> return solution; <ide> }, <del> enabled: true <add> enabled: true, <add> shouldRun() { <add> return !this.getKeyInQuery( <add> (location.search || location.hash).replace(/^(\?|#\?)/, ''), <add> 'run' <add> ); <add> } <ide> }; <ide> <ide> common.init.push(function() { <ide><path>client/commonFramework/update-preview.js <ide> window.common = (function(global) { <ide> preview.write( <ide> libraryIncludes + <ide> jQuery + <del> code + <add> (common.codeUri.shouldRun() ? code : '' ) + <ide> '<!-- -->' + <ide> iframeScript <ide> );
2
Ruby
Ruby
clarify failed assertion
703d31c20a7b531053d5c009972a89e857b07376
<ide><path>activerecord/test/cases/relations_test.rb <ide> def test_relation_responds_to_delegated_methods <ide> relation = Topic.all <ide> <ide> ["map", "uniq", "sort", "insert", "delete", "update"].each do |method| <del> assert relation.respond_to?(method) <add> assert relation.respond_to?(method), "Topic.all should respond to #{method.inspect}" <ide> end <ide> end <ide>
1
Text
Text
add delete function
ad4d7c72b264acb1250779be74c036c41640e206
<ide><path>guide/english/computer-science/data-structures/linked-lists/index.md <ide> class List <ide> public: <ide> void display(); <ide> void insertBefore(int); <add> void deleteNode(int); <ide> List(); <ide> }; <ide> <ide> void List :: insertBefore(int data) <ide> count++; <ide> } <ide> <add>void List :: deleteNode(int loc) <add>{ <add> //delete first node <add> if(loc == 1 || count == 1) <add> { <add> N *node = new N; <add> node = head; <add> head = head->tail; <add> delete node; <add> } <add> //delete last node <add> else if(loc == count) <add> { <add> N *curr = new N; <add> N *prev = new N; <add> curr = head; <add> while(curr->tail != NULL) <add> { <add> prev = curr; <add> curr = curr->tail; <add> } <add> prev->tail = NULL; <add> end = prev; <add> delete curr; <add> } <add> //delete in between <add> else <add> { <add> N *curr=new N; <add> N *prev=new N; <add> curr=head; <add> for(int i=1;i<loc;i++) <add> { <add> prev=curr; <add> curr=curr->tail; <add> } <add> prev->tail=curr->tail; <add> } <add> count--; <add>} <add> <ide> void List :: display() <ide> { <ide> cout<<"Number of nodes in the list = "<<count<<endl; <ide> int main() <ide> l1.insertBefore(40); <ide> l1.insertBefore(50); <ide> l1.display(); <add> l1.deleteNode(3); <add> l1.display(); <ide> <ide> return 0; <ide> } <ide> Number of nodes in the list = 5 <ide> 30 <ide> 20 <ide> 10 <add>Number of nodes in the list = 4 <add>50 <add>40 <add>20 <add>10 <ide> ``` <ide> <ide> #### Explanation
1
PHP
PHP
trim comment bloat from url class
2f999397e3355e33337dd8dec5a3c170c42a0e65
<ide><path>system/url.php <ide> class URL { <ide> */ <ide> public static function to($url = '', $https = false, $asset = false) <ide> { <del> // ---------------------------------------------------- <del> // Return the URL unchanged if it is already formed. <del> // ---------------------------------------------------- <ide> if (strpos($url, '://') !== false) <ide> { <ide> return $url; <ide> } <ide> <ide> $base = Config::get('application.url'); <ide> <del> // ---------------------------------------------------- <del> // Assets live in the public directory, so we don't <del> // want to append the index file to the URL if the <del> // URL is to an asset. <del> // ---------------------------------------------------- <add> // Assets live in the public directory, so we only want to append <add> // the index file if the URL is to an asset. <ide> if ( ! $asset) <ide> { <ide> $base .= '/'.Config::get('application.index'); <ide> } <ide> <del> // ---------------------------------------------------- <del> // Does the URL need an HTTPS protocol? <del> // ---------------------------------------------------- <ide> if (strpos($base, 'http://') === 0 and $https) <ide> { <ide> $base = 'https://'.substr($base, 7); <ide> public static function to_route($name, $parameters = array(), $https = false) <ide> { <ide> if ( ! is_null($route = Route\Finder::find($name))) <ide> { <del> // ---------------------------------------------------- <ide> // Get the first URI assigned to the route. <del> // ---------------------------------------------------- <ide> $uris = explode(', ', key($route)); <ide> <ide> $uri = substr($uris[0], strpos($uris[0], '/')); <ide> <del> // ---------------------------------------------------- <del> // Replace any parameters in the URI. This allows <del> // the dynamic creation of URLs that contain parameter <del> // wildcards. <del> // ---------------------------------------------------- <add> // Replace any parameters in the URI. This allows the dynamic creation of URLs <add> // that contain parameter wildcards. <ide> foreach ($parameters as $parameter) <ide> { <ide> $uri = preg_replace('/\(.+?\)/', $parameter, $uri, 1); <ide> public static function to_secure_route($name, $parameters = array()) <ide> */ <ide> public static function slug($title, $separator = '-') <ide> { <del> // ---------------------------------------------------- <del> // Remove all characters that are not the separator, <del> // letters, numbers, or whitespace. <del> // ---------------------------------------------------- <add> // Remove all characters that are not the separator, letters, numbers, or whitespace. <ide> $title = preg_replace('![^'.preg_quote($separator).'\pL\pN\s]+!u', '', Str::lower($title)); <ide> <del> // ---------------------------------------------------- <del> // Replace all separator characters and whitespace by <del> // a single separator <del> // ---------------------------------------------------- <add> // Replace all separator characters and whitespace by a single separator <ide> $title = preg_replace('!['.preg_quote($separator).'\s]+!u', $separator, $title); <ide> <ide> return trim($title, $separator); <ide> public static function __callStatic($method, $parameters) <ide> { <ide> $parameters = (isset($parameters[0])) ? $parameters[0] : array(); <ide> <del> // ---------------------------------------------------- <ide> // Dynamically create a secure route URL. <del> // ---------------------------------------------------- <ide> if (strpos($method, 'to_secure_') === 0) <ide> { <ide> return static::to_route(substr($method, 10), $parameters, true); <ide> } <ide> <del> // ---------------------------------------------------- <ide> // Dynamically create a route URL. <del> // ---------------------------------------------------- <ide> if (strpos($method, 'to_') === 0) <ide> { <ide> return static::to_route(substr($method, 3), $parameters);
1
Ruby
Ruby
initialize our instance variables
e3671422556ac61f39539264713ba9c04814b80f
<ide><path>actionpack/lib/action_dispatch/middleware/remote_ip.rb <ide> def call(env) <ide> <ide> class GetIp <ide> def initialize(env, middleware) <del> @env, @middleware = env, middleware <add> @env = env <add> @middleware = middleware <add> @calculate_ip = false <ide> end <ide> <ide> # Determines originating IP address. REMOTE_ADDR is the standard
1
Python
Python
set version to v3.0.0a18
475323cd360c7912d67a6aecf186d26726369a3d
<ide><path>spacy/about.py <ide> # fmt: off <ide> __title__ = "spacy-nightly" <del>__version__ = "3.0.0a17" <add>__version__ = "3.0.0a18" <ide> __release__ = True <ide> __download_url__ = "https://github.com/explosion/spacy-models/releases/download" <ide> __compatibility__ = "https://raw.githubusercontent.com/explosion/spacy-models/master/compatibility.json"
1
Text
Text
make contributing.md more contributor-friendly
baeb98e847a8339ed2e234aa8504d397f719e8a8
<ide><path>contributing.md <ide> # Contributing to Next.js <ide> <del>Read about our [Commitment to Open Source](https://vercel.com/oss). <add>Read about our [Commitment to Open Source](https://vercel.com/oss). To <add>contribute to [our examples](examples), please see **[Adding <add>examples](#adding-examples)** below. <ide> <del>1. [Fork](https://help.github.com/articles/fork-a-repo/) this repository to your own GitHub account and then [clone](https://help.github.com/articles/cloning-a-repository/) it to your local device. <del>2. Create a new branch: `git checkout -b MY_BRANCH_NAME` <del>3. Install yarn: `npm install -g yarn` <del>4. Install the dependencies: `yarn` <del>5. Run `yarn dev` to build and watch for code changes <del>6. In a new terminal, run `yarn types` to compile declaration files from TypeScript <del>7. The development branch is `canary` (this is the branch pull requests should be made against). On a release, the relevant parts of the changes in the `canary` branch are rebased into `master`. <add>## Developing <ide> <del>> You may need to run `yarn types` again if your types get outdated. <add>The development branch is `canary`, and this is the branch that all pull <add>requests should be made against. After publishing a stable release, the changes <add>in the `canary` branch are rebased into `master`. The changes on the `canary` <add>branch are published to the `@canary` dist-tag daily. <ide> <del>To contribute to [our examples](examples), take a look at the [“Adding examples” <del>section](#adding-examples). <add>To develop locally: <add> <add>1. [Fork](https://help.github.com/articles/fork-a-repo/) this repository to your <add> own GitHub account and then <add> [clone](https://help.github.com/articles/cloning-a-repository/) it to your <add> local device. <add>2. Create a new branch: <add> ``` <add> git checkout -b MY_BRANCH_NAME <add> ``` <add>3. Install yarn: <add> ``` <add> npm install -g yarn <add> ``` <add>4. Install the dependencies with: <add> ``` <add> yarn <add> ``` <add>5. Start developing and watch for code changes: <add> ``` <add> yarn dev <add> ``` <add>6. In a new terminal, run `yarn types` to compile declaration files from <add> TypeScript. <add> <add> _Note: You may need to repeat this step if your types get outdated._ <add> <add>For instructions on how to build a project with your local version of the CLI, <add>see **[Developing with your local version of Next.js](#developing-with-your-local-version-of-nextjs)** <add>below. (Naively linking the binary is not sufficient to develop locally.) <ide> <ide> ## Building <ide> <ide> yarn prepublish <ide> <ide> If you need to clean the project for any reason, use `yarn clean`. <ide> <del>## Adding warning/error descriptions <del> <del>In Next.js we have a system to add helpful links to warnings and errors. <del> <del>This allows for the logged message to be short while giving a broader description and instructions on how to solve the warning/error. <add>## Testing <ide> <del>In general all warnings and errors added should have these links attached. <del> <del>Below are the steps to add a new link: <del> <del>- Create a new markdown file under the `errors` directory based on `errors/template.md`: `cp errors/template.md errors/<error-file-name>.md` <del>- Add the newly added file to `errors/manifest.json` <del>- Add the following url to your warning/error: `https://nextjs.org/docs/messages/<file-path-without-dotmd>`. For example to link to `errors/api-routes-static-export.md` you use the url: `https://nextjs.org/docs/messages/api-routes-static-export` <del> <del>## To run tests <del> <del>Make sure you have `chromedriver` installed for your Chrome version. You can install it with <add>Make sure you have `chromedriver` installed, and it should match your Chrome version. <add>You can install it with: <ide> <add>- `apt install chromedriver` on Ubuntu/Debian <ide> - `brew install --cask chromedriver` on Mac OS X <ide> - `chocolatey install chromedriver` on Windows <add> <ide> - Or manually download the version that matches your installed chrome version (if there's no match, download a version under it, but not above) from the [chromedriver repo](https://chromedriver.storage.googleapis.com/index.html) and add the binary to `<next-repo>/node_modules/.bin` <ide> <ide> You may also have to [install Rust](https://www.rust-lang.org/tools/install) and build our native packages to see all tests pass locally. We check in binaries for the most common targets and those required for CI so that most people don't have to, but if you do not see a binary for your target in `packages/next/native`, you can build it by running `yarn --cwd packages/next build-native`. If you are working on the Rust code and you need to build the binaries for ci, you can manually trigger [the workflow](https://github.com/vercel/next.js/actions/workflows/build_native.yml) to build and commit with the "Run workflow" button. <ide> <del>Running all tests: <add>### Running tests <ide> <ide> ```sh <ide> yarn testonly <ide> Running one test in the `production` test suite: <ide> yarn testonly --testPathPattern "production" -t "should allow etag header support" <ide> ``` <ide> <del>## Running the integration apps <add>### Running the integration apps <ide> <ide> Running examples can be done with: <ide> <ide> EXAMPLE=./test/integration/basic <ide> ) <ide> ``` <ide> <del>## Running your own app with locally compiled version of Next.js <del> <del>1. Move your app inside of the Next.js monorepo. <del> <del>2. Run with `yarn next-with-deps ./app-path-in-monorepo` <add>## Developing with your local version of Next.js <ide> <del>This will use the version of `next` built inside of the Next.js monorepo and the main `yarn dev` monorepo command can be running to make changes to the local Next.js version at the same time (some changes might require re-running `yarn next-with-deps` to take affect). <add>There are two options to develop with your local version of the codebase: <ide> <del>or <add>### Set as local dependency in package.json <ide> <ide> 1. In your app's `package.json`, replace: <ide> <ide> or <ide> with: <ide> <ide> ```json <del> "next": "file:<local-path-to-cloned-nextjs-repo>/packages/next", <add> "next": "file:/path/to/next.js/packages/next", <ide> ``` <ide> <ide> 2. In your app's root directory, make sure to remove `next` from `node_modules` with: <ide> or <ide> yarn install --force <ide> ``` <ide> <add>or <add> <add>### Develop inside the monorepo <add> <add>1. Move your app inside of the Next.js monorepo. <add> <add>2. Run with `yarn next-with-deps ./app-path-in-monorepo` <add> <add>This will use the version of `next` built inside of the Next.js monorepo and the <add>main `yarn dev` monorepo command can be running to make changes to the local <add>Next.js version at the same time (some changes might require re-running `yarn next-with-deps` to take affect). <add> <add>## Adding warning/error descriptions <add> <add>In Next.js we have a system to add helpful links to warnings and errors. <add> <add>This allows for the logged message to be short while giving a broader description and instructions on how to solve the warning/error. <add> <add>In general all warnings and errors added should have these links attached. <add> <add>Below are the steps to add a new link: <add> <add>1. Create a new markdown file under the `errors` directory based on <add> `errors/template.md`: <add> <add> ```shell <add> cp errors/template.md errors/<error-file-name>.md <add> ``` <add> <add>2. Add the newly added file to `errors/manifest.json` <add>3. Add the following url to your warning/error: <add> `https://nextjs.org/docs/messages/<file-path-without-dotmd>`. <add> <add> For example, to link to `errors/api-routes-static-export.md` you use the url: <add> `https://nextjs.org/docs/messages/api-routes-static-export` <add> <ide> ## Adding examples <ide> <ide> When you add an example to the [examples](examples) directory, don’t forget to add a `README.md` file with the following format:
1
Java
Java
remove fabricbinder interface
4802cffa14c5540d0a4a2d842108f6a14ac191f1
<ide><path>ReactAndroid/src/main/java/com/facebook/react/fabric/FabricBinder.java <del>/** <del> * Copyright (c) Facebook, Inc. and its affiliates. <del> * <del> * This source code is licensed under the MIT license found in the <del> * LICENSE file in the root directory of this source tree. <del> */ <del> <del>package com.facebook.react.fabric; <del> <del>public interface FabricBinder<T extends FabricBinding> { <del> <del> void setBinding(T binding); <del> <del>} <ide><path>ReactAndroid/src/main/java/com/facebook/react/fabric/FabricBinding.java <ide> public interface FabricBinding { <ide> // TODO: T31905686 change types of UIManager and EventBeatManager when moving to OSS <ide> void register( <ide> JavaScriptContextHolder jsContext, <del> FabricBinder fabricBinder, <add> FabricUIManager fabricUIManager, <ide> EventBeatManager eventBeatManager, <ide> MessageQueueThread jsMessageQueueThread, <ide> ComponentFactoryDelegate componentFactoryDelegate); <ide><path>ReactAndroid/src/main/java/com/facebook/react/fabric/FabricJSIModuleProvider.java <ide> public FabricJSIModuleProvider( <ide> public UIManager get() { <ide> final EventBeatManager eventBeatManager = <ide> new EventBeatManager(mJSContext, mReactApplicationContext); <del> final UIManager uiManager = createUIManager(eventBeatManager); <add> final FabricUIManager uiManager = createUIManager(eventBeatManager); <ide> Systrace.beginSection( <ide> Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "FabricJSIModuleProvider.registerBinding"); <ide> final FabricBinding binding = new Binding(); <ide> public UIManager get() { <ide> .getCatalystInstance() <ide> .getReactQueueConfiguration() <ide> .getJSQueueThread(); <del> binding.register(mJSContext, (FabricBinder) uiManager, eventBeatManager, jsMessageQueueThread, <add> binding.register(mJSContext, uiManager, eventBeatManager, jsMessageQueueThread, <ide> mComponentFactoryDelegate); <ide> Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE); <ide> return uiManager; <ide> } <ide> <del> private UIManager createUIManager(EventBeatManager eventBeatManager) { <add> private FabricUIManager createUIManager(EventBeatManager eventBeatManager) { <ide> Systrace.beginSection( <ide> Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "FabricJSIModuleProvider.createUIManager"); <ide> UIManagerModule nativeModule = mReactApplicationContext.getNativeModule(UIManagerModule.class); <ide><path>ReactAndroid/src/main/java/com/facebook/react/fabric/FabricUIManager.java <ide> import java.util.concurrent.ConcurrentHashMap; <ide> <ide> @SuppressLint("MissingNativeLoadLibrary") <del>public class FabricUIManager implements UIManager, FabricBinder<Binding>, LifecycleEventListener { <add>public class FabricUIManager implements UIManager, LifecycleEventListener { <ide> <ide> private static final String TAG = FabricUIManager.class.getSimpleName(); <ide> <ide> private void flushMountItems() { <ide> } <ide> } <ide> <del> @Override <ide> public void setBinding(Binding binding) { <ide> mBinding = binding; <ide> } <ide><path>ReactAndroid/src/main/java/com/facebook/react/fabric/jsi/Binding.java <ide> import com.facebook.react.bridge.JavaScriptContextHolder; <ide> import com.facebook.react.bridge.NativeMap; <ide> import com.facebook.react.bridge.queue.MessageQueueThread; <del>import com.facebook.react.fabric.FabricBinder; <ide> import com.facebook.react.fabric.FabricBinding; <add>import com.facebook.react.fabric.FabricUIManager; <ide> import com.facebook.react.uimanager.PixelUtil; <ide> <ide> @DoNotStrip <ide> public native void setConstraints( <ide> @Override <ide> public void register( <ide> JavaScriptContextHolder jsContext, <del> FabricBinder fabricModule, <add> FabricUIManager fabricUIManager, <ide> EventBeatManager eventBeatManager, <ide> MessageQueueThread jsMessageQueueThread, <ide> ComponentFactoryDelegate componentFactoryDelegate) { <del> fabricModule.setBinding(this); <add> fabricUIManager.setBinding(this); <ide> installFabricUIManager( <del> jsContext.get(), fabricModule, eventBeatManager, jsMessageQueueThread, componentFactoryDelegate); <add> jsContext.get(), fabricUIManager, eventBeatManager, jsMessageQueueThread, componentFactoryDelegate); <ide> setPixelDensity(PixelUtil.getDisplayMetricDensity()); <ide> } <ide>
5
Python
Python
correct the fill_diagonal examples
8910afb52490f113b855299d1126d5935f8b0300
<ide><path>numpy/lib/index_tricks.py <ide> def fill_diagonal(a, val, wrap=False): <ide> # tall matrices no wrap <ide> >>> a = np.zeros((5, 3),int) <ide> >>> fill_diagonal(a, 4) <add> >>> a <ide> array([[4, 0, 0], <ide> [0, 4, 0], <ide> [0, 0, 4], <ide> def fill_diagonal(a, val, wrap=False): <ide> <ide> # tall matrices wrap <ide> >>> a = np.zeros((5, 3),int) <del> >>> fill_diagonal(a, 4) <add> >>> fill_diagonal(a, 4, wrap=True) <add> >>> a <ide> array([[4, 0, 0], <ide> [0, 4, 0], <ide> [0, 0, 4], <ide> def fill_diagonal(a, val, wrap=False): <ide> <ide> # wide matrices <ide> >>> a = np.zeros((3, 5),int) <del> >>> fill_diagonal(a, 4) <add> >>> fill_diagonal(a, 4, wrap=True) <add> >>> a <ide> array([[4, 0, 0, 0, 0], <ide> [0, 4, 0, 0, 0], <ide> [0, 0, 4, 0, 0]])
1
Text
Text
change html `img` tag to lowercase [ci skip]
95242fa69b0f8608b3b9329e727ca2911c1d7e7d
<ide><path>guides/source/security.md <ide> As a second step, _it is good practice to escape all output of the application_, <ide> Network traffic is mostly based on the limited Western alphabet, so new character encodings, such as Unicode, emerged, to transmit characters in other languages. But, this is also a threat to web applications, as malicious code can be hidden in different encodings that the web browser might be able to process, but the web application might not. Here is an attack vector in UTF-8 encoding: <ide> <ide> ```html <del><IMG SRC=&#106;&#97;&#118;&#97;&#115;&#99;&#114;&#105;&#112;&#116;&#58;&#97; <add><img src=&#106;&#97;&#118;&#97;&#115;&#99;&#114;&#105;&#112;&#116;&#58;&#97; <ide> &#108;&#101;&#114;&#116;&#40;&#39;&#88;&#83;&#83;&#39;&#41;> <ide> ``` <ide>
1
Java
Java
remove unnecessary import
cc3616da66ade8d4063a1a2c9507a12e812188e5
<ide><path>spring-core-test/src/test/java/org/springframework/core/test/io/support/MockSpringFactoriesLoaderTests.java <ide> import org.junit.jupiter.api.Test; <ide> <ide> import org.springframework.core.annotation.Order; <del>import org.springframework.core.test.io.support.MockSpringFactoriesLoader; <ide> <ide> import static org.assertj.core.api.Assertions.assertThat; <ide>
1
Go
Go
fix data race in logfile
90c54320c88ca342a545363409a32b531f8e3e4f
<ide><path>api/types/backend/backend.go <ide> type PartialLogMetaData struct { <ide> // LogMessage is datastructure that represents piece of output produced by some <ide> // container. The Line member is a slice of an array whose contents can be <ide> // changed after a log driver's Log() method returns. <del>// changes to this struct need to be reflect in the reset method in <del>// daemon/logger/logger.go <ide> type LogMessage struct { <ide> Line []byte <ide> Source string <ide><path>daemon/logger/logger.go <ide> func PutMessage(msg *Message) { <ide> // Message is subtyped from backend.LogMessage because there is a lot of <ide> // internal complexity around the Message type that should not be exposed <ide> // to any package not explicitly importing the logger type. <del>// <del>// Any changes made to this struct must also be updated in the `reset` function <ide> type Message backend.LogMessage <ide> <ide> // reset sets the message back to default values <ide> // This is used when putting a message back into the message pool. <del>// Any changes to the `Message` struct should be reflected here. <ide> func (m *Message) reset() { <del> m.Line = m.Line[:0] <del> m.Source = "" <del> m.Attrs = nil <del> m.PLogMetaData = nil <del> <del> m.Err = nil <add> *m = Message{Line: m.Line[:0]} <ide> } <ide> <ide> // AsLogMessage returns a pointer to the message as a pointer to <ide><path>daemon/logger/loggerutils/logfile.go <ide> func (w *LogFile) WriteLogEntry(msg *logger.Message) error { <ide> return errors.Wrap(err, "error marshalling log message") <ide> } <ide> <add> ts := msg.Timestamp <ide> logger.PutMessage(msg) <add> msg = nil // Turn use-after-put bugs into panics. <ide> <ide> w.mu.Lock() <ide> if w.closed { <ide> func (w *LogFile) WriteLogEntry(msg *logger.Message) error { <ide> n, err := w.f.Write(b) <ide> if err == nil { <ide> w.currentSize += int64(n) <del> w.lastTimestamp = msg.Timestamp <add> w.lastTimestamp = ts <ide> } <ide> <ide> w.mu.Unlock()
3
Python
Python
update unique docstring example
17612fc5f7194be946433d0bab6d1a7792e1226e
<ide><path>numpy/lib/arraysetops.py <ide> def unique(ar, return_index=False, return_inverse=False, <ide> >>> u <ide> array([1, 2, 3, 4, 6]) <ide> >>> indices <del> array([0, 1, 4, ..., 1, 2, 1]) <add> array([0, 1, 4, 3, 1, 2, 1]) <ide> >>> u[indices] <del> array([1, 2, 6, ..., 2, 3, 2]) <add> array([1, 2, 6, 4, 2, 3, 2]) <ide> <ide> """ <ide> ar = np.asanyarray(ar)
1
PHP
PHP
fix bug in pagination page resolution
83ad23cbd3b7d1b3930cd68d57776aae331ce7f5
<ide><path>src/Illuminate/Pagination/PaginationServiceProvider.php <ide> public function register() <ide> }); <ide> <ide> Paginator::currentPageResolver(function ($pageName = 'page') { <del> return $this->app['request']->input($pageName); <add> $page = $this->app['request']->input($pageName); <add> <add> if (filter_var($page, FILTER_VALIDATE_INT) !== false && (int) $page >= 1) { <add> return $page; <add> } <add> <add> return 1; <ide> }); <ide> } <ide> }
1
Text
Text
add an explanatory gif
49b10023acc89d9beca877ef69a2aee9c1cd30b1
<ide><path>README.md <ide> Read **[The Evolution of Flux Frameworks](https://medium.com/@dan_abramov/the-ev <ide> <ide> ## Demo <ide> <add>![gif](https://s3.amazonaws.com/f.cl.ly/items/2Z2D3U260d2A311k2B0z/Screen%20Recording%202015-06-03%20at%2003.22%20pm.gif) <add> <ide> ``` <ide> git clone https://github.com/gaearon/redux.git redux <ide> cd redux
1
Javascript
Javascript
update nested vlist warning to error
646605b90e666c4b0d1c1200a137eacf62b46f87
<ide><path>Libraries/Lists/VirtualizedList.js <ide> class VirtualizedList extends React.PureComponent<Props, State> { <ide> this.context == null <ide> ) { <ide> // TODO (T46547044): use React.warn once 16.9 is sync'd: https://github.com/facebook/react/pull/15170 <del> console.warn( <add> console.error( <ide> 'VirtualizedLists should never be nested inside plain ScrollViews with the same ' + <del> 'orientation - use another VirtualizedList-backed container instead.', <add> 'orientation because it can break windowing and other functionality - use another ' + <add> 'VirtualizedList-backed container instead.', <ide> ); <ide> this._hasWarned.nesting = true; <ide> }
1
Java
Java
reimplement the 'single' operator
7ce4c84f97c9cff52361fe5362cb5473a5226a1b
<ide><path>rxjava-core/src/main/java/rx/Observable.java <ide> import rx.operators.OperationReplay; <ide> import rx.operators.OperationSample; <ide> import rx.operators.OperationSequenceEqual; <del>import rx.operators.OperationSingle; <add>import rx.operators.OperatorSingle; <ide> import rx.operators.OperationSkip; <ide> import rx.operators.OperationSkipLast; <ide> import rx.operators.OperationSkipUntil; <ide> public final Observable<T> serialize() { <ide> * @see "MSDN: Observable.singleAsync()" <ide> */ <ide> public final Observable<T> single() { <del> return create(OperationSingle.<T> single(this)); <add> return lift(new OperatorSingle<T>()); <ide> } <ide> <ide> /** <ide> public final Observable<T> single(Func1<? super T, Boolean> predicate) { <ide> * @see "MSDN: Observable.singleOrDefaultAsync()" <ide> */ <ide> public final Observable<T> singleOrDefault(T defaultValue) { <del> return create(OperationSingle.<T> singleOrDefault(this, defaultValue)); <add> return lift(new OperatorSingle<T>(defaultValue)); <ide> } <ide> <ide> /** <ide><path>rxjava-core/src/main/java/rx/operators/OperationSingle.java <del>/** <del> * Copyright 2014 Netflix, Inc. <del> * <del> * Licensed under the Apache License, Version 2.0 (the "License"); <del> * you may not use this file except in compliance with the License. <del> * You may obtain a copy of the License at <del> * <del> * http://www.apache.org/licenses/LICENSE-2.0 <del> * <del> * Unless required by applicable law or agreed to in writing, software <del> * distributed under the License is distributed on an "AS IS" BASIS, <del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <del> * See the License for the specific language governing permissions and <del> * limitations under the License. <del> */ <del>package rx.operators; <del> <del>import rx.Observable; <del>import rx.Observable.OnSubscribeFunc; <del>import rx.Observer; <del>import rx.Subscription; <del> <del>/** <del> * If the Observable completes after emitting a single item that matches a <del> * predicate, return an Observable containing that item. If it emits more than <del> * one such item or no item, throw an IllegalArgumentException. <del> */ <del>public class OperationSingle { <del> <del> public static <T> OnSubscribeFunc<T> single( <del> final Observable<? extends T> source) { <del> return single(source, false, null); <del> } <del> <del> public static <T> OnSubscribeFunc<T> singleOrDefault( <del> final Observable<? extends T> source, final T defaultValue) { <del> return single(source, true, defaultValue); <del> } <del> <del> private static <T> OnSubscribeFunc<T> single( <del> final Observable<? extends T> source, <del> final boolean hasDefaultValue, final T defaultValue) { <del> return new OnSubscribeFunc<T>() { <del> <del> @Override <del> public Subscription onSubscribe(final Observer<? super T> observer) { <del> final SafeObservableSubscription subscription = new SafeObservableSubscription(); <del> subscription.wrap(source.subscribe(new Observer<T>() { <del> <del> private T value; <del> private boolean isEmpty = true; <del> private boolean hasTooManyElemenets; <del> <del> @Override <del> public void onCompleted() { <del> if (hasTooManyElemenets) { <del> // We has already sent an onError message <del> } else { <del> if (isEmpty) { <del> if (hasDefaultValue) { <del> observer.onNext(defaultValue); <del> observer.onCompleted(); <del> } else { <del> observer.onError(new IllegalArgumentException( <del> "Sequence contains no elements")); <del> } <del> } else { <del> observer.onNext(value); <del> observer.onCompleted(); <del> } <del> } <del> } <del> <del> @Override <del> public void onError(Throwable e) { <del> observer.onError(e); <del> } <del> <del> @Override <del> public void onNext(T value) { <del> if (isEmpty) { <del> this.value = value; <del> isEmpty = false; <del> } else { <del> hasTooManyElemenets = true; <del> observer.onError(new IllegalArgumentException( <del> "Sequence contains too many elements")); <del> subscription.unsubscribe(); <del> } <del> } <del> })); <del> return subscription; <del> } <del> }; <del> } <del>} <ide><path>rxjava-core/src/main/java/rx/operators/OperatorSingle.java <add>/** <add> * Copyright 2014 Netflix, Inc. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add>package rx.operators; <add> <add>import rx.Observable.Operator; <add>import rx.Subscriber; <add> <add>/** <add> * If the Observable completes after emitting a single item that matches a <add> * predicate, return an Observable containing that item. If it emits more than <add> * one such item or no item, throw an IllegalArgumentException. <add> */ <add>public final class OperatorSingle<T> implements Operator<T, T> { <add> <add> private final boolean hasDefaultValue; <add> private final T defaultValue; <add> <add> public OperatorSingle() { <add> this(false, null); <add> } <add> <add> public OperatorSingle(T defaultValue) { <add> this(true, defaultValue); <add> } <add> <add> private OperatorSingle(boolean hasDefaultValue, final T defaultValue) { <add> this.hasDefaultValue = hasDefaultValue; <add> this.defaultValue = defaultValue; <add> } <add> <add> @Override <add> public Subscriber<? super T> call(final Subscriber<? super T> subscriber) { <add> return new Subscriber<T>(subscriber) { <add> <add> private T value; <add> private boolean isNonEmpty = false; <add> private boolean hasTooManyElemenets = false; <add> <add> @Override <add> public void onNext(T value) { <add> if (isNonEmpty) { <add> hasTooManyElemenets = true; <add> subscriber.onError(new IllegalArgumentException("Sequence contains too many elements")); <add> } else { <add> this.value = value; <add> isNonEmpty = true; <add> } <add> } <add> <add> @Override <add> public void onCompleted() { <add> if (hasTooManyElemenets) { <add> // We has already sent an onError message <add> } else { <add> if (isNonEmpty) { <add> subscriber.onNext(value); <add> subscriber.onCompleted(); <add> } else { <add> if (hasDefaultValue) { <add> subscriber.onNext(defaultValue); <add> subscriber.onCompleted(); <add> } else { <add> subscriber.onError(new IllegalArgumentException("Sequence contains no elements")); <add> } <add> } <add> } <add> } <add> <add> @Override <add> public void onError(Throwable e) { <add> subscriber.onError(e); <add> } <add> <add> }; <add> } <add> <add>} <add><path>rxjava-core/src/test/java/rx/operators/OperatorSingleTest.java <del><path>rxjava-core/src/test/java/rx/operators/OperationSingleTest.java <ide> import rx.Observer; <ide> import rx.functions.Func1; <ide> <del>public class OperationSingleTest { <add>public class OperatorSingleTest { <ide> <ide> @Test <ide> public void testSingle() {
4
PHP
PHP
add space after component closing tag
48d1c194375edd024edacd918d17ef0cce587842
<ide><path>src/Illuminate/View/Compilers/ComponentTagCompiler.php <ide> protected function compileSelfClosingTags(string $value) <ide> <ide> $attributes = $this->getAttributesFromAttributeString($matches['attributes']); <ide> <del> return $this->componentString($matches[1], $attributes)."\n@endcomponentClass"; <add> return $this->componentString($matches[1], $attributes)."\n@endcomponentClass "; <ide> }, $value); <ide> } <ide> <ide> protected function partitionDataAndAttributes($class, array $attributes) <ide> */ <ide> protected function compileClosingTags(string $value) <ide> { <del> return preg_replace("/<\/\s*x[-\:][\w\-\:\.]*\s*>/", ' @endcomponentClass', $value); <add> return preg_replace("/<\/\s*x[-\:][\w\-\:\.]*\s*>/", ' @endcomponentClass ', $value); <ide> } <ide> <ide> /** <ide><path>tests/View/Blade/BladeComponentTagCompilerTest.php <ide> public function testBasicComponentParsing() <ide> <ide> $this->assertSame("<div> @component('Illuminate\Tests\View\Blade\TestAlertComponent', []) <ide> <?php \$component->withAttributes(['type' => 'foo','limit' => '5','@click' => 'foo','required' => true]); ?> <del>@endcomponentClass @component('Illuminate\Tests\View\Blade\TestAlertComponent', []) <add>@endcomponentClass @component('Illuminate\Tests\View\Blade\TestAlertComponent', []) <ide> <?php \$component->withAttributes([]); ?> <del>@endcomponentClass</div>", trim($result)); <add>@endcomponentClass </div>", trim($result)); <ide> } <ide> <ide> public function testBasicComponentWithEmptyAttributesParsing() <ide> public function testBasicComponentWithEmptyAttributesParsing() <ide> <ide> $this->assertSame("<div> @component('Illuminate\Tests\View\Blade\TestAlertComponent', []) <ide> <?php \$component->withAttributes(['type' => '','limit' => '','@click' => '','required' => true]); ?> <del>@endcomponentClass</div>", trim($result)); <add>@endcomponentClass </div>", trim($result)); <ide> } <ide> <ide> public function testDataCamelCasing() <ide> public function testSelfClosingComponentsCanBeCompiled() <ide> <ide> $this->assertSame("<div> @component('Illuminate\Tests\View\Blade\TestAlertComponent', []) <ide> <?php \$component->withAttributes([]); ?> <del>@endcomponentClass</div>", trim($result)); <add>@endcomponentClass </div>", trim($result)); <ide> } <ide> <ide> public function testClassNamesCanBeGuessed() <ide> public function testSelfClosingComponentsCanBeCompiledWithDataAndAttributes() <ide> @endcomponentClass", trim($result)); <ide> } <ide> <add> public function testComponentsCanHaveAttachedWord() <add> { <add> $result = (new ComponentTagCompiler(['profile' => TestProfileComponent::class]))->compileTags('<x-profile></x-profile>Words'); <add> <add> $this->assertSame("@component('Illuminate\Tests\View\Blade\TestProfileComponent', []) <add><?php \$component->withAttributes([]); ?> @endcomponentClass Words", trim($result)); <add> } <add> <add> public function testSelfClosingComponentsCanHaveAttachedWord() <add> { <add> $result = (new ComponentTagCompiler(['alert' => TestAlertComponent::class]))->compileTags('<x-alert/>Words'); <add> <add> $this->assertSame("@component('Illuminate\Tests\View\Blade\TestAlertComponent', []) <add><?php \$component->withAttributes([]); ?> <add>@endcomponentClass Words", trim($result)); <add> } <add> <ide> public function testSelfClosingComponentsCanBeCompiledWithBoundData() <ide> { <ide> $result = (new ComponentTagCompiler(['alert' => TestAlertComponent::class]))->compileTags('<x-alert :title="$title" class="bar" />');
2
Python
Python
remove print statement in test
29e60ab372e1a123be2f2884a6818f9a2508bf68
<ide><path>tests/keras/test_initializations.py <ide> def _runner(init, shape, target_mean=None, target_std=None, <ide> target_max=None, target_min=None): <ide> variable = init(shape) <ide> output = K.get_value(variable) <del> print target_std <del> print output.std() <del> print output.mean() <ide> lim = 1e-2 <ide> if target_std is not None: <ide> assert abs(output.std() - target_std) < lim
1
PHP
PHP
update copyright to match new style
35ca61ad80b27702b74a0f85bdd30b245de1d013
<ide><path>lib/Cake/Utility/ViewVarsTrait.php <ide> <?php <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <del> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) <add> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide> * Licensed under The MIT License <ide> * Redistributions of files must retain the above copyright notice. <ide> * <del> * @copyright Copyright 2005-2013, Cake Software Foundation, Inc. (http://cakefoundation.org) <add> * @copyright Copyright (c), Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * @link http://cakephp.org CakePHP(tm) Project <ide> * @since CakePHP(tm) v 3.0.0 <ide> * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
1
Text
Text
add model card for electricidad-base-generator
0f94151dc7809128b40ab68ba164742fe1c5b4e6
<ide><path>model_cards/mrm8488/electricidad-base-generator/README.md <add>--- <add>language: es <add>thumbnail: https://i.imgur.com/uxAvBfh.png <add> <add> <add>--- <add> <add>## ELECTRICIDAD: The Spanish Electra [Imgur](https://imgur.com/uxAvBfh) <add> <add>**Electricidad-base-generator** (uncased) is a ```base``` Electra like model (generator in this case) trained on a + 20 GB of the [OSCAR](https://oscar-corpus.com/) Spanish corpus. <add> <add>As mentioned in the original [paper](https://openreview.net/pdf?id=r1xMH1BtvB): <add>**ELECTRA** is a new method for self-supervised language representation learning. It can be used to pre-train transformer networks using relatively little compute. ELECTRA models are trained to distinguish "real" input tokens vs "fake" input tokens generated by another neural network, similar to the discriminator of a [GAN](https://arxiv.org/pdf/1406.2661.pdf). At small scale, ELECTRA achieves strong results even when trained on a single GPU. At large scale, ELECTRA achieves state-of-the-art results on the [SQuAD 2.0](https://rajpurkar.github.io/SQuAD-explorer/) dataset. <add> <add>For a detailed description and experimental results, please refer the paper [ELECTRA: Pre-training Text Encoders as Discriminators Rather Than Generators](https://openreview.net/pdf?id=r1xMH1BtvB). <add> <add> <add> <add> <add> <add>## Fast example of usage 🚀 <add> <add>```python <add>from transformers import pipeline <add> <add>fill_mask = pipeline( <add> "fill-mask", <add> model="mrm8488/electricidad-base-generator", <add> tokenizer="mrm8488/electricidad-base-generator" <add>) <add> <add>print( <add> fill_mask(f"HuggingFace está creando {fill_mask.tokenizer.mask_token} que la comunidad usa para resolver tareas de NLP.") <add>) <add> <add># Output: [{'sequence': '[CLS] huggingface esta creando herramientas que la comunidad usa para resolver tareas de nlp. [SEP]', 'score': 0.0896105170249939, 'token': 8760, 'token_str': 'herramientas'}, ...] <add> <add>``` <add> <add>## Acknowledgments <add> <add>I thank [🤗/transformers team](https://github.com/huggingface/transformers) for allowing me to train the model (specially to [Julien Chaumond](https://twitter.com/julien_c)). <add> <add> <add> <add>> Created by [Manuel Romero/@mrm8488](https://twitter.com/mrm8488) <add> <add>> Made with <span style="color: #e25555;">&hearts;</span> in Spain
1
Python
Python
add tests for filled_like function
474ec4858cd3b6a09cd8bec01c67759d95896cca
<ide><path>numpy/core/numeric.py <ide> def ones_like(a, dtype=None, order='K', subok=True): <ide> multiarray.copyto(res, 1, casting='unsafe') <ide> return res <ide> <del>def _check_dtype_nan(dtype): <del> if not issubdtype(dtype, 'float'): <del> raise ValueError('Invalid dtype because only floating point numbers ' <del> 'can represent non-numbers as defined in ' <del> 'IEEE 754-1985.') <del> <ide> def filled(shape, val, dtype=None, order='C'): <ide> """ <ide> Return a new array of given shape and type, filled with `val`. <ide> def filled(shape, val, dtype=None, order='C'): <ide> empty : Return a new uninitialized array. <ide> <ide> """ <del> <del> _check_dtype_nan(dtype) <ide> a = empty(shape, dtype, order) <ide> multiarray.copyto(a, val, casting='unsafe') <ide> return a <ide> def filled_like(a, val, dtype=None, order='K', subok=True): <ide> filled : Fill a new array. <ide> <ide> """ <del> <del> _check_dtype_nan(dtype) <ide> res = empty_like(a, dtype=dtype, order=order, subok=subok) <ide> multiarray.copyto(res, val, casting='unsafe') <ide> return res <ide><path>numpy/core/tests/test_numeric.py <ide> def setUp(self): <ide> (arange(24).reshape(4,3,2).swapaxes(0,1), '?'), <ide> ] <ide> <del> def check_like_function(self, like_function, value): <add> def check_like_function(self, like_function, value, fill_value=False): <add> if fill_value: <add> fill_kwarg = {'val': value} <add> else: <add> fill_kwarg = {} <ide> for d, dtype in self.data: <ide> # default (K) order, dtype <del> dz = like_function(d, dtype=dtype) <add> dz = like_function(d, dtype=dtype, **fill_kwarg) <ide> assert_equal(dz.shape, d.shape) <ide> assert_equal(array(dz.strides)*d.dtype.itemsize, <ide> array(d.strides)*dz.dtype.itemsize) <ide> def check_like_function(self, like_function, value): <ide> else: <ide> assert_equal(dz.dtype, np.dtype(dtype)) <ide> if not value is None: <del> assert_(all(dz == value)) <add> if fill_value: <add> try: <add> z = dz.dtype.type(value) <add> except OverflowError: <add> pass <add> else: <add> assert_(all(dz == z)) <add> else: <add> assert_(all(dz == value)) <ide> <ide> # C order, default dtype <del> dz = like_function(d, order='C', dtype=dtype) <add> dz = like_function(d, order='C', dtype=dtype, **fill_kwarg) <ide> assert_equal(dz.shape, d.shape) <ide> assert_(dz.flags.c_contiguous) <ide> if dtype is None: <ide> assert_equal(dz.dtype, d.dtype) <ide> else: <ide> assert_equal(dz.dtype, np.dtype(dtype)) <ide> if not value is None: <del> assert_(all(dz == value)) <add> if fill_value: <add> try: <add> z = dz.dtype.type(value) <add> except OverflowError: <add> pass <add> else: <add> assert_(all(dz == z)) <add> else: <add> assert_(all(dz == value)) <ide> <ide> # F order, default dtype <del> dz = like_function(d, order='F', dtype=dtype) <add> dz = like_function(d, order='F', dtype=dtype, **fill_kwarg) <ide> assert_equal(dz.shape, d.shape) <ide> assert_(dz.flags.f_contiguous) <ide> if dtype is None: <ide> assert_equal(dz.dtype, d.dtype) <ide> else: <ide> assert_equal(dz.dtype, np.dtype(dtype)) <ide> if not value is None: <del> assert_(all(dz == value)) <add> if fill_value: <add> try: <add> z = dz.dtype.type(value) <add> except OverflowError: <add> pass <add> else: <add> assert_(all(dz == z)) <add> else: <add> assert_(all(dz == value)) <ide> <ide> # A order <del> dz = like_function(d, order='A', dtype=dtype) <add> dz = like_function(d, order='A', dtype=dtype, **fill_kwarg) <ide> assert_equal(dz.shape, d.shape) <ide> if d.flags.f_contiguous: <ide> assert_(dz.flags.f_contiguous) <ide> def check_like_function(self, like_function, value): <ide> else: <ide> assert_equal(dz.dtype, np.dtype(dtype)) <ide> if not value is None: <del> assert_(all(dz == value)) <add> if fill_value: <add> try: <add> z = dz.dtype.type(value) <add> except OverflowError: <add> pass <add> else: <add> assert_(all(dz == z)) <add> else: <add> assert_(all(dz == value)) <ide> <ide> # Test the 'subok' parameter <ide> a = np.matrix([[1,2],[3,4]]) <ide> <del> b = like_function(a) <add> b = like_function(a, **fill_kwarg) <ide> assert_(type(b) is np.matrix) <ide> <del> b = like_function(a, subok=False) <add> b = like_function(a, subok=False, **fill_kwarg) <ide> assert_(type(b) is not np.matrix) <ide> <ide> def test_ones_like(self): <ide> def test_zeros_like(self): <ide> def test_empty_like(self): <ide> self.check_like_function(np.empty_like, None) <ide> <add> def test_filled_like(self): <add> self.check_like_function(np.filled_like, 0, True) <add> self.check_like_function(np.filled_like, 1, True) <add> self.check_like_function(np.filled_like, 1000, True) <add> self.check_like_function(np.filled_like, 123.456, True) <add> self.check_like_function(np.filled_like, np.inf, True) <add> <ide> class _TestCorrelate(TestCase): <ide> def _setup(self, dt): <ide> self.x = np.array([1, 2, 3, 4, 5], dtype=dt)
2
Text
Text
add administration guide for managers and raft
24f87f26e73a49383e0606813a86ed96da7f5a18
<ide><path>docs/swarm/admin_guide.md <add><!--[metadata]> <add>+++ <add>aliases = [ <add>"/engine/swarm/manager-administration-guide/" <add>] <add>title = "Swarm Manager Administration Guide" <add>description = "Manager administration guide" <add>keywords = ["docker, container, cluster, swarm, manager, raft"] <add>advisory = "rc" <add>[menu.main] <add>identifier="manager_admin_guide" <add>parent="engine_swarm" <add>weight="12" <add>+++ <add><![end-metadata]--> <add> <add># Administer and maintain a swarm of Docker Engines <add> <add>When you run a swarm of Docker Engines, **manager nodes** are the key components <add>for managing the cluster and storing the cluster state. It is important to understand <add>some key features of manager nodes in order to properly deploy and maintain the <add>swarm. <add> <add>This article covers the following swarm administration tasks: <add> <add>* [Add Manager nodes for fault tolerance](#add-manager-nodes-for-fault-tolerance) <add>* [Distributing manager nodes](#distributing-manager-nodes) <add>* [Running manager-only nodes](#run-manager-only-nodes) <add>* [Backing up the cluster state](#back-up-the-cluster-state) <add>* [Monitoring the swarm health](#monitor-swarm-health) <add>* [Recovering from disaster](#recover-from-disaster) <add> <add>Refer to [How swarm mode nodes work](how-swarm-mode-works/nodes.md) <add>for a brief overview of Docker Swarm mode and the difference between manager and <add>worker nodes. <add> <add>## Operating manager nodes in a swarm <add> <add>Swarm manager nodes use the [Raft Consensus Algorithm](raft.md) to manage the <add>cluster state. You only need to understand some general concepts of Raft in <add>order to manage a swarm. <add> <add>There is no limit on the number of manager nodes. The decision about how many <add>manager nodes to implement is a trade-off between performance and <add>fault-tolerance. Adding manager nodes to a swarm makes the swarm more <add>fault-tolerant. However, additional manager nodes reduce write performance <add>because more nodes must acknowledge proposals to update the cluster state. <add>This means more network round-trip traffic. <add> <add>Raft requires a majority of managers, also called a quorum, to agree on proposed <add>updates to the cluster. A quorum of managers must also agree on node additions <add>and removals. Membership operations are subject to the same constraints as state <add>replication. <add> <add>## Add manager nodes for fault tolerance <add> <add>You should maintain an odd number of managers in the swarm to support manager <add>node failures. Having an odd number of managers ensures that during a network <add>partition, there is a higher chance that a quorum remains available to process <add>requests if the network is partitioned into two sets. Keeping a quorum is not <add>guaranteed if you encounter more than two network partitions. <add> <add>| Cluster Size | Majority | Fault Tolerance | <add>|:------------:|:----------:|:-----------------:| <add>| 1 | 1 | 0 | <add>| 2 | 2 | 0 | <add>| **3** | 2 | **1** | <add>| 4 | 3 | 2 | <add>| **5** | 3 | **2** | <add>| 6 | 4 | 2 | <add>| **7** | 4 | **3** | <add>| 8 | 5 | 3 | <add>| **9** | 5 | **4** | <add> <add>For example, in a swarm with *5 nodes*, if you lose *3 nodes*, you don't have a <add>quorum. Therefore you can't add or remove nodes until you recover one of the <add>unavailable manager nodes or recover the cluster with disaster recovery <add>commands. See [Recover from disaster](#recover-from-disaster). <add> <add>While it is possible to scale a swarm down to a single manager node, it is <add>impossible to demote the last manager node. This ensures you maintain access to <add>the swarm and that the swarm can still process requests. Scaling down to a <add>single manager is an unsafe operation and is not recommended. If <add>the last node leaves the cluster unexpetedly during the demote operation, the <add>cluster swarm will become unavailable until you reboot the node or restart with <add>`--force-new-cluster`. <add> <add>You manage cluster membership with the `docker swarm` and `docker node` <add>subsystems. Refer to [Add nodes to a swarm](join-nodes.md) for more information <add>on how to add worker nodes and promote a worker node to be a manager. <add> <add>## Distributing manager nodes <add> <add>In addition to maintaining an odd number of manager nodes, pay attention to <add>datacenter topology when placing managers. For optimal fault-tolerance, distribute <add>manager nodes across a minimum of 3 availability-zones to support failures of an <add>entire set of machines or common maintenance scenarios. If you suffer a failure <add>in any of those zones, the swarm should maintain a quorum of manager nodes <add>available to process requests and rebalance workloads. <add> <add>| Swarm manager nodes | Repartition (on 3 Availability zones) | <add>|:-------------------:|:--------------------------------------:| <add>| 3 | 1-1-1 | <add>| 5 | 2-2-1 | <add>| 7 | 3-2-2 | <add>| 9 | 3-3-3 | <add> <add>## Run manager-only nodes <add> <add>By default manager nodes also act as a worker nodes. This means the scheduler <add>can assign tasks to a manager node. For small and non-critical clusters <add>assigning tasks to managers is relatively low-risk as long as you schedule <add>services using **resource constraints** for *cpu* and *memory*. <add> <add>However, because manager nodes use the Raft consensus algorithm to replicate data <add>in a consistent way, they are sensitive to resource starvation. You should <add>isolate managers in your swarm from processes that might block cluster <add>operations like cluster heartbeat or leader elections. <add> <add>To avoid interference with manager node operation, you can drain manager nodes <add>to make them unavailable as worker nodes: <add> <add>```bash <add>docker node update --availability drain <NODE-ID> <add>``` <add> <add>When you drain a node, the scheduler reassigns any tasks running on the node to <add>other available worker nodes in the cluster. It also prevents the scheduler from <add>assigning tasks to the node. <add> <add>## Back up the cluster state <add> <add>Docker manager nodes store the cluster state and manager logs in the following <add>directory: <add> <add>`/var/lib/docker/swarm/raft` <add> <add>Back up the raft data directory often so that you can use it in case of disaster <add>recovery. <add> <add>You should never restart a manager node with the data directory from another <add>node (for example, by copying the `raft` directory from one node to another). <add>The data directory is unique to a node ID and a node can only use a given node <add>ID once to join the swarm. (ie. Node ID space should be globally unique) <add> <add>To cleanly re-join a manager node to a cluster: <add> <add>1. Run `docker node demote <id-node>` to demote the node to a worker. <add>2. Run `docker node rm <id-node>` before adding a node back with a fresh state. <add>3. Re-join the node to the cluster using `docker swarm join`. <add> <add>In case of [disaster recovery](#recover-from-disaster), you can take the raft data <add>directory of one of the manager nodes to restore to a new swarm cluster. <add> <add>## Monitor swarm health <add> <add>You can monitor the health of Manager nodes by querying the docker `nodes` API <add>in JSON format through the `/nodes` HTTP endpoint. Refer to the [nodes API documentation](../reference/api/docker_remote_api_v1.24.md#36-nodes) <add>for more information. <add> <add>From the command line, run `docker node inspect <id-node>` to query the nodes. <add>For instance, to query the reachability of the node as a Manager: <add> <add>```bash <add>docker node inspect manager1 --format "{{ .ManagerStatus.Reachability }}" <add>reachable <add>``` <add> <add>To query the status of the node as a Worker that accept tasks: <add> <add>```bash <add>docker node inspect manager1 --format "{{ .Status.State }}" <add>ready <add>``` <add> <add>From those commands, we can see that `manager1` is both at the status <add>`reachable` as a manager and `ready` as a worker. <add> <add>An `unreachable` health status means that this particular manager node is unreachable <add>from other manager nodes. In this case you need to take action to restore the unreachable <add>manager: <add> <add>- Restart the daemon and see if the manager comes back as reachable. <add>- Reboot the machine. <add>- If neither restarting or rebooting work, you should add another manager node or promote a worker to be a manager node. You also need to cleanly remove the failed node entry from the Manager set with `docker node demote <id-node>` and `docker node rm <id-node>`. <add> <add>Alternatively you can also get an overview of the cluster health with `docker node ls`: <add> <add>```bash <add># From a Manager node <add>docker node ls <add>ID HOSTNAME MEMBERSHIP STATUS AVAILABILITY MANAGER STATUS <add>1mhtdwhvsgr3c26xxbnzdc3yp node05 Accepted Ready Active <add>516pacagkqp2xc3fk9t1dhjor node02 Accepted Ready Active Reachable <add>9ifojw8of78kkusuc4a6c23fx * node01 Accepted Ready Active Leader <add>ax11wdpwrrb6db3mfjydscgk7 node04 Accepted Ready Active <add>bb1nrq2cswhtbg4mrsqnlx1ck node03 Accepted Ready Active Reachable <add>di9wxgz8dtuh9d2hn089ecqkf node06 Accepted Ready Active <add>``` <add> <add>## Manager advertise address <add> <add>When initiating or joining a Swarm cluster, you have to specify the `--listen-addr` <add>flag to advertise your address to other Manager nodes in the cluster. <add> <add>We recommend that you use a *fixed IP address* for the advertised address, otherwise <add>the cluster could become unstable on machine reboot. <add> <add>Indeed if the whole cluster restarts and every Manager gets a new IP address on <add>restart, there is no way for any of those nodes to contact an existing Manager <add>and the cluster will stay stuck trying to contact other nodes through their old address. <add>While having dynamic IP addresses for Worker nodes is acceptable, Managers are <add>meant to be a stable piece in the infrastructure thus it is highly recommended to <add>deploy those critical nodes with static IPs. <add> <add>## Recover from disaster <add> <add>Swarm is resilient to failures and the cluster can recover from any number <add>of temporary node failures (machine reboots or crash with restart). <add> <add>In a swarm of `N` managers, there must be a quorum of manager nodes greater than <add>50% of the total number of managers (or `(N/2)+1`) in order for the swarm to <add>process requests and remain available. This means the swarm can tolerate up to <add>`(N-1)/2` permanent failures beyond which requests involving cluster management <add>cannot be processed. These types of failures include data corruption or hardware <add>failures. <add> <add>Even if you follow the guidelines here, it is possible that you can lose a <add>quorum of manager nodes. If you can't recover the quorum by conventional <add>means such as restarting faulty nodes, you can recover the cluster by running <add>`docker swarm init --force-new-cluster` on a manager node. <add> <add>```bash <add># From the node to recover <add>docker swarm init --force-new-cluster --listen-addr node01:2377 <add>``` <add> <add>The `--force-new-cluster` flag puts the Docker Engine into swarm mode as a <add>manager node of a single-node cluster. It discards cluster membership information <add>that existed before the loss of the quorum but it retains data necessary to the <add>Swarm cluster such as services, tasks and the list of worker nodes. <ide><path>docs/swarm/raft.md <add><!--[metadata]> <add>+++ <add>title = "Raft consensus in swarm mode" <add>description = "Raft consensus algorithm in swarm mode" <add>keywords = ["docker, container, cluster, swarm, raft"] <add>advisory = "rc" <add>[menu.main] <add>identifier="raft" <add>parent="engine_swarm" <add>weight="13" <add>+++ <add><![end-metadata]--> <add> <add>## Raft consensus algorithm <add> <add>When the Docker Engine runs in swarm mode, manager nodes implement the <add>[Raft Consensus Algorithm](http://thesecretlivesofdata.com/raft/) to manage the global cluster state. <add> <add>The reason why *Docker swarm mode* is using a consensus algorithm is to make sure that <add>all the manager nodes that are in charge of managing and scheduling tasks in the cluster, <add>are storing the same consistent state. <add> <add>Having the same consistent state across the cluster means that in case of a failure, <add>any Manager node can pick up the tasks and restore the services to a stable state. <add>For example, if the *Leader Manager* which is responsible for scheduling tasks in the <add>cluster dies unexpectedly, any other Manager can pick up the task of scheduling and <add>re-balance tasks to match the desired state. <add> <add>Systems using consensus algorithms to replicate logs in a distributed systems <add>do require special care. They ensure that the cluster state stays consistent <add>in the presence of failures by requiring a majority of nodes to agree on values. <add> <add>Raft tolerates up to `(N-1)/2` failures and requires a majority or quorum of <add>`(N/2)+1` members to agree on values proposed to the cluster. This means that in <add>a cluster of 5 Managers running Raft, if 3 nodes are unavailable, the system <add>will not process any more requests to schedule additional tasks. The existing <add>tasks will keep running but the scheduler will not be able to rebalance tasks to <add>cope with failures if when the manager set is not healthy. <add> <add>The implementation of the consensus algorithm in swarm mode means it features <add>the properties inherent to distributed systems: <add> <add>- *agreement on values* in a fault tolerant system. (Refer to [FLP impossibility theorem](http://the-paper-trail.org/blog/a-brief-tour-of-flp-impossibility/) <add> and the [Raft Consensus Algorithm paper](https://www.usenix.org/system/files/conference/atc14/atc14-paper-ongaro.pdf)) <add>- *mutual exclusion* through the leader election process <add>- *cluster membership* management <add>- *globally consistent object sequencing* and CAS (compare-and-swap) primitives
2
Text
Text
use serial comma in console docs
7ad5b420aebc1bcd07be187481cf48a4180a60c0
<ide><path>doc/api/console.md <ide> the JavaScript console mechanism provided by web browsers. <ide> <ide> The module exports two specific components: <ide> <del>* A `Console` class with methods such as `console.log()`, `console.error()` and <add>* A `Console` class with methods such as `console.log()`, `console.error()`, and <ide> `console.warn()` that can be used to write to any Node.js stream. <ide> * A global `console` instance configured to write to [`process.stdout`][] and <ide> [`process.stderr`][]. The global `console` can be used without calling
1
Javascript
Javascript
move passive logic out of layout phase
ede9170648d07a63cd282e6acb3ea1fe9e22ded9
<ide><path>packages/react-reconciler/src/ReactFiberCommitWork.new.js <ide> import { <ide> NoEffect as NoHookEffect, <ide> HasEffect as HookHasEffect, <ide> Layout as HookLayout, <del> Passive as HookPassive, <ide> } from './ReactHookEffectTags'; <ide> import {didWarnAboutReassigningProps} from './ReactFiberBeginWork.new'; <ide> import { <ide> function safelyDetachRef(current: Fiber) { <ide> } <ide> } <ide> <del>function safelyCallDestroy(current, destroy) { <add>export function safelyCallDestroy(current: Fiber, destroy: () => void) { <ide> if (__DEV__) { <ide> invokeGuardedCallback(null, destroy, null); <ide> if (hasCaughtError()) { <ide> function commitUnmount( <ide> do { <ide> const {destroy, tag} = effect; <ide> if (destroy !== undefined) { <del> if ((tag & HookPassive) !== NoHookEffect) { <del> // TODO: Consider if we can move this block out of the synchronous commit phase <del> effect.tag |= HookHasEffect; <del> } else { <add> if ((tag & HookLayout) !== NoHookEffect) { <ide> if ( <ide> enableProfilerTimer && <ide> enableProfilerCommitHooks && <ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.new.js <ide> import type {Interaction} from 'scheduler/src/Tracing'; <ide> import type {SuspenseConfig} from './ReactFiberSuspenseConfig'; <ide> import type {SuspenseState} from './ReactFiberSuspenseComponent.new'; <ide> import type {Effect as HookEffect} from './ReactFiberHooks.new'; <add>import type {HookEffectTag} from './ReactHookEffectTags'; <ide> import type {StackCursor} from './ReactFiberStack.new'; <ide> import type {FunctionComponentUpdateQueue} from './ReactFiberHooks.new'; <ide> <ide> import { <ide> commitPassiveEffectDurations, <ide> commitResetTextContent, <ide> isSuspenseBoundaryBeingHidden, <add> safelyCallDestroy, <ide> } from './ReactFiberCommitWork.new'; <ide> import {enqueueUpdate} from './ReactUpdateQueue.new'; <ide> import {resetContextDependencies} from './ReactFiberNewContext.new'; <ide> function flushPassiveMountEffects(firstChild: Fiber): void { <ide> } <ide> <ide> function flushPassiveMountEffectsImpl(fiber: Fiber): void { <add> setCurrentDebugFiberInDEV(fiber); <add> <ide> const updateQueue: FunctionComponentUpdateQueue | null = (fiber.updateQueue: any); <ide> const lastEffect = updateQueue !== null ? updateQueue.lastEffect : null; <ide> if (lastEffect !== null) { <ide> function flushPassiveMountEffectsImpl(fiber: Fiber): void { <ide> (tag & HookHasEffect) !== NoHookEffect <ide> ) { <ide> if (__DEV__) { <del> setCurrentDebugFiberInDEV(fiber); <ide> if ( <ide> enableProfilerTimer && <ide> enableProfilerCommitHooks && <ide> function flushPassiveMountEffectsImpl(fiber: Fiber): void { <ide> const error = clearCaughtError(); <ide> captureCommitPhaseError(fiber, error); <ide> } <del> resetCurrentDebugFiberInDEV(); <ide> } else { <ide> try { <ide> const create = effect.create; <ide> function flushPassiveMountEffectsImpl(fiber: Fiber): void { <ide> <ide> effect = next; <ide> } while (effect !== firstEffect); <add> <add> resetCurrentDebugFiberInDEV(); <ide> } <ide> } <ide> <ide> function flushPassiveUnmountEffects(firstChild: Fiber): void { <ide> case Block: { <ide> const primaryEffectTag = fiber.effectTag & Passive; <ide> if (primaryEffectTag !== NoEffect) { <del> flushPassiveUnmountEffectsImpl(fiber); <add> flushPassiveUnmountEffectsImpl(fiber, HookPassive | HookHasEffect); <ide> } <ide> } <ide> } <ide> function flushPassiveUnmountEffectsInsideOfDeletedTree( <ide> case ForwardRef: <ide> case SimpleMemoComponent: <ide> case Block: { <del> flushPassiveUnmountEffectsImpl(fiber); <add> flushPassiveUnmountEffectsImpl(fiber, HookPassive); <ide> } <ide> } <ide> } <ide> function flushPassiveUnmountEffectsInsideOfDeletedTree( <ide> } <ide> } <ide> <del>function flushPassiveUnmountEffectsImpl(fiber: Fiber): void { <add>function flushPassiveUnmountEffectsImpl( <add> fiber: Fiber, <add> // Tags to check for when deciding whether to unmount. e.g. to skip over <add> // layout effects <add> hookEffectTag: HookEffectTag, <add>): void { <ide> const updateQueue: FunctionComponentUpdateQueue | null = (fiber.updateQueue: any); <ide> const lastEffect = updateQueue !== null ? updateQueue.lastEffect : null; <ide> if (lastEffect !== null) { <add> setCurrentDebugFiberInDEV(fiber); <add> <ide> const firstEffect = lastEffect.next; <ide> let effect = firstEffect; <ide> do { <ide> const {next, tag} = effect; <del> if ( <del> (tag & HookPassive) !== NoHookEffect && <del> (tag & HookHasEffect) !== NoHookEffect <del> ) { <add> if ((tag & hookEffectTag) === hookEffectTag) { <ide> const destroy = effect.destroy; <del> effect.destroy = undefined; <del> <del> if (typeof destroy === 'function') { <del> if (__DEV__) { <del> setCurrentDebugFiberInDEV(fiber); <del> if ( <del> enableProfilerTimer && <del> enableProfilerCommitHooks && <del> fiber.mode & ProfileMode <del> ) { <del> startPassiveEffectTimer(); <del> invokeGuardedCallback(null, destroy, null); <del> recordPassiveEffectDuration(fiber); <del> } else { <del> invokeGuardedCallback(null, destroy, null); <del> } <del> if (hasCaughtError()) { <del> invariant(fiber !== null, 'Should be working on an effect.'); <del> const error = clearCaughtError(); <del> captureCommitPhaseError(fiber, error); <del> } <del> resetCurrentDebugFiberInDEV(); <add> if (destroy !== undefined) { <add> effect.destroy = undefined; <add> if ( <add> enableProfilerTimer && <add> enableProfilerCommitHooks && <add> fiber.mode & ProfileMode <add> ) { <add> startPassiveEffectTimer(); <add> safelyCallDestroy(fiber, destroy); <add> recordPassiveEffectDuration(fiber); <ide> } else { <del> try { <del> if ( <del> enableProfilerTimer && <del> enableProfilerCommitHooks && <del> fiber.mode & ProfileMode <del> ) { <del> try { <del> startPassiveEffectTimer(); <del> destroy(); <del> } finally { <del> recordPassiveEffectDuration(fiber); <del> } <del> } else { <del> destroy(); <del> } <del> } catch (error) { <del> invariant(fiber !== null, 'Should be working on an effect.'); <del> captureCommitPhaseError(fiber, error); <del> } <add> safelyCallDestroy(fiber, destroy); <ide> } <ide> } <ide> } <del> <ide> effect = next; <ide> } while (effect !== firstEffect); <add> <add> resetCurrentDebugFiberInDEV(); <ide> } <ide> } <ide>
2