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
use validators for consistency
4157317f4cec9fe2166c095dfade113c5d3d30e6
<ide><path>lib/internal/console/constructor.js <ide> const { <ide> isStackOverflowError, <ide> codes: { <ide> ERR_CONSOLE_WRITABLE_STREAM, <del> ERR_INVALID_ARG_TYPE, <ide> ERR_INVALID_ARG_VALUE, <ide> ERR_INCOMPATIBLE_OPTION_PAIR, <ide> }, <ide> } = require('internal/errors'); <del>const { validateInteger } = require('internal/validators'); <add>const { <add> validateArray, <add> validateInteger, <add> validateObject, <add>} = require('internal/validators'); <ide> const { previewEntries } = internalBinding('util'); <ide> const { Buffer: { isBuffer } } = require('buffer'); <ide> const { <ide> function Console(options /* or: stdout, stderr, ignoreErrors = true */) { <ide> 0, kMaxGroupIndentation); <ide> } <ide> <del> if (typeof inspectOptions === 'object' && inspectOptions !== null) { <add> if (inspectOptions !== undefined) { <add> validateObject(inspectOptions, 'options.inspectOptions'); <add> <ide> if (inspectOptions.colors !== undefined && <ide> options.colorMode !== undefined) { <ide> throw new ERR_INCOMPATIBLE_OPTION_PAIR( <ide> 'options.inspectOptions.color', 'colorMode'); <ide> } <ide> optionsMap.set(this, inspectOptions); <del> } else if (inspectOptions !== undefined) { <del> throw new ERR_INVALID_ARG_TYPE( <del> 'options.inspectOptions', <del> 'object', <del> inspectOptions); <ide> } <ide> <ide> // Bind the prototype functions to this Console instance <ide> const consoleMethods = { <ide> <ide> // https://console.spec.whatwg.org/#table <ide> table(tabularData, properties) { <del> if (properties !== undefined && !ArrayIsArray(properties)) <del> throw new ERR_INVALID_ARG_TYPE('properties', 'Array', properties); <add> if (properties !== undefined) <add> validateArray(properties, 'properties'); <ide> <ide> if (tabularData === null || typeof tabularData !== 'object') <ide> return this.log(tabularData);
1
Ruby
Ruby
add utility method to quell output
af7bf47e3112a9d50a1cd915d29f36fc6d6463dd
<ide><path>Library/Homebrew/test/test_formula_install.rb <ide> def initialize <ide> <ide> class ConfigureTests < Test::Unit::TestCase <ide> def test_detect_failed_configure <del> tmperr = $stderr <del> tmpout = $stdout <del> require 'stringio' <del> $stderr = StringIO.new <del> $stdout = StringIO.new <del> <ide> f = ConfigureFails.new <del> <ide> begin <del> f.brew { f.install } <add> shutup { f.brew { f.install } } <ide> rescue BuildError => e <ide> assert e.was_running_configure? <ide> end <del> <del> $stderr = tmperr <del> $stdout = tmpout <ide> end <ide> end <ide> <ide><path>Library/Homebrew/test/test_patching.rb <ide> def read_file path <ide> end <ide> <ide> def test_single_patch <del> nostdout do <add> shutup do <ide> DefaultPatchBall.new('test_patch').brew do <ide> s = read_file 'libexec/NOOP' <ide> assert !s.include?("NOOP"), "File was unpatched." <ide> def test_single_patch <ide> end <ide> <ide> def test_patch_list <del> nostdout do <add> shutup do <ide> ListPatchBall.new('test_patch_list').brew do <ide> s = read_file 'libexec/NOOP' <ide> assert !s.include?("NOOP"), "File was unpatched." <ide> def test_patch_list <ide> end <ide> <ide> def test_p0_patch <del> nostdout do <add> shutup do <ide> P0PatchBall.new('test_p0_patch').brew do <ide> s = read_file 'libexec/NOOP' <ide> assert !s.include?("NOOP"), "File was unpatched." <ide> def test_p0_patch <ide> end <ide> <ide> def test_p1_patch <del> nostdout do <add> shutup do <ide> P1PatchBall.new('test_p1_patch').brew do <ide> s = read_file 'libexec/NOOP' <ide> assert !s.include?("NOOP"), "File was unpatched." <ide><path>Library/Homebrew/test/testing_env.rb <ide> module Homebrew extend self <ide> include FileUtils <ide> end <ide> <add>def shutup <add> if ARGV.verbose? <add> yield <add> else <add> begin <add> tmperr = $stderr.clone <add> tmpout = $stdout.clone <add> $stderr.reopen '/dev/null', 'w' <add> $stdout.reopen '/dev/null', 'w' <add> yield <add> ensure <add> $stderr.reopen tmperr <add> $stdout.reopen tmpout <add> end <add> end <add>end <add> <ide> require 'test/unit' # must be after at_exit
3
Go
Go
increase timeout in waitclose to 10sec
a70beda1ecfb049a3f80ad5b159ba51d653fd067
<ide><path>runtime/graphdriver/devmapper/deviceset.go <ide> func (devices *DeviceSet) removeDeviceAndWait(devname string) error { <ide> <ide> // waitRemove blocks until either: <ide> // a) the device registered at <device_set_prefix>-<hash> is removed, <del>// or b) the 1 second timeout expires. <add>// or b) the 10 second timeout expires. <ide> func (devices *DeviceSet) waitRemove(devname string) error { <ide> utils.Debugf("[deviceset %s] waitRemove(%s)", devices.devicePrefix, devname) <ide> defer utils.Debugf("[deviceset %s] waitRemove(%s) END", devices.devicePrefix, devname) <ide> func (devices *DeviceSet) waitRemove(devname string) error { <ide> <ide> // waitClose blocks until either: <ide> // a) the device registered at <device_set_prefix>-<hash> is closed, <del>// or b) the 1 second timeout expires. <add>// or b) the 10 second timeout expires. <ide> func (devices *DeviceSet) waitClose(hash string) error { <ide> info := devices.Devices[hash] <ide> if info == nil { <ide> func (devices *DeviceSet) waitClose(hash string) error { <ide> if devinfo.OpenCount == 0 { <ide> break <ide> } <del> time.Sleep(1 * time.Millisecond) <add> devices.Unlock() <add> time.Sleep(10 * time.Millisecond) <add> devices.Lock() <ide> } <ide> if i == 1000 { <ide> return fmt.Errorf("Timeout while waiting for device %s to close", hash)
1
Python
Python
add systemd support
7968182ccf237dd085700a958681942768770e33
<ide><path>glances/glances.py <ide> def __init__(self): <ide> """ <ide> <ide> # Ignore the following FS name <del> self.ignore_fsname = ('', 'none', 'gvfs-fuse-daemon', 'fusectl', <del> 'cgroup') <add> self.ignore_fsname = ('', 'cgroup', 'fusectl', 'gvfs-fuse-daemon', <add> 'gvfsd-fuse', 'none') <ide> <ide> # Ignore the following FS type <del> self.ignore_fstype = ('binfmt_misc', 'devpts', 'iso9660', 'none', <del> 'proc', 'sysfs', 'usbfs', 'rootfs', 'autofs', <del> 'devtmpfs') <add> self.ignore_fstype = ('autofs', 'binfmt_misc', 'debugfs', 'devpts', <add> 'devtmpfs', 'hugetlbfs', 'iso9660', 'mqueue', <add> 'none', 'proc', 'rootfs', 'securityfs', 'sysfs', <add> 'usbfs') <add> <add> # ignore fs by mount point <add> self.ignore_mntpoint = ('', '/dev/shm', '/sys/fs/cgroup') <ide> <ide> def __update__(self): <ide> """ <ide> def __update__(self): <ide> if fs_current['fs_type'] in self.ignore_fstype: <ide> continue <ide> fs_current['mnt_point'] = fs_stat[fs].mountpoint <add> if fs_current['mnt_point'] in self.ignore_mntpoint: <add> continue <ide> try: <ide> fs_usage = psutil.disk_usage(fs_current['mnt_point']) <ide> except Exception:
1
Mixed
Ruby
create sqlite3 directory if not present
f036239447c79843983ee1c0d3dfe68484d63203
<ide><path>activerecord/CHANGELOG.md <add>* Create a directory for sqlite3 file if not present on the system. <add> <add> *Richard Schneeman* <add> <ide> * Removed redundant override of `xml` column definition for PG, <ide> in order to use `xml` column type instead of `text`. <ide> <ide><path>activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb <ide> def sqlite3_connection(config) <ide> # Allow database path relative to Rails.root, but only if <ide> # the database path is not the special path that tells <ide> # Sqlite to build a database only in memory. <del> if defined?(Rails.root) && ':memory:' != config[:database] <del> config[:database] = File.expand_path(config[:database], Rails.root) <add> if ':memory:' != config[:database] <add> config[:database] = Pathname.new(config[:database]) <add> config[:database] = config[:database].expand_path(Rails.root) if defined?(Rails.root) <add> config[:database].dirname.mkdir unless config[:database].dirname.directory? <ide> end <ide> <ide> db = SQLite3::Database.new( <del> config[:database], <add> config[:database].to_s, <ide> :results_as_hash => true <ide> ) <ide> <ide><path>activerecord/test/cases/adapters/sqlite3/sqlite3_create_folder_test.rb <add># encoding: utf-8 <add>require "cases/helper" <add>require 'models/owner' <add> <add>module ActiveRecord <add> module ConnectionAdapters <add> class SQLite3CreateFolder < ActiveRecord::TestCase <add> def test_sqlite_creates_directory <add> Dir.mktmpdir do |dir| <add> dir = Pathname.new(dir) <add> @conn = Base.sqlite3_connection :database => dir.join("db/foo.sqlite3"), <add> :adapter => 'sqlite3', <add> :timeout => 100 <add> <add> assert Dir.exists? dir.join('db') <add> assert File.exist? dir.join('db/foo.sqlite3') <add> end <add> end <add> end <add> end <add>end
3
Ruby
Ruby
use memoized dup of url_helpers for reinclusion
7bcca5b763425f34250bf28dc0980ff21de1183a
<ide><path>actionpack/lib/abstract_controller/railties/routes_helpers.rb <ide> def self.with(routes, include_path_helpers = true) <ide> define_method(:inherited) do |klass| <ide> super(klass) <ide> <del> namespace = klass.module_parents.detect { |m| m.respond_to?(:railtie_routes_url_helpers) } <del> actual_routes = namespace ? namespace.railtie_routes_url_helpers._routes : routes <del> <del> if namespace <add> if namespace = klass.module_parents.detect { |m| m.respond_to?(:railtie_routes_url_helpers) } <ide> klass.include(namespace.railtie_routes_url_helpers(include_path_helpers)) <ide> else <ide> klass.include(routes.url_helpers(include_path_helpers)) <ide> end <del> <del> # In the case that we have ex. <del> # class A::Foo < ApplicationController <del> # class Bar < A::Foo <del> # We will need to redefine _routes because it will not be correct <del> # via inheritance. <del> unless klass._routes.equal?(actual_routes) <del> klass.redefine_singleton_method(:_routes) { actual_routes } <del> klass.include(Module.new do <del> define_method(:_routes) { @_routes || actual_routes } <del> end) <del> end <ide> end <ide> end <ide> end <ide><path>actionpack/lib/action_dispatch/routing/route_set.rb <ide> def url_options; {}; end <ide> end <ide> <ide> private :_generate_paths_by_default <add> <add> # If the module is included more than once (for example, in a subclass <add> # of an ancestor that includes the module), ensure that the `_routes` <add> # singleton and instance methods return the desired route set by <add> # including a new copy of the module (recursively if necessary). Note <add> # that this method is called for each inclusion, whereas the above <add> # `included` block is run only for the initial inclusion of each copy. <add> def self.included(base) <add> super <add> if !base._routes.equal?(@_proxy._routes) <add> @dup_for_reinclude ||= self.dup <add> base.include @dup_for_reinclude <add> end <add> end <ide> end <ide> end <ide> <ide><path>actionpack/test/controller/route_helpers_test.rb <ide> require "abstract_unit" <ide> <ide> class RouteHelperIntegrationTest < ActionDispatch::IntegrationTest <del> def self.routes <del> @routes ||= ActionDispatch::Routing::RouteSet.new <del> end <del> <del> class FakeACBase < ActionController::Base <del> # Normally done by app initialization to ActionController::Base <del> app = RouteHelperIntegrationTest <del> extend ::AbstractController::Railties::RoutesHelpers.with(app.routes) <del> end <del> <del> class ApplicationController < FakeACBase <del> end <del> <ide> class FooController < ApplicationController <ide> end <ide> <ide> class FooController < ApplicationController <ide> # duplicate these modules and make method cache invalidation expensive. <ide> # https://github.com/rails/rails/pull/37927 <ide> test "only includes one module with route helpers" do <del> app = self.class <del> <del> url_helpers_module = app.routes.named_routes.url_helpers_module <del> path_helpers_module = app.routes.named_routes.path_helpers_module <add> url_helpers_module = SharedTestRoutes.named_routes.url_helpers_module <add> path_helpers_module = SharedTestRoutes.named_routes.path_helpers_module <ide> <ide> assert_operator FooController, :<, url_helpers_module <ide> assert_operator ApplicationController, :<, url_helpers_module <del> assert_not_operator FakeACBase, :<, url_helpers_module <add> assert_not_operator ActionController::Base, :<, url_helpers_module <ide> <ide> assert_operator FooController, :<, path_helpers_module <ide> assert_operator ApplicationController, :<, path_helpers_module <del> assert_not_operator FakeACBase, :<, path_helpers_module <add> assert_not_operator ActionController::Base, :<, path_helpers_module <ide> <ide> included_modules = FooController.ancestors.grep_v(Class) <ide> included_modules -= [url_helpers_module, path_helpers_module]
3
Javascript
Javascript
update _app.js to use a function component.
ba2fbc2b65394ba29bceba9d3c6494391bfb00ac
<ide><path>examples/with-styled-components/pages/_app.js <del>import App from 'next/app' <ide> import { ThemeProvider } from 'styled-components' <ide> <ide> const theme = { <ide> const theme = { <ide> }, <ide> } <ide> <del>export default class MyApp extends App { <del> render() { <del> const { Component, pageProps } = this.props <del> return ( <del> <ThemeProvider theme={theme}> <del> <Component {...pageProps} /> <del> </ThemeProvider> <del> ) <del> } <add>export default function App({ Component, pageProps }) { <add> return ( <add> <ThemeProvider theme={theme}> <add> <Component {...pageProps} /> <add> </ThemeProvider> <add> ) <ide> }
1
Python
Python
correct an error in rmsprop optimizer
32b15912a216a5517e751c810e3f172c3b8f6be2
<ide><path>keras/optimizers/optimizer_experimental/rmsprop.py <ide> def update_step(self, gradient, variable): <ide> average_grad.assign(rho * average_grad) <ide> average_grad.scatter_add( <ide> tf.IndexedSlices( <del> tf.square(gradient.values) * (1 - rho), gradient.indices <add> gradient.values * (1 - rho), gradient.indices <ide> ) <ide> ) <ide> velocity.assign_add(-tf.square(average_grad)) <ide> def update_step(self, gradient, variable): <ide> # Dense gradients. <ide> velocity.assign(rho * velocity + (1 - rho) * tf.square(gradient)) <ide> if self.centered: <del> average_grad.assign( <del> rho * average_grad + (1 - rho) * tf.square(gradient) <del> ) <add> average_grad.assign(rho * average_grad + (1 - rho) * gradient) <ide> velocity.assign_add(-tf.square(average_grad)) <ide> transformed_grad = gradient / (tf.sqrt(velocity) + self.epsilon) <ide> if self.momentum > 0:
1
Text
Text
update documentation for #pluck method [ci skip]
1e2650acbb1178da7d24bb9cdac31920c2f75dc9
<ide><path>guides/source/active_record_querying.md <ide> Client.pluck(:name) <ide> # => ["David", "Jeremy", "Jose"] <ide> ``` <ide> <add>You are not limited to querying fields from a single table, you can query multiple tables as well. <add> <add>``` <add>Client.joins(:comments, :categories).pluck("clients.email, comments.title, categories.name") <add>``` <add> <ide> Furthermore, unlike `select` and other `Relation` scopes, `pluck` triggers an immediate <ide> query, and thus cannot be chained with any further scopes, although it can work with <ide> scopes already constructed earlier:
1
Javascript
Javascript
replace object.assign with object spread
b2e7837288d79d8671fbe316bc58aabe46775ac9
<ide><path>lib/Compilation.js <ide> class Compilation { <ide> optionsOrPreset = { preset: optionsOrPreset }; <ide> } <ide> if (typeof optionsOrPreset === "object" && optionsOrPreset !== null) { <del> const options = Object.assign({}, optionsOrPreset); <add> const options = { ...optionsOrPreset }; <ide> if (options.preset !== undefined) { <ide> this.hooks.statsPreset.for(options.preset).call(options, context); <ide> } <ide> class Compilation { <ide> */ <ide> getPath(filename, data) { <ide> if (!data.hash) { <del> data = Object.assign( <del> { <del> hash: this.hash <del> }, <del> data <del> ); <add> data = { <add> hash: this.hash, <add> ...data <add> }; <ide> } <ide> return this.mainTemplate.getAssetPath(filename, data); <ide> } <ide><path>lib/ContextModule.js <ide> class ContextModule extends Module { <ide> // Info from Factory <ide> this.resolveDependencies = resolveDependencies; <ide> /** @type {ContextModuleOptions} */ <del> this.options = Object.assign({}, options, { <add> this.options = ({ <add> ...options, <ide> resource: resource, <ide> resourceQuery: resourceQuery <ide> }); <ide> class ContextModule extends Module { <ide> // for the lazy-once mode create a new async dependency block <ide> // and add that block to this context <ide> if (dependencies.length > 0) { <del> const block = new AsyncDependenciesBlock( <del> Object.assign({}, this.options.groupOptions, { <del> name: this.options.chunkName <del> }) <del> ); <add> const block = new AsyncDependenciesBlock({ <add> ...this.options.groupOptions, <add> name: this.options.chunkName <add> }); <ide> for (const dep of dependencies) { <ide> block.addDependency(dep); <ide> } <ide> class ContextModule extends Module { <ide> ); <ide> } <ide> const block = new AsyncDependenciesBlock( <del> Object.assign({}, this.options.groupOptions, { <add> { <add> ...this.options.groupOptions, <ide> name: chunkName <del> }), <add> }, <ide> dep.loc, <ide> dep.userRequest <ide> ); <ide><path>lib/ContextModuleFactory.js <ide> module.exports = class ContextModuleFactory extends ModuleFactory { <ide> const missingDependencies = new Set(); <ide> const contextDependencies = new Set(); <ide> this.hooks.beforeResolve.callAsync( <del> Object.assign( <del> { <del> context: context, <del> dependencies: dependencies, <del> resolveOptions, <del> fileDependencies, <del> missingDependencies, <del> contextDependencies <del> }, <del> dependency.options <del> ), <add> { <add> context: context, <add> dependencies: dependencies, <add> resolveOptions, <add> fileDependencies, <add> missingDependencies, <add> contextDependencies, <add> ...dependency.options <add> }, <ide> (err, beforeResolveResult) => { <ide> if (err) return callback(err); <ide> <ide> module.exports = class ContextModuleFactory extends ModuleFactory { <ide> if (err) return callback(err); <ide> <ide> this.hooks.afterResolve.callAsync( <del> Object.assign( <del> { <del> addon: <del> loadersPrefix + <del> result[1].join("!") + <del> (result[1].length > 0 ? "!" : ""), <del> resource: result[0], <del> resolveDependencies: this.resolveDependencies.bind(this) <del> }, <del> beforeResolveResult <del> ), <add> { <add> addon: <add> loadersPrefix + <add> result[1].join("!") + <add> (result[1].length > 0 ? "!" : ""), <add> resource: result[0], <add> resolveDependencies: this.resolveDependencies.bind(this), <add> ...beforeResolveResult <add> }, <ide> (err, result) => { <ide> if (err) return callback(err); <ide> <ide><path>lib/DelegatedModule.js <ide> class DelegatedModule extends Module { <ide> * @returns {void} <ide> */ <ide> build(options, compilation, resolver, fs, callback) { <del> this.buildMeta = Object.assign({}, this.delegateData.buildMeta); <add> this.buildMeta = { ...this.delegateData.buildMeta }; <ide> this.buildInfo = {}; <ide> this.dependencies.length = 0; <ide> this.delegatedSourceDependency = new DelegatedSourceDependency( <ide><path>lib/DelegatedPlugin.js <ide> class DelegatedPlugin { <ide> ); <ide> <ide> compiler.hooks.compile.tap("DelegatedPlugin", ({ normalModuleFactory }) => { <del> new DelegatedModuleFactoryPlugin( <del> Object.assign( <del> { <del> associatedObjectForCache: compiler.root <del> }, <del> this.options <del> ) <del> ).apply(normalModuleFactory); <add> new DelegatedModuleFactoryPlugin({ <add> associatedObjectForCache: compiler.root, <add> ...this.options <add> }).apply(normalModuleFactory); <ide> }); <ide> } <ide> } <ide><path>lib/JavascriptParser.js <ide> class JavascriptParser { <ide> <ide> static parse(code, options) { <ide> const type = options ? options.sourceType : "module"; <del> const parserOptions = Object.assign( <del> Object.create(null), <del> defaultParserOptions, <del> options <del> ); <add> const parserOptions = { <add> ...defaultParserOptions, <add> ...options <add> }; <ide> <ide> if (type === "auto") { <ide> parserOptions.sourceType = "module"; <ide><path>lib/ModuleFilenameHelpers.js <ide> ModuleFilenameHelpers.createFilename = ( <ide> options, <ide> { requestShortener, chunkGraph } <ide> ) => { <del> const opts = Object.assign( <del> { <del> namespace: "", <del> moduleFilenameTemplate: "" <del> }, <del> typeof options === "object" <add> const opts = { <add> namespace: "", <add> moduleFilenameTemplate: "", <add> ...(typeof options === "object" <ide> ? options <ide> : { <ide> moduleFilenameTemplate: options <del> } <del> ); <add> }) <add> }; <ide> <ide> let absoluteResourcePath; <ide> let hash; <ide><path>lib/MultiStats.js <ide> class MultiStats { <ide> ? options.children[idx] <ide> : options.children; <ide> return stat.compilation.createStatsOptions( <del> Object.assign( <del> {}, <del> baseOptions, <del> childOptions && typeof childOptions === "object" <add> { <add> ...baseOptions, <add> ...(childOptions && typeof childOptions === "object" <ide> ? childOptions <del> : { preset: childOptions } <del> ), <add> : { preset: childOptions }) <add> }, <ide> context <ide> ); <ide> }); <ide> class MultiStats { <ide> if (!j.errors) return arr; <ide> return arr.concat( <ide> j.errors.map(obj => { <del> return Object.assign({}, obj, { <add> return { <add> ...obj, <ide> compilerPath: obj.compilerPath <ide> ? `${j.name}.${obj.compilerPath}` <ide> : j.name <del> }); <add> }; <ide> }) <ide> ); <ide> }, []); <ide> obj.warnings = jsons.reduce((arr, j) => { <ide> if (!j.warnings) return arr; <ide> return arr.concat( <ide> j.warnings.map(obj => { <del> return Object.assign({}, obj, { <add> return { <add> ...obj, <ide> compilerPath: obj.compilerPath <ide> ? `${j.name}.${obj.compilerPath}` <ide> : j.name <del> }); <add> }; <ide> }) <ide> ); <ide> }, []); <ide><path>lib/NodeStuffPlugin.js <ide> class NodeStuffPlugin { <ide> <ide> let localOptions = options; <ide> if (parserOptions.node) { <del> localOptions = Object.assign({}, localOptions, parserOptions.node); <add> localOptions = { ...localOptions, ...parserOptions.node }; <ide> } <ide> <ide> const setModuleConstant = (expressionName, fn) => { <ide><path>lib/NormalModule.js <ide> class NormalModule extends Module { <ide> */ <ide> markModuleAsErrored(error) { <ide> // Restore build meta from successful build to keep importing state <del> this.buildMeta = Object.assign({}, this._lastSuccessfulBuildMeta); <add> this.buildMeta = { ...this._lastSuccessfulBuildMeta }; <ide> this.error = error; <ide> this.errors.push(error); <ide> } <ide><path>lib/OptionsDefaulter.js <ide> class OptionsDefaulter { <ide> } <ide> <ide> process(options) { <del> options = Object.assign({}, options); <add> options = { ...options }; <ide> for (let name in this.defaults) { <ide> switch (this.config[name]) { <ide> case undefined: <ide><path>lib/ProgressPlugin.js <ide> class ProgressPlugin { <ide> <ide> options = options || {}; <ide> validateOptions(schema, options, "Progress Plugin"); <del> options = Object.assign({}, ProgressPlugin.defaultOptions, options); <add> options = { ...ProgressPlugin.defaultOptions, ...options }; <ide> <ide> this.profile = options.profile; <ide> this.handler = options.handler; <ide><path>lib/ResolverFactory.js <ide> module.exports = class ResolverFactory { <ide> * @returns {Resolver} the resolver <ide> */ <ide> _create(type, resolveOptions) { <del> const originalResolveOptions = Object.assign({}, resolveOptions); <add> const originalResolveOptions = { ...resolveOptions }; <ide> resolveOptions = this.hooks.resolveOptions.for(type).call(resolveOptions); <ide> const resolver = Factory.createResolver(resolveOptions); <ide> if (!resolver) { <ide><path>lib/Watching.js <ide> class Watching { <ide> aggregateTimeout: watchOptions <ide> }; <ide> } else if (watchOptions && typeof watchOptions === "object") { <del> this.watchOptions = Object.assign({}, watchOptions); <add> this.watchOptions = { ...watchOptions }; <ide> } else { <ide> this.watchOptions = {}; <ide> } <ide><path>lib/WebpackOptionsApply.js <ide> class WebpackOptionsApply extends OptionsApply { <ide> compiler.resolverFactory.hooks.resolveOptions <ide> .for("normal") <ide> .tap("WebpackOptionsApply", resolveOptions => { <del> return Object.assign( <del> { <del> fileSystem: compiler.inputFileSystem <del> }, <del> cachedCleverMerge(options.resolve, resolveOptions) <del> ); <add> return { <add> fileSystem: compiler.inputFileSystem, <add> ...cachedCleverMerge(options.resolve, resolveOptions) <add> }; <ide> }); <ide> compiler.resolverFactory.hooks.resolveOptions <ide> .for("context") <ide> .tap("WebpackOptionsApply", resolveOptions => { <del> return Object.assign( <del> { <del> fileSystem: compiler.inputFileSystem, <del> resolveToContext: true <del> }, <del> cachedCleverMerge(options.resolve, resolveOptions) <del> ); <add> return { <add> fileSystem: compiler.inputFileSystem, <add> resolveToContext: true, <add> ...cachedCleverMerge(options.resolve, resolveOptions) <add> }; <ide> }); <ide> compiler.resolverFactory.hooks.resolveOptions <ide> .for("loader") <ide> .tap("WebpackOptionsApply", resolveOptions => { <del> return Object.assign( <del> { <del> fileSystem: compiler.inputFileSystem <del> }, <del> cachedCleverMerge(options.resolveLoader, resolveOptions) <del> ); <add> return { <add> fileSystem: compiler.inputFileSystem, <add> ...cachedCleverMerge(options.resolveLoader, resolveOptions) <add> }; <ide> }); <ide> compiler.hooks.afterResolvers.call(compiler); <ide> return options; <ide><path>lib/WebpackOptionsDefaulter.js <ide> class WebpackOptionsDefaulter extends OptionsDefaulter { <ide> constructor() { <ide> super(); <ide> <del> this.set("experiments", "call", value => Object.assign({}, value)); <add> this.set("experiments", "call", value => ({ ...value })); <ide> this.set("experiments.mjs", false); <ide> this.set("experiments.importAwait", false); <ide> this.set("experiments.importAsync", false); <ide> class WebpackOptionsDefaulter extends OptionsDefaulter { <ide> if (!value) { <ide> return false; <ide> } <del> value = Object.assign({}, value); <add> value = { ...value }; <ide> if (value.type === "filesystem") { <ide> if (value.name === undefined) { <ide> value.name = <ide> class WebpackOptionsDefaulter extends OptionsDefaulter { <ide> this.set("context", process.cwd()); <ide> this.set("target", "web"); <ide> <del> this.set("module", "call", value => Object.assign({}, value)); <add> this.set("module", "call", value => ({ ...value })); <ide> this.set("module.unknownContextRequest", "."); <ide> this.set("module.unknownContextRegExp", false); <ide> this.set("module.unknownContextRecursive", true); <ide> class WebpackOptionsDefaulter extends OptionsDefaulter { <ide> } else if (typeof value !== "object") { <ide> return {}; <ide> } else { <del> return Object.assign({}, value); <add> return { ...value }; <ide> } <ide> }); <ide> <ide> class WebpackOptionsDefaulter extends OptionsDefaulter { <ide> if (typeof value === "boolean") { <ide> return value; <ide> } else { <del> return Object.assign({}, value); <add> return { ...value }; <ide> } <ide> }); <ide> this.set("node.global", "make", options => { <ide> class WebpackOptionsDefaulter extends OptionsDefaulter { <ide> (!isProductionLikeMode(options) || !isWebLikeTarget(options)) <ide> ) <ide> return false; <del> return Object.assign({}, value); <add> return { ...value }; <ide> }); <ide> this.set("performance.maxAssetSize", 250000); <ide> this.set("performance.maxEntrypointSize", 250000); <ide> this.set("performance.hints", "make", options => <ide> isProductionLikeMode(options) ? "warning" : false <ide> ); <ide> <del> this.set("optimization", "call", value => Object.assign({}, value)); <add> this.set("optimization", "call", value => ({ ...value })); <ide> this.set("optimization.removeAvailableModules", true); <ide> this.set("optimization.removeEmptyChunks", true); <ide> this.set("optimization.mergeDuplicateChunks", true); <ide> class WebpackOptionsDefaulter extends OptionsDefaulter { <ide> } <ide> }); <ide> <del> this.set("resolve", "call", value => Object.assign({}, value)); <add> this.set("resolve", "call", value => ({ ...value })); <ide> this.set("resolve.cache", "make", options => !!options.cache); <ide> this.set("resolve.modules", ["node_modules"]); <ide> this.set("resolve.extensions", "make", options => <ide> class WebpackOptionsDefaulter extends OptionsDefaulter { <ide> } <ide> }); <ide> <del> this.set("resolveLoader", "call", value => Object.assign({}, value)); <add> this.set("resolveLoader", "call", value => ({ ...value })); <ide> this.set("resolveLoader.cache", "make", options => !!options.cache); <ide> this.set("resolveLoader.mainFields", ["loader", "main"]); <ide> this.set("resolveLoader.extensions", [".js"]); <ide><path>lib/WebpackOptionsValidationError.js <ide> class WebpackOptionsValidationError extends WebpackError { <ide> 0, <ide> err.children.length - 1 <ide> ); <del> return WebpackOptionsValidationError.formatValidationError( <del> Object.assign({}, lastChild, { <del> children: remainingChildren, <del> parentSchema: Object.assign( <del> {}, <del> err.parentSchema, <del> lastChild.parentSchema <del> ) <del> }) <del> ); <add> return WebpackOptionsValidationError.formatValidationError({ <add> ...lastChild, <add> children: remainingChildren, <add> parentSchema: { ...err.parentSchema, ...lastChild.parentSchema } <add> }); <ide> } <ide> const children = filterChildren(err.children); <ide> if (children.length === 1) { <ide><path>lib/cache/ResolverCachePlugin.js <ide> class ResolverCachePlugin { <ide> request, <ide> callback <ide> ) => { <del> const newRequest = Object.assign( <del> { <del> _ResolverCachePluginCacheMiss: true <del> }, <del> request <del> ); <del> const newResolveContext = Object.assign({}, resolveContext, { <add> const newRequest = { <add> _ResolverCachePluginCacheMiss: true, <add> ...request <add> }; <add> const newResolveContext = { <add> ...resolveContext, <ide> stack: new Set(), <ide> missing: new Set(), <ide> fileDependencies: new Set(), <ide> contextDependencies: new Set() <del> }); <add> }; <ide> const propagate = key => { <ide> if (resolveContext[key]) { <ide> for (const dep of newResolveContext[key]) { <ide><path>lib/dependencies/ContextDependency.js <ide> class ContextDependency extends Dependency { <ide> this.options && <ide> (this.options.regExp.global || this.options.regExp.sticky) <ide> ) { <del> this.options = Object.assign({}, this.options, { regExp: null }); <add> this.options = { ...this.options, regExp: null }; <ide> this.hadGlobalOrStickyRegExp = true; <ide> } <ide> <ide><path>lib/dependencies/ContextDependencyHelpers.js <ide> exports.create = (Dep, range, param, expr, options, contextOptions, parser) => { <ide> `^${quotemeta(prefix)}${innerRegExp}${quotemeta(postfix)}$` <ide> ); <ide> const dep = new Dep( <del> Object.assign( <del> { <del> request: context + query, <del> recursive: options.wrappedContextRecursive, <del> regExp, <del> mode: "sync" <del> }, <del> contextOptions <del> ), <add> { <add> request: context + query, <add> recursive: options.wrappedContextRecursive, <add> regExp, <add> mode: "sync", <add> ...contextOptions <add> }, <ide> range, <ide> valueRange <ide> ); <ide> exports.create = (Dep, range, param, expr, options, contextOptions, parser) => { <ide> )}$` <ide> ); <ide> const dep = new Dep( <del> Object.assign( <del> { <del> request: context + query, <del> recursive: options.wrappedContextRecursive, <del> regExp, <del> mode: "sync" <del> }, <del> contextOptions <del> ), <add> { <add> request: context + query, <add> recursive: options.wrappedContextRecursive, <add> regExp, <add> mode: "sync", <add> ...contextOptions <add> }, <ide> range, <ide> valueRange <ide> ); <ide> exports.create = (Dep, range, param, expr, options, contextOptions, parser) => { <ide> return dep; <ide> } else { <ide> const dep = new Dep( <del> Object.assign( <del> { <del> request: options.exprContextRequest, <del> recursive: options.exprContextRecursive, <del> regExp: options.exprContextRegExp, <del> mode: "sync" <del> }, <del> contextOptions <del> ), <add> { <add> request: options.exprContextRequest, <add> recursive: options.exprContextRecursive, <add> regExp: options.exprContextRegExp, <add> mode: "sync", <add> ...contextOptions <add> }, <ide> range, <ide> param.range <ide> ); <ide><path>lib/dependencies/ImportParserPlugin.js <ide> class ImportParserPlugin { <ide> parser.state.current.addDependency(dep); <ide> } else { <ide> const depBlock = new ImportDependenciesBlock( <del> Object.assign(groupOptions, { <add> { <add> ...groupOptions, <ide> name: chunkName <del> }), <add> }, <ide> expr.loc, <ide> param.string, <ide> expr.range <ide><path>lib/ids/HashedModuleIdsPlugin.js <ide> class HashedModuleIdsPlugin { <ide> validateOptions(schema, options || {}, "Hashed Module Ids Plugin"); <ide> <ide> /** @type {HashedModuleIdsPluginOptions} */ <del> this.options = Object.assign( <del> { <del> context: null, <del> hashFunction: "md4", <del> hashDigest: "base64", <del> hashDigestLength: 4 <del> }, <del> options <del> ); <add> this.options = { <add> context: null, <add> hashFunction: "md4", <add> hashDigest: "base64", <add> hashDigestLength: 4, <add> ...options <add> }; <ide> } <ide> <ide> apply(compiler) { <ide><path>lib/node/NodeSourcePlugin.js <ide> module.exports = class NodeSourcePlugin { <ide> <ide> let localOptions = options; <ide> if (parserOptions.node) { <del> localOptions = Object.assign({}, localOptions, parserOptions.node); <add> localOptions = { ...localOptions, ...parserOptions.node }; <ide> } <ide> <ide> if (localOptions.global) { <ide><path>lib/optimize/ConcatenatedModule.js <ide> class ConcatenatedModule extends Module { <ide> moduleToInfoMap <ide> ); <ide> <del> const innerContext = Object.assign({}, context, { <add> const innerContext = { <add> ...context, <ide> dependencyTemplates: innerDependencyTemplates <del> }); <add> }; <ide> <ide> const set = new Set([ <ide> RuntimeGlobals.exports, // TODO check if really used <ide><path>lib/optimize/RuntimeChunkPlugin.js <ide> const { STAGE_ADVANCED } = require("../OptimizationStages"); <ide> <ide> class RuntimeChunkPlugin { <ide> constructor(options) { <del> this.options = Object.assign( <del> { <del> name: entrypoint => `runtime~${entrypoint.name}` <del> }, <del> options <del> ); <add> this.options = { <add> name: entrypoint => `runtime~${entrypoint.name}`, <add> ...options <add> }; <ide> } <ide> <ide> /** <ide><path>lib/optimize/SplitChunksPlugin.js <ide> const normalizeSizes = value => { <ide> javascript: value <ide> }; <ide> } else if (typeof value === "object" && value !== null) { <del> return Object.assign({}, value); <add> return { ...value }; <ide> } else { <ide> return {}; <ide> } <ide> const normalizeCacheGroups = cacheGroups => { <ide> if (result) { <ide> const groups = Array.isArray(result) ? result : [result]; <ide> for (const group of groups) { <del> results.push( <del> createCacheGroupSource(Object.assign({ key }, group)) <del> ); <add> results.push(createCacheGroupSource({ key, ...group })); <ide> } <ide> } <ide> } else { <ide> if ( <ide> checkTest(option.test, module, context) && <ide> checkModuleType(option.type, module) <ide> ) { <del> results.push( <del> createCacheGroupSource(Object.assign({ key }, option)) <del> ); <add> results.push(createCacheGroupSource({ key, ...option })); <ide> } <ide> } <ide> } <ide> module.exports = class SplitChunksPlugin { <ide> hasNonZeroSizes(item.cacheGroup.minRemainingSize) <ide> ) { <ide> const chunk = validChunks[0]; <del> const chunkSizes = Object.assign( <del> {}, <del> chunkGraph.getChunkModulesSizes(chunk) <del> ); <add> const chunkSizes = { ...chunkGraph.getChunkModulesSizes(chunk) }; <ide> for (const key of Object.keys(item.sizes)) { <ide> chunkSizes[key] -= item.sizes[key]; <ide> } <ide><path>lib/serialization/ObjectMiddleware.js <ide> class ObjectMiddleware extends SerializerMiddleware { <ide> let currentPosTypeLookup = 0; <ide> const objectTypeLookup = new Map(); <ide> const cycleStack = new Set(); <del> const ctx = Object.assign( <del> { <del> write(value) { <del> process(value); <del> }, <del> snapshot() { <del> return { <del> length: result.length, <del> cycleStackSize: cycleStack.size, <del> referenceableSize: referenceable.size, <del> currentPos, <del> objectTypeLookupSize: objectTypeLookup.size, <del> currentPosTypeLookup <del> }; <del> }, <del> rollback(snapshot) { <del> result.length = snapshot.length; <del> setSetSize(cycleStack, snapshot.cycleStackSize); <del> setMapSize(referenceable, snapshot.referenceableSize); <del> currentPos = snapshot.currentPos; <del> setMapSize(objectTypeLookup, snapshot.objectTypeLookupSize); <del> currentPosTypeLookup = snapshot.currentPosTypeLookup; <del> } <add> const ctx = { <add> write(value) { <add> process(value); <add> }, <add> snapshot() { <add> return { <add> length: result.length, <add> cycleStackSize: cycleStack.size, <add> referenceableSize: referenceable.size, <add> currentPos, <add> objectTypeLookupSize: objectTypeLookup.size, <add> currentPosTypeLookup <add> }; <add> }, <add> rollback(snapshot) { <add> result.length = snapshot.length; <add> setSetSize(cycleStack, snapshot.cycleStackSize); <add> setMapSize(referenceable, snapshot.referenceableSize); <add> currentPos = snapshot.currentPos; <add> setMapSize(objectTypeLookup, snapshot.objectTypeLookupSize); <add> currentPosTypeLookup = snapshot.currentPosTypeLookup; <ide> }, <del> context <del> ); <add> ...context <add> }; <ide> const process = item => { <ide> // check if we can emit a reference <ide> const ref = referenceable.get(item); <ide> class ObjectMiddleware extends SerializerMiddleware { <ide> let currentPosTypeLookup = 0; <ide> const objectTypeLookup = new Map(); <ide> const result = []; <del> const ctx = Object.assign( <del> { <del> read() { <del> return decodeValue(); <del> } <add> const ctx = { <add> read() { <add> return decodeValue(); <ide> }, <del> context <del> ); <add> ...context <add> }; <ide> const decodeValue = () => { <ide> const item = read(); <ide> <ide><path>lib/serialization/Serializer.js <ide> class Serializer { <ide> } <ide> <ide> serialize(obj, context) { <del> const ctx = Object.assign({}, context, this.context); <add> const ctx = { ...context, ...this.context }; <ide> return new Promise((resolve, reject) => <ide> resolve( <ide> this.middlewares.reduce((last, middleware) => { <ide> class Serializer { <ide> } <ide> <ide> deserialize(context) { <del> const ctx = Object.assign({}, context, this.context); <add> const ctx = { ...context, ...this.context }; <ide> return Promise.resolve().then(() => <ide> this.middlewares.reduceRight((last, middleware) => { <ide> if (last instanceof Promise) <ide><path>lib/stats/DefaultStatsFactoryPlugin.js <ide> const { <ide> * @property {string} modulesSort <ide> * @property {string} assetsSort <ide> * @property {Function[]} excludeAssets <add> * @property {Function[]} excludeModules <ide> * @property {Function[]} warningsFilter <ide> * @property {number} maxModules <ide> * @property {any} _env <ide> const FILTER = { <ide> if (excluded) return false; <ide> } <ide> }, <del> "compilation.modules": Object.assign( <del> { <del> excludeModules: EXCLUDE_MODULES_FILTER("module"), <del> "!orphanModules": (module, { compilation: { chunkGraph } }) => { <del> if (chunkGraph.getNumberOfModuleChunks(module) === 0) return false; <del> } <del> }, <del> BASE_MODULES_FILTER <del> ), <del> "module.modules": Object.assign( <del> { <del> excludeModules: EXCLUDE_MODULES_FILTER("nested") <del> }, <del> BASE_MODULES_FILTER <del> ), <del> "chunk.modules": Object.assign( <del> { <del> excludeModules: EXCLUDE_MODULES_FILTER("chunk") <del> }, <del> BASE_MODULES_FILTER <del> ), <del> "chunk.rootModules": Object.assign( <del> { <del> excludeModules: EXCLUDE_MODULES_FILTER("root-of-chunk") <add> "compilation.modules": ({ <add> excludeModules: EXCLUDE_MODULES_FILTER("module"), <add> "!orphanModules": (module, { compilation: { chunkGraph } }) => { <add> if (chunkGraph.getNumberOfModuleChunks(module) === 0) return false; <ide> }, <del> BASE_MODULES_FILTER <del> ) <add> ...BASE_MODULES_FILTER <add> }), <add> "module.modules": ({ <add> excludeModules: EXCLUDE_MODULES_FILTER("nested"), <add> ...BASE_MODULES_FILTER <add> }), <add> "chunk.modules": ({ <add> excludeModules: EXCLUDE_MODULES_FILTER("chunk"), <add> ...BASE_MODULES_FILTER <add> }), <add> "chunk.rootModules": ({ <add> excludeModules: EXCLUDE_MODULES_FILTER("root-of-chunk"), <add> ...BASE_MODULES_FILTER <add> }) <ide> }; <ide> <ide> /** @type {Record<string, (module: Module, context: UsualContext, options: UsualOptions, idx: number, i: number) => boolean | undefined>} */ <ide><path>lib/stats/DefaultStatsPrinterPlugin.js <ide> const SIMPLE_PRINTERS = { <ide> "compilation.entrypoints": (entrypoints, context, printer) => <ide> Array.isArray(entrypoints) <ide> ? undefined <del> : printer.print( <del> context.type, <del> Object.values(entrypoints), <del> Object.assign({}, context, { chunkGroupKind: "Entrypoint" }) <del> ), <add> : printer.print(context.type, Object.values(entrypoints), ({ <add> ...context, <add> chunkGroupKind: "Entrypoint" <add> })), <ide> "compilation.namedChunkGroups": (namedChunkGroups, context, printer) => { <ide> if (!Array.isArray(namedChunkGroups)) { <ide> const { <ide> const SIMPLE_PRINTERS = { <ide> !Object.prototype.hasOwnProperty.call(entrypoints, group.name) <ide> ); <ide> } <del> return printer.print( <del> context.type, <del> chunkGroups, <del> Object.assign({}, context, { chunkGroupKind: "Chunk Group" }) <del> ); <add> return printer.print(context.type, chunkGroups, ({ <add> ...context, <add> chunkGroupKind: "Chunk Group" <add> })); <ide> } <ide> }, <ide> "compilation.assetsByChunkName": () => "", <ide><path>lib/stats/StatsFactory.js <ide> class StatsFactory { <ide> } <ide> <ide> create(type, data, baseContext) { <del> const context = Object.assign({}, baseContext, { <add> const context = { <add> ...baseContext, <ide> type, <ide> [type]: data <del> }); <add> }; <ide> if (Array.isArray(data)) { <ide> // run filter on unsorted items <ide> const items = forEachLevelFilter( <ide> class StatsFactory { <ide> <ide> // for each item <ide> const resultItems = items2.map((item, i) => { <del> const itemContext = Object.assign({}, context, { <add> const itemContext = { <add> ...context, <ide> _index: i <del> }); <add> }; <ide> <ide> // run getItemName <ide> const itemName = forEachLevel(this.hooks.getItemName, `${type}[]`, h => <ide><path>lib/stats/StatsPrinter.js <ide> class StatsPrinter { <ide> } <ide> <ide> print(type, object, baseContext) { <del> const context = Object.assign({}, baseContext, { <add> const context = { <add> ...baseContext, <ide> type, <ide> [type]: object <del> }); <add> }; <ide> <ide> let printResult = forEachLevel(this.hooks.print, type, hook => <ide> hook.call(object, context) <ide> class StatsPrinter { <ide> h.call(sortedItems, context) <ide> ); <ide> const printedItems = sortedItems.map((item, i) => { <del> const itemContext = Object.assign({}, context, { <add> const itemContext = { <add> ...context, <ide> _index: i <del> }); <add> }; <ide> const itemName = forEachLevel( <ide> this.hooks.getItemName, <ide> `${type}[]`, <ide> class StatsPrinter { <ide> h.call(elements, context) <ide> ); <ide> const printedElements = elements.map(element => { <del> const content = this.print( <del> `${type}.${element}`, <del> object[element], <del> Object.assign({}, context, { <del> _parent: object, <del> _element: element, <del> [element]: object[element] <del> }) <del> ); <add> const content = this.print(`${type}.${element}`, object[element], { <add> ...context, <add> _parent: object, <add> _element: element, <add> [element]: object[element] <add> }); <ide> return { element, content }; <ide> }); <ide> printResult = forEachLevel(this.hooks.printElements, type, h => <ide><path>lib/util/cleverMerge.js <ide> const cachedCleverMerge = (first, second) => { <ide> * @returns {object} merged object of first and second object <ide> */ <ide> const cleverMerge = (first, second) => { <del> const newObject = Object.assign({}, first); <add> const newObject = { ...first }; <ide> for (const key of Object.keys(second)) { <ide> if (!(key in newObject)) { <ide> newObject[key] = second[key]; <ide><path>test/Errors.test.js <ide> const defaults = { <ide> <ide> async function compile(options) { <ide> const stats = await new Promise((resolve, reject) => { <del> const compiler = webpack(Object.assign({}, defaults.options, options)); <add> const compiler = webpack({ ...defaults.options, ...options }); <ide> if (options.mode === "production") { <ide> if (options.optimization) options.optimization.minimize = true; <ide> else options.optimization = { minimize: true }; <ide><path>test/TestCases.template.js <ide> const describeCases = config => { <ide> mode: config.mode || "none", <ide> optimization: config.mode <ide> ? NO_EMIT_ON_ERRORS_OPTIMIZATIONS <del> : Object.assign( <del> {}, <del> config.optimization, <del> DEFAULT_OPTIMIZATIONS <del> ), <add> : { <add> ...config.optimization, <add> ...DEFAULT_OPTIMIZATIONS <add> }, <ide> performance: { <ide> hints: false <ide> }, <ide> node: { <ide> __dirname: "mock", <ide> __filename: "mock" <ide> }, <del> cache: <del> config.cache && <del> Object.assign( <del> { <del> loglevel: "warning", <del> cacheDirectory <del> }, <del> config.cache <del> ), <add> cache: config.cache && { <add> loglevel: "warning", <add> cacheDirectory, <add> ...config.cache <add> }, <ide> output: { <ide> pathinfo: true, <ide> path: outputDirectory, <ide><path>test/cases/loaders/issue-2299/loader/index.js <ide> module.exports = function(content) { <ide> json.imports, <ide> function(url, callback) { <ide> this.loadModule(url, function(err, source, map, module) { <del> if(err) { <add> if (err) { <ide> return callback(err); <ide> } <ide> callback(null, JSON.parse(source)); <ide> }); <ide> }.bind(this), <ide> function(err, results) { <del> if(err) { <add> if (err) { <ide> return cb(err); <ide> } <ide> // Combine all the results into one object and return it <del> cb(null, "module.exports = " + JSON.stringify(results.reduce(function(prev, result) { <del> return Object.assign({}, prev, result); <del> }, json))); <add> cb( <add> null, <add> "module.exports = " + <add> JSON.stringify( <add> results.reduce(function(prev, result) { <add> return { ...prev, ...result }; <add> }, json) <add> ) <add> ); <ide> } <ide> ); <ide> }; <ide><path>test/compareLocations.unittest.js <ide> <ide> const { compareLocations } = require("../lib/util/comparators"); <ide> const createPosition = overrides => { <del> return Object.assign( <del> { <del> line: 10, <del> column: 5 <del> }, <del> overrides <del> ); <add> return { <add> line: 10, <add> column: 5, <add> ...overrides <add> }; <ide> }; <ide> <ide> const createLocation = (start, end, index) => { <ide><path>test/statsCases/filter-warnings/webpack.config.js <ide> module.exports = [ <ide> ["should not filter"], <ide> [/should not filter/], <ide> [warnings => false] <del>].map(filter => <del> Object.assign({}, baseConfig, { <del> name: Array.isArray(filter) ? `[${filter}]` : `${filter}`, <del> stats: Object.assign({}, baseConfig.stats, { <del> warningsFilter: filter <del> }) <del> }) <del>); <add>].map(filter => ({ <add> ...baseConfig, <add> name: Array.isArray(filter) ? `[${filter}]` : `${filter}`, <add> stats: { ...baseConfig.stats, warningsFilter: filter } <add>})); <ide><path>test/statsCases/issue-7577/webpack.config.js <ide> const base = { <ide> } <ide> }; <ide> module.exports = [ <del> Object.assign( <del> { <del> entry: "./a.js", <del> output: { <del> filename: "a-[name]-[chunkhash].js" <del> } <add> { <add> entry: "./a.js", <add> output: { <add> filename: "a-[name]-[chunkhash].js" <ide> }, <del> base <del> ), <del> Object.assign( <del> { <del> entry: "./b.js", <del> output: { <del> filename: "b-[name]-[chunkhash].js" <del> } <add> ...base <add> }, <add> { <add> entry: "./b.js", <add> output: { <add> filename: "b-[name]-[chunkhash].js" <ide> }, <del> base <del> ), <del> Object.assign( <del> { <del> entry: "./c.js", <del> output: { <del> filename: "c-[name]-[chunkhash].js" <del> } <add> ...base <add> }, <add> { <add> entry: "./c.js", <add> output: { <add> filename: "c-[name]-[chunkhash].js" <ide> }, <del> base <del> ) <add> ...base <add> } <ide> ]; <ide><path>test/statsCases/named-chunk-groups/webpack.config.js <ide> const config = { <ide> }; <ide> <ide> module.exports = [ <del> Object.assign( <del> { <del> stats: Object.assign({ entrypoints: false, chunkGroups: true }, stats) <del> }, <del> config <del> ), <del> Object.assign( <del> { <del> stats: Object.assign({ entrypoints: true, chunkGroups: true }, stats) <del> }, <del> config <del> ) <add> { <add> stats: { entrypoints: false, chunkGroups: true, ...stats }, <add> ...config <add> }, <add> { <add> stats: { entrypoints: true, chunkGroups: true, ...stats }, <add> ...config <add> } <ide> ]; <ide><path>test/statsCases/runtime-chunk-integration/webpack.config.js <ide> const baseConfig = { <ide> ] <ide> }; <ide> <del>const withoutNamedEntry = Object.assign({}, baseConfig, { <add>const withoutNamedEntry = { <add> ...baseConfig, <ide> name: "base", <ide> entry: { <ide> main1: "./main1" <ide> }, <ide> optimization: { <ide> runtimeChunk: "single" <ide> } <del>}); <add>}; <ide> <del>const withNamedEntry = Object.assign({}, baseConfig, { <add>const withNamedEntry = { <add> ...baseConfig, <ide> name: "manifest is named entry", <ide> entry: { <ide> main1: "./main1", <ide> const withNamedEntry = Object.assign({}, baseConfig, { <ide> name: "manifest" <ide> } <ide> } <del>}); <add>}; <ide> <ide> module.exports = [withoutNamedEntry, withNamedEntry];
41
Python
Python
fix bug in warnings t5 pipelines
06dd597552a78c53ce52ec1acf5ff3ab3ece82ea
<ide><path>src/transformers/pipelines.py <ide> def __call__( <ide> elif self.framework == "tf": <ide> input_length = tf.shape(inputs["input_ids"])[-1].numpy() <ide> <del> if input_length < self.model.config.min_length // 2: <add> min_length = generate_kwargs.get("min_length", self.model.config.min_length) <add> if input_length < min_length // 2: <ide> logger.warning( <ide> "Your min_length is set to {}, but you input_length is only {}. You might consider decreasing min_length manually, e.g. summarizer('...', min_length=10)".format( <del> self.model.config.min_length, input_length <add> min_length, input_length <ide> ) <ide> ) <ide> <del> if input_length < self.model.config.max_length: <add> max_length = generate_kwargs.get("max_length", self.model.config.max_length) <add> if input_length < max_length: <ide> logger.warning( <ide> "Your max_length is set to {}, but you input_length is only {}. You might consider decreasing max_length manually, e.g. summarizer('...', max_length=50)".format( <del> self.model.config.max_length, input_length <add> max_length, input_length <ide> ) <ide> ) <ide> <ide> def __call__( <ide> elif self.framework == "tf": <ide> input_length = tf.shape(inputs["input_ids"])[-1].numpy() <ide> <del> if input_length > 0.9 * self.model.config.max_length: <add> max_length = generate_kwargs.get("max_length", self.model.config.max_length) <add> if input_length > 0.9 * max_length: <ide> logger.warning( <ide> "Your input_length: {} is bigger than 0.9 * max_length: {}. You might consider increasing your max_length manually, e.g. translator('...', max_length=400)".format( <del> input_length, self.model.config.max_length <add> input_length, max_length <ide> ) <ide> ) <ide>
1
Python
Python
remove unused imports
1b3b01e042920e13934608d36da93a4d02dd95e9
<ide><path>rest_framework/request.py <ide> from __future__ import unicode_literals <ide> <ide> import sys <del>import warnings <ide> <ide> from django.conf import settings <ide> from django.http import QueryDict <ide><path>rest_framework/serializers.py <ide> """ <ide> from __future__ import unicode_literals <ide> <del>import warnings <del> <ide> from django.db import models <ide> from django.db.models.fields import Field as DjangoModelField <ide> from django.db.models.fields import FieldDoesNotExist <ide><path>rest_framework/views.py <ide> """ <ide> from __future__ import unicode_literals <ide> <del>import inspect <del>import warnings <del> <ide> from django.core.exceptions import PermissionDenied <ide> from django.db import models <ide> from django.http import Http404
3
Go
Go
fix some missing synchronization in libcontainerd
647cec4324186faa3183bd6a7bc72a032a86c8c9
<ide><path>libcontainerd/client_daemon.go <ide> import ( <ide> const InitProcessName = "init" <ide> <ide> type container struct { <del> sync.Mutex <add> mu sync.Mutex <ide> <ide> bundleDir string <ide> ctr containerd.Container <ide> type container struct { <ide> oomKilled bool <ide> } <ide> <add>func (c *container) setTask(t containerd.Task) { <add> c.mu.Lock() <add> c.task = t <add> c.mu.Unlock() <add>} <add> <add>func (c *container) getTask() containerd.Task { <add> c.mu.Lock() <add> t := c.task <add> c.mu.Unlock() <add> return t <add>} <add> <add>func (c *container) addProcess(id string, p containerd.Process) { <add> c.mu.Lock() <add> if c.execs == nil { <add> c.execs = make(map[string]containerd.Process) <add> } <add> c.execs[id] = p <add> c.mu.Unlock() <add>} <add> <add>func (c *container) deleteProcess(id string) { <add> c.mu.Lock() <add> delete(c.execs, id) <add> c.mu.Unlock() <add>} <add> <add>func (c *container) getProcess(id string) containerd.Process { <add> c.mu.Lock() <add> p := c.execs[id] <add> c.mu.Unlock() <add> return p <add>} <add> <add>func (c *container) setOOMKilled(killed bool) { <add> c.mu.Lock() <add> c.oomKilled = killed <add> c.mu.Unlock() <add>} <add> <add>func (c *container) getOOMKilled() bool { <add> c.mu.Lock() <add> killed := c.oomKilled <add> c.mu.Unlock() <add> return killed <add>} <add> <ide> type client struct { <ide> sync.RWMutex // protects containers map <ide> <ide> func (c *client) Create(ctx context.Context, id string, ociSpec *specs.Spec, run <ide> // Start create and start a task for the specified containerd id <ide> func (c *client) Start(ctx context.Context, id, checkpointDir string, withStdin bool, attachStdio StdioCallback) (int, error) { <ide> ctr := c.getContainer(id) <del> switch { <del> case ctr == nil: <add> if ctr == nil { <ide> return -1, errors.WithStack(newNotFoundError("no such container")) <del> case ctr.task != nil: <add> } <add> if t := ctr.getTask(); t != nil { <ide> return -1, errors.WithStack(newConflictError("container already started")) <ide> } <ide> <ide> func (c *client) Start(ctx context.Context, id, checkpointDir string, withStdin <ide> return -1, err <ide> } <ide> <del> c.Lock() <del> c.containers[id].task = t <del> c.Unlock() <add> ctr.setTask(t) <ide> <ide> // Signal c.createIO that it can call CloseIO <ide> close(stdinCloseSync) <ide> func (c *client) Start(ctx context.Context, id, checkpointDir string, withStdin <ide> c.logger.WithError(err).WithField("container", id). <ide> Error("failed to delete task after fail start") <ide> } <del> c.Lock() <del> c.containers[id].task = nil <del> c.Unlock() <add> ctr.setTask(nil) <ide> return -1, err <ide> } <ide> <ide> func (c *client) Start(ctx context.Context, id, checkpointDir string, withStdin <ide> <ide> func (c *client) Exec(ctx context.Context, containerID, processID string, spec *specs.Process, withStdin bool, attachStdio StdioCallback) (int, error) { <ide> ctr := c.getContainer(containerID) <del> switch { <del> case ctr == nil: <add> if ctr == nil { <ide> return -1, errors.WithStack(newNotFoundError("no such container")) <del> case ctr.task == nil: <add> } <add> t := ctr.getTask() <add> if t == nil { <ide> return -1, errors.WithStack(newInvalidParameterError("container is not running")) <del> case ctr.execs != nil && ctr.execs[processID] != nil: <add> } <add> <add> if p := ctr.getProcess(processID); p != nil { <ide> return -1, errors.WithStack(newConflictError("id already in use")) <ide> } <ide> <ide> func (c *client) Exec(ctx context.Context, containerID, processID string, spec * <ide> } <ide> }() <ide> <del> p, err = ctr.task.Exec(ctx, processID, spec, func(id string) (cio.IO, error) { <add> p, err = t.Exec(ctx, processID, spec, func(id string) (cio.IO, error) { <ide> rio, err = c.createIO(fifos, containerID, processID, stdinCloseSync, attachStdio) <ide> return rio, err <ide> }) <ide> func (c *client) Exec(ctx context.Context, containerID, processID string, spec * <ide> return -1, err <ide> } <ide> <del> ctr.Lock() <del> if ctr.execs == nil { <del> ctr.execs = make(map[string]containerd.Process) <del> } <del> ctr.execs[processID] = p <del> ctr.Unlock() <add> ctr.addProcess(processID, p) <ide> <ide> // Signal c.createIO that it can call CloseIO <ide> close(stdinCloseSync) <ide> <ide> if err = p.Start(ctx); err != nil { <ide> p.Delete(context.Background()) <del> ctr.Lock() <del> delete(ctr.execs, processID) <del> ctr.Unlock() <add> ctr.deleteProcess(processID) <ide> return -1, err <ide> } <ide> <ide> func (c *client) DeleteTask(ctx context.Context, containerID string) (uint32, ti <ide> return 255, time.Now(), nil <ide> } <ide> <del> c.Lock() <del> if ctr, ok := c.containers[containerID]; ok { <del> ctr.task = nil <add> if ctr := c.getContainer(containerID); ctr != nil { <add> ctr.setTask(nil) <ide> } <del> c.Unlock() <del> <ide> return status.ExitCode(), status.ExitTime(), nil <ide> } <ide> <ide> func (c *client) Status(ctx context.Context, containerID string) (Status, error) <ide> return StatusUnknown, errors.WithStack(newNotFoundError("no such container")) <ide> } <ide> <del> s, err := ctr.task.Status(ctx) <add> t := ctr.getTask() <add> if t == nil { <add> return StatusUnknown, errors.WithStack(newNotFoundError("no such task")) <add> } <add> <add> s, err := t.Status(ctx) <ide> if err != nil { <ide> return StatusUnknown, err <ide> } <ide> func (c *client) removeContainer(id string) { <ide> <ide> func (c *client) getProcess(containerID, processID string) (containerd.Process, error) { <ide> ctr := c.getContainer(containerID) <del> switch { <del> case ctr == nil: <add> if ctr == nil { <ide> return nil, errors.WithStack(newNotFoundError("no such container")) <del> case ctr.task == nil: <add> } <add> <add> t := ctr.getTask() <add> if t == nil { <ide> return nil, errors.WithStack(newNotFoundError("container is not running")) <del> case processID == InitProcessName: <del> return ctr.task, nil <del> default: <del> ctr.Lock() <del> defer ctr.Unlock() <del> if ctr.execs == nil { <del> return nil, errors.WithStack(newNotFoundError("no execs")) <del> } <add> } <add> if processID == InitProcessName { <add> return t, nil <ide> } <ide> <del> p := ctr.execs[processID] <add> p := ctr.getProcess(processID) <ide> if p == nil { <ide> return nil, errors.WithStack(newNotFoundError("no such exec")) <ide> } <del> <ide> return p, nil <ide> } <ide> <ide> func (c *client) processEvent(ctr *container, et EventType, ei EventInfo) { <ide> } <ide> <ide> if et == EventExit && ei.ProcessID != ei.ContainerID { <del> var p containerd.Process <del> ctr.Lock() <del> if ctr.execs != nil { <del> p = ctr.execs[ei.ProcessID] <del> } <del> ctr.Unlock() <add> p := ctr.getProcess(ei.ProcessID) <ide> if p == nil { <ide> c.logger.WithError(errors.New("no such process")). <ide> WithFields(logrus.Fields{ <ide> func (c *client) processEvent(ctr *container, et EventType, ei EventInfo) { <ide> "process": ei.ProcessID, <ide> }).Warn("failed to delete process") <ide> } <del> c.Lock() <del> delete(ctr.execs, ei.ProcessID) <del> c.Unlock() <add> ctr.deleteProcess(ei.ProcessID) <add> <ide> ctr := c.getContainer(ei.ContainerID) <ide> if ctr == nil { <ide> c.logger.WithFields(logrus.Fields{ <ide> func (c *client) processEventStream(ctx context.Context) { <ide> } <ide> <ide> if oomKilled { <del> ctr.oomKilled = true <add> ctr.setOOMKilled(true) <ide> oomKilled = false <ide> } <del> ei.OOMKilled = ctr.oomKilled <add> ei.OOMKilled = ctr.getOOMKilled() <ide> <ide> c.processEvent(ctr, et, ei) <ide> }
1
Python
Python
raise proper exception, not a string
aa3441ae45b348aa2e1b422d1c5a69b49e909a95
<ide><path>tools/js2c.py <ide> def ReadMacros(lines): <ide> fun = eval("lambda " + ",".join(args) + ': ' + body) <ide> macros[name] = PythonMacro(args, fun) <ide> else: <del> raise ("Illegal line: " + line) <add> raise Exception("Illegal line: " + line) <ide> return (constants, macros) <ide> <ide>
1
Python
Python
pass additional options in task.retry
6c1faced5063b10c251be294809e94853dd44dc2
<ide><path>celery/app/task.py <ide> def retry(self, args=None, kwargs=None, exc=None, throw=True, <ide> S = self.subtask_from_request( <ide> request, args, kwargs, <ide> countdown=countdown, eta=eta, retries=retries, <add> **options <ide> ) <ide> <ide> if max_retries is not None and retries > max_retries:
1
Javascript
Javascript
add types to new hooks
49f79cb702f1898c21a8f7cd9dd66a18773511a6
<ide><path>lib/Compilation.js <ide> class Compilation { <ide> /** @type {SyncBailHook} */ <ide> shouldRecord: new SyncBailHook([]), <ide> <del> /** @type {SyncHook<Chunk>} */ <add> /** @type {SyncHook<Chunk, Set<string>>} */ <ide> additionalChunkRuntimeRequirements: new SyncHook([ <ide> "chunk", <ide> "runtimeRequirements" <ide> ]), <add> /** @type {HookMap<Chunk, Set<string>>} */ <ide> runtimeRequirementInChunk: new HookMap( <ide> () => new SyncBailHook(["chunk", "runtimeRequirements"]) <ide> ), <del> /** @type {SyncHook<Module>} */ <add> /** @type {SyncHook<Module, Set<string>>} */ <ide> additionalModuleRuntimeRequirements: new SyncHook([ <ide> "module", <ide> "runtimeRequirements" <ide> ]), <add> /** @type {HookMap<Module, Set<string>>} */ <ide> runtimeRequirementInModule: new HookMap( <ide> () => new SyncBailHook(["module", "runtimeRequirements"]) <ide> ), <del> /** @type {SyncHook<Chunk>} */ <add> /** @type {SyncHook<Chunk, Set<string>>} */ <ide> additionalTreeRuntimeRequirements: new SyncHook([ <ide> "chunk", <ide> "runtimeRequirements" <ide> ]), <add> /** @type {HookMap<Chunk, Set<string>>} */ <ide> runtimeRequirementInTree: new HookMap( <ide> () => new SyncBailHook(["chunk", "runtimeRequirements"]) <ide> ),
1
Ruby
Ruby
add test for slug to id with id is out of range
b74256be5bcd8703148bbf13713002dbad725703
<ide><path>activerecord/test/cases/base_test.rb <ide> def test_find_by_slug <ide> assert_equal Topic.find("1-meowmeow"), Topic.find(1) <ide> end <ide> <add> def test_out_of_range_slugs <add> assert_equal [Topic.find(1)], Topic.where(id: ["1-meowmeow", "9223372036854775808-hello"]) <add> end <add> <ide> def test_find_by_slug_with_array <ide> assert_equal Topic.find([1, 2]), Topic.find(["1-meowmeow", "2-hello"]) <ide> assert_equal "The Second Topic of the day", Topic.find(["2-hello", "1-meowmeow"]).first.title
1
Ruby
Ruby
remove dead code
3ff3e7443857aa15ec6a2c9db6810c6dbf91a915
<ide><path>Library/Homebrew/superenv.rb <ide> def superenv? <ide> MacOS.sdk_path.nil?) and # because superenv will fail to find stuff <ide> superbin and superbin.directory? and <ide> not ARGV.include? "--env=std" <del>rescue # blanket rescue because there are naked raises <del> false <ide> end <ide> <ide> # Note that this block is guarded with `if superenv?`
1
Java
Java
refine use of substring operations
edfc6c0293fc45096876d9821670892aba2ea2ec
<ide><path>spring-aop/src/main/java/org/springframework/aop/aspectj/AspectJAdviceParameterNameDiscoverer.java <ide> private PointcutBody getPointcutBody(String[] tokens, int startIndex) { <ide> } <ide> <ide> if (tokens[currentIndex].endsWith(")")) { <del> sb.append(tokens[currentIndex].substring(0, tokens[currentIndex].length() - 1)); <add> sb.append(tokens[currentIndex], 0, tokens[currentIndex].length() - 1); <ide> return new PointcutBody(numTokensConsumed, sb.toString().trim()); <ide> } <ide> <ide><path>spring-beans/src/main/java/org/springframework/beans/PropertyEditorRegistrySupport.java <ide> private void addStrippedPropertyPaths(List<String> strippedPaths, String nestedP <ide> if (endIndex != -1) { <ide> String prefix = propertyPath.substring(0, startIndex); <ide> String key = propertyPath.substring(startIndex, endIndex + 1); <del> String suffix = propertyPath.substring(endIndex + 1, propertyPath.length()); <add> String suffix = propertyPath.substring(endIndex + 1); <ide> // Strip the first key. <ide> strippedPaths.add(nestedPath + prefix + suffix); <ide> // Search for further keys to strip, with the first key stripped. <ide><path>spring-context/src/main/java/org/springframework/scheduling/config/TaskExecutorFactoryBean.java <ide> private void determinePoolSizeRange(ThreadPoolTaskExecutor executor) { <ide> int separatorIndex = this.poolSize.indexOf('-'); <ide> if (separatorIndex != -1) { <ide> corePoolSize = Integer.parseInt(this.poolSize.substring(0, separatorIndex)); <del> maxPoolSize = Integer.parseInt(this.poolSize.substring(separatorIndex + 1, this.poolSize.length())); <add> maxPoolSize = Integer.parseInt(this.poolSize.substring(separatorIndex + 1)); <ide> if (corePoolSize > maxPoolSize) { <ide> throw new IllegalArgumentException( <ide> "Lower bound of pool-size range must not exceed the upper bound"); <ide><path>spring-jms/src/main/java/org/springframework/jms/listener/DefaultMessageListenerContainer.java <ide> public void setConcurrency(String concurrency) { <ide> int separatorIndex = concurrency.indexOf('-'); <ide> if (separatorIndex != -1) { <ide> setConcurrentConsumers(Integer.parseInt(concurrency.substring(0, separatorIndex))); <del> setMaxConcurrentConsumers(Integer.parseInt(concurrency.substring(separatorIndex + 1, concurrency.length()))); <add> setMaxConcurrentConsumers(Integer.parseInt(concurrency.substring(separatorIndex + 1))); <ide> } <ide> else { <ide> setConcurrentConsumers(1); <ide><path>spring-jms/src/main/java/org/springframework/jms/listener/SimpleMessageListenerContainer.java <ide> public void setConcurrency(String concurrency) { <ide> try { <ide> int separatorIndex = concurrency.indexOf('-'); <ide> if (separatorIndex != -1) { <del> setConcurrentConsumers(Integer.parseInt(concurrency.substring(separatorIndex + 1, concurrency.length()))); <add> setConcurrentConsumers(Integer.parseInt(concurrency.substring(separatorIndex + 1))); <ide> } <ide> else { <ide> setConcurrentConsumers(Integer.parseInt(concurrency)); <ide><path>spring-jms/src/main/java/org/springframework/jms/listener/endpoint/JmsActivationSpecConfig.java <ide> public void setConcurrency(String concurrency) { <ide> try { <ide> int separatorIndex = concurrency.indexOf('-'); <ide> if (separatorIndex != -1) { <del> setMaxConcurrency(Integer.parseInt(concurrency.substring(separatorIndex + 1, concurrency.length()))); <add> setMaxConcurrency(Integer.parseInt(concurrency.substring(separatorIndex + 1))); <ide> } <ide> else { <ide> setMaxConcurrency(Integer.parseInt(concurrency)); <ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/StompDecoder.java <ide> private String unescape(String inString) { <ide> int index = inString.indexOf('\\'); <ide> <ide> while (index >= 0) { <del> sb.append(inString.substring(pos, index)); <add> sb.append(inString, pos, index); <ide> if (index + 1 >= inString.length()) { <ide> throw new StompConversionException("Illegal escape sequence at index " + index + ": " + inString); <ide> } <ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/StompEncoder.java <ide> else if (sb != null){ <ide> private StringBuilder getStringBuilder(@Nullable StringBuilder sb, String inString, int i) { <ide> if (sb == null) { <ide> sb = new StringBuilder(inString.length()); <del> sb.append(inString.substring(0, i)); <add> sb.append(inString, 0, i); <ide> } <ide> return sb; <ide> } <ide><path>spring-test/src/main/java/org/springframework/test/web/servlet/setup/PatternMappingFilterProxy.java <ide> public PatternMappingFilterProxy(Filter delegate, String... urlPatterns) { <ide> private void addUrlPattern(String urlPattern) { <ide> Assert.notNull(urlPattern, "Found null URL Pattern"); <ide> if (urlPattern.startsWith(EXTENSION_MAPPING_PATTERN)) { <del> this.endsWithMatches.add(urlPattern.substring(1, urlPattern.length())); <add> this.endsWithMatches.add(urlPattern.substring(1)); <ide> } <ide> else if (urlPattern.equals(PATH_MAPPING_PATTERN)) { <ide> this.startsWithMatches.add(""); <ide><path>spring-web/src/main/java/org/springframework/web/util/UriTemplate.java <ide> else if (c == '}') { <ide> throw new IllegalArgumentException( <ide> "No custom regular expression specified after ':' in \"" + variable + "\""); <ide> } <del> String regex = variable.substring(idx + 1, variable.length()); <add> String regex = variable.substring(idx + 1); <ide> pattern.append('('); <ide> pattern.append(regex); <ide> pattern.append(')'); <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/view/RedirectView.java <ide> protected StringBuilder expandTargetUrlTemplate(String targetUrl, <ide> String name = matcher.group(1); <ide> Object value = (model.containsKey(name) ? model.get(name) : uriVariables.get(name)); <ide> Assert.notNull(value, () -> "No value for URI variable '" + name + "'"); <del> result.append(targetUrl.substring(endLastMatch, matcher.start())); <add> result.append(targetUrl, endLastMatch, matcher.start()); <ide> result.append(encodeUriVariable(value.toString())); <ide> endLastMatch = matcher.end(); <ide> found = matcher.find(); <ide> } <del> result.append(targetUrl.substring(endLastMatch, targetUrl.length())); <add> result.append(targetUrl.substring(endLastMatch)); <ide> return result; <ide> } <ide> <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/tags/UrlTag.java <ide> String createUrl() throws JspException { <ide> } <ide> else { <ide> if (this.context.endsWith("/")) { <del> url.append(this.context.substring(0, this.context.length() - 1)); <add> url.append(this.context, 0, this.context.length() - 1); <ide> } <ide> else { <ide> url.append(this.context); <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/view/RedirectView.java <ide> protected StringBuilder replaceUriTemplateVariables( <ide> if (value == null) { <ide> throw new IllegalArgumentException("Model has no value for key '" + name + "'"); <ide> } <del> result.append(targetUrl.substring(endLastMatch, matcher.start())); <add> result.append(targetUrl, endLastMatch, matcher.start()); <ide> result.append(UriUtils.encodePathSegment(value.toString(), encodingScheme)); <ide> endLastMatch = matcher.end(); <ide> } <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/WebSocketExtension.java <ide> private static WebSocketExtension parseExtension(String extension) { <ide> int eqIndex = parameter.indexOf('='); <ide> if (eqIndex != -1) { <ide> String attribute = parameter.substring(0, eqIndex); <del> String value = parameter.substring(eqIndex + 1, parameter.length()); <add> String value = parameter.substring(eqIndex + 1); <ide> parameters.put(attribute, value); <ide> } <ide> }
14
Javascript
Javascript
eliminate caching of linesvnode
b23dcb7b9f3c606a349d6cc9f88a5988f83e001b
<ide><path>src/text-editor-component.js <ide> class CustomGutterDecorationComponent { <ide> class LinesTileComponent { <ide> constructor (props) { <ide> this.props = props <del> this.linesVnode = null <ide> etch.initialize(this) <ide> } <ide> <ide> update (newProps) { <ide> if (this.shouldUpdate(newProps)) { <del> if (newProps.width !== this.props.width) { <del> this.linesVnode = null <del> } <ide> this.props = newProps <ide> etch.updateSync(this) <ide> } <ide> class LinesTileComponent { <ide> lineNodesByScreenLineId, textNodesByScreenLineId <ide> } = this.props <ide> <del> if (!measuredContent || !this.linesVnode) { <del> this.linesVnode = $(LinesComponent, { <del> height, <del> width, <del> tileStartRow, <del> screenLines, <del> lineDecorations, <del> blockDecorations, <del> displayLayer, <del> lineNodesByScreenLineId, <del> textNodesByScreenLineId <del> }) <del> } <del> <del> return this.linesVnode <add> return $(LinesComponent, { <add> height, <add> width, <add> tileStartRow, <add> screenLines, <add> lineDecorations, <add> blockDecorations, <add> displayLayer, <add> lineNodesByScreenLineId, <add> textNodesByScreenLineId <add> }) <ide> } <ide> <ide> shouldUpdate (newProps) {
1
Javascript
Javascript
avoid dependency on shared state
065f4c48ec66654a604af5408fb5efb6ddb461fa
<ide><path>spec/text-editor-spec.js <ide> describe('TextEditor', () => { <ide> await atom.packages.activatePackage('language-javascript') <ide> }) <ide> <del> it('generates unique ids for each editor', () => { <del> // Deserialized editors are initialized with an id: <del> new TextEditor({id: 0}) <del> new TextEditor({id: 1}) <del> new TextEditor({id: 2}) <del> // Initializing an editor without an id causes a new id to be generated: <del> const generatedId = new TextEditor().id <del> expect(generatedId).toBe(3) <add> it('generates unique ids for each editor', async () => { <add> // Deserialized editors are initialized with the serialized id. We can <add> // initialize an editor with what we expect to be the next id: <add> const deserialized = new TextEditor({id: editor.id+1}) <add> expect(deserialized.id).toEqual(editor.id+1) <add> <add> // The id generator should skip the id used up by the deserialized one: <add> const fresh = new TextEditor() <add> expect(fresh.id).toNotEqual(deserialized.id) <ide> }) <ide> <ide> describe('when the editor is deserialized', () => {
1
Javascript
Javascript
make color.setscalar returns this.
4ce415a6a8f2c5bcfc89434ada4e0529dd85fe69
<ide><path>src/math/Color.js <ide> Color.prototype = { <ide> this.g = scalar; <ide> this.b = scalar; <ide> <add> return this; <add> <ide> }, <ide> <ide> setHex: function ( hex ) {
1
Java
Java
improve performance of stringutils#cleanpath
1c6dda3ca4dc28beee98a4337985f9e4a12a8157
<ide><path>spring-core/src/main/java/org/springframework/util/StringUtils.java <ide> /* <del> * Copyright 2002-2019 the original author or authors. <add> * Copyright 2002-2020 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> else if (TOP_PATH.equals(element)) { <ide> } <ide> } <ide> <add> // All path elements stayed the same - shortcut <add> if (pathArray.length == pathElements.size()) { <add> return prefix + pathToUse; <add> } <ide> // Remaining top paths need to be retained. <ide> for (int i = 0; i < tops; i++) { <ide> pathElements.add(0, TOP_PATH); <ide><path>spring-core/src/test/java/org/springframework/util/StringUtilsTests.java <ide> void cleanPath() { <ide> assertThat(StringUtils.cleanPath("file:../")).isEqualTo("file:../"); <ide> assertThat(StringUtils.cleanPath("file:./../")).isEqualTo("file:../"); <ide> assertThat(StringUtils.cleanPath("file:.././")).isEqualTo("file:../"); <add> assertThat(StringUtils.cleanPath("file:/mypath/spring.factories")).isEqualTo("file:/mypath/spring.factories"); <ide> assertThat(StringUtils.cleanPath("file:///c:/some/../path/the%20file.txt")).isEqualTo("file:///c:/path/the%20file.txt"); <ide> } <ide>
2
Java
Java
fix issue with extracting matrix variables
d8469d118b41fd18b70a11f0c0dcd12b60a8f6c6
<ide><path>spring-web/src/main/java/org/springframework/web/util/UrlPathHelper.java <ide> <ide> import org.apache.commons.logging.Log; <ide> import org.apache.commons.logging.LogFactory; <add>import org.springframework.util.Assert; <ide> import org.springframework.util.StringUtils; <ide> <ide> /** <ide> public String getLookupPathForRequest(HttpServletRequest request) { <ide> public String getPathWithinServletMapping(HttpServletRequest request) { <ide> String pathWithinApp = getPathWithinApplication(request); <ide> String servletPath = getServletPath(request); <del> if (pathWithinApp.startsWith(servletPath)) { <add> String path = getRemainingPath(pathWithinApp, servletPath, false); <add> if (path != null) { <ide> // Normal case: URI contains servlet path. <del> return pathWithinApp.substring(servletPath.length()); <add> return path; <ide> } <ide> else { <ide> // Special case: URI is different from servlet path. <ide> public String getPathWithinServletMapping(HttpServletRequest request) { <ide> public String getPathWithinApplication(HttpServletRequest request) { <ide> String contextPath = getContextPath(request); <ide> String requestUri = getRequestUri(request); <del> if (StringUtils.startsWithIgnoreCase(requestUri, contextPath)) { <add> String path = getRemainingPath(requestUri, contextPath, true); <add> if (path != null) { <ide> // Normal case: URI contains context path. <del> String path = requestUri.substring(contextPath.length()); <ide> return (StringUtils.hasText(path) ? path : "/"); <ide> } <ide> else { <del> // Special case: rather unusual. <ide> return requestUri; <ide> } <ide> } <ide> <add> /** <add> * Match the given "mapping" to the start of the "requestUri" and if there <add> * is a match return the extra part. This method is needed because the <add> * context path and the servlet path returned by the HttpServletRequest are <add> * stripped of semicolon content unlike the requesUri. <add> */ <add> private String getRemainingPath(String requestUri, String mapping, boolean ignoreCase) { <add> int index1 = 0; <add> int index2 = 0; <add> for ( ; (index1 < requestUri.length()) && (index2 < mapping.length()); index1++, index2++) { <add> char c1 = requestUri.charAt(index1); <add> char c2 = mapping.charAt(index2); <add> if (c1 == ';') { <add> index1 = requestUri.indexOf('/', index1); <add> if (index1 == -1) { <add> return null; <add> } <add> c1 = requestUri.charAt(index1); <add> } <add> if (c1 == c2) { <add> continue; <add> } <add> if (ignoreCase && (Character.toLowerCase(c1) == Character.toLowerCase(c2))) { <add> continue; <add> } <add> return null; <add> } <add> if (index2 != mapping.length()) { <add> return null; <add> } <add> if (index1 == requestUri.length()) { <add> return ""; <add> } <add> else if (requestUri.charAt(index1) == ';') { <add> index1 = requestUri.indexOf('/', index1); <add> } <add> return (index1 != -1) ? requestUri.substring(index1) : ""; <add> } <ide> <ide> /** <ide> * Return the request URI for the given request, detecting an include request <ide><path>spring-web/src/test/java/org/springframework/web/util/UrlPathHelperTests.java <ide> public void getPathWithinApplicationForSlashContextPath() { <ide> assertEquals("Incorrect path returned", "/welcome.html", helper.getPathWithinApplication(request)); <ide> } <ide> <add> @Test <add> public void getPathWithinServlet() { <add> request.setContextPath("/petclinic"); <add> request.setServletPath("/main"); <add> request.setRequestURI("/petclinic/main/welcome.html"); <add> <add> assertEquals("Incorrect path returned", "/welcome.html", helper.getPathWithinServletMapping(request)); <add> } <add> <ide> @Test <ide> public void getRequestUri() { <ide> request.setRequestURI("/welcome.html"); <ide> public void getRequestKeepSemicolonContent() throws UnsupportedEncodingException <ide> assertEquals("jsessionid should always be removed", "/foo;a=b;c=d", helper.getRequestUri(request)); <ide> } <ide> <add> @Test <add> public void getLookupPathWithSemicolonContent() { <add> helper.setRemoveSemicolonContent(false); <add> <add> request.setContextPath("/petclinic"); <add> request.setServletPath("/main"); <add> request.setRequestURI("/petclinic;a=b/main;b=c/welcome.html;c=d"); <add> <add> assertEquals("/welcome.html;c=d", helper.getLookupPathForRequest(request)); <add> } <add> <add> @Test <add> public void getLookupPathWithSemicolonContentAndNullPathInfo() { <add> helper.setRemoveSemicolonContent(false); <add> <add> request.setContextPath("/petclinic"); <add> request.setServletPath("/welcome.html"); <add> request.setRequestURI("/petclinic;a=b/welcome.html;c=d"); <add> <add> assertEquals("/welcome.html;c=d", helper.getLookupPathForRequest(request)); <add> } <add> <add> <ide> // <ide> // suite of tests root requests for default servlets (SRV 11.2) on Websphere vs Tomcat and other containers <ide> // see: http://jira.springframework.org/browse/SPR-7064 <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/MatrixVariableMethodArgumentResolver.java <ide> else if (paramValues.size() == 1) { <ide> protected void handleMissingValue(String name, MethodParameter param) throws ServletRequestBindingException { <ide> String paramType = param.getParameterType().getName(); <ide> throw new ServletRequestBindingException( <del> "Missing URI path parameter '" + name + "' for method parameter type [" + paramType + "]"); <add> "Missing matrix variable '" + name + "' for method parameter type [" + paramType + "]"); <ide> } <ide> <ide>
3
Ruby
Ruby
recognize version_scheme in merge
2f2304ea408640439be010c4b6c433083fd771be
<ide><path>Library/Homebrew/dev-cmd/bottle.rb <ide> def merge <ide> (\n^\ {3}[\S\ ]+$)* # options can be in multiple lines <ide> )?| <ide> (homepage|desc|sha1|sha256|version|mirror)\ ['"][\S\ ]+['"]| # specs with a string <del> revision\ \d+ # revision with a number <add> (revision|version_scheme)\ \d+ # revision with a number <ide> )\n+ # multiple empty lines <ide> )+ <ide> /mx
1
PHP
PHP
add tests for contentdisposition flag
6ce4a3a1ec5994e2b60180875812f6953d0490bf
<ide><path>lib/Cake/Network/Email/CakeEmail.php <ide> protected function _attachFiles($boundary = null) { <ide> $msg[] = '--' . $boundary; <ide> $msg[] = 'Content-Type: ' . $fileInfo['mimetype']; <ide> $msg[] = 'Content-Transfer-Encoding: base64'; <del> if (!isset($fileInfo['contentDisposition']) || $fileInfo['contentDisposition']) { <add> if ( <add> !isset($fileInfo['contentDisposition']) || <add> $fileInfo['contentDisposition'] <add> ) { <ide> $msg[] = 'Content-Disposition: attachment; filename="' . $filename . '"'; <ide> } <ide> $msg[] = ''; <ide><path>lib/Cake/Test/Case/Network/Email/CakeEmailTest.php <ide> public function testViewVars() { <ide> */ <ide> public function testAttachments() { <ide> $this->CakeEmail->attachments(CAKE . 'basics.php'); <del> $expected = array('basics.php' => array('file' => CAKE . 'basics.php', 'mimetype' => 'application/octet-stream')); <add> $expected = array( <add> 'basics.php' => array( <add> 'file' => CAKE . 'basics.php', <add> 'mimetype' => 'application/octet-stream' <add> ) <add> ); <ide> $this->assertSame($this->CakeEmail->attachments(), $expected); <ide> <ide> $this->CakeEmail->attachments(array()); <ide> $this->assertSame($this->CakeEmail->attachments(), array()); <ide> <del> $this->CakeEmail->attachments(array(array('file' => CAKE . 'basics.php', 'mimetype' => 'text/plain'))); <add> $this->CakeEmail->attachments(array( <add> array('file' => CAKE . 'basics.php', 'mimetype' => 'text/plain') <add> )); <ide> $this->CakeEmail->addAttachments(CAKE . 'bootstrap.php'); <ide> $this->CakeEmail->addAttachments(array(CAKE . 'bootstrap.php')); <ide> $this->CakeEmail->addAttachments(array('other.txt' => CAKE . 'bootstrap.php', 'license' => CAKE . 'LICENSE.txt')); <ide> public function testSendWithInlineAttachments() { <ide> $this->assertContains('--' . $boundary . '--', $result['message']); <ide> } <ide> <add>/** <add> * Test disabling content-disposition. <add> * <add> * @return void <add> */ <add> public function testSendWithNoContentDispositionAttachments() { <add> $this->CakeEmail->transport('debug'); <add> $this->CakeEmail->from('[email protected]'); <add> $this->CakeEmail->to('[email protected]'); <add> $this->CakeEmail->subject('My title'); <add> $this->CakeEmail->emailFormat('text'); <add> $this->CakeEmail->attachments(array( <add> 'cake.png' => array( <add> 'file' => CAKE . 'VERSION.txt', <add> 'contentDisposition' => false <add> ) <add> )); <add> $result = $this->CakeEmail->send('Hello'); <add> <add> $boundary = $this->CakeEmail->getBoundary(); <add> $this->assertContains('Content-Type: multipart/mixed; boundary="' . $boundary . '"', $result['headers']); <add> $expected = "--$boundary\r\n" . <add> "Content-Type: text/plain; charset=UTF-8\r\n" . <add> "Content-Transfer-Encoding: 8bit\r\n" . <add> "\r\n" . <add> "Hello" . <add> "\r\n" . <add> "\r\n" . <add> "\r\n" . <add> "--{$boundary}\r\n" . <add> "Content-Type: application/octet-stream\r\n" . <add> "Content-Transfer-Encoding: base64\r\n" . <add> "\r\n"; <add> <add> $this->assertContains($expected, $result['message']); <add> $this->assertContains('--' . $boundary . '--', $result['message']); <add> } <ide> /** <ide> * testSendWithLog method <ide> *
2
Text
Text
fix changelog typo [ci skip]
135f9aad0993f2d095b350d8662a5ea9c75d79dd
<ide><path>CHANGELOG.md <ide> ### 2.12.0 (March 14, 2017) <ide> <ide> - [#15000](https://github.com/emberjs/ember.js/pull/15000) / [#15002](https://github.com/emberjs/ember.js/pull/15002) / [#15006](https://github.com/emberjs/ember.js/pull/15006) / [#15008](https://github.com/emberjs/ember.js/pull/15008) / [#15009](https://github.com/emberjs/ember.js/pull/15009) / [#15011](https://github.com/emberjs/ember.js/pull/15011) [PERF] Assorted performance improvements for modern browsers. <del>- [#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 handlertemplate compilation). <add>- [#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). <ide> - [#14360](https://github.com/emberjs/ember.js/pull/14360) [FEATURE factory-for] Implement `factoryFor`. <ide> - [#14751](https://github.com/emberjs/ember.js/pull/14751) [DEPRECATION] Deprecate `Ember.K`. <ide> - [#14756](https://github.com/emberjs/ember.js/pull/14756) [PERF] Disable costly `eventManager` support when unused.
1
PHP
PHP
fix duplicate keys in paginatorcomponent tests
608a903a06b9f9d00bc9a5324213a86e48a58c8c
<ide><path>tests/TestCase/Controller/Component/PaginatorComponentTest.php <ide> public function checkLimitProvider() <ide> ['limit' => 0, 'maxLimit' => 100], <ide> 1, <ide> ], <del> 'limit = 0' => [ <add> 'limit = 0 v2' => [ <ide> ['limit' => 0, 'maxLimit' => 0], <ide> 1, <ide> ], <ide> public function checkLimitProvider() <ide> ['limit' => null, 'maxLimit' => null], <ide> 1, <ide> ], <del> 'bad input, results in 1' => [ <add> 'bad input, results in 1 v2' => [ <ide> ['limit' => false, 'maxLimit' => false], <ide> 1, <ide> ],
1
PHP
PHP
add breadcrumbshelper to doc block
589e142ac2a2ace6f1e77566db439a119805def1
<ide><path>src/View/View.php <ide> * `plugins/SuperHot/Template/Posts/index.ctp`. If a theme template <ide> * is not found for the current action the default app template file is used. <ide> * <add> * @property \Cake\View\Helper\BreadCrumbsHelper $BreadCrumbs <ide> * @property \Cake\View\Helper\FlashHelper $Flash <ide> * @property \Cake\View\Helper\FormHelper $Form <ide> * @property \Cake\View\Helper\HtmlHelper $Html
1
Text
Text
use example from website
271fa8fb75cf83f61b2bb4ba2ca0236602a15ef7
<ide><path>README.md <ide> webpack can do many optimizations to **reduce the output size**. It also cares a <ide> # A small example what's possible <ide> <ide> ``` javascript <add>// webpack is a module bundler <add>// This means webpack takes modules with dependencies <add>// and emit static assets representing that modules. <add> <add>// dependencies can be written in CommonJs <ide> var commonjs = require("./commonjs"); <del>define(["amd-module", "./file"], function(amdModule, file) { <add>// or in AMD <add>define(["amd-module", "../file"], function(amdModule, file) { <add> // while previous constructs are sync <add> // this is async <ide> require(["big-module/big/file"], function(big) { <del> // AMD require acts as split point <del> // and "big-module/big/file" is only downloaded when requested <add> // for async dependencies webpack splits <add> // your application into multiple "chunks". <add> // This part of your application is <add> // loaded on demand (Code Splitting) <ide> var stuff = require("../my/stuff"); <del> // dependencies automatically goes in chunk too <add> // "../my/stuff" is also loaded on demand <add> // because it's in the callback function <add> // of the AMD require <ide> }); <ide> }); <del> <add> <add> <ide> require("coffee!./cup.coffee"); <del>// The loader syntax allows to proprocess files <del>// for common stuff you can bind RegExps to loaders <del>// if you also add ".coffee" to the default extensions <del>// you can write: <add>// "Loaders" can be used to preprocess files. <add>// They can be prefixed in the require call <add>// or configured in the configuration. <ide> require("./cup"); <del> <add>// This does the same when you add ".coffee" to the extensions <add>// and configure the "coffee" loader for /\.coffee$/ <add> <add> <ide> function loadTemplate(name) { <del> return require("./templates/" + name ".jade"); <del> // dynamic requires are supported <del> // while compiling we figure out what can be requested <del> // here everything in "./templates" that matches /^.*\.jade$/ <del> // (can also be in subdirectories) <add> return require("./templates/" + name + ".jade"); <add> // many expression are supported in require calls <add> // a clever parser extract information and concludes <add> // that everything in "./templates" that matches <add> // /\.jade$/ should be included in the bundle, as it <add> // can be required. <ide> } <del> <del>require("imports?_=underscore!../loaders/my-ejs-loader!./template.html"); <del>// you can chain loaders <del>// you can configure loaders with query parameters <del>// and loaders resolve similar to modules <del> <del>// ...you can combine everything <add> <add> <add>// ... and you can combine everything <ide> function loadTemplateAsync(name, callback) { <del> require(["bundle?lazy!./templates/" + name + ".jade"], function(templateBundle) { <add> require(["bundle?lazy!./templates/" + name + ".jade"], <add> function(templateBundle) { <ide> templateBundle(callback); <ide> }); <ide> }
1
Python
Python
update other calls to backend.rnn
aada299b09e909d435743e5aa9a9d4197ad3620a
<ide><path>keras/layers/rnn/base_rnn.py <ide> def step(inputs, states): <ide> unroll=self.unroll, <ide> input_length=row_lengths if row_lengths is not None else timesteps, <ide> time_major=self.time_major, <del> zero_output_for_mask=self.zero_output_for_mask) <add> zero_output_for_mask=self.zero_output_for_mask, <add> return_all_outputs=self.return_sequences) <ide> <ide> if self.stateful: <ide> updates = [ <ide><path>keras/layers/rnn/gru.py <ide> def step(cell_inputs, cell_states): <ide> unroll=self.unroll, <ide> input_length=row_lengths if row_lengths is not None else timesteps, <ide> time_major=self.time_major, <del> zero_output_for_mask=self.zero_output_for_mask) <add> zero_output_for_mask=self.zero_output_for_mask, <add> return_all_outputs=self.return_sequences) <ide> # This is a dummy tensor for testing purpose. <ide> runtime = gru_lstm_utils.runtime(gru_lstm_utils.RUNTIME_UNKNOWN) <ide> else: <ide> def _defun_gru_call(self, inputs, initial_state, training, mask, <ide> normal_gru_kwargs = gpu_gru_kwargs.copy() <ide> normal_gru_kwargs.update({ <ide> 'zero_output_for_mask': self.zero_output_for_mask, <add> 'return_sequences': self.return_sequences, <ide> }) <ide> <ide> if tf.executing_eagerly(): <ide> def _defun_gru_call(self, inputs, initial_state, training, mask, <ide> <ide> def standard_gru(inputs, init_h, kernel, recurrent_kernel, bias, mask, <ide> time_major, go_backwards, sequence_lengths, <del> zero_output_for_mask): <add> zero_output_for_mask, return_sequences): <ide> """GRU with standard kernel implementation. <ide> <ide> This implementation can be run on all types of hardware. <ide> def standard_gru(inputs, init_h, kernel, recurrent_kernel, bias, mask, <ide> input, such as ragged tensors. If the input has a fixed timestep size, <ide> this should be None. <ide> zero_output_for_mask: Boolean, whether to output zero for masked timestep. <add> return_sequences: Boolean. If True, all outputs of the process will be <add> returned, whereas in the False case, only last_output will be kept <add> during the process, saving the corresponding memory, and <add> outputs=[last_output] is returned. <ide> <ide> Returns: <ide> last_output: output tensor for the last timestep, which has shape <ide> [batch, units]. <del> outputs: output tensor for all timesteps, which has shape <del> [batch, time, units]. <add> outputs: <add> - If `return_sequences`: output tensor for all timesteps, <add> which has shape [batch, time, units]. <add> - Else, a tensor equal to last_output <ide> state_0: the cell output, which has same shape as init_h. <ide> runtime: constant string tensor which indicate real runtime hardware. This <ide> value is for testing purpose and should be used by user. <ide> def step(cell_inputs, cell_states): <ide> go_backwards=go_backwards, <ide> input_length=sequence_lengths <ide> if sequence_lengths is not None else timesteps, <del> zero_output_for_mask=zero_output_for_mask) <add> zero_output_for_mask=zero_output_for_mask, <add> return_all_outputs=return_sequences) <ide> return last_output, outputs, new_states[0], gru_lstm_utils.runtime( <ide> gru_lstm_utils.RUNTIME_CPU) <ide> <ide> def gpu_gru(inputs, init_h, kernel, recurrent_kernel, bias, mask, time_major, <ide> <ide> def gru_with_backend_selection(inputs, init_h, kernel, recurrent_kernel, bias, <ide> mask, time_major, go_backwards, sequence_lengths, <del> zero_output_for_mask): <add> zero_output_for_mask, return_sequences): <ide> """Call the GRU with optimized backend kernel selection. <ide> <ide> Under the hood, this function will create two TF function, one with the most <ide> def gru_with_backend_selection(inputs, init_h, kernel, recurrent_kernel, bias, <ide> input, such as ragged tensors. If the input has a fixed timestep size, <ide> this should be None. <ide> zero_output_for_mask: Boolean, whether to output zero for masked timestep. <add> return_sequences: Boolean. If True, all outputs of the process will be <add> returned, whereas in the False case, only last_output will be kept <add> during the process, saving the corresponding memory, and <add> outputs=[last_output] is returned. <ide> <ide> Returns: <ide> List of output tensors, same as standard_gru. <ide> def gru_with_backend_selection(inputs, init_h, kernel, recurrent_kernel, bias, <ide> 'go_backwards': go_backwards, <ide> 'sequence_lengths': sequence_lengths, <ide> 'zero_output_for_mask': zero_output_for_mask, <add> 'return_sequences': return_sequences, <ide> } <ide> <ide> def gpu_gru_with_fallback(inputs, init_h, kernel, recurrent_kernel, bias, <ide> mask, time_major, go_backwards, sequence_lengths, <del> zero_output_for_mask): <add> zero_output_for_mask, return_sequences): <ide> """Use cuDNN kernel when mask is none or strictly right padded.""" <ide> if mask is None: <ide> return gpu_gru( <ide> def standard_gru_fn(): <ide> time_major=time_major, <ide> go_backwards=go_backwards, <ide> sequence_lengths=sequence_lengths, <del> zero_output_for_mask=zero_output_for_mask) <add> zero_output_for_mask=zero_output_for_mask, <add> return_sequences=return_sequences) <ide> <ide> return tf.cond( <ide> gru_lstm_utils.is_cudnn_supported_inputs(mask, time_major), <ide><path>keras/layers/rnn/lstm.py <ide> def step(inputs, states): <ide> unroll=self.unroll, <ide> input_length=row_lengths if row_lengths is not None else timesteps, <ide> time_major=self.time_major, <del> zero_output_for_mask=self.zero_output_for_mask) <add> zero_output_for_mask=self.zero_output_for_mask, <add> return_all_outputs=self.return_sequences) <ide> runtime = gru_lstm_utils.runtime(gru_lstm_utils.RUNTIME_UNKNOWN) <ide> else: <ide> # Use the new defun approach for backend implementation swap. <ide> def step(inputs, states): <ide> normal_lstm_kwargs = gpu_lstm_kwargs.copy() <ide> normal_lstm_kwargs.update({ <ide> 'zero_output_for_mask': self.zero_output_for_mask, <add> 'return_sequences': self.return_sequences, <ide> }) <ide> <ide> if tf.executing_eagerly(): <ide> def step(inputs, states): <ide> <ide> def standard_lstm(inputs, init_h, init_c, kernel, recurrent_kernel, bias, <ide> mask, time_major, go_backwards, sequence_lengths, <del> zero_output_for_mask): <add> zero_output_for_mask, return_sequences): <ide> """LSTM with standard kernel implementation. <ide> <ide> This implementation can be run on all types for hardware. <ide> def standard_lstm(inputs, init_h, init_c, kernel, recurrent_kernel, bias, <ide> input, such as ragged tensors. If the input has a fixed timestep size, <ide> this should be None. <ide> zero_output_for_mask: Boolean, whether to output zero for masked timestep. <add> return_sequences: Boolean. If True, all outputs of the process will be <add> returned, whereas in the False case, only last_output will be kept <add> during the process, saving the corresponding memory, and <add> outputs=[last_output] is returned. <ide> <ide> Returns: <ide> last_output: output tensor for the last timestep, which has shape <ide> [batch, units]. <del> outputs: output tensor for all timesteps, which has shape <del> [batch, time, units]. <add> outputs: <add> - If `return_sequences`: output tensor for all timesteps, <add> which has shape [batch, time, units]. <add> - Else, a tensor equal to last_output <ide> state_0: the cell output, which has same shape as init_h. <ide> state_1: the cell hidden state, which has same shape as init_c. <ide> runtime: constant string tensor which indicate real runtime hardware. This <ide> def step(cell_inputs, cell_states): <ide> go_backwards=go_backwards, <ide> input_length=(sequence_lengths <ide> if sequence_lengths is not None else timesteps), <del> zero_output_for_mask=zero_output_for_mask) <add> zero_output_for_mask=zero_output_for_mask, <add> return_all_outputs=return_sequences) <ide> return (last_output, outputs, new_states[0], new_states[1], <ide> gru_lstm_utils.runtime(gru_lstm_utils.RUNTIME_CPU)) <ide> <ide> def gpu_lstm(inputs, init_h, init_c, kernel, recurrent_kernel, bias, mask, <ide> def lstm_with_backend_selection(inputs, init_h, init_c, kernel, <ide> recurrent_kernel, bias, mask, time_major, <ide> go_backwards, sequence_lengths, <del> zero_output_for_mask): <add> zero_output_for_mask, return_sequences): <ide> """Call the LSTM with optimized backend kernel selection. <ide> <ide> Under the hood, this function will create two TF function, one with the most <ide> def lstm_with_backend_selection(inputs, init_h, init_c, kernel, <ide> input, such as ragged tensors. If the input has a fixed timestep size, <ide> this should be None. <ide> zero_output_for_mask: Boolean, whether to output zero for masked timestep. <add> return_sequences: Boolean. If True, all outputs of the process will be <add> returned, whereas in the False case, only last_output will be kept <add> during the process, saving the corresponding memory, and <add> outputs=[last_output] is returned. <ide> <ide> Returns: <ide> List of output tensors, same as standard_lstm. <ide> def lstm_with_backend_selection(inputs, init_h, init_c, kernel, <ide> 'go_backwards': go_backwards, <ide> 'sequence_lengths': sequence_lengths, <ide> 'zero_output_for_mask': zero_output_for_mask, <add> 'return_sequences': return_sequences, <ide> } <ide> <ide> def gpu_lstm_with_fallback(inputs, init_h, init_c, kernel, recurrent_kernel, <ide> bias, mask, time_major, go_backwards, <del> sequence_lengths, zero_output_for_mask): <add> sequence_lengths, zero_output_for_mask, <add> return_sequences): <ide> """Use cuDNN kernel when mask is none or strictly right padded.""" <ide> if mask is None: <ide> return gpu_lstm( <ide> def stardard_lstm_fn(): <ide> time_major=time_major, <ide> go_backwards=go_backwards, <ide> sequence_lengths=sequence_lengths, <del> zero_output_for_mask=zero_output_for_mask) <add> zero_output_for_mask=zero_output_for_mask, <add> return_sequences=return_sequences) <ide> <ide> return tf.cond( <ide> gru_lstm_utils.is_cudnn_supported_inputs(mask, time_major),
3
Ruby
Ruby
support separate downloads for intel and arm
5f92d002443a4fce6aa3d6cae6863e43282d6bd9
<ide><path>Library/Homebrew/dev-cmd/bump-cask-pr.rb <ide> def bump_cask_pr <ide> tmp_config = cask.config <ide> tmp_url = tmp_cask.url.to_s <ide> <del> if new_hash.nil? && old_hash != :no_check <del> resource_path = fetch_resource(cask, new_version, tmp_url) <del> Utils::Tar.validate_file(resource_path) <del> new_hash = resource_path.sha256 <add> if old_hash != :no_check <add> if new_hash.nil? <add> resource_path = fetch_resource(cask, new_version, tmp_url) <add> Utils::Tar.validate_file(resource_path) <add> new_hash = resource_path.sha256 <add> end <add> <add> if tmp_contents.include?("Hardware::CPU.intel?") <add> other_contents = tmp_contents.gsub("Hardware::CPU.intel?", (!Hardware::CPU.intel?).to_s) <add> other_cask = Cask::CaskLoader.load(other_contents) <add> other_url = other_cask.url.to_s <add> other_old_hash = other_cask.sha256.to_s <add> <add> resource_path = fetch_resource(cask, new_version, other_url) <add> Utils::Tar.validate_file(resource_path) <add> other_new_hash = resource_path.sha256 <add> <add> replacement_pairs << [ <add> other_old_hash, <add> other_new_hash, <add> ] <add> end <ide> end <ide> <ide> cask.languages.each do |language|
1
PHP
PHP
simulate exit code for closure scheduled tasks
46686ae80466bcdf6d9fe1931aeb1408f1f1f72a
<ide><path>src/Illuminate/Console/Scheduling/CallbackEvent.php <ide> use Illuminate\Contracts\Container\Container; <ide> use InvalidArgumentException; <ide> use LogicException; <add>use Exception; <ide> <ide> class CallbackEvent extends Event <ide> { <ide> public function run(Container $container) <ide> $response = is_object($this->callback) <ide> ? $container->call([$this->callback, '__invoke'], $this->parameters) <ide> : $container->call($this->callback, $this->parameters); <add> } catch(Exception $e) { <add> $this->exitCode = 1; <add> <add> throw $e; <ide> } finally { <ide> $this->removeMutex(); <ide> <ide> parent::callAfterCallbacks($container); <ide> } <ide> <add> $this->exitCode = $response === false ? 1 : 0; <add> <ide> return $response; <ide> } <ide> <ide><path>tests/Console/Scheduling/CallbackEventTest.php <add><?php <add> <add>namespace Illuminate\Tests\Console\Scheduling; <add> <add>use Illuminate\Console\Scheduling\CallbackEvent; <add>use Illuminate\Console\Scheduling\EventMutex; <add>use Mockery as m; <add>use Orchestra\Testbench\TestCase; <add>use Exception; <add> <add>class CallbackEventTest extends TestCase <add>{ <add> protected function tearDown(): void <add> { <add> m::close(); <add> } <add> <add> public function testDefaultResultIsSuccess() <add> { <add> $event = new CallbackEvent(m::mock(EventMutex::class), function() {}); <add> <add> $event->run($this->app); <add> <add> $this->assertSame(0, $event->exitCode); <add> } <add> <add> public function testFalseResponseIsFailure() <add> { <add> $event = new CallbackEvent(m::mock(EventMutex::class), function() { <add> return false; <add> }); <add> <add> $event->run($this->app); <add> <add> $this->assertSame(1, $event->exitCode); <add> } <add> <add> public function testExceptionIsFailure() <add> { <add> $event = new CallbackEvent(m::mock(EventMutex::class), function() { <add> throw new \Exception; <add> }); <add> <add> try { <add> $event->run($this->app); <add> } catch(Exception $e) {} <add> <add> $this->assertSame(1, $event->exitCode); <add> } <add> <add> public function testExceptionBubbles() <add> { <add> $event = new CallbackEvent(m::mock(EventMutex::class), function() { <add> throw new Exception; <add> }); <add> <add> $this->expectException(Exception::class); <add> <add> $event->run($this->app); <add> } <add>}
2
PHP
PHP
remove unnecessary code
fae67da8ad12017ac592c774fb88419d489ba816
<ide><path>src/Illuminate/Database/Eloquent/Relations/BelongsTo.php <ide> protected function getEagerModelKeys(array $models) <ide> } <ide> } <ide> <del> // If there are no keys that were not null we will just return an array with null <del> // so this query wont fail plus returns zero results, which should be what the <del> // developer expects to happen in this situation. Otherwise we'll sort them. <del> if (count($keys) === 0) { <del> return [null]; <del> } <del> <ide> sort($keys); <ide> <ide> return array_values(array_unique($keys)); <ide><path>tests/Database/DatabaseEloquentBelongsToTest.php <ide> public function testDefaultEagerConstraintsWhenIncrementing() <ide> $relation = $this->getRelation(); <ide> $relation->getRelated()->shouldReceive('getKeyName')->andReturn('id'); <ide> $relation->getRelated()->shouldReceive('getKeyType')->andReturn('int'); <del> $relation->getQuery()->shouldReceive('whereIntegerInRaw')->once()->with('relation.id', m::mustBe([null])); <add> $relation->getQuery()->shouldReceive('whereIntegerInRaw')->once()->with('relation.id', m::mustBe([])); <ide> $models = [new MissingEloquentBelongsToModelStub, new MissingEloquentBelongsToModelStub]; <ide> $relation->addEagerConstraints($models); <ide> } <ide> <ide> public function testDefaultEagerConstraintsWhenIncrementingAndNonIntKeyType() <ide> { <ide> $relation = $this->getRelation(null, false, 'string'); <del> $relation->getQuery()->shouldReceive('whereIn')->once()->with('relation.id', m::mustBe([null])); <add> $relation->getQuery()->shouldReceive('whereIn')->once()->with('relation.id', m::mustBe([])); <ide> $models = [new MissingEloquentBelongsToModelStub, new MissingEloquentBelongsToModelStub]; <ide> $relation->addEagerConstraints($models); <ide> } <ide> public function testDefaultEagerConstraintsWhenNotIncrementing() <ide> { <ide> $relation = $this->getRelation(null, false); <ide> $relation->getRelated()->shouldReceive('getKeyName')->andReturn('id'); <del> $relation->getQuery()->shouldReceive('whereIn')->once()->with('relation.id', m::mustBe([null])); <add> $relation->getQuery()->shouldReceive('whereIn')->once()->with('relation.id', m::mustBe([])); <ide> $models = [new MissingEloquentBelongsToModelStub, new MissingEloquentBelongsToModelStub]; <ide> $relation->addEagerConstraints($models); <ide> }
2
Ruby
Ruby
simplify regex detecting comments in sql query
f63a347d134f5091d7c230d34dab85c7c5fc7021
<ide><path>activerecord/lib/active_record/connection_adapters/abstract_adapter.rb <ide> class AbstractAdapter <ide> include Savepoints <ide> <ide> SIMPLE_INT = /\A\d+\z/ <del> COMMENT_REGEX = %r{(?:--.*\n)*|/\*(?:[^*]|\*[^/])*\*/}m <add> COMMENT_REGEX = %r{(?:--.*\n)|/\*(?:[^*]|\*[^/])*\*/}m <ide> <ide> attr_accessor :pool <ide> attr_reader :visitor, :owner, :logger, :lock
1
Python
Python
set version to v2.1.0a9.dev0
829c9091a4e254f831684a83c6a163fb6c18cd97
<ide><path>spacy/about.py <ide> # fmt: off <ide> <ide> __title__ = "spacy-nightly" <del>__version__ = "2.1.0a8" <add>__version__ = "2.1.0a9.dev0" <ide> __summary__ = "Industrial-strength Natural Language Processing (NLP) with Python and Cython" <ide> __uri__ = "https://spacy.io" <ide> __author__ = "Explosion AI"
1
Mixed
Javascript
fix typos in comments and docs
823295fee058f169523e84f94be13962a9513d3d
<ide><path>CHANGELOG.md <ide> to make the fixes available to people that still need IE8 support._ <ide> - secure `link[href]` as a `RESOURCE_URL`s in `$sce` <ide> ([f35f334b](https://github.com/angular/angular.js/commit/f35f334bd3197585bdf034f4b6d9ffa3122dac62), <ide> [#14687](https://github.com/angular/angular.js/issues/14687)) <del> - properly sanitize `xlink:href` attribute interoplation <add> - properly sanitize `xlink:href` attribute interpolation <ide> ([f2fa1ed8](https://github.com/angular/angular.js/commit/f2fa1ed83d18d4e79a36f8c0db1c2524d762e513), <ide> [2687c261](https://github.com/angular/angular.js/commit/2687c26140585d9e3716f9f559390f5d8d598fdf)) <ide> - **ngSanitize:** blacklist the attribute `usemap` as it can be used as a security exploit <ide> for more info. <ide> - prevent assignment on constructor properties <ide> ([f47e2180](https://github.com/angular/angular.js/commit/f47e218006029f39b4785d820b430de3a0eebcb0), <ide> [#13417](https://github.com/angular/angular.js/issues/13417)) <del> - preserve expensive checks when runnning `$eval` inside an expression <add> - preserve expensive checks when running `$eval` inside an expression <ide> ([96d62cc0](https://github.com/angular/angular.js/commit/96d62cc0fc77248d7e3ec4aa458bac0d3e072629)) <ide> - copy `inputs` for expressions with expensive checks <ide> ([0b7fff30](https://github.com/angular/angular.js/commit/0b7fff303f46202bbae1ff3ca9d0e5fa76e0fc9a)) <ide> changes section for more information <ide> - handle boolean attributes in `@` bindings <ide> ([db5e0ffe](https://github.com/angular/angular.js/commit/db5e0ffe124ac588f01ef0fe79efebfa72f5eec7), <ide> [#13767](https://github.com/angular/angular.js/issues/13767), [#13769](https://github.com/angular/angular.js/issues/13769)) <del>- **$parse:** Preserve expensive checks when runnning $eval inside an expression <add>- **$parse:** Preserve expensive checks when running $eval inside an expression <ide> ([acfda102](https://github.com/angular/angular.js/commit/acfda1022d23ecaea34bbc8931588a0715b3ab03)) <ide> - **dateFilter:** follow the CLDR on pattern escape sequences <ide> ([1ab4e444](https://github.com/angular/angular.js/commit/1ab4e44443716c33cd857dcb1098d20580dbb0cc), <ide><path>i18n/closure/numberSymbolsExt.js <ide> * using the --for_closure flag. <ide> * File generated from CLDR ver. 29 <ide> * <del> * This file coveres those locales that are not covered in <add> * This file covers those locales that are not covered in <ide> * "numberformatsymbols.js". <ide> * <ide> * Before checkin, this file could have been manually edited. This is <ide> if (goog.LOCALE == 'zh_Hant_MO' || goog.LOCALE == 'zh-Hant-MO') { <ide> if (goog.LOCALE == 'zh_Hant_TW' || goog.LOCALE == 'zh-Hant-TW') { <ide> goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_zh_Hant; <ide> } <del> <ide><path>src/ng/animate.js <ide> var $AnimateProvider = ['$provide', /** @this */ function($provide) { <ide> * <ide> * @description Performs an inline animation on the element which applies the provided to and from CSS styles to the element. <ide> * If any detected CSS transition, keyframe or JavaScript matches the provided className value, then the animation will take <del> * on the provided styles. For example, if a transition animation is set for the given classNamem, then the provided `from` and <add> * on the provided styles. For example, if a transition animation is set for the given className, then the provided `from` and <ide> * `to` styles will be applied alongside the given transition. If the CSS style provided in `from` does not have a corresponding <ide> * style in `to`, the style in `from` is applied immediately, and no animation is run. <ide> * If a JavaScript animation is detected then the provided styles will be given in as function parameters into the `animate` <ide><path>src/ng/compile.js <ide> * usual containers (e.g. like `<svg>`). <ide> * * See also the `directive.templateNamespace` property. <ide> * * `slotName`: (optional) the name of the slot to transclude. If falsy (e.g. `null`, `undefined` or `''`) <del> * then the default translusion is provided. <add> * then the default transclusion is provided. <ide> * The `$transclude` function also has a method on it, `$transclude.isSlotFilled(slotName)`, which returns <ide> * `true` if the specified slot contains content (i.e. one or more DOM nodes). <ide> * <ide><path>src/ng/directive/ngSwitch.js <ide> * <ide> * * `ngSwitchWhen`: the case statement to match against. If match then this <ide> * case will be displayed. If the same match appears multiple times, all the <del> * elements will be displayed. It is possible to associate mutiple values to <add> * elements will be displayed. It is possible to associate multiple values to <ide> * the same `ngSwitchWhen` by defining the optional attribute <ide> * `ngSwitchWhenSeparator`. The separator will be used to split the value of <ide> * the `ngSwitchWhen` attribute into multiple tokens, and the element will show <ide><path>src/ng/filter/orderBy.js <ide> * String, etc). <ide> * <ide> * The `expression` can be a single predicate, or a list of predicates each serving as a tie-breaker <del> * for the preceeding one. The `expression` is evaluated against each item and the output is used <add> * for the preceding one. The `expression` is evaluated against each item and the output is used <ide> * for comparing with other items. <ide> * <ide> * You can change the sorting order by setting `reverse` to `true`. By default, items are sorted in <ide><path>src/ng/http.js <ide> function $HttpProvider() { <ide> * <ide> * @description <ide> * Shortcut method to perform `JSONP` request. <del> * If you would like to customise where and how the callbacks are stored then try overriding <add> * If you would like to customize where and how the callbacks are stored then try overriding <ide> * or decorating the {@link $jsonpCallbacks} service. <ide> * <ide> * @param {string} url Relative or absolute URL specifying the destination of the request. <ide><path>src/ng/parse.js <ide> var objectValueOf = {}.constructor.prototype.valueOf; <ide> <ide> // Sandboxing Angular Expressions <ide> // ------------------------------ <del>// Angular expressions are no longer sandboxed. So it is now even easier to access arbitary JS code by <add>// Angular expressions are no longer sandboxed. So it is now even easier to access arbitrary JS code by <ide> // various means such as obtaining a reference to native JS functions like the Function constructor. <ide> // <ide> // As an example, consider the following Angular expression: <ide> // <ide> // {}.toString.constructor('alert("evil JS code")') <ide> // <del>// It is important to realise that if you create an expression from a string that contains user provided <add>// It is important to realize that if you create an expression from a string that contains user provided <ide> // content then it is possible that your application contains a security vulnerability to an XSS style attack. <ide> // <ide> // See https://docs.angularjs.org/guide/security <ide> function $ParseProvider() { <ide> * representation. It is expected for the function to return `true` or `false`, whether that <ide> * character is allowed or not. <ide> * <del> * Since this function will be called extensivelly, keep the implementation of these functions fast, <add> * Since this function will be called extensively, keep the implementation of these functions fast, <ide> * as the performance of these functions have a direct impact on the expressions parsing speed. <ide> * <ide> * @param {function=} identifierStart The function that will decide whether the given character is <ide><path>src/ngMessages/messages.js <ide> var jqLite; <ide> * By default, `ngMessages` will only display one message for a particular key/value collection at any time. If more <ide> * than one message (or error) key is currently true, then which message is shown is determined by the order of messages <ide> * in the HTML template code (messages declared first are prioritised). This mechanism means the developer does not have <del> * to prioritise messages using custom JavaScript code. <add> * to prioritize messages using custom JavaScript code. <ide> * <ide> * Given the following error object for our example (which informs us that the field `myField` currently has both the <ide> * `required` and `email` errors): <ide><path>test/ng/compileSpec.js <ide> describe('$compile', function() { <ide> element = $compile('<c1 prop="a + b"></c1>')($rootScope); <ide> <ide> // We add this watch after the compilation to ensure that it will run after the binding watchers <del> // therefore triggering the thing that this test is hoping to enfore <add> // therefore triggering the thing that this test is hoping to enforce <ide> $rootScope.$watch('a', function(val) { $rootScope.b = val * 2; }); <ide> <ide> expect(log).toEqual([{prop: jasmine.objectContaining({currentValue: undefined})}]); <ide><path>test/ng/directive/inputSpec.js <ide> describe('input', function() { <ide> <ide> if (supportsRange) { <ide> // Browsers that implement range will never allow you to set a value that doesn't match the step value <del> // However, currently only Firefox fully inplements the spec when setting the value after the step value changes. <add> // However, currently only Firefox fully implements the spec when setting the value after the step value changes. <ide> // Other browsers fail in various edge cases, which is why they are not tested here. <ide> it('should round the input value to the nearest step on user input', function() { <ide> var inputElm = helper.compileInput('<input type="range" ng-model="value" name="alias" step="5" />'); <ide> describe('input', function() { <ide> ['scheme-://example.com', true], <ide> ['scheme_://example.com', false], <ide> <del> // Vaidating `:` and `/` after `scheme` <add> // Validating `:` and `/` after `scheme` <ide> ['scheme//example.com', false], <ide> ['scheme:example.com', true], <ide> ['scheme:/example.com', true], <ide><path>test/ng/filter/orderBySpec.js <ide> describe('Filter: orderBy', function() { <ide> return (isNerd1 && isNerd2) ? 0 : (isNerd1) ? -1 : 1; <ide> } <ide> <del> // No "nerd"; alpabetical order <add> // No "nerd"; alphabetical order <ide> return (v1 === v2) ? 0 : (v1 < v2) ? -1 : 1; <ide> }; <ide> <ide><path>test/ngMock/angular-mocksSpec.js <ide> describe('ngMock', function() { <ide> <ide> <ide> it('should fake getLocalDateString method', function() { <del> var millenium = new Date('2000').getTime(); <add> var millennium = new Date('2000').getTime(); <ide> <del> // millenium in -3h <del> var t0 = new angular.mock.TzDate(-3, millenium); <add> // millennium in -3h <add> var t0 = new angular.mock.TzDate(-3, millennium); <ide> expect(t0.toLocaleDateString()).toMatch('2000'); <ide> <del> // millenium in +0h <del> var t1 = new angular.mock.TzDate(0, millenium); <add> // millennium in +0h <add> var t1 = new angular.mock.TzDate(0, millennium); <ide> expect(t1.toLocaleDateString()).toMatch('2000'); <ide> <del> // millenium in +3h <del> var t2 = new angular.mock.TzDate(3, millenium); <add> // millennium in +3h <add> var t2 = new angular.mock.TzDate(3, millennium); <ide> expect(t2.toLocaleDateString()).toMatch('1999'); <ide> }); <ide>
13
Javascript
Javascript
remove this aliases
b594b3bc34e7a8f1b8c016744488e2230210da1e
<ide><path>lib/dgram.js <ide> function replaceHandle(self, newHandle) { <ide> } <ide> <ide> Socket.prototype.bind = function(port_ /*, address, callback*/) { <del> var self = this; <ide> let port = port_; <ide> <del> self._healthCheck(); <add> this._healthCheck(); <ide> <ide> if (this._bindState !== BIND_STATE_UNBOUND) <ide> throw new Error('Socket is already bound'); <ide> <ide> this._bindState = BIND_STATE_BINDING; <ide> <ide> if (typeof arguments[arguments.length - 1] === 'function') <del> self.once('listening', arguments[arguments.length - 1]); <add> this.once('listening', arguments[arguments.length - 1]); <ide> <ide> if (port instanceof UDP) { <del> replaceHandle(self, port); <del> startListening(self); <del> return self; <add> replaceHandle(this, port); <add> startListening(this); <add> return this; <ide> } <ide> <ide> var address; <ide> Socket.prototype.bind = function(port_ /*, address, callback*/) { <ide> } <ide> <ide> // defaulting address for bind to all interfaces <del> if (!address && self._handle.lookup === lookup4) { <add> if (!address && this._handle.lookup === lookup4) { <ide> address = '0.0.0.0'; <del> } else if (!address && self._handle.lookup === lookup6) { <add> } else if (!address && this._handle.lookup === lookup6) { <ide> address = '::'; <ide> } <ide> <ide> // resolve address first <del> self._handle.lookup(address, function(err, ip) { <add> this._handle.lookup(address, (err, ip) => { <ide> if (err) { <del> self._bindState = BIND_STATE_UNBOUND; <del> self.emit('error', err); <add> this._bindState = BIND_STATE_UNBOUND; <add> this.emit('error', err); <ide> return; <ide> } <ide> <ide> if (!cluster) <ide> cluster = require('cluster'); <ide> <ide> var flags = 0; <del> if (self._reuseAddr) <add> if (this._reuseAddr) <ide> flags |= UV_UDP_REUSEADDR; <ide> <ide> if (cluster.isWorker && !exclusive) { <del> function onHandle(err, handle) { <add> const onHandle = (err, handle) => { <ide> if (err) { <ide> var ex = exceptionWithHostPort(err, 'bind', ip, port); <del> self.emit('error', ex); <del> self._bindState = BIND_STATE_UNBOUND; <add> this.emit('error', ex); <add> this._bindState = BIND_STATE_UNBOUND; <ide> return; <ide> } <ide> <del> if (!self._handle) <add> if (!this._handle) <ide> // handle has been closed in the mean time. <ide> return handle.close(); <ide> <del> replaceHandle(self, handle); <del> startListening(self); <del> } <del> cluster._getServer(self, { <add> replaceHandle(this, handle); <add> startListening(this); <add> }; <add> cluster._getServer(this, { <ide> address: ip, <ide> port: port, <del> addressType: self.type, <add> addressType: this.type, <ide> fd: -1, <ide> flags: flags <ide> }, onHandle); <del> <ide> } else { <del> if (!self._handle) <add> if (!this._handle) <ide> return; // handle has been closed in the mean time <ide> <del> const err = self._handle.bind(ip, port || 0, flags); <add> const err = this._handle.bind(ip, port || 0, flags); <ide> if (err) { <ide> var ex = exceptionWithHostPort(err, 'bind', ip, port); <del> self.emit('error', ex); <del> self._bindState = BIND_STATE_UNBOUND; <add> this.emit('error', ex); <add> this._bindState = BIND_STATE_UNBOUND; <ide> // Todo: close? <ide> return; <ide> } <ide> <del> startListening(self); <add> startListening(this); <ide> } <ide> }); <ide> <del> return self; <add> return this; <ide> }; <ide> <ide> <ide> Socket.prototype.send = function(buffer, <ide> port, <ide> address, <ide> callback) { <del> const self = this; <ide> let list; <ide> <ide> if (address || (port && typeof port !== 'function')) { <ide> Socket.prototype.send = function(buffer, <ide> if (typeof callback !== 'function') <ide> callback = undefined; <ide> <del> self._healthCheck(); <add> this._healthCheck(); <ide> <del> if (self._bindState === BIND_STATE_UNBOUND) <del> self.bind({port: 0, exclusive: true}, null); <add> if (this._bindState === BIND_STATE_UNBOUND) <add> this.bind({port: 0, exclusive: true}, null); <ide> <ide> if (list.length === 0) <ide> list.push(Buffer.alloc(0)); <ide> <ide> // If the socket hasn't been bound yet, push the outbound packet onto the <ide> // send queue and send after binding is complete. <del> if (self._bindState !== BIND_STATE_BOUND) { <del> enqueue(self, self.send.bind(self, list, port, address, callback)); <add> if (this._bindState !== BIND_STATE_BOUND) { <add> enqueue(this, this.send.bind(this, list, port, address, callback)); <ide> return; <ide> } <ide> <del> self._handle.lookup(address, function afterDns(ex, ip) { <del> doSend(ex, self, ip, list, address, port, callback); <del> }); <add> const afterDns = (ex, ip) => { <add> doSend(ex, this, ip, list, address, port, callback); <add> }; <add> <add> this._handle.lookup(address, afterDns); <ide> }; <ide> <ide>
1
Javascript
Javascript
remove doreload arg used only for testing
36a547b852a7d254535e2d203cffe10f2e5c5617
<ide><path>src/Angular.js <ide> function bootstrap(element, modules, config) { <ide> * The page should reload and the debug information should now be available. <ide> * <ide> */ <del>function reloadWithDebugInfo(doReload) { <add>function reloadWithDebugInfo() { <ide> window.name = 'NG_ENABLE_DEBUG_INFO!' + window.name; <del> if ( doReload !== false ) window.location.reload(); <add> window.location.reload(); <ide> } <ide> <ide> var SNAKE_CASE_REGEXP = /[A-Z]/g; <ide><path>test/AngularSpec.js <ide> describe('angular', function() { <ide> }); <ide> <ide> <del> describe("reloadWithDebugInfo", function() { <del> <del> it("should reload the current page with debugInfo turned on", function() { <del> <del> element = jqLite('<div>{{1+2}}</div>'); <del> angular.bootstrap(element); <del> expect(element.hasClass('ng-scope')).toBe(false); <del> dealoc(element); <del> <del> // We pass the false to prevent the page actually reloading <del> angular.reloadWithDebugInfo(false); <del> <del> element = jqLite('<div>{{1+2}}</div>'); <del> angular.bootstrap(element); <del> expect(element.hasClass('ng-scope')).toBe(true); <del> dealoc(element); <del> }); <del> }); <del> <del> <ide> describe('startingElementHtml', function(){ <ide> it('should show starting element tag only', function(){ <ide> expect(startingTag('<ng-abc x="2A"><div>text</div></ng-abc>')).
2
Text
Text
clarify `redirects` on client-side navigation
46bdef81373d286408047241f8f8ef744b0a5a2f
<ide><path>docs/api-reference/next.config.js/redirects.md <ide> module.exports = { <ide> <ide> > **Why does Next.js use 307 and 308?** Traditionally a 302 was used for a temporary redirect, and a 301 for a permanent redirect, but many browsers changed the request method of the redirect to `GET`, regardless of the original method. For example, if the browser made a request to `POST /v1/users` which returned status code `302` with location `/v2/users`, the subsequent request might be `GET /v2/users` instead of the expected `POST /v2/users`. Next.js uses the 307 temporary redirect, and 308 permanent redirect status codes to explicitly preserve the request method used. <ide> <del>- `basePath`: `false` or `undefined` - if false the basePath won't be included when matching, can be used for external rewrites only. <add>- `basePath`: `false` or `undefined` - if false the `basePath` won't be included when matching, can be used for external redirects only. <ide> - `locale`: `false` or `undefined` - whether the locale should not be included when matching. <ide> - `has` is an array of [has objects](#header-cookie-and-query-matching) with the `type`, `key` and `value` properties. <ide> <ide> Redirects are checked before the filesystem which includes pages and `/public` files. <ide> <add>Redirects are not applied to client-side routing (`Link`, `router.push`), unless [Middleware](/docs/advanced-features/middleware) is present and matches the path. <add> <ide> When a redirect is applied, any query values provided in the request will be passed through to the redirect destination. For example, see the following redirect configuration: <ide> <ide> ```js
1
PHP
PHP
add currentlocale method
318c226907707e6d82941e8449ab9527b789cd90
<ide><path>src/Illuminate/Foundation/Application.php <ide> public function getLocale() <ide> return $this['config']->get('app.locale'); <ide> } <ide> <add> /** <add> * Get the current application locale. <add> * <add> * @return string <add> */ <add> public function currentLocale() <add> { <add> return $this->getLocale(); <add> } <add> <ide> /** <ide> * Get the current application fallback locale. <ide> * <ide><path>src/Illuminate/Support/Facades/App.php <ide> * @method static string getCachedRoutesPath() <ide> * @method static string getCachedServicesPath() <ide> * @method static string getLocale() <add> * @method static string currentLocale() <ide> * @method static string getNamespace() <ide> * @method static string resourcePath(string $path = '') <ide> * @method static string storagePath(string $path = '')
2
Go
Go
apply volumes-from before creating volumes
3bd73a96333e011738136f6a9eda23642cc204ab
<ide><path>container.go <ide> func (container *Container) Start(hostConfig *HostConfig) error { <ide> binds[path.Clean(dst)] = bindMap <ide> } <ide> <del> // FIXME: evaluate volumes-from before individual volumes, so that the latter can override the former. <del> // Create the requested volumes volumes <ide> if container.Volumes == nil || len(container.Volumes) == 0 { <ide> container.Volumes = make(map[string]string) <ide> container.VolumesRW = make(map[string]bool) <del> <del> for volPath := range container.Config.Volumes { <del> volPath = path.Clean(volPath) <del> // If an external bind is defined for this volume, use that as a source <del> if bindMap, exists := binds[volPath]; exists { <del> container.Volumes[volPath] = bindMap.SrcPath <del> if strings.ToLower(bindMap.Mode) == "rw" { <del> container.VolumesRW[volPath] = true <del> } <del> // Otherwise create an directory in $ROOT/volumes/ and use that <del> } else { <del> c, err := container.runtime.volumes.Create(nil, container, "", "", nil) <del> if err != nil { <del> return err <del> } <del> srcPath, err := c.layer() <del> if err != nil { <del> return err <del> } <del> container.Volumes[volPath] = srcPath <del> container.VolumesRW[volPath] = true // RW by default <del> } <del> // Create the mountpoint <del> if err := os.MkdirAll(path.Join(container.RootfsPath(), volPath), 0755); err != nil { <del> return nil <del> } <del> } <ide> } <ide> <add> // Apply volumes from another container if requested <ide> if container.Config.VolumesFrom != "" { <ide> c := container.runtime.Get(container.Config.VolumesFrom) <ide> if c == nil { <ide> func (container *Container) Start(hostConfig *HostConfig) error { <ide> } <ide> } <ide> <add> // Create the requested volumes if they don't exist <add> for volPath := range container.Config.Volumes { <add> volPath = path.Clean(volPath) <add> // If an external bind is defined for this volume, use that as a source <add> if _, exists := container.Volumes[volPath]; exists { <add> // Skip existing mounts <add> } else if bindMap, exists := binds[volPath]; exists { <add> container.Volumes[volPath] = bindMap.SrcPath <add> if strings.ToLower(bindMap.Mode) == "rw" { <add> container.VolumesRW[volPath] = true <add> } <add> // Otherwise create an directory in $ROOT/volumes/ and use that <add> } else { <add> c, err := container.runtime.volumes.Create(nil, container, "", "", nil) <add> if err != nil { <add> return err <add> } <add> srcPath, err := c.layer() <add> if err != nil { <add> return err <add> } <add> container.Volumes[volPath] = srcPath <add> container.VolumesRW[volPath] = true // RW by default <add> } <add> // Create the mountpoint <add> if err := os.MkdirAll(path.Join(container.RootfsPath(), volPath), 0755); err != nil { <add> return nil <add> } <add> } <add> <ide> if err := container.generateLXCConfig(); err != nil { <ide> return err <ide> } <ide><path>container_test.go <ide> func TestRestartWithVolumes(t *testing.T) { <ide> } <ide> } <ide> <add>// Test for #1351 <add>func TestVolumesFromWithVolumes(t *testing.T) { <add> runtime := mkRuntime(t) <add> defer nuke(runtime) <add> <add> container, err := NewBuilder(runtime).Create(&Config{ <add> Image: GetTestImage(runtime).ID, <add> Cmd: []string{"sh", "-c", "echo -n bar > /test/foo"}, <add> Volumes: map[string]struct{}{"/test": {}}, <add> }, <add> ) <add> if err != nil { <add> t.Fatal(err) <add> } <add> defer runtime.Destroy(container) <add> <add> for key := range container.Config.Volumes { <add> if key != "/test" { <add> t.Fail() <add> } <add> } <add> <add> _, err = container.Output() <add> if err != nil { <add> t.Fatal(err) <add> } <add> <add> expected := container.Volumes["/test"] <add> if expected == "" { <add> t.Fail() <add> } <add> <add> container2, err := NewBuilder(runtime).Create( <add> &Config{ <add> Image: GetTestImage(runtime).ID, <add> Cmd: []string{"cat", "/test/foo"}, <add> VolumesFrom: container.ID, <add> Volumes: map[string]struct{}{"/test": {}}, <add> }, <add> ) <add> if err != nil { <add> t.Fatal(err) <add> } <add> defer runtime.Destroy(container2) <add> <add> output, err := container2.Output() <add> if err != nil { <add> t.Fatal(err) <add> } <add> <add> if string(output) != "bar" { <add> t.Fail() <add> } <add> <add> if container.Volumes["/test"] != container2.Volumes["/test"] { <add> t.Fail() <add> } <add>} <add> <ide> func TestOnlyLoopbackExistsWhenUsingDisableNetworkOption(t *testing.T) { <ide> runtime := mkRuntime(t) <ide> defer nuke(runtime)
2
Javascript
Javascript
use arrow function
156a38fef1122cae39f4852b51bcdc8a65b45893
<ide><path>test/parallel/test-writeuint.js <ide> function testUint(clazz) { <ide> type: RangeError, <ide> message: /^The value "[^"]*" is invalid for option "value"$/ <ide> }, 2); <del> assert.throws(function() { <add> assert.throws(() => { <ide> data.writeUIntBE(val, 0, i); <ide> }, errMsg); <del> assert.throws(function() { <add> assert.throws(() => { <ide> data.writeUIntLE(val, 0, i); <ide> }, errMsg); <ide> val *= 0x100;
1
Ruby
Ruby
add a couple of missing requires in ar
2d80591f11b19bfc06fb712993648212ba5926df
<ide><path>activerecord/lib/active_record/scoping.rb <ide> # frozen_string_literal: true <ide> <ide> require "active_support/core_ext/module/delegation" <add>require "active_record/scoping/default" <add>require "active_record/scoping/named" <ide> <ide> module ActiveRecord <ide> module Scoping
1
Text
Text
remove cli doc entry related to api-only function
4f0429621c7e6ccaac8bc9a62a703bf68f2d4cd4
<ide><path>docs/sources/reference/commandline/cli.md <ide> container at any point. <ide> This is useful when you want to set up a container configuration ahead <ide> of time so that it is ready to start when you need it. <ide> <del>Note that volumes set by `create` may be over-ridden by options set with <del>`start`. <del> <ide> Please see the [run command](#run) section for more details. <ide> <ide> #### Examples
1
Javascript
Javascript
add workaround for node.js memory leak
cdf73dacf525bffd9e6396f86266026564ec1a02
<ide><path>lib/hmr/lazyCompilationBackend.js <ide> module.exports = (compiler, client, callback) => { <ide> const activeModules = new Map(); <ide> const prefix = "/lazy-compilation-using-"; <ide> <del> const server = http.createServer((req, res) => { <add> const requestListener = (req, res) => { <ide> const keys = req.url.slice(prefix.length).split("@"); <ide> req.socket.on("close", () => { <ide> setTimeout(() => { <ide> module.exports = (compiler, client, callback) => { <ide> } <ide> } <ide> if (moduleActivated && compiler.watching) compiler.watching.invalidate(); <del> }); <add> }; <add> const server = http.createServer(requestListener); <ide> let isClosing = false; <ide> /** @type {Set<import("net").Socket>} */ <ide> const sockets = new Set(); <ide> module.exports = (compiler, client, callback) => { <ide> callback(null, { <ide> dispose(callback) { <ide> isClosing = true; <add> // Removing the listener is a workaround for a memory leak in node.js <add> server.off("request", requestListener); <ide> server.close(err => { <ide> callback(err); <ide> });
1
Javascript
Javascript
handle elements with no childnodes property
bec614fd90c48c3921a4b659912008574e553b40
<ide><path>src/ng/compile.js <ide> function $CompileProvider($provide) { <ide> ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement) <ide> : null; <ide> <del> childLinkFn = (nodeLinkFn && nodeLinkFn.terminal || !nodeList[i].childNodes.length) <add> childLinkFn = (nodeLinkFn && nodeLinkFn.terminal || !nodeList[i].childNodes || !nodeList[i].childNodes.length) <ide> ? null <ide> : compileNodes(nodeList[i].childNodes, <ide> nodeLinkFn ? nodeLinkFn.transclude : transcludeFn); <ide><path>test/ng/compileSpec.js <ide> describe('$compile', function() { <ide> expect(calcCacheSize()).toEqual(0); <ide> }); <ide> <add> <add> it('should not blow up when elements with no childNodes property are compiled', inject( <add> function($compile, $rootScope) { <add> // it turns out that when a browser plugin is bound to an DOM element (typically <object>), <add> // the plugin's context rather than the usual DOM apis are exposed on this element, so <add> // childNodes might not exist. <add> if (msie < 9) return; <add> <add> element = jqLite('<div>{{1+2}}</div>'); <add> element[0].childNodes[1] = {nodeType: 3, nodeName: 'OBJECT', textContent: 'fake node'}; <add> <add> if (!element[0].childNodes[1]) return; //browser doesn't support this kind of mocking <add> expect(element[0].childNodes[1].textContent).toBe('fake node'); <add> <add> $compile(element)($rootScope); <add> $rootScope.$apply(); <add> <add> // object's children can't be compiled in this case, so we expect them to be raw <add> expect(element.html()).toBe("3"); <add> })); <add> <add> <ide> describe('multiple directives per element', function() { <ide> it('should allow multiple directives per element', inject(function($compile, $rootScope, log){ <ide> element = $compile(
2
PHP
PHP
add an accessor for the input registry
178c286bcb06c5695576af294b48cb63948883f0
<ide><path>src/View/Helper/FormHelper.php <ide> public function __construct(View $View, $settings = array()) { <ide> parent::__construct($View, $settings); <ide> <ide> $this->initStringTemplates($this->_defaultTemplates); <del> if (empty($settings['registry'])) { <del> $settings['registry'] = new InputRegistry($this->_templater, $settings['widgets']); <del> } <del> $this->_registry = $settings['registry']; <del> unset($this->settings['registry']); <add> $this->inputRegistry($settings['registry'], $settings['widgets']); <add> unset($this->settings['widgets'], $this->settings['registry']); <ide> <ide> $this->_addDefaultContextProviders(); <ide> } <ide> <add>/** <add> * Set the input registry the helper will use. <add> * <add> * @param Cake\View\Widget\InputRegistry $instance The registry instance to set. <add> * @param array $widgets An array of widgets <add> * @return Cake\View\Widget\InputRegistry <add> */ <add> public function inputRegistry(InputRegistry $instance = null, $widgets = []) { <add> if ($instance === null) { <add> if ($this->_registry === null) { <add> $this->_registry = new InputRegistry($this->_templater, $widgets); <add> } <add> return $this->_registry; <add> } <add> $this->_registry = $instance; <add> return $this->_registry; <add> } <add> <ide> /** <ide> * Add the default suite of context providers provided by CakePHP. <ide> *
1
Java
Java
simplify hint registration for spring aop proxies
5178e9c28eda20859829937c1bc3d38b8b314726
<ide><path>spring-aop/src/main/java/org/springframework/aop/framework/AopProxyUtils.java <ide> import java.lang.reflect.Proxy; <ide> import java.util.ArrayList; <ide> import java.util.Arrays; <add>import java.util.Collections; <ide> import java.util.List; <ide> <ide> import org.springframework.aop.SpringProxy; <ide> import org.springframework.aop.TargetClassAware; <ide> import org.springframework.aop.TargetSource; <ide> import org.springframework.aop.support.AopUtils; <ide> import org.springframework.aop.target.SingletonTargetSource; <add>import org.springframework.aot.hint.ProxyHints; <add>import org.springframework.aot.hint.RuntimeHints; <ide> import org.springframework.core.DecoratingProxy; <ide> import org.springframework.lang.Nullable; <ide> import org.springframework.util.Assert; <ide> public static Class<?> ultimateTargetClass(Object candidate) { <ide> return result; <ide> } <ide> <add> /** <add> * Complete the set of interfaces that are typically required in a JDK dynamic <add> * proxy generated by Spring AOP. <add> * <p>Specifically, {@link SpringProxy}, {@link Advised}, and {@link DecoratingProxy} <add> * will be appended to the set of user-specified interfaces. <add> * <p>Any {@linkplain Class#isSealed() sealed} interface in the set of <add> * user-specified interfaces will be omitted from the results, since only <add> * non-sealed interfaces are eligible for JDK dynamic proxies. <add> * <p>This method can be useful when registering {@linkplain ProxyHints proxy <add> * hints} for Spring's AOT support, as demonstrated in the following example <add> * which uses this method via a {@code static} import. <add> * <pre class="code"> <add> * RuntimeHints hints = ... <add> * hints.proxies().registerJdkProxy(completeJdkProxyInterfaces(MyInterface.class)); <add> * </pre> <add> * @param userInterfaces the set of user-specified interfaces implemented by <add> * the component to be proxied <add> * @return the complete set of interfaces that the proxy should implement <add> * @since 6.0 <add> * @see SpringProxy <add> * @see Advised <add> * @see DecoratingProxy <add> * @see RuntimeHints#proxies() <add> * @see ProxyHints#registerJdkProxy(Class...) <add> * @see #completeJdkProxyInterfaces(String...) <add> */ <add> public static Class<?>[] completeJdkProxyInterfaces(Class<?>... userInterfaces) { <add> List<Class<?>> completedInterfaces = new ArrayList<>(userInterfaces.length + 3); <add> for (Class<?> ifc : userInterfaces) { <add> Assert.isTrue(ifc.isInterface(), () -> ifc.getName() + " must be an interface"); <add> if (!ifc.isSealed()) { <add> completedInterfaces.add(ifc); <add> } <add> } <add> completedInterfaces.add(SpringProxy.class); <add> completedInterfaces.add(Advised.class); <add> completedInterfaces.add(DecoratingProxy.class); <add> return completedInterfaces.toArray(Class<?>[]::new); <add> } <add> <add> /** <add> * Complete the set of interfaces that are typically required in a JDK dynamic <add> * proxy generated by Spring AOP. <add> * <p>Specifically, {@link SpringProxy}, {@link Advised}, and {@link DecoratingProxy} <add> * will be appended to the set of user-specified interfaces. <add> * <p>This method can be useful when registering {@linkplain ProxyHints proxy <add> * hints} for Spring's AOT support, as demonstrated in the following example <add> * which uses this method via a {@code static} import. <add> * <pre class="code"> <add> * RuntimeHints hints = ... <add> * hints.proxies().registerJdkProxy(completeJdkProxyInterfaces("com.example.MyInterface")); <add> * </pre> <add> * @param userInterfaces the set of fully qualified names of user-specified <add> * interfaces implemented by the component to be proxied <add> * @return the complete set of fully qualified names of interfaces that the <add> * proxy should implement <add> * @since 6.0 <add> * @see SpringProxy <add> * @see Advised <add> * @see DecoratingProxy <add> * @see RuntimeHints#proxies() <add> * @see ProxyHints#registerJdkProxy(Class...) <add> * @see #completeJdkProxyInterfaces(Class...) <add> */ <add> public static String[] completeJdkProxyInterfaces(String... userInterfaces) { <add> List<String> completedInterfaces = new ArrayList<>(userInterfaces.length + 3); <add> Collections.addAll(completedInterfaces, userInterfaces); <add> completedInterfaces.add(SpringProxy.class.getName()); <add> completedInterfaces.add(Advised.class.getName()); <add> completedInterfaces.add(DecoratingProxy.class.getName()); <add> return completedInterfaces.toArray(String[]::new); <add> } <add> <ide> /** <ide> * Determine the complete set of interfaces to proxy for the given AOP configuration. <ide> * <p>This will always add the {@link Advised} interface unless the AdvisedSupport's <ide><path>spring-aop/src/test/java/org/springframework/aop/framework/AopProxyUtilsTests.java <ide> import org.springframework.aop.SpringProxy; <ide> import org.springframework.beans.testfixture.beans.ITestBean; <ide> import org.springframework.beans.testfixture.beans.TestBean; <add>import org.springframework.core.DecoratingProxy; <ide> <ide> import static org.assertj.core.api.Assertions.assertThat; <ide> import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; <ide> void proxiedUserInterfacesWithNoInterface() { <ide> assertThatIllegalArgumentException().isThrownBy(() -> AopProxyUtils.proxiedUserInterfaces(proxy)); <ide> } <ide> <add> @Test <add> void completeJdkProxyInterfacesFromClassThatIsNotAnInterface() { <add> assertThatIllegalArgumentException() <add> .isThrownBy(() -> AopProxyUtils.completeJdkProxyInterfaces(TestBean.class)) <add> .withMessage(TestBean.class.getName() + " must be an interface"); <add> } <add> <add> @Test <add> void completeJdkProxyInterfacesFromSingleClass() { <add> Class<?>[] jdkProxyInterfaces = AopProxyUtils.completeJdkProxyInterfaces(ITestBean.class); <add> assertThat(jdkProxyInterfaces).containsExactly( <add> ITestBean.class, SpringProxy.class, Advised.class, DecoratingProxy.class); <add> } <add> <add> @Test <add> void completeJdkProxyInterfacesFromMultipleClasses() { <add> Class<?>[] jdkProxyInterfaces = AopProxyUtils.completeJdkProxyInterfaces(ITestBean.class, Comparable.class); <add> assertThat(jdkProxyInterfaces).containsExactly( <add> ITestBean.class, Comparable.class, SpringProxy.class, Advised.class, DecoratingProxy.class); <add> } <add> <add> @Test <add> void completeJdkProxyInterfacesIgnoresSealedInterfaces() { <add> Class<?>[] jdkProxyInterfaces = AopProxyUtils.completeJdkProxyInterfaces(SealedInterface.class, Comparable.class); <add> assertThat(jdkProxyInterfaces).containsExactly( <add> Comparable.class, SpringProxy.class, Advised.class, DecoratingProxy.class); <add> } <add> <add> @Test <add> void completeJdkProxyInterfacesFromSingleClassName() { <add> String[] jdkProxyInterfaces = AopProxyUtils.completeJdkProxyInterfaces(ITestBean.class.getName()); <add> assertThat(jdkProxyInterfaces).containsExactly( <add> ITestBean.class.getName(), SpringProxy.class.getName(), Advised.class.getName(), <add> DecoratingProxy.class.getName()); <add> } <add> <add> @Test <add> void completeJdkProxyInterfacesFromMultipleClassNames() { <add> String[] jdkProxyInterfaces = <add> AopProxyUtils.completeJdkProxyInterfaces(ITestBean.class.getName(), Comparable.class.getName()); <add> assertThat(jdkProxyInterfaces).containsExactly( <add> ITestBean.class.getName(), Comparable.class.getName(), SpringProxy.class.getName(), <add> Advised.class.getName(), DecoratingProxy.class.getName()); <add> } <add> <add> <add> sealed interface SealedInterface { <add> } <add> <add> static final class SealedType implements SealedInterface { <add> } <add> <ide> } <ide><path>spring-context/src/main/java/org/springframework/validation/beanvalidation/MethodValidationRuntimeHintsRegistrar.java <ide> <ide> import jakarta.validation.Validator; <ide> <del>import org.springframework.aop.SpringProxy; <del>import org.springframework.aop.framework.Advised; <add>import org.springframework.aop.framework.AopProxyUtils; <ide> import org.springframework.aot.hint.RuntimeHints; <ide> import org.springframework.aot.hint.RuntimeHintsRegistrar; <del>import org.springframework.core.DecoratingProxy; <ide> import org.springframework.lang.Nullable; <ide> <ide> /** <ide> public class MethodValidationRuntimeHintsRegistrar implements RuntimeHintsRegist <ide> <ide> @Override <ide> public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) { <del> hints.proxies().registerJdkProxy(Validator.class, SpringProxy.class, Advised.class, DecoratingProxy.class); <add> hints.proxies().registerJdkProxy(AopProxyUtils.completeJdkProxyInterfaces(Validator.class)); <ide> } <add> <ide> } <ide><path>spring-core/src/main/java/org/springframework/aot/hint/ProxyHints.java <ide> public ProxyHints registerJdkProxy(TypeReference... proxiedInterfaces) { <ide> /** <ide> * Register that a JDK proxy implementing the specified interfaces is <ide> * required. <add> * <p>When registering a JDK proxy for Spring AOP, consider using <add> * {@link org.springframework.aop.framework.AopProxyUtils#completeJdkProxyInterfaces(Class...) <add> * AopProxyUtils.completeJdkProxyInterfaces()} for convenience. <ide> * @param proxiedInterfaces the interfaces the proxy should implement <ide> * @return {@code this}, to facilitate method chaining <ide> */ <ide> public ProxyHints registerJdkProxy(Class<?>... proxiedInterfaces) { <ide> /** <ide> * Register that a JDK proxy implementing the specified interfaces is <ide> * required. <add> * <p>When registering a JDK proxy for Spring AOP, consider using <add> * {@link org.springframework.aop.framework.AopProxyUtils#completeJdkProxyInterfaces(String...) <add> * AopProxyUtils.completeJdkProxyInterfaces()} for convenience. <ide> * @param proxiedInterfaces the fully qualified class names of interfaces the <ide> * proxy should implement <ide> * @return {@code this}, to facilitate method chaining <ide><path>spring-tx/src/main/java/org/springframework/transaction/annotation/TransactionBeanRegistrationAotProcessor.java <ide> import java.util.LinkedHashSet; <ide> import java.util.Set; <ide> <del>import org.springframework.aop.SpringProxy; <del>import org.springframework.aop.framework.Advised; <add>import org.springframework.aop.framework.AopProxyUtils; <ide> import org.springframework.aot.generate.GenerationContext; <ide> import org.springframework.aot.hint.MemberCategory; <ide> import org.springframework.aot.hint.RuntimeHints; <ide> import org.springframework.beans.factory.aot.BeanRegistrationAotContribution; <ide> import org.springframework.beans.factory.aot.BeanRegistrationAotProcessor; <ide> import org.springframework.beans.factory.aot.BeanRegistrationCode; <ide> import org.springframework.beans.factory.support.RegisteredBean; <del>import org.springframework.core.DecoratingProxy; <ide> import org.springframework.core.annotation.MergedAnnotations; <ide> import org.springframework.util.ClassUtils; <ide> import org.springframework.util.ReflectionUtils; <ide> public TransactionBeanRegistrationAotContribution(Class<?> beanClass) { <ide> @Override <ide> public void applyTo(GenerationContext generationContext, BeanRegistrationCode beanRegistrationCode) { <ide> RuntimeHints runtimeHints = generationContext.getRuntimeHints(); <del> LinkedHashSet<Class<?>> interfaces = new LinkedHashSet<>(); <ide> Class<?>[] proxyInterfaces = ClassUtils.getAllInterfacesForClass(this.beanClass); <ide> if (proxyInterfaces.length == 0) { <ide> return; <ide> } <ide> for (Class<?> proxyInterface : proxyInterfaces) { <del> interfaces.add(proxyInterface); <ide> runtimeHints.reflection().registerType(proxyInterface, builder -> builder.withMembers(MemberCategory.INVOKE_DECLARED_METHODS)); <ide> } <del> interfaces.add(SpringProxy.class); <del> interfaces.add(Advised.class); <del> interfaces.add(DecoratingProxy.class); <del> runtimeHints.proxies().registerJdkProxy(interfaces.toArray(Class[]::new)); <add> runtimeHints.proxies().registerJdkProxy(AopProxyUtils.completeJdkProxyInterfaces(proxyInterfaces)); <ide> } <ide> } <add> <ide> }
5
Python
Python
fix small doc error
5fcd832b5c5025b164c99f0bd46cb94d707b93d3
<ide><path>keras/engine/training.py <ide> def predict(self, x, <ide> <ide> # Arguments <ide> x: The input data, as a Numpy array <del> (or list of Numpy arrays if the model has multiple outputs). <add> (or list of Numpy arrays if the model has multiple inputs). <ide> batch_size: Integer. If unspecified, it will default to 32. <ide> verbose: Verbosity mode, 0 or 1. <ide> steps: Total number of steps (batches of samples)
1
Python
Python
avoid use of numpy.tensordot
c9987cf131a5cc8d41437136dad1c765f20e5862
<ide><path>spacy/_ml.py <ide> def __init__(self, nO=None, nI=None, nF=None, nP=None, **kwargs): <ide> self.nF = nF <ide> <ide> def begin_update(self, X, drop=0.): <del> tensordot = self.ops.xp.tensordot <del> ascontiguous = self.ops.xp.ascontiguousarray <del> <del> Yf = tensordot(X, self.W, axes=[[1], [3]]) <add> Yf = self.ops.dot(X, <add> self.W.reshape((self.nF*self.nO*self.nP, self.nI)).T) <add> <add> Yf = Yf.reshape((X.shape[0], self.nF, self.nO, self.nP)) <ide> <ide> def backward(dY_ids, sgd=None): <ide> dY, ids = dY_ids <ide> Xf = X[ids] <add> Xf = Xf.reshape((Xf.shape[0], self.nF * self.nI)) <ide> <del> dXf = tensordot(dY, self.W, axes=[[1,2], [1,2]]) <del> dW = tensordot(dY, Xf, axes=[[0], [0]]) <del> # (o, p, f, i) --> (f, o, p, i) <del> self.d_W += dW.transpose((2, 0, 1, 3)) <ide> self.d_b += dY.sum(axis=0) <add> dY = dY.reshape((dY.shape[0], self.nO*self.nP)) <add> <add> Wopfi = self.W.transpose((1, 2, 0, 3)) <add> Wopfi = self.ops.xp.ascontiguousarray(Wopfi) <add> Wopfi = Wopfi.reshape((self.nO*self.nP, self.nF * self.nI)) <add> dXf = self.ops.dot(dY.reshape((dY.shape[0], self.nO*self.nP)), Wopfi) <add> <add> # Reuse the buffer <add> dWopfi = Wopfi; dWopfi.fill(0.) <add> self.ops.xp.dot(dY.T, Xf, out=dWopfi) <add> dWopfi = dWopfi.reshape((self.nO, self.nP, self.nF, self.nI)) <add> # (o, p, f, i) --> (f, o, p, i) <add> self.d_W += dWopfi.transpose((2, 0, 1, 3)) <ide> <ide> if sgd is not None: <ide> sgd(self._mem.weights, self._mem.gradient, key=self.id) <del> return dXf <add> return dXf.reshape((dXf.shape[0], self.nF, self.nI)) <ide> return Yf, backward <ide> <ide> @staticmethod <ide> def init_weights(model): <ide> size=tokvecs.size).reshape(tokvecs.shape) <ide> <ide> def predict(ids, tokvecs): <del> hiddens = model(tokvecs) <add> hiddens = model(tokvecs) # (b, f, o, p) <ide> vector = model.ops.allocate((hiddens.shape[0], model.nO, model.nP)) <del> model.ops.scatter_add(vector, ids, hiddens) <add> model.ops.xp.add.at(vector, ids, hiddens) <ide> vector += model.b <ide> if model.nP >= 2: <ide> return model.ops.maxout(vector)[0] <ide> def Tok2Vec(width, embed_size, **kwargs): <ide> <ide> tok2vec = ( <ide> FeatureExtracter(cols) <del> >> with_flatten( <del> embed >> (convolution ** 4), pad=4) <add> >> with_flatten(embed >> (convolution ** 4), pad=4) <ide> ) <ide> <ide> # Work around thinc API limitations :(. TODO: Revise in Thinc 7
1
Python
Python
add wait_for_completion to glue job run
e0af0b976c0cc43d2b1aa204d047fe755e4c5be7
<ide><path>airflow/providers/amazon/aws/operators/glue.py <ide> class AwsGlueJobOperator(BaseOperator): <ide> :type create_job_kwargs: Optional[dict] <ide> :param run_job_kwargs: Extra arguments for Glue Job Run <ide> :type run_job_kwargs: Optional[dict] <add> :param wait_for_completion: Whether or not wait for job run completion. (default: True) <add> :type wait_for_completion: bool <ide> """ <ide> <ide> template_fields = ('script_args',) <ide> def __init__( <ide> iam_role_name: Optional[str] = None, <ide> create_job_kwargs: Optional[dict] = None, <ide> run_job_kwargs: Optional[dict] = None, <add> wait_for_completion: bool = True, <ide> **kwargs, <ide> ): <ide> super().__init__(**kwargs) <ide> def __init__( <ide> self.s3_artifacts_prefix = 'artifacts/glue-scripts/' <ide> self.create_job_kwargs = create_job_kwargs <ide> self.run_job_kwargs = run_job_kwargs or {} <add> self.wait_for_completion = wait_for_completion <ide> <ide> def execute(self, context): <ide> """ <ide> def execute(self, context): <ide> iam_role_name=self.iam_role_name, <ide> create_job_kwargs=self.create_job_kwargs, <ide> ) <del> self.log.info("Initializing AWS Glue Job: %s", self.job_name) <del> glue_job_run = glue_job.initialize_job(self.script_args, self.run_job_kwargs) <del> glue_job_run = glue_job.job_completion(self.job_name, glue_job_run['JobRunId']) <ide> self.log.info( <del> "AWS Glue Job: %s status: %s. Run Id: %s", <add> "Initializing AWS Glue Job: %s. Wait for completion: %s", <ide> self.job_name, <del> glue_job_run['JobRunState'], <del> glue_job_run['JobRunId'], <add> self.wait_for_completion, <ide> ) <add> glue_job_run = glue_job.initialize_job(self.script_args, self.run_job_kwargs) <add> if self.wait_for_completion: <add> glue_job_run = glue_job.job_completion(self.job_name, glue_job_run['JobRunId']) <add> self.log.info( <add> "AWS Glue Job: %s status: %s. Run Id: %s", <add> self.job_name, <add> glue_job_run['JobRunState'], <add> glue_job_run['JobRunId'], <add> ) <add> else: <add> self.log.info("AWS Glue Job: %s. Run Id: %s", self.job_name, glue_job_run['JobRunId']) <ide> return glue_job_run['JobRunId'] <ide><path>tests/providers/amazon/aws/operators/test_glue.py <ide> def test_execute_without_failure( <ide> glue.execute(None) <ide> mock_initialize_job.assert_called_once_with({}, {}) <ide> assert glue.job_name == 'my_test_job' <add> <add> @mock.patch.object(AwsGlueJobHook, 'job_completion') <add> @mock.patch.object(AwsGlueJobHook, 'initialize_job') <add> @mock.patch.object(AwsGlueJobHook, "get_conn") <add> @mock.patch.object(S3Hook, "load_file") <add> def test_execute_without_waiting_for_completion( <add> self, mock_load_file, mock_get_conn, mock_initialize_job, mock_job_completion <add> ): <add> glue = AwsGlueJobOperator( <add> task_id='test_glue_operator', <add> job_name='my_test_job', <add> script_location='s3://glue-examples/glue-scripts/sample_aws_glue_job.py', <add> aws_conn_id='aws_default', <add> region_name='us-west-2', <add> s3_bucket='some_bucket', <add> iam_role_name='my_test_role', <add> wait_for_completion=False, <add> ) <add> mock_initialize_job.return_value = {'JobRunState': 'RUNNING', 'JobRunId': '11111'} <add> job_run_id = glue.execute(None) <add> mock_initialize_job.assert_called_once_with({}, {}) <add> mock_job_completion.assert_not_called() <add> assert glue.job_name == 'my_test_job' <add> assert job_run_id == '11111'
2
Javascript
Javascript
fix deprecation warning due to util.print
0179e940cc3cbd81e6abaf7b12677b72070f94c5
<ide><path>test/parallel/test-child-process-double-pipe.js <ide> const common = require('../common'); <ide> const assert = require('assert'); <ide> const os = require('os'); <del>const util = require('util'); <ide> const spawn = require('child_process').spawn; <ide> <ide> // We're trying to reproduce: <ide> let result = ''; <ide> // print sed's output <ide> sed.stdout.on('data', function(data) { <ide> result += data.toString('utf8', 0, data.length); <del> util.print(data); <add> console.log(data); <ide> }); <ide> <ide> sed.stdout.on('end', function(code) {
1
Text
Text
fix nits regarding stream utilities
daa512b5765c898893535d838472eca20d9d50c4
<ide><path>doc/api/stream.md <ide> There are four fundamental stream types within Node.js: <ide> * [`Transform`][] - `Duplex` streams that can modify or transform the data as it <ide> is written and read (for example, [`zlib.createDeflate()`][]). <ide> <del>Additionally, this module includes the utility functions [pipeline][], <del>[finished][] and [Readable.from][]. <add>Additionally, this module includes the utility functions <add>[`stream.pipeline()`][], [`stream.finished()`][] and <add>[`stream.Readable.from()`][]. <ide> <ide> ### Object Mode <ide> <ide> async function run() { <ide> run().catch(console.error); <ide> ``` <ide> <del>### Readable.from(iterable, [options]) <add>### stream.Readable.from(iterable, [options]) <ide> <ide> * `iterable` {Iterable} Object implementing the `Symbol.asyncIterator` or <ide> `Symbol.iterator` iterable protocol. <ide> and async iterators are provided below. <ide> #### Creating Readable Streams with Async Generators <ide> <ide> We can construct a Node.js Readable Stream from an asynchronous generator <del>using the `Readable.from` utility method: <add>using the `Readable.from()` utility method: <ide> <ide> ```js <ide> const { Readable } = require('stream'); <ide> const writeable = fs.createWriteStream('./file'); <ide> ``` <ide> <ide> In the above, errors on the write stream would be caught and thrown by the two <del>`once` listeners, since `once` will also handle `'error'` events. <add>`once()` listeners, since `once()` will also handle `'error'` events. <ide> <del>Alternatively the readable stream could be wrapped with `Readable.from` and <del>then piped via `.pipe`: <add>Alternatively the readable stream could be wrapped with `Readable.from()` and <add>then piped via `.pipe()`: <ide> <ide> ```js <ide> const { once } = require('events'); <ide> contain multi-byte characters. <ide> [`process.stdin`]: process.html#process_process_stdin <ide> [`process.stdout`]: process.html#process_process_stdout <ide> [`readable.push('')`]: #stream_readable_push <add>[`stream.Readable.from()`]: #stream_stream_readable_from_iterable_options <ide> [`stream.cork()`]: #stream_writable_cork <add>[`stream.finished()`]: #stream_stream_finished_stream_options_callback <ide> [`stream.pipe()`]: #stream_readable_pipe_destination_options <add>[`stream.pipeline()`]: #stream_stream_pipeline_streams_callback <ide> [`stream.uncork()`]: #stream_writable_uncork <ide> [`stream.unpipe()`]: #stream_readable_unpipe_destination <ide> [`stream.wrap()`]: #stream_readable_wrap_stream <ide> contain multi-byte characters. <ide> [Compatibility]: #stream_compatibility_with_older_node_js_versions <ide> [HTTP requests, on the client]: http.html#http_class_http_clientrequest <ide> [HTTP responses, on the server]: http.html#http_class_http_serverresponse <del>[Readable.from]: #readable.from <ide> [TCP sockets]: net.html#net_class_net_socket <ide> [child process stdin]: child_process.html#child_process_subprocess_stdin <ide> [child process stdout and stderr]: child_process.html#child_process_subprocess_stdout <ide> [crypto]: crypto.html <del>[finished]: #stream_stream_finished_stream_options_callback <ide> [fs read streams]: fs.html#fs_class_fs_readstream <ide> [fs write streams]: fs.html#fs_class_fs_writestream <ide> [http-incoming-message]: http.html#http_class_http_incomingmessage <ide> [hwm-gotcha]: #stream_highwatermark_discrepancy_after_calling_readable_setencoding <ide> [object-mode]: #stream_object_mode <del>[pipeline]: #stream_stream_pipeline_streams_callback <ide> [readable-_destroy]: #stream_readable_destroy_err_callback <ide> [readable-destroy]: #stream_readable_destroy_error <ide> [stream-_final]: #stream_writable_final_callback
1
Text
Text
translate 02.3 to korean
fe8cd0c44272497f6f827ed453bd35b80155347a
<ide><path>docs/docs/02.3-jsx-gotchas.ko-KR.md <add>--- <add>id: jsx-gotchas-ko-KR <add>title: JSX Gotchas <add>permalink: jsx-gotchas-ko-KR.html <add>prev: jsx-spread-ko-KR.html <add>next: interactivity-and-dynamic-uis-ko-KR.html <add>--- <add> <add>JSX는 HTML처럼 보이지만 하다 보면 부딪히게 될 몇 가지 중요한 차이점이 있습니다. <add> <add>> 주의: <add>> <add>> 인라인 `style` 어트리뷰트 같은 DOM 차이점은 [여기](/react/docs/dom-differences.html)를 보세요. <add> <add>## HTML 엔티티 <add> <add>JSX의 리터럴 텍스트에 HTML 엔티티를 넣을 수 있습니다. <add> <add>```javascript <add><div>First &middot; Second</div> <add>``` <add> <add>동적 콘텐츠 안에 HTML 엔티티를 표시하려 할 때, React에서는 XSS 공격을 광범위하게 막기 위해 기본적으로 모든 표시하는 문자열을 이스케이프 하기 때문에 더블 이스케이프 문제에 부딪히게 됩니다. <add> <add>```javascript <add>// 나쁨: "First &middot; Second"를 표시 <add><div>{'First &middot; Second'}</div> <add>``` <add> <add>이 이슈를 피해 갈 방법은 여럿 있지만, 가장 쉬운 방법은 유니코드 문자를 JavaScript에 직접 쓰는 것입니다. 브라우저가 올바르게 표시하도록 파일이 UTF-8으로 저장되어 있고 올바른 UTF-8 지시자를 사용하고 있는지 확인해야 합니다. <add> <add>```javascript <add><div>{'First · Second'}</div> <add>``` <add> <add>더 안전한 대안으로 [엔티티에 대응하는 유니코드 숫자](http://www.fileformat.info/info/unicode/char/b7/index.htm)를 찾아 JavaScript 스트링 안에서 사용하는 방법도 있습니다. <add> <add>```javascript <add><div>{'First \u00b7 Second'}</div> <add><div>{'First ' + String.fromCharCode(183) + ' Second'}</div> <add>``` <add> <add>문자열과 JSX 엘리먼트를 혼합한 배열을 사용할 수도 있습니다. <add> <add>```javascript <add><div>{['First ', <span>&middot;</span>, ' Second']}</div> <add>``` <add> <add>최후의 수단으로, 항상 [생 HTML을 삽입](/react/docs/dom-differences.html)할 수는 있습니다. <add> <add>```javascript <add><div dangerouslySetInnerHTML={{'{{'}}__html: 'First &middot; Second'}} /> <add>``` <add> <add> <add>## 커스텀 HTML 어트리뷰트 <add> <add>프로퍼티를 HTML 사양에는 없는 네이티브 HTML 엘리먼트에 넘기면, React는 그 프로퍼티를 렌더하지 않습니다. 커스텀 어트리뷰트를 사용하고 싶다면, 접두사로 `data-`를 붙이셔야 합니다. <add> <add>```javascript <add><div data-custom-attribute="foo" /> <add>``` <add> <add>`aria-`로 시작하는 [Web 접근성](http://www.w3.org/WAI/intro/aria) 어트리뷰트는 제대로 렌더될 것입니다. <add> <add>```javascript <add><div aria-hidden={true} /> <add>```
1
Java
Java
enable javascript systrace markers via js module
619da521f318ad10f9d2a8df0dd3a5ed9be5b9b2
<ide><path>ReactAndroid/src/main/java/com/facebook/react/CoreModulesPackage.java <ide> import java.util.Arrays; <ide> import java.util.List; <ide> <add>import com.facebook.react.bridge.BridgeProfiling; <ide> import com.facebook.react.bridge.JavaScriptModule; <ide> import com.facebook.react.bridge.NativeModule; <ide> import com.facebook.react.bridge.ReactApplicationContext; <ide> public List<Class<? extends JavaScriptModule>> createJSModules() { <ide> RCTEventEmitter.class, <ide> RCTNativeAppEventEmitter.class, <ide> AppRegistry.class, <add> BridgeProfiling.class, <ide> ReactNative.class, <ide> DebugComponentOwnershipModule.RCTDebugComponentOwnership.class); <ide> } <ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/BridgeProfiling.java <add>// Copyright 2004-present Facebook. All Rights Reserved. <add> <add>package com.facebook.react.bridge; <add> <add>import com.facebook.proguard.annotations.DoNotStrip; <add> <add>/** <add> * Interface to the JavaScript BridgeProfiling Module <add> */ <add>@DoNotStrip <add>public interface BridgeProfiling extends JavaScriptModule{ <add> @DoNotStrip <add> void setEnabled(boolean enabled); <add>} <ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/CatalystInstance.java <ide> public class CatalystInstance { <ide> private @Nullable ReactBridge mBridge; <ide> private boolean mJSBundleHasLoaded; <ide> <del> private CatalystInstance( <add> private CatalystInstance( <ide> final CatalystQueueConfigurationSpec catalystQueueConfigurationSpec, <ide> final JavaScriptExecutor jsExecutor, <ide> final NativeModuleRegistry registry, <ide> public void run() { <ide> private class JSProfilerTraceListener implements TraceListener { <ide> @Override <ide> public void onTraceStarted() { <del> mCatalystQueueConfiguration.getJSQueueThread().runOnQueue( <del> new Runnable() { <del> @Override <del> public void run() { <del> mCatalystQueueConfiguration.getJSQueueThread().assertIsOnThread(); <del> <del> if (mDestroyed) { <del> return; <del> } <del> Assertions.assertNotNull(mBridge).setGlobalVariable( <del> "__BridgeProfilingIsProfiling", <del> "true"); <del> } <del> }); <add> getJSModule(BridgeProfiling.class).setEnabled(true); <ide> } <ide> <ide> @Override <ide> public void onTraceStopped() { <del> mCatalystQueueConfiguration.getJSQueueThread().runOnQueue( <del> new Runnable() { <del> @Override <del> public void run() { <del> mCatalystQueueConfiguration.getJSQueueThread().assertIsOnThread(); <del> <del> if (mDestroyed) { <del> return; <del> } <del> Assertions.assertNotNull(mBridge).setGlobalVariable( <del> "__BridgeProfilingIsProfiling", <del> "false"); <del> } <del> }); <add> getJSModule(BridgeProfiling.class).setEnabled(false); <ide> } <ide> } <ide>
3
Text
Text
fix changelog [ci skip]
040e22b10413481ca017bd8ada7691231ef8d5bf
<ide><path>actionview/CHANGELOG.md <del>## Rails 7.0.0.alpha2 (September 15, 2021) ## <del> <ide> * Support svg unpaired tags for `tag` helper. <ide> <ide> tag.svg { tag.use('href' => "#cool-icon") } <ide> *Oleksii Vasyliev* <ide> <ide> <add>## Rails 7.0.0.alpha2 (September 15, 2021) ## <add> <add>* No changes. <add> <add> <ide> ## Rails 7.0.0.alpha1 (September 15, 2021) ## <ide> <ide> * Improves the performance of ActionView::Helpers::NumberHelper formatters by avoiding the use of
1
Ruby
Ruby
convert `brew linkapps` test to spec
5bf70805d8c134174dfb55791c25066239d9bc0e
<ide><path>Library/Homebrew/test/cmd/linkapps_spec.rb <add>describe "brew linkapps", :integration_test do <add> let(:home_dir) { @home_dir = Pathname.new(Dir.mktmpdir) } <add> let(:apps_dir) { home_dir/"Applications" } <add> <add> after(:each) do <add> home_dir.rmtree unless @home_dir.nil? <add> end <add> <add> it "symlinks applications" do <add> apps_dir.mkpath <add> <add> setup_test_formula "testball" <add> <add> source_app = HOMEBREW_CELLAR/"testball/0.1/TestBall.app" <add> source_app.mkpath <add> <add> expect { brew "linkapps", "--local", "HOME" => home_dir } <add> .to output(/Linking: #{Regexp.escape(source_app)}/).to_stdout <add> .and output(/`brew linkapps` has been deprecated/).to_stderr <add> .and be_a_success <add> <add> expect(apps_dir/"TestBall.app").to be_a_symlink <add> end <add>end <ide><path>Library/Homebrew/test/linkapps_test.rb <del>require "testing_env" <del> <del>class IntegrationCommandTestLinkapps < IntegrationCommandTestCase <del> def test_linkapps <del> home_dir = Pathname.new(mktmpdir) <del> (home_dir/"Applications").mkpath <del> <del> setup_test_formula "testball" <del> <del> source_dir = HOMEBREW_CELLAR/"testball/0.1/TestBall.app" <del> source_dir.mkpath <del> assert_match "Linking: #{source_dir}", <del> cmd("linkapps", "--local", "HOME" => home_dir) <del> end <del>end
2
Javascript
Javascript
remove flakey test for selected attribute
87bd130289c6ed9bfc355c1f8587ae6ce00a4776
<ide><path>test/unit/attributes.js <ide> QUnit.test( "attr('tabindex', value)", function( assert ) { <ide> } ); <ide> <ide> QUnit.test( "removeAttr(String)", function( assert ) { <del> assert.expect( 13 ); <add> assert.expect( 12 ); <ide> var $first; <ide> <ide> assert.equal( jQuery( "#mark" ).removeAttr( "class" ).attr( "class" ), undefined, "remove class" ); <ide> QUnit.test( "removeAttr(String)", function( assert ) { <ide> <ide> jQuery( "#check1" ).removeAttr( "checked" ).prop( "checked", true ).removeAttr( "checked" ); <ide> assert.equal( document.getElementById( "check1" ).checked, true, "removeAttr should not set checked to false, since the checked attribute does NOT mirror the checked property" ); <del> jQuery( "#option1b" ).attr( "selected", "selected" ).removeAttr( "selected" ).attr( "selected", "selected" ); <del> assert.notEqual( document.getElementById( "select1" ).selectedIndex, 1, "Once the selected attribute is dirty, subsequent settings should not select the option (gh-1759)" ); <ide> jQuery( "#text1" ).prop( "readOnly", true ).removeAttr( "readonly" ); <ide> assert.equal( document.getElementById( "text1" ).readOnly, false, "removeAttr sets boolean properties to false" ); <ide>
1
Java
Java
paramaterize websocket tests by client and server
1b8cdb89241290af2999dd073cf463cd30271537
<ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/socket/server/AbstractWebSocketIntegrationTests.java <ide> import org.junit.runners.Parameterized; <ide> import org.junit.runners.Parameterized.Parameter; <ide> import org.junit.runners.Parameterized.Parameters; <add>import reactor.core.publisher.Flux; <add>import reactor.util.function.Tuple3; <ide> <add>import org.springframework.context.Lifecycle; <ide> import org.springframework.context.annotation.AnnotationConfigApplicationContext; <ide> import org.springframework.context.annotation.Bean; <ide> import org.springframework.context.annotation.Configuration; <ide> import org.springframework.http.server.reactive.bootstrap.UndertowHttpServer; <ide> import org.springframework.util.SocketUtils; <ide> import org.springframework.web.reactive.DispatcherHandler; <add>import org.springframework.web.reactive.socket.client.JettyWebSocketClient; <add>import org.springframework.web.reactive.socket.client.ReactorNettyWebSocketClient; <add>import org.springframework.web.reactive.socket.client.RxNettyWebSocketClient; <add>import org.springframework.web.reactive.socket.client.StandardWebSocketClient; <add>import org.springframework.web.reactive.socket.client.UndertowWebSocketClient; <add>import org.springframework.web.reactive.socket.client.WebSocketClient; <ide> import org.springframework.web.reactive.socket.server.support.HandshakeWebSocketService; <ide> import org.springframework.web.reactive.socket.server.support.WebSocketHandlerAdapter; <ide> import org.springframework.web.reactive.socket.server.upgrade.JettyRequestUpgradeStrategy; <ide> import org.springframework.web.reactive.socket.server.upgrade.TomcatRequestUpgradeStrategy; <ide> import org.springframework.web.reactive.socket.server.upgrade.UndertowRequestUpgradeStrategy; <ide> <add>import static org.junit.Assume.assumeFalse; <add> <ide> /** <ide> * Base class for WebSocket integration tests. <ide> * Sub-classes must implement {@link #getWebConfigClass()} to return Spring <ide> public abstract class AbstractWebSocketIntegrationTests { <ide> protected int port; <ide> <ide> @Parameter(0) <del> public HttpServer server; <add> public WebSocketClient client; <ide> <ide> @Parameter(1) <del> public Class<?> handlerAdapterConfigClass; <add> public HttpServer server; <ide> <add> @Parameter(2) <add> public Class<?> serverConfigClass; <ide> <del> @Parameters(name = "server [{0}]") <add> <add> @Parameters(name = "client[{0}] - server [{1}]") <ide> public static Object[][] arguments() { <add> <ide> File base = new File(System.getProperty("java.io.tmpdir")); <del> return new Object[][] { <del> {new ReactorHttpServer(), ReactorNettyConfig.class}, <del> {new RxNettyHttpServer(), RxNettyConfig.class}, <del> {new TomcatHttpServer(base.getAbsolutePath(), WsContextListener.class), TomcatConfig.class}, <del> {new UndertowHttpServer(), UndertowConfig.class}, <del> {new JettyHttpServer(), JettyConfig.class} <del> }; <add> <add> Flux<? extends WebSocketClient> clients = Flux.concat( <add> Flux.just(new StandardWebSocketClient()).repeat(5), <add> Flux.just(new JettyWebSocketClient()).repeat(5), <add> Flux.just(new ReactorNettyWebSocketClient()).repeat(5), <add> Flux.just(new RxNettyWebSocketClient()).repeat(5), <add> Flux.just(new UndertowWebSocketClient()).repeat(5)); <add> <add> Flux<? extends HttpServer> servers = Flux.just( <add> new TomcatHttpServer(base.getAbsolutePath(), WsContextListener.class), <add> new JettyHttpServer(), <add> new ReactorHttpServer(), <add> new RxNettyHttpServer(), <add> new UndertowHttpServer()).repeat(5); <add> <add> Flux<? extends Class<?>> configs = Flux.just( <add> TomcatConfig.class, <add> JettyConfig.class, <add> ReactorNettyConfig.class, <add> RxNettyConfig.class, <add> UndertowConfig.class).repeat(5); <add> <add> return Flux.zip(clients, servers, configs) <add> .map(Tuple3::toArray) <add> .collectList() <add> .block() <add> .toArray(new Object[25][2]); <ide> } <ide> <ide> <ide> @Before <ide> public void setup() throws Exception { <add> <add> // TODO <add> // Caused by: java.io.IOException: Upgrade responses cannot have a transfer coding <add> // at org.xnio.http.HttpUpgrade$HttpUpgradeState.handleUpgrade(HttpUpgrade.java:490) <add> // at org.xnio.http.HttpUpgrade$HttpUpgradeState.access$1200(HttpUpgrade.java:165) <add> // at org.xnio.http.HttpUpgrade$HttpUpgradeState$UpgradeResultListener.handleEvent(HttpUpgrade.java:461) <add> // at org.xnio.http.HttpUpgrade$HttpUpgradeState$UpgradeResultListener.handleEvent(HttpUpgrade.java:400) <add> // at org.xnio.ChannelListeners.invokeChannelListener(ChannelListeners.java:92) <add> <add> assumeFalse(this.client instanceof UndertowWebSocketClient && this.server instanceof RxNettyHttpServer); <add> <ide> this.port = SocketUtils.findAvailableTcpPort(); <ide> this.server.setPort(this.port); <ide> this.server.setHandler(createHttpHandler()); <ide> this.server.afterPropertiesSet(); <ide> this.server.start(); <add> <add> if (this.client instanceof Lifecycle) { <add> ((Lifecycle) this.client).start(); <add> } <ide> } <ide> <ide> private HttpHandler createHttpHandler() { <ide> AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); <del> context.register(DispatcherConfig.class, this.handlerAdapterConfigClass); <add> context.register(DispatcherConfig.class, this.serverConfigClass); <ide> context.register(getWebConfigClass()); <ide> context.refresh(); <ide> return DispatcherHandler.toHttpHandler(context); <ide> private HttpHandler createHttpHandler() { <ide> <ide> @After <ide> public void tearDown() throws Exception { <add> if (this.client instanceof Lifecycle) { <add> ((Lifecycle) this.client).stop(); <add> } <ide> this.server.stop(); <ide> } <ide> <ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/socket/server/WebSocketIntegrationTests.java <ide> */ <ide> package org.springframework.web.reactive.socket.server; <ide> <del>import java.net.URISyntaxException; <ide> import java.util.HashMap; <ide> import java.util.Map; <ide> import java.util.concurrent.atomic.AtomicReference; <ide> <ide> import org.hamcrest.Matchers; <del>import org.junit.Ignore; <ide> import org.junit.Test; <ide> import org.reactivestreams.Publisher; <ide> import reactor.core.publisher.Flux; <ide> import org.springframework.context.annotation.Bean; <ide> import org.springframework.context.annotation.Configuration; <ide> import org.springframework.http.HttpHeaders; <del>import org.springframework.http.server.reactive.bootstrap.RxNettyHttpServer; <ide> import org.springframework.web.reactive.HandlerMapping; <ide> import org.springframework.web.reactive.handler.SimpleUrlHandlerMapping; <ide> import org.springframework.web.reactive.socket.HandshakeInfo; <ide> import org.springframework.web.reactive.socket.WebSocketSession; <ide> import org.springframework.web.reactive.socket.client.JettyWebSocketClient; <ide> import org.springframework.web.reactive.socket.client.ReactorNettyWebSocketClient; <del>import org.springframework.web.reactive.socket.client.RxNettyWebSocketClient; <del>import org.springframework.web.reactive.socket.client.StandardWebSocketClient; <del>import org.springframework.web.reactive.socket.client.UndertowWebSocketClient; <del>import org.springframework.web.reactive.socket.client.WebSocketClient; <ide> <ide> import static org.junit.Assert.assertEquals; <ide> import static org.junit.Assert.assertThat; <add>import static org.junit.Assume.assumeFalse; <ide> <ide> /** <ide> * Integration tests with server-side {@link WebSocketHandler}s. <ide> protected Class<?> getWebConfigClass() { <ide> <ide> <ide> @Test <del> public void echoReactorClient() throws Exception { <del> testEcho(new ReactorNettyWebSocketClient()); <del> } <del> <del> @Test <del> public void echoRxNettyClient() throws Exception { <del> testEcho(new RxNettyWebSocketClient()); <del> } <del> <del> @Test <del> public void echoJettyClient() throws Exception { <del> JettyWebSocketClient client = new JettyWebSocketClient(); <del> client.start(); <del> testEcho(client); <del> client.stop(); <del> } <del> <del> @Test <del> public void echoStandardClient() throws Exception { <del> testEcho(new StandardWebSocketClient()); <del> } <del> <del> @Test <del> public void echoUndertowClient() throws Exception { <del> if (server instanceof RxNettyHttpServer) { <del> // Caused by: java.io.IOException: Upgrade responses cannot have a transfer coding <del> // at org.xnio.http.HttpUpgrade$HttpUpgradeState.handleUpgrade(HttpUpgrade.java:490) <del> // at org.xnio.http.HttpUpgrade$HttpUpgradeState.access$1200(HttpUpgrade.java:165) <del> // at org.xnio.http.HttpUpgrade$HttpUpgradeState$UpgradeResultListener.handleEvent(HttpUpgrade.java:461) <del> // at org.xnio.http.HttpUpgrade$HttpUpgradeState$UpgradeResultListener.handleEvent(HttpUpgrade.java:400) <del> // at org.xnio.ChannelListeners.invokeChannelListener(ChannelListeners.java:92) <del> <del> return; <del> } <del> testEcho(new UndertowWebSocketClient()); <del> } <del> <del> private void testEcho(WebSocketClient client) throws URISyntaxException { <add> public void echo() throws Exception { <ide> int count = 100; <ide> Flux<String> input = Flux.range(1, count).map(index -> "msg-" + index); <ide> ReplayProcessor<Object> output = ReplayProcessor.create(count); <ide> private void testEcho(WebSocketClient client) throws URISyntaxException { <ide> } <ide> <ide> @Test <del> @Ignore("https://github.com/reactor/reactor-netty/issues/20") <del> public void subProtocolReactorClient() throws Exception { <del> testSubProtocol(new ReactorNettyWebSocketClient()); <del> } <del> <del> @Test <del> public void subProtocolRxNettyClient() throws Exception { <del> testSubProtocol(new RxNettyWebSocketClient()); <del> } <del> <del> @Test <del> public void subProtocolJettyClient() throws Exception { <del> JettyWebSocketClient client = new JettyWebSocketClient(); <del> client.start(); <del> testSubProtocol(client); <del> client.stop(); <del> } <add> public void subProtocol() throws Exception { <ide> <del> @Test <del> public void subProtocolStandardClient() throws Exception { <del> testSubProtocol(new StandardWebSocketClient()); <del> } <add> // TODO <add> // https://github.com/reactor/reactor-netty/issues/20 <add> assumeFalse(client instanceof ReactorNettyWebSocketClient); <ide> <del> @Test <del> public void subProtocolUndertowClient() throws Exception { <del> if (server instanceof RxNettyHttpServer) { <del> // Caused by: java.io.IOException: Upgrade responses cannot have a transfer coding <del> // at org.xnio.http.HttpUpgrade$HttpUpgradeState.handleUpgrade(HttpUpgrade.java:490) <del> // at org.xnio.http.HttpUpgrade$HttpUpgradeState.access$1200(HttpUpgrade.java:165) <del> // at org.xnio.http.HttpUpgrade$HttpUpgradeState$UpgradeResultListener.handleEvent(HttpUpgrade.java:461) <del> // at org.xnio.http.HttpUpgrade$HttpUpgradeState$UpgradeResultListener.handleEvent(HttpUpgrade.java:400) <del> // at org.xnio.ChannelListeners.invokeChannelListener(ChannelListeners.java:92) <del> <del> return; <del> } <del> testSubProtocol(new UndertowWebSocketClient()); <del> } <del> <del> private void testSubProtocol(WebSocketClient client) throws URISyntaxException { <ide> String protocol = "echo-v1"; <ide> AtomicReference<HandshakeInfo> infoRef = new AtomicReference<>(); <ide> MonoProcessor<Object> output = MonoProcessor.create(); <ide> public Mono<Void> handle(WebSocketSession session) { <ide> } <ide> <ide> @Test <del> public void customHeaderReactorClient() throws Exception { <del> testCustomHeader(new ReactorNettyWebSocketClient()); <del> } <del> <del> @Test <del> public void customHeaderRxNettyClient() throws Exception { <del> testCustomHeader(new RxNettyWebSocketClient()); <del> } <del> <del> @Test <del> @Ignore <del> public void customHeaderJettyClient() throws Exception { <del> JettyWebSocketClient client = new JettyWebSocketClient(); <del> client.start(); <del> testCustomHeader(client); <del> client.stop(); <del> } <del> <del> @Test <del> public void customHeaderStandardClient() throws Exception { <del> testCustomHeader(new StandardWebSocketClient()); <del> } <del> <del> @Test <del> public void customHeaderUndertowClient() throws Exception { <del> if (server instanceof RxNettyHttpServer) { <del> // Caused by: java.io.IOException: Upgrade responses cannot have a transfer coding <del> // at org.xnio.http.HttpUpgrade$HttpUpgradeState.handleUpgrade(HttpUpgrade.java:490) <del> // at org.xnio.http.HttpUpgrade$HttpUpgradeState.access$1200(HttpUpgrade.java:165) <del> // at org.xnio.http.HttpUpgrade$HttpUpgradeState$UpgradeResultListener.handleEvent(HttpUpgrade.java:461) <del> // at org.xnio.http.HttpUpgrade$HttpUpgradeState$UpgradeResultListener.handleEvent(HttpUpgrade.java:400) <del> // at org.xnio.ChannelListeners.invokeChannelListener(ChannelListeners.java:92) <del> <del> return; <del> } <del> testCustomHeader(new UndertowWebSocketClient()); <del> } <add> public void customHeader() throws Exception { <ide> <del> private void testCustomHeader(WebSocketClient client) throws Exception { <add> // TODO <add> assumeFalse(client instanceof JettyWebSocketClient); <ide> <ide> HttpHeaders headers = new HttpHeaders(); <ide> headers.add("my-header", "my-value");
2
Mixed
Javascript
enable autodestroy by default
4bec6d13f9e9068fba778d0c806a2ca1335c8180
<ide><path>doc/api/stream.md <ide> added: v0.9.4 <ide> The `'error'` event is emitted if an error occurred while writing or piping <ide> data. The listener callback is passed a single `Error` argument when called. <ide> <del>The stream is not closed when the `'error'` event is emitted unless the <del>[`autoDestroy`][writable-new] option was set to `true` when creating the <add>The stream is closed when the `'error'` event is emitted unless the <add>[`autoDestroy`][writable-new] option was set to `false` when creating the <ide> stream. <ide> <ide> After `'error'`, no further events other than `'close'` *should* be emitted <ide> const { Writable } = require('stream'); <ide> <ide> class MyWritable extends Writable { <ide> constructor({ highWaterMark, ...options }) { <del> super({ <del> highWaterMark, <del> autoDestroy: true, <del> emitClose: true <del> }); <add> super({ highWaterMark }); <ide> // ... <ide> } <ide> } <ide> changes: <ide> pr-url: https://github.com/nodejs/node/pull/22795 <ide> description: Add `autoDestroy` option to automatically `destroy()` the <ide> stream when it emits `'finish'` or errors. <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/30623 <add> description: Change `autoDestroy` option default to `true`. <ide> --> <ide> <ide> * `options` {Object} <ide> changes: <ide> * `final` {Function} Implementation for the <ide> [`stream._final()`][stream-_final] method. <ide> * `autoDestroy` {boolean} Whether this stream should automatically call <del> `.destroy()` on itself after ending. **Default:** `false`. <add> `.destroy()` on itself after ending. **Default:** `true`. <ide> <ide> <!-- eslint-disable no-useless-constructor --> <ide> ```js <ide> changes: <ide> pr-url: https://github.com/nodejs/node/pull/22795 <ide> description: Add `autoDestroy` option to automatically `destroy()` the <ide> stream when it emits `'end'` or errors. <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/30623 <add> description: Change `autoDestroy` option default to `true`. <ide> --> <ide> <ide> * `options` {Object} <ide> changes: <ide> * `destroy` {Function} Implementation for the <ide> [`stream._destroy()`][readable-_destroy] method. <ide> * `autoDestroy` {boolean} Whether this stream should automatically call <del> `.destroy()` on itself after ending. **Default:** `false`. <add> `.destroy()` on itself after ending. **Default:** `true`. <ide> <ide> <!-- eslint-disable no-useless-constructor --> <ide> ```js <ide><path>lib/_http_incoming.js <ide> function IncomingMessage(socket) { <ide> }; <ide> } <ide> <del> Stream.Readable.call(this, streamOptions); <add> Stream.Readable.call(this, { autoDestroy: false, ...streamOptions }); <ide> <ide> this._readableState.readingMore = true; <ide> <ide><path>lib/_stream_readable.js <ide> function ReadableState(options, stream, isDuplex) { <ide> this.emitClose = !options || options.emitClose !== false; <ide> <ide> // Should .destroy() be called after 'end' (and potentially 'finish') <del> this.autoDestroy = !!(options && options.autoDestroy); <add> this.autoDestroy = !options || options.autoDestroy !== false; <ide> <ide> // Has it been destroyed <ide> this.destroyed = false; <ide> Readable.prototype._destroy = function(err, cb) { <ide> }; <ide> <ide> Readable.prototype[EE.captureRejectionSymbol] = function(err) { <del> // TODO(mcollina): remove the destroyed if once errorEmitted lands in <del> // Readable. <del> if (!this.destroyed) { <del> this.destroy(err); <del> } <add> this.destroy(err); <ide> }; <ide> <ide> // Manually shove something into the read() buffer. <ide><path>lib/_stream_writable.js <ide> function WritableState(options, stream, isDuplex) { <ide> this.emitClose = !options || options.emitClose !== false; <ide> <ide> // Should .destroy() be called after 'finish' (and potentially 'end') <del> this.autoDestroy = !!(options && options.autoDestroy); <add> this.autoDestroy = !options || options.autoDestroy !== false; <ide> <ide> // Indicates whether the stream has errored. When true all write() calls <ide> // should return false. This is needed since when autoDestroy <ide><path>lib/internal/fs/streams.js <ide> function ReadStream(path, options) { <ide> if (options.emitClose === undefined) { <ide> options.emitClose = false; <ide> } <add> if (options.autoDestroy === undefined) { <add> options.autoDestroy = false; <add> } <ide> <ide> this[kFs] = options.fs || fs; <ide> <ide> function WriteStream(path, options) { <ide> if (options.emitClose === undefined) { <ide> options.emitClose = false; <ide> } <add> if (options.autoDestroy === undefined) { <add> options.autoDestroy = false; <add> } <ide> <ide> this[kFs] = options.fs || fs; <ide> if (typeof this[kFs].open !== 'function') { <ide><path>lib/internal/http2/compat.js <ide> function onStreamTimeout(kind) { <ide> <ide> class Http2ServerRequest extends Readable { <ide> constructor(stream, headers, options, rawHeaders) { <del> super(options); <add> super({ autoDestroy: false, ...options }); <ide> this[kState] = { <ide> closed: false, <ide> didRead: false, <ide><path>lib/internal/http2/core.js <ide> class Http2Stream extends Duplex { <ide> constructor(session, options) { <ide> options.allowHalfOpen = true; <ide> options.decodeStrings = false; <add> options.autoDestroy = false; <ide> super(options); <ide> this[async_id_symbol] = -1; <ide> <ide><path>lib/net.js <ide> function Socket(options) { <ide> options.allowHalfOpen = true; <ide> // For backwards compat do not emit close on destroy. <ide> options.emitClose = false; <add> options.autoDestroy = false; <ide> // Handle strings directly. <ide> options.decodeStrings = false; <ide> stream.Duplex.call(this, options); <ide><path>lib/zlib.js <ide> function ZlibBase(opts, mode, handle, { flush, finishFlush, fullFlush }) { <ide> } <ide> } <ide> <del> Transform.call(this, opts); <add> Transform.call(this, { autoDestroy: false, ...opts }); <ide> this._hadError = false; <ide> this.bytesWritten = 0; <ide> this._handle = handle; <ide><path>test/parallel/test-stream-pipe-error-handling.js <ide> const Stream = require('stream').Stream; <ide> const R = Stream.Readable; <ide> const W = Stream.Writable; <ide> <del> const r = new R(); <del> const w = new W(); <add> const r = new R({ autoDestroy: false }); <add> const w = new W({ autoDestroy: false }); <ide> let removed = false; <ide> <ide> r._read = common.mustCall(function() { <ide><path>test/parallel/test-stream-unshift-read-race.js <ide> const assert = require('assert'); <ide> <ide> const stream = require('stream'); <ide> const hwm = 10; <del>const r = stream.Readable({ highWaterMark: hwm }); <add>const r = stream.Readable({ highWaterMark: hwm, autoDestroy: false }); <ide> const chunks = 10; <ide> <ide> const data = Buffer.allocUnsafe(chunks * hwm + Math.ceil(hwm / 2)); <ide><path>test/parallel/test-stream-writable-null.js <ide> const assert = require('assert'); <ide> const stream = require('stream'); <ide> <ide> class MyWritable extends stream.Writable { <add> constructor(options) { <add> super({ autoDestroy: false, ...options }); <add> } <ide> _write(chunk, encoding, callback) { <ide> assert.notStrictEqual(chunk, null); <ide> callback(); <ide><path>test/parallel/test-stream-writable-write-cb-twice.js <ide> 'use strict'; <ide> const common = require('../common'); <ide> const { Writable } = require('stream'); <del>const assert = require('assert'); <ide> <ide> { <ide> // Sync + Sync <ide> const writable = new Writable({ <ide> write: common.mustCall((buf, enc, cb) => { <ide> cb(); <del> assert.throws(cb, { <del> code: 'ERR_MULTIPLE_CALLBACK', <del> name: 'Error' <del> }); <add> cb(); <ide> }) <ide> }); <ide> writable.write('hi'); <add> writable.on('error', common.expectsError({ <add> code: 'ERR_MULTIPLE_CALLBACK', <add> name: 'Error' <add> })); <ide> } <ide> <ide> { <ide> const assert = require('assert'); <ide> write: common.mustCall((buf, enc, cb) => { <ide> cb(); <ide> process.nextTick(() => { <del> assert.throws(cb, { <del> code: 'ERR_MULTIPLE_CALLBACK', <del> name: 'Error' <del> }); <add> cb(); <ide> }); <ide> }) <ide> }); <ide> writable.write('hi'); <add> writable.on('error', common.expectsError({ <add> code: 'ERR_MULTIPLE_CALLBACK', <add> name: 'Error' <add> })); <ide> } <ide> <ide> { <ide> const assert = require('assert'); <ide> write: common.mustCall((buf, enc, cb) => { <ide> process.nextTick(cb); <ide> process.nextTick(() => { <del> assert.throws(cb, { <del> code: 'ERR_MULTIPLE_CALLBACK', <del> name: 'Error' <del> }); <add> cb(); <ide> }); <ide> }) <ide> }); <ide> writable.write('hi'); <add> writable.on('error', common.expectsError({ <add> code: 'ERR_MULTIPLE_CALLBACK', <add> name: 'Error' <add> })); <ide> } <ide><path>test/parallel/test-stream2-pipe-error-handling.js <ide> const stream = require('stream'); <ide> stream.Readable.prototype.unpipe.call(this, dest); <ide> }; <ide> <del> const dest = new stream.Writable(); <add> const dest = new stream.Writable({ autoDestroy: false }); <ide> dest._write = function(chunk, encoding, cb) { <ide> cb(); <ide> }; <ide><path>test/parallel/test-stream2-writable.js <ide> const helloWorldBuffer = Buffer.from('hello world'); <ide> <ide> { <ide> // Verify writables cannot be piped <del> const w = new W(); <add> const w = new W({ autoDestroy: false }); <ide> w._write = common.mustNotCall(); <ide> let gotError = false; <ide> w.on('error', function() {
15
Ruby
Ruby
move the yaml hook closer to `init_with`
b71732c84a4bb5f8f7cbf65c5193db97c7e31eca
<ide><path>actionpack/lib/action_controller/metal/strong_parameters.rb <ide> require 'set' <ide> require 'yaml' <ide> <del># Wire up YAML format compatibility with Rails 4.2. Makes the YAML parser call <del># `init_with` when it encounters `!ruby/hash-with-ivars:ActionController::Parameters`, <del># instead of trying to parse it as a regular hash subclass. <del># Second `load_tags` is for compatibility with Psych prior to 2.0.9 where hashes <del># were dumped without instance variables. <del>YAML.load_tags['!ruby/hash-with-ivars:ActionController::Parameters'] = 'ActionController::Parameters' <del>YAML.load_tags['!ruby/hash:ActionController::Parameters'] = 'ActionController::Parameters' <del> <ide> module ActionController <ide> # Raised when a required parameter is missing. <ide> # <ide> def inspect <ide> "<#{self.class} #{@parameters} permitted: #{@permitted}>" <ide> end <ide> <add> def self.hook_into_yaml_loading # :nodoc: <add> # Wire up YAML format compatibility with Rails 4.2 and Psych 2.0.8 and 2.0.9+. <add> # Makes the YAML parser call `init_with` when it encounters the keys below <add> # instead of trying its own parsing routines. <add> YAML.load_tags['!ruby/hash-with-ivars:ActionController::Parameters'] = name <add> YAML.load_tags['!ruby/hash:ActionController::Parameters'] = name <add> end <add> hook_into_yaml_loading <add> <ide> def init_with(coder) # :nodoc: <ide> case coder.tag <ide> when '!ruby/hash:ActionController::Parameters'
1
Ruby
Ruby
register autload for deduplicable
d6895fb8b4cb83d85dfcb690e87764044e02ea65
<ide><path>activerecord/lib/active_record/connection_adapters.rb <ide> module ConnectionAdapters <ide> autoload :PoolManager <ide> autoload :LegacyPoolManager <ide> autoload :SchemaCache <add> autoload :Deduplicable <ide> <ide> autoload_at "active_record/connection_adapters/abstract/schema_definitions" do <ide> autoload :IndexDefinition <ide><path>activerecord/lib/active_record/connection_adapters/sql_type_metadata.rb <ide> # frozen_string_literal: true <ide> <del>require "active_record/connection_adapters/deduplicable" <del> <ide> module ActiveRecord <ide> # :stopdoc: <ide> module ConnectionAdapters
2
Javascript
Javascript
add note about blackboxing
bf0af6dbb16d9c405338d48bc6f194626c99c4f3
<ide><path>src/ng/log.js <ide> * <ide> * The main purpose of this service is to simplify debugging and troubleshooting. <ide> * <add> * To reveal the location of the calls to `$log` in the JavaScript console, <add> * you can "blackbox" the AngularJS source in your browser: <add> * <add> * [Mozilla description of blackboxing](https://developer.mozilla.org/en-US/docs/Tools/Debugger/How_to/Black_box_a_source). <add> * [Chrome description of blackboxing](https://developer.chrome.com/devtools/docs/blackboxing). <add> * <add> * Note: Not all browsers support blackboxing. <add> * <ide> * The default is to log `debug` messages. You can use <ide> * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this. <ide> *
1
Javascript
Javascript
fix typo in animationclip
ae1573e26cf78e41e9eef5d4afd9111dba20229b
<ide><path>src/animation/AnimationClip.js <ide> Object.assign( AnimationClip, { <ide> var times = []; <ide> var values = []; <ide> <del> for ( var m = 0; <del> m !== animationKeys[k].morphTargets.length; ++ m ) { <add> for ( var m = 0; m !== animationKeys[k].morphTargets.length; ++ m ) { <ide> <ide> var animationKey = animationKeys[k]; <ide> <ide> Object.assign( AnimationClip, { <ide> <ide> } <ide> <del> tracks.push( new NumberKeyframeTrack( <del> '.morphTargetInfluence[' + morphTargetName + ']', times, values ) ); <add> tracks.push( new NumberKeyframeTrack('.morphTargetInfluence[' + morphTargetName + ']', times, values ) ); <ide> <ide> } <ide>
1
Javascript
Javascript
remove unused variables
28f6fcb763266ecd476274f430cce0ef625f8b16
<ide><path>src/manipulation.js <ide> var rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, <ide> rtagName = /<([\w:]+)/, <del> rtbody = /<tbody/i, <ide> rhtml = /<|&#?\w+;/, <ide> rnoInnerhtml = /<(?:script|style|link)/i, <ide> manipulation_rcheckableType = /^(?:checkbox|radio)$/i, <ide> jQuery.extend({ <ide> }, <ide> <ide> clean: function( elems, context, fragment, scripts, selection ) { <del> var elem, i, j, tmp, tag, wrap, tbody, <add> var elem, i, j, tmp, tag, wrap, <ide> ret = [], <ide> container = context === document && fragment; <ide>
1
Python
Python
add percentile function
44b42db55290aedbf3e30ef2de81d0bccc547a04
<ide><path>numpy/lib/function_base.py <ide> __docformat__ = "restructuredtext en" <ide> __all__ = ['select', 'piecewise', 'trim_zeros', <del> 'copy', 'iterable', <add> 'copy', 'iterable', 'percentile', <ide> 'diff', 'gradient', 'angle', 'unwrap', 'sort_complex', 'disp', <ide> 'extract', 'place', 'nansum', 'nanmax', 'nanargmax', <ide> 'nanargmin', 'nanmin', 'vectorize', 'asarray_chkfinite', 'average', <ide> def median(a, axis=None, out=None, overwrite_input=False): <ide> <ide> See Also <ide> -------- <del> mean <add> mean, percentile <ide> <ide> Notes <ide> ----- <ide> def median(a, axis=None, out=None, overwrite_input=False): <ide> # and check, use out array. <ide> return mean(sorted[indexer], axis=axis, out=out) <ide> <add>def percentile(a, q, axis=None, out=None, overwrite_input=False): <add> """ <add> Compute the qth percentile of the data along the specified axis. <add> <add> Returns the qth percentile of the array elements. <add> <add> Parameters <add> ---------- <add> a : array_like <add> Input array or object that can be converted to an array. <add> q : float in range of [0,100] (or sequence of floats) <add> percentile to compute which must be between 0 and 100 inclusive <add> axis : {None, int}, optional <add> Axis along which the percentiles are computed. The default (axis=None) <add> is to compute the median along a flattened version of the array. <add> out : ndarray, optional <add> Alternative output array in which to place the result. It must <add> have the same shape and buffer length as the expected output, <add> but the type (of the output) will be cast if necessary. <add> overwrite_input : {False, True}, optional <add> If True, then allow use of memory of input array (a) for <add> calculations. The input array will be modified by the call to <add> median. This will save memory when you do not need to preserve <add> the contents of the input array. Treat the input as undefined, <add> but it will probably be fully or partially sorted. Default is <add> False. Note that, if `overwrite_input` is True and the input <add> is not already an ndarray, an error will be raised. <add> <add> Returns <add> ------- <add> pcntile : ndarray <add> A new array holding the result (unless `out` is specified, in <add> which case that array is returned instead). If the input contains <add> integers, or floats of smaller precision than 64, then the output <add> data-type is float64. Otherwise, the output data-type is the same <add> as that of the input. <add> <add> See Also <add> -------- <add> mean, median <add> <add> Notes <add> ----- <add> Given a vector V of length N, the qth percentile of V is the qth ranked <add> value in a sorted copy of V. A weighted average of the two nearest neighbors <add> is used if the normalized ranking does not match q exactly. <add> The same as the median if q is 0.5; the same as the min if q is 0; <add> and the same as the max if q is 1 <add> <add> Examples <add> -------- <add> >>> a = np.array([[10, 7, 4], [3, 2, 1]]) <add> >>> a <add> array([[10, 7, 4], <add> [ 3, 2, 1]]) <add> >>> np.percentile(a, 0.5) <add> 3.5 <add> >>> np.percentile(a, 0.5, axis=0) <add> array([ 6.5, 4.5, 2.5]) <add> >>> np.percentile(a, 0.5, axis=1) <add> array([ 7., 2.]) <add> >>> m = np.percentile(a, 0.5, axis=0) <add> >>> out = np.zeros_like(m) <add> >>> np.percentile(a, 0.5, axis=0, out=m) <add> array([ 6.5, 4.5, 2.5]) <add> >>> m <add> array([ 6.5, 4.5, 2.5]) <add> >>> b = a.copy() <add> >>> np.percentile(b, 0.5, axis=1, overwrite_input=True) <add> array([ 7., 2.]) <add> >>> assert not np.all(a==b) <add> >>> b = a.copy() <add> >>> np.percentile(b, 0.5, axis=None, overwrite_input=True) <add> 3.5 <add> >>> assert not np.all(a==b) <add> <add> """ <add> if q == 0: <add> return a.min(axis=axis, out=out) <add> elif q == 100: <add> return a.max(axis=axis, out=out) <add> <add> if overwrite_input: <add> if axis is None: <add> sorted = a.ravel() <add> sorted.sort() <add> else: <add> a.sort(axis=axis) <add> sorted = a <add> else: <add> sorted = sort(a, axis=axis) <add> if axis is None: <add> axis = 0 <add> <add> return _compute_qth_percentile(sorted, q, axis, out) <add> <add># handle sequence of q's without calling sort multiple times <add>def _compute_qth_percentile(sorted, q, axis, out): <add> if not isscalar(q): <add> return [_compute_qth_percentile(sorted, qi, axis, out) <add> for qi in q] <add> q = q / 100.0 <add> if (q < 0) or (q > 1): <add> raise ValueError, "percentile must be either in the range [0,100]" <add> <add> indexer = [slice(None)] * sorted.ndim <add> Nx = sorted.shape[axis] <add> index = q*(Nx-1) <add> i = int(index) <add> if i == index: <add> indexer[axis] = slice(i, i+1) <add> weights = array(1) <add> sumval = 1.0 <add> else: <add> indexer[axis] = slice(i, i+2) <add> j = i + 1 <add> weights = array([(j - index), (index - i)],float) <add> wshape = [1]*sorted.ndim <add> wshape[axis] = 2 <add> weights.shape = wshape <add> sumval = weights.sum() <add> <add> # Use add.reduce in both cases to coerce data type as well as <add> # check and use out array. <add> return add.reduce(sorted[indexer]*weights, axis=axis, out=out)/sumval <add> <ide> def trapz(y, x=None, dx=1.0, axis=-1): <ide> """ <ide> Integrate along the given axis using the composite trapezoidal rule.
1
Javascript
Javascript
fix net keepalive and nodelay
8e19dab677e64ec5ba40ab8523d23d02c92a24a2
<ide><path>lib/net.js <ide> Socket.prototype.setKeepAlive = function(enable, initialDelayMsecs) { <ide> return this; <ide> } <ide> <del> if (this._handle.setKeepAlive && enable !== this[kSetKeepAlive]) { <add> if (!this._handle.setKeepAlive) { <add> return this; <add> } <add> <add> if (enable !== this[kSetKeepAlive] || <add> ( <add> enable && <add> this[kSetKeepAliveInitialDelay] !== initialDelay <add> ) <add> ) { <ide> this[kSetKeepAlive] = enable; <ide> this[kSetKeepAliveInitialDelay] = initialDelay; <ide> this._handle.setKeepAlive(enable, initialDelay); <ide> function onconnection(err, clientHandle) { <ide> }); <ide> <ide> if (self.noDelay && clientHandle.setNoDelay) { <add> socket[kSetNoDelay] = true; <ide> clientHandle.setNoDelay(true); <ide> } <ide> if (self.keepAlive && clientHandle.setKeepAlive) { <add> socket[kSetKeepAlive] = true; <add> socket[kSetKeepAliveInitialDelay] = self.keepAliveInitialDelay; <ide> clientHandle.setKeepAlive(true, self.keepAliveInitialDelay); <ide> } <ide> <ide><path>test/parallel/test-net-server-keepalive.js <ide> const server = net.createServer({ <ide> keepAlive: true, <ide> keepAliveInitialDelay: 1000 <ide> }, common.mustCall((socket) => { <add> const setKeepAlive = socket._handle.setKeepAlive; <add> socket._handle.setKeepAlive = common.mustCall((enable, initialDelay) => { <add> assert.strictEqual(enable, true); <add> assert.match(String(initialDelay), /^2|3$/); <add> return setKeepAlive.call(socket._handle, enable, initialDelay); <add> }, 2); <add> socket.setKeepAlive(true, 1000); <add> socket.setKeepAlive(true, 2000); <add> socket.setKeepAlive(true, 3000); <ide> socket.destroy(); <ide> server.close(); <ide> })).listen(0, common.mustCall(() => { <ide> server._handle.onconnection = common.mustCall((err, clientHandle) => { <ide> assert.strictEqual(enable, server.keepAlive); <ide> assert.strictEqual(initialDelayMsecs, server.keepAliveInitialDelay); <ide> setKeepAlive.call(clientHandle, enable, initialDelayMsecs); <add> clientHandle.setKeepAlive = setKeepAlive; <ide> }); <ide> onconnection.call(server._handle, err, clientHandle); <ide> }); <ide><path>test/parallel/test-net-server-nodelay.js <ide> const net = require('net'); <ide> const server = net.createServer({ <ide> noDelay: true <ide> }, common.mustCall((socket) => { <add> socket._handle.setNoDelay = common.mustNotCall(); <add> socket.setNoDelay(true); <ide> socket.destroy(); <ide> server.close(); <ide> })).listen(0, common.mustCall(() => { <ide> server._handle.onconnection = common.mustCall((err, clientHandle) => { <ide> clientHandle.setNoDelay = common.mustCall((enable) => { <ide> assert.strictEqual(enable, server.noDelay); <ide> setNoDelay.call(clientHandle, enable); <add> clientHandle.setNoDelay = setNoDelay; <ide> }); <ide> onconnection.call(server._handle, err, clientHandle); <ide> });
3
Text
Text
fix items orderting in nativecomponentsandroid.md
0b9c704544330b34477ae9a07a32eda183678ce8
<ide><path>docs/NativeComponentsAndroid.md <ide> Setter declaration requirements for methods annotated with `@ReactPropGroup` are <ide> } <ide> ``` <ide> <del>## 5. Register the `ViewManager` <add>## 4. Register the `ViewManager` <ide> <ide> The final Java step is to register the ViewManager to the application, this happens in a similar way to [Native Modules](NativeModulesAndroid.md), via the applications package member function `createViewManagers.` <ide> <ide> The final Java step is to register the ViewManager to the application, this happ <ide> } <ide> ``` <ide> <del>## 6. Implement the JavaScript module <add>## 5. Implement the JavaScript module <ide> <ide> The very final step is to create the JavaScript module that defines the interface layer between Java and JavaScript for the users of your new view. Much of the effort is handled by internal React code in Java and JavaScript and all that is left for you is to describe the `propTypes`. <ide>
1
Text
Text
update chinese translation of fornt-end-libraries
797cc3024e286c4d87a3ad920562de2066e7c8de
<ide><path>curriculum/challenges/chinese/03-front-end-libraries/bootstrap/use-comments-to-clarify-code.md <ide> forumTopicId: 18347 <ide> <ide> 我们必须确保让每个人都知道,他们不应该直接修改此页面上这些代码。 <ide> <del>记住,你可以在 `<!--` 为开始,`-->` 为结束的地方进行评论注释(像这样,`<!-- 我是一段注释 -->`)。 <add>记住,你可以在 `<!--` 为开始,`-->` 为结束的地方进行评论注释。 <ide> <del>请你在你的 HTML 顶部加如下一段注释: `Only change code above this line.` 。 <add>请你在你的 HTML 顶部加如下一段注释: `Code below this line should not be changed` 。 <ide> <ide> # --hints-- <ide> <ide> forumTopicId: 18347 <ide> assert(code.match(/^\s*<!--/)); <ide> ``` <ide> <del>注释内容应该为 `Only change code above this line`。 <add>注释内容应该为 `Code below this line should not be changed`。 <ide> <ide> ```js <ide> assert(code.match(/<!--(?!(>|->|.*-->.*this line))\s*.*this line.*\s*-->/gi)); <ide> assert(code.match(/-->.*\n+.+/g)); <ide> assert(code.match(/<!--/g).length === code.match(/-->/g).length); <ide> ``` <ide> <add># --seed-- <add> <add>## --seed-contents-- <add> <add>```html <add><div class="container-fluid"> <add> <h3 class="text-primary text-center">jQuery Playground</h3> <add> <div class="row"> <add> <div class="col-xs-6"> <add> <h4>#left-well</h4> <add> <div class="well" id="left-well"> <add> <button class="btn btn-default target" id="target1">#target1</button> <add> <button class="btn btn-default target" id="target2">#target2</button> <add> <button class="btn btn-default target" id="target3">#target3</button> <add> </div> <add> </div> <add> <div class="col-xs-6"> <add> <h4>#right-well</h4> <add> <div class="well" id="right-well"> <add> <button class="btn btn-default target" id="target4">#target4</button> <add> <button class="btn btn-default target" id="target5">#target5</button> <add> <button class="btn btn-default target" id="target6">#target6</button> <add> </div> <add> </div> <add> </div> <add></div> <add>``` <add> <ide> # --solutions-- <ide> <add>```html <add><!-- Code below this line should not be changed --> <add><div class="container-fluid"> <add> <h3 class="text-primary text-center">jQuery Playground</h3> <add> <div class="row"> <add> <div class="col-xs-6"> <add> <h4>#left-well</h4> <add> <div class="well" id="left-well"> <add> <button class="btn btn-default target" id="target1">#target1</button> <add> <button class="btn btn-default target" id="target2">#target2</button> <add> <button class="btn btn-default target" id="target3">#target3</button> <add> </div> <add> </div> <add> <div class="col-xs-6"> <add> <h4>#right-well</h4> <add> <div class="well" id="right-well"> <add> <button class="btn btn-default target" id="target4">#target4</button> <add> <button class="btn btn-default target" id="target5">#target5</button> <add> <button class="btn btn-default target" id="target6">#target6</button> <add> </div> <add> </div> <add> </div> <add></div> <add>``` <ide><path>curriculum/challenges/chinese/03-front-end-libraries/front-end-libraries-projects/build-a-drum-machine.md <ide> forumTopicId: 301370 <ide> <ide> **需求 7:** 当触发一个具有`.drum-pad`属性的元素时,`#display`元素内应该展示这个触发元素关联音频片段的描述字符串(每一个字符串都应该是独一无二的)。 <ide> <del>你可以 fork [这个 CodePen pen 项目](http://codepen.io/freeCodeCamp/pen/MJjpwO) 来构建你的项目。或者你可以在任何你喜欢的环境中使用以下 CDN 链接来运行测试:`https://gitcdn.link/repo/freeCodeCamp/testable-projects-fcc/master/build/bundle.js`。 <add>你可以 fork [这个 CodePen pen 项目](http://codepen.io/freeCodeCamp/pen/MJjpwO) 来构建你的项目。或者你可以在任何你喜欢的环境中使用以下 CDN 链接来运行测试:`https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js`。 <ide> <ide> 一旦你完成了本项目并且该项目所有测试运行通过,请提交项目的 URL。 <ide> <ide> # --hints-- <ide> <ide> <add># --seed-- <ide> # --solutions-- <ide> <add>```js <add>// solution required <add>``` <ide><path>curriculum/challenges/chinese/03-front-end-libraries/front-end-libraries-projects/build-a-javascript-calculator.md <ide> forumTopicId: 301371 <ide> <ide> **需求 3:** 我的计算器应该包含四个可以点击的元素,文本内容对应4个主要数学运算符,且应具有如下 id 属性: `id="add"`, `id="subtract"`, `id="multiply"`, `id="divide"`。 <ide> <del>**需求 4:** 计算器应该包含一个可点击的\`.\`(小数点)符号,对应的`id="decimal"`。 <add>**需求 4:** 计算器应该包含一个可点击的 `.`(小数点)符号,对应的`id="decimal"`。 <ide> <ide> **需求 5:** 我的计算器应该包含一个具有`id="clear"`属性的可以点击的元素。 <ide> <ide> forumTopicId: 301371 <ide> <ide> **需求 9:** 我应该可以在任意顺序下对一串任意长度的数字执行加、减、乘、除操作,并且当我按下`=`时,正确答案应该显示在 id 为`display`的元素中。 <ide> <del>**需求 10:** 在我输入数字的同时,我的计算器应该允许一个数字以多个零开头。 <add>**需求 10:** 在我输入数字的同时,我的计算器应该不允许一个数字以多个零开头。 <ide> <ide> **需求 11:** 当点击小数点元素时,当前展示的数值后面应该添加一个`.`符号;数字中不允许出现两个`.`符号。 <ide> <ide> **需求 12:** 我可以对包含小数点的数字执行任何四则运算(+、-、\*、/)。 <ide> <del>**需求 13:** 如果连续键入了两个及以上的运算符,应该执行最后一次键入的运算符。 <add>**需求 13:** 如果连续键入了两个及以上的运算符,应该执行最后一次键入的运算符(负数(-)运算符除外)。例如,如果输入 `5 + * 7 = `,结果应该是 `35` (等同于 5 \* 7);如果输入 `5 * - 5 =`,结果应该是 `-25`(等同于 5 x (-5))。 <ide> <ide> **需求 14:** 如果在按下`=`符号后继续按一个运算符,则应该在上一次计算结果的基础上进行新的计算。 <ide> <ide> forumTopicId: 301371 <ide> - **立即执行逻辑:** `11.5` <ide> - **公式/表达式逻辑:** `32.5` <ide> <del>你可以 fork [这个 CodePen pen 项目](http://codepen.io/freeCodeCamp/pen/MJjpwO) 来构建你的项目。或者你可以在任何你喜欢的环境中使用以下 CDN 链接来运行测试:`https://gitcdn.link/repo/freeCodeCamp/testable-projects-fcc/master/build/bundle.js`。 <add>你可以 fork [这个 CodePen pen 项目](http://codepen.io/freeCodeCamp/pen/MJjpwO) 来构建你的项目。或者你可以在任何你喜欢的环境中使用以下 CDN 链接来运行测试:`https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js`。 <ide> <ide> 一旦你完成了本项目并且该项目所有测试运行通过,请提交项目的 URL。 <ide> <ide> # --hints-- <ide> <ide> <add># --seed-- <add> <ide> # --solutions-- <ide> <add>```js <add>// solution required <add>``` <ide><path>curriculum/challenges/chinese/03-front-end-libraries/front-end-libraries-projects/build-a-markdown-previewer.md <ide> forumTopicId: 301372 <ide> <ide> **需求 3:** 当我在具有`#editor`属性的元素内输入文本时,具有`#preview`属性的元素应该同步更新展示我键入的内容。 <ide> <del>**需求 4:** 当我在具有`#editor`属性的元素内输入 Github 风格的 Markdown 内容时,文本应该以 HTML 的形式,把我所键入的内容渲染在具有`#preview`属性的元素中(提示:你不需要自己解析 Markdown——你可以引入一个叫做 Marked 的库来完成这项工作:<https://cdnjs.com/libraries/marked>)。 <add>**需求 4:** 当我在具有`#editor`属性的元素内输入 GitHub 风格的 markdown 内容时,文本应该以 HTML 的形式,把我所键入的内容渲染在具有`#preview`属性的元素中(提示:你不需要自己解析 Markdown——你可以引入一个叫做 Marked 的库来完成这项工作:<https://cdnjs.com/libraries/marked>)。 <ide> <ide> **需求 5:** 当我的 Markdown 预览器首次加载时,具有`#editor`属性的元素内的默认内容应该包含以下每个种类的至少一段有效的 Markdown 代码:标题(H1 标签)、次级标题(H2 标签)、链接、行内代码、代码块、列表、引用块、图片、加粗文本。 <ide> <ide> **需求 6:** 当我的 Markdown 预览器首次加载时,具有`#editor`属性的元素内容应该以 HTML 的形式渲染在具有`#preview`属性的元素中。 <ide> <ide> **可选需求(你无需通过这项测试):** 我的 Markdown 预览器能够解析回车符并且将他们以`br`(换行)元素的形式渲染出来。 <ide> <del>你可以 fork [这个 CodePen pen 项目](http://codepen.io/freeCodeCamp/pen/MJjpwO) 来构建你的项目。或者你可以在任何你喜欢的环境中使用以下 CDN 链接来运行测试:`https://gitcdn.link/repo/freeCodeCamp/testable-projects-fcc/master/build/bundle.js`。 <add>你可以 fork [这个 CodePen pen 项目](http://codepen.io/freeCodeCamp/pen/MJjpwO) 来构建你的项目。或者你可以在任何你喜欢的环境中使用以下 CDN 链接来运行测试:`https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js`。 <ide> <ide> 一旦你完成了本项目并且该项目所有测试运行通过,请提交项目的 URL。 <ide> <ide> # --hints-- <ide> <ide> <add># --seed-- <add> <ide> # --solutions-- <ide> <add>```js <add>// solution required <add>``` <ide><path>curriculum/challenges/chinese/03-front-end-libraries/front-end-libraries-projects/build-a-random-quote-machine.md <ide> id: bd7158d8c442eddfaeb5bd13 <ide> title: 构建一个随机引语生成器 <ide> challengeType: 3 <add>forumTopicId: 301374 <ide> --- <ide> <ide> # --description-- <ide> challengeType: 3 <ide> <ide> 在满足以下[需求](https://en.wikipedia.org/wiki/User_story)并能通过所有测试的前提下,你可以根据自己的喜好来美化你的 app。 <ide> <del>你可以使用 HTML、JavaScript、CSS、Bootstrap、SASS、React、Redux、jQuery 来完成这个挑战。但鉴于这个章节的学习内容与前端框架相关,推荐使用一款前端框架(比如 React)来完成这个挑战;不推荐你使用前面没有提到的技术,否则风险自负。我们有计划新增其他前端框架课程,例如 Angular 和 Vue,不过目前还没有这些内容。我们会接受并尽力处理你在使用建议的技术栈过程中遇到的问题。编码愉快! <add>你可以使用 HTML、JavaScript、CSS、Bootstrap、SASS、React、Redux、jQuery 来完成这个挑战。但鉴于这个章节的学习内容与前端框架相关,推荐使用一款前端框架(比如 React)来完成这个挑战;不推荐你使用前面没有提到的技术,否则风险自担。我们有计划新增其他前端框架课程,例如 Angular 和 Vue,不过目前还没有这些内容。我们会接受并尽力处理你在使用建议的技术栈过程中遇到的问题。编码愉快! <ide> <ide> **需求 1:** 我应该能看到一个具有`id="quote-box"`属性的包裹元素。 <ide> <ide> challengeType: 3 <ide> <ide> **需求 4:** 在`#quote-box`元素内,我应该能看到一个具有`id="new-quote"`属性的可点击元素。 <ide> <del>**需求 5:** 在`#quote-box`元素内,我应该能看到一个具有`id="tweet-quote"`属性的可点击元素。 <add>**需求 5:** 在`#quote-box`元素内,我应该能看到一个具有`id="tweet-quote"`属性的可点击 `a` 元素。 <ide> <ide> **需求 6:** 首次加载时,我的 App 应该在具有`id="text"`属性的元素内展示一条随机引语。 <ide> <ide> challengeType: 3 <ide> <ide> 一旦你完成了本项目并且该项目所有测试运行通过,请提交项目的 URL。 <ide> <add>**注意:** Twitter 不允许在 iframe 里加载链接。如果你的 tweet 不能加载,尝试在 `#tweet-quote` 元素上使用 `target="_blank"` 或者 `target="_top"` 属性。`target="_top"` 会替换当前 tab 页的内容,所以确保当前内容已经保存了。 <ide> # --hints-- <ide> <ide> <add># --seed-- <add> <ide> # --solutions-- <ide> <add>```js <add>// solution required <add>``` <ide><path>curriculum/challenges/chinese/03-front-end-libraries/jquery/change-text-inside-an-element-using-jquery.md <ide> jQuery 有一个`.html()`函数,你能用其在标签里添加 HTML 标签和 <ide> <ide> 请强调 id 为`target4`的按钮的文本。 <ide> <del>请查看此[链接](https://developer.mozilla.org/en/docs/Web/HTML/Element/em)来了解更多`<i>`和`<em>`的区别和用法。 <add>请查看此[链接](https://www.freecodecamp.org/news/html-elements-explained-what-are-html-tags/#em-elemen)来了解更多`<i>`和`<em>`的区别和用法。 <ide> <ide> 注意,`<i>`标签虽然传统上用来强调文本,但此后常用作图标的标签;`<em>`标签作为强调标签现在已被广泛接受。两者都可以应对本次挑战。 <ide> <ide><path>curriculum/challenges/chinese/03-front-end-libraries/react-and-redux/connect-redux-to-the-messages-app.md <ide> assert( <ide> ); <ide> ``` <ide> <del>`Presentational`组件应渲染`h2`、`input`、`button`、`ul`四个元素。 <add>`Presentational` 组件应该渲染到页面上。 <ide> <ide> ```js <ide> assert( <ide> assert( <ide> ); <ide> ``` <ide> <add># --seed-- <add> <add>## --after-user-code-- <add> <add>```jsx <add>ReactDOM.render(<AppWrapper />, document.getElementById('root')) <add>``` <add> <add>## --seed-contents-- <add> <add>```jsx <add>// Redux: <add>const ADD = 'ADD'; <add> <add>const addMessage = (message) => { <add> return { <add> type: ADD, <add> message: message <add> } <add>}; <add> <add>const messageReducer = (state = [], action) => { <add> switch (action.type) { <add> case ADD: <add> return [ <add> ...state, <add> action.message <add> ]; <add> default: <add> return state; <add> } <add>}; <add> <add>const store = Redux.createStore(messageReducer); <add> <add>// React: <add>class Presentational extends React.Component { <add> constructor(props) { <add> super(props); <add> this.state = { <add> input: '', <add> messages: [] <add> } <add> this.handleChange = this.handleChange.bind(this); <add> this.submitMessage = this.submitMessage.bind(this); <add> } <add> handleChange(event) { <add> this.setState({ <add> input: event.target.value <add> }); <add> } <add> submitMessage() { <add> this.setState((state) => { <add> const currentMessage = state.input; <add> return { <add> input: '', <add> messages: state.messages.concat(currentMessage) <add> }; <add> }); <add> } <add> render() { <add> return ( <add> <div> <add> <h2>Type in a new Message:</h2> <add> <input <add> value={this.state.input} <add> onChange={this.handleChange}/><br/> <add> <button onClick={this.submitMessage}>Submit</button> <add> <ul> <add> {this.state.messages.map( (message, idx) => { <add> return ( <add> <li key={idx}>{message}</li> <add> ) <add> }) <add> } <add> </ul> <add> </div> <add> ); <add> } <add>}; <add> <add>// React-Redux: <add>const mapStateToProps = (state) => { <add> return { messages: state } <add>}; <add> <add>const mapDispatchToProps = (dispatch) => { <add> return { <add> submitNewMessage: (newMessage) => { <add> dispatch(addMessage(newMessage)) <add> } <add> } <add>}; <add> <add>const Provider = ReactRedux.Provider; <add>const connect = ReactRedux.connect; <add> <add>// Define the Container component here: <add> <add> <add>class AppWrapper extends React.Component { <add> constructor(props) { <add> super(props); <add> } <add> render() { <add> // Complete the return statement: <add> return (null); <add> } <add>}; <add>``` <add> <ide> # --solutions-- <ide> <add>```jsx <add>// Redux: <add>const ADD = 'ADD'; <add> <add>const addMessage = (message) => { <add> return { <add> type: ADD, <add> message: message <add> } <add>}; <add> <add>const messageReducer = (state = [], action) => { <add> switch (action.type) { <add> case ADD: <add> return [ <add> ...state, <add> action.message <add> ]; <add> default: <add> return state; <add> } <add>}; <add> <add>const store = Redux.createStore(messageReducer); <add> <add>// React: <add>class Presentational extends React.Component { <add> constructor(props) { <add> super(props); <add> this.state = { <add> input: '', <add> messages: [] <add> } <add> this.handleChange = this.handleChange.bind(this); <add> this.submitMessage = this.submitMessage.bind(this); <add> } <add> handleChange(event) { <add> this.setState({ <add> input: event.target.value <add> }); <add> } <add> submitMessage() { <add> this.setState((state) => { <add> const currentMessage = state.input; <add> return { <add> input: '', <add> messages: state.messages.concat(currentMessage) <add> }; <add> }); <add> } <add> render() { <add> return ( <add> <div> <add> <h2>Type in a new Message:</h2> <add> <input <add> value={this.state.input} <add> onChange={this.handleChange}/><br/> <add> <button onClick={this.submitMessage}>Submit</button> <add> <ul> <add> {this.state.messages.map( (message, idx) => { <add> return ( <add> <li key={idx}>{message}</li> <add> ) <add> }) <add> } <add> </ul> <add> </div> <add> ); <add> } <add>}; <add> <add>// React-Redux: <add>const mapStateToProps = (state) => { <add> return { messages: state } <add>}; <add> <add>const mapDispatchToProps = (dispatch) => { <add> return { <add> submitNewMessage: (newMessage) => { <add> dispatch(addMessage(newMessage)) <add> } <add> } <add>}; <add> <add>const Provider = ReactRedux.Provider; <add>const connect = ReactRedux.connect; <add> <add>const Container = connect(mapStateToProps, mapDispatchToProps)(Presentational); <add> <add>class AppWrapper extends React.Component { <add> constructor(props) { <add> super(props); <add> } <add> render() { <add> return ( <add> <Provider store={store}> <add> <Container/> <add> </Provider> <add> ); <add> } <add>}; <add>``` <ide><path>curriculum/challenges/chinese/03-front-end-libraries/react/introducing-inline-styles.md <ide> forumTopicId: 301395 <ide> <ide> # --description-- <ide> <del>还有其他复杂的概念可以为你的 React 代码增加强大的功能。但是,你可能会想知道更简单的问题,比如:如何对在 React 中创建的 JSX 元素进行风格化。你可能知道,由于[将 class 应用于 JSX 元素的方式](define-an-html-class-in-jsx)与 HTML 中的使用并不完全相同。 <add>还有其他复杂的概念可以为你的 React 代码增加强大的功能。但是,你可能会想知道更简单的问题,比如:如何对在 React 中创建的 JSX 元素进行风格化。你可能知道,由于[将 class 应用于 JSX 元素的方式](/learn/front-end-libraries/react/define-an-html-class-in-jsx)与 HTML 中的使用并不完全相同。 <ide> <ide> 如果从样式表导入样式,它就没有太大的不同。使用`className`属性将 class 应用于 JSX 元素,并将样式应用于样式表中的 class。另一种选择是使用***内联***样式,这在 ReactJS 开发中非常常见。 <ide> <ide><path>curriculum/challenges/chinese/03-front-end-libraries/react/pass-state-as-props-to-child-components.md <ide> forumTopicId: 301403 <ide> <ide> # --instructions-- <ide> <del>`MyApp`组件是有状态的,它将`Navbar`组件渲染成它的为子组件。将`MyApp`组件`state`中的`name`属性向下传递给子组件,然后在`h1`标签中显示`name`,`name`是`Navbar`render 方法的一部分。 <add>`MyApp`组件是有状态的,它将`Navbar`组件渲染成它的为子组件。将`MyApp`组件`state`中的`name`属性向下传递给子组件,然后在`h1`标签中显示`name`,`name`是`Navbar`render 方法的一部分。`name` 应该显示在文字 `Hello, my name is:` 后面。 <ide> <ide> # --hints-- <ide> <ide><path>curriculum/challenges/chinese/03-front-end-libraries/react/render-conditionally-from-props.md <ide> forumTopicId: 301405 <ide> <ide> 代码编辑器有两个部分为你定义的组件:一个名为`GameOfChance`的父组件和一个名为`Results`的子组件。他们被用来创建一个简单的游戏,用户按下按钮来看他们是赢还是输。 <ide> <del>首先,你需要一个简单的表达式,每次运行时都会随机返回一个不同的值。你可以使用`Math.random()`。每次调用此方法时,此方法返回`0`(包括)和`1`(不包括)之间的值。因此,对于50/50的几率,请在表达式中使用`Math.random() > .5`。从统计学上讲,这个表达式有 50% 的几率返回`true`,另外 50% 返回`false`。在第 30 行,用此表达式替换注释以完成变量声明。 <add>首先,你需要一个简单的表达式,每次运行时都会随机返回一个不同的值。你可以使用`Math.random()`。每次调用此方法时,此方法返回`0`(包括)和`1`(不包括)之间的值。因此,对于50/50的几率,请在表达式中使用`Math.random() > .5`。从统计学上讲,这个表达式有 50% 的几率返回`true`,另外 50% 返回`false`。在第 render 方法里,用此表达式替换注释以完成变量声明。 <ide> <del>现在你有了一个表达式,可以用来在代码中做出随机决定,接下来你需要实现以下功能:将`Results`组件渲染为`GameOfChance`的子组件,并将`expression`作为 prop 传递出去,prop 的名字是`fiftyFifty`。在`Results`组件中,编写一个三元表达式基于从`GameOfChance`传来的 prop`fiftyFifty`来渲染文本`"You win!"`或者`"You lose!"`。最后,确保`handleClick()`方法正确计算每个回合,以便用户知道他们玩过多少次。这也可以让用户知道组件实际上已经更新,以防他们连续赢两次或输两次时自己不知道。 <add>现在你有了一个表达式,可以用来在代码中做出随机决定,接下来你需要实现以下功能:将`Results`组件渲染为`GameOfChance`的子组件,并将`expression`作为 prop 传递出去,prop 的名字是`fiftyFifty`。在`Results`组件中,编写一个三元表达式基于从`GameOfChance`传来的 prop`fiftyFifty`来渲染文本`"You Win!"`或者`"You Lose!"`。最后,确保`handleClick()`方法正确计算每个回合,以便用户知道他们玩过多少次。这也可以让用户知道组件实际上已经更新,以防他们连续赢两次或输两次时自己不知道。 <ide> <ide> # --hints-- <ide> <ide><path>curriculum/challenges/chinese/03-front-end-libraries/react/use-proptypes-to-define-the-props-you-expect.md <ide> assert( <ide> (getUserInput) => <ide> assert( <ide> (function () { <del> const noWhiteSpace = getUserInput('index').replace(/ /g, ''); <add> const noWhiteSpace = __helpers.removeWhiteSpace(getUserInput('index')); <ide> return ( <ide> noWhiteSpace.includes('quantity:PropTypes.number.isRequired') && <ide> noWhiteSpace.includes('Items.propTypes=') <ide><path>curriculum/challenges/chinese/03-front-end-libraries/react/use-state-to-toggle-an-element.md <ide> forumTopicId: 301421 <ide> <ide> # --description-- <ide> <del>有时可能在更新状态的时候想知道上一个状态是什么。但是状态更新是异步的,这意味着 React 可能会把多个 `setState()` 集中在一起批量更新。所以设置 `this.state` 或者 `this.props` 后值没有立即更新。所以最好不要写如下的代码: <add>有时可能在更新状态的时候想知道上一个状态是什么。但是状态更新是异步的,这意味着 React 可能会把多个 `setState()` 集中在一起批量更新。所以设置 `this.state` 或者 `this.props` 后值后可能没有立即更新。所以最好不要写如下的代码: <ide> <del>```js <add>```jsx <ide> this.setState({ <ide> counter: this.state.counter + this.props.increment <ide> }); <ide> ``` <ide> <ide> 正确的做法是,给 `setState` 传入一个函数,这个函数可以访问 state 和 props。给 `setState` 传入函数可以返回赋值后的 state 和 props。代码可以重写为这样: <ide> <del>```js <add>```jsx <ide> this.setState((state, props) => ({ <ide> counter: state.counter + props.increment <ide> })); <ide> ``` <ide> <ide> 如果只需要 `state`,那么用下面的格式也是可以的: <ide> <del>```js <add>```jsx <ide> this.setState(state => ({ <ide> counter: state.counter + 1 <ide> })); <ide><path>curriculum/challenges/chinese/03-front-end-libraries/react/use-the-lifecycle-method-componentdidmount.md <ide> React 的最佳实践是在生命周期方法`componentDidMount()`中对服务 <ide> <ide> # --instructions-- <ide> <del>`componentDidMount()`中有一个模拟 API 调用。它在 2.5 秒后设置 state,以模拟调用服务器检索数据。本示例请求站点的当前活动用户总数。在 render 方法中,把`activeUsers`渲染到`h1`标签中。观看预览中发生的事情,随意更改超时时间以查看不同的效果。 <add>`componentDidMount()` 中有一个模拟 API 调用。它在 2.5 秒后设置 state,以模拟调用服务器检索数据。本示例请求站点的当前活动用户总数。在 render 方法中,把 `activeUsers` 渲染到文字 `Active Users:` 后的 `h1` 标签中。观看预览中发生的事情,随意更改超时时间以查看不同的效果。 <ide> <ide> # --hints-- <ide> <ide><path>curriculum/challenges/chinese/03-front-end-libraries/react/write-a-react-component-from-scratch.md <ide> assert( <ide> assert(document.getElementById('challenge-node').childNodes.length === 1); <ide> ``` <ide> <add>`MyComponent` 应该有一个构造器,里面调用了传参 `props` 的 `super` 函数。 <add> <add>```js <add>assert( <add> MyComponent.toString().includes('MyComponent(props)') && <add> MyComponent.toString().includes('_super.call(this, props)') <add>); <add>``` <ide> # --solutions-- <ide> <ide><path>curriculum/challenges/chinese/03-front-end-libraries/sass/create-reusable-css-with-mixins.md <ide> div { <ide> } <ide> ``` <ide> <del>定义以`@mixin`开头,后跟自定义名称。参数(`$x`,`$y`,`$blur`,以及上例中的`$c`是可选的。 现在,只要在需要的地方使用`@include`调用上面定义的`mixin`,就可以自动添加好所有的浏览器前缀:`mixin`使用`@include`指令调用: <add>定义以`@mixin`开头,后跟自定义名称。参数(`$x`,`$y`,`$blur`,以及上例中的`$c`是可选的。 现在,只要在需要 `box-shadow` 的地方使用`@include`调用上面定义的`mixin`,就可以自动添加好所有的浏览器前缀:`mixin`使用`@include`指令调用: <ide> <ide> ```scss <ide> div { <ide> assert(code.match(/@mixin\s+?border-radius\s*?\(\s*?\$radius\s*?\)\s*?{/gi)); <ide> 你应该给`$radius`添加`-webkit-border-radius`浏览器前缀。 <ide> <ide> ```js <del>assert(code.match(/-webkit-border-radius:\s*?\$radius;/gi)); <add>assert( <add> __helpers.removeWhiteSpace(code).match(/-webkit-border-radius:\$radius;/gi) <add>); <ide> ``` <ide> <ide> 你应该给`$radius`添加`-moz-border-radius`浏览器前缀。 <ide> <ide> ```js <del>assert(code.match(/-moz-border-radius:\s*?\$radius;/gi)); <add>assert( <add> __helpers.removeWhiteSpace(code).match(/-moz-border-radius:\$radius;/gi) <add>); <ide> ``` <ide> <ide> 你应该给`$radius`添加`-ms-border-radius`浏览器前缀。 <ide> <ide> ```js <del>assert(code.match(/-ms-border-radius:\s*?\$radius;/gi)); <add>assert(__helpers.removeWhiteSpace(code).match(/-ms-border-radius:\$radius;/gi)); <ide> ``` <ide> <ide> 你应该给`$radius`添加`border-radius`。 <ide> <ide> ```js <del>assert(code.match(/border-radius:\s*?\$radius;/gi).length == 4); <add>assert( <add> __helpers.removeWhiteSpace(code).match(/border-radius:\$radius;/gi).length == <add> 4 <add>); <ide> ``` <ide> <ide> 你应使用`@include`关键字调用`border-radius mixin`,并将其设置为 15px。 <ide> <ide> ```js <del>assert(code.match(/@include\s+?border-radius\(\s*?15px\s*?\);/gi)); <add>assert(code.match(/@include\s+?border-radius\(\s*?15px\s*?\)\s*;/gi)); <add>``` <add> <add># --seed-- <add> <add>## --seed-contents-- <add> <add>```html <add><style type='text/scss'> <add> <add> <add> <add> #awesome { <add> width: 150px; <add> height: 150px; <add> background-color: green; <add> <add> } <add></style> <add> <add><div id="awesome"></div> <ide> ``` <ide> <ide> # --solutions-- <ide> <add>```html <add><style type='text/scss'> <add> @mixin border-radius($radius) { <add> -webkit-border-radius: $radius; <add> -moz-border-radius: $radius; <add> -ms-border-radius: $radius; <add> border-radius: $radius; <add> } <add> <add> #awesome { <add> width: 150px; <add> height: 150px; <add> background-color: green; <add> @include border-radius(15px); <add> } <add></style> <add> <add><div id="awesome"></div> <add>``` <ide><path>curriculum/challenges/chinese/03-front-end-libraries/sass/use-for-to-create-a-sass-loop.md <ide> forumTopicId: 301462 <ide> <ide> 你可以在 Sass 中使用`@for`循环,它的表现类似与 JavaScript 中的`for`循环。 <ide> <del>`@for`以两种方式使用:"start through end" 或 "start to end"。主要区别在于“开始结束”*排除* 结束号码,而“开始结束”*包括* 结束号码。 <add>`@for`以两种方式使用:"开始 through 到" 或 "开始 to 结束"。主要区别在于“开始结束”*排除* 结束号码,而“开始结束”*包括* 结束号码。 <ide> <ide> 这是一个开始 **到** 结束示例: <ide> <ide> assert($('.text-5').css('font-size') == '75px'); <ide> ``` <ide> <ide> # --solutions-- <del>
16
Text
Text
update man pages to reflect prior change
75d3ca8e6f89aa67dbd5b891295c4bf6d05b6beb
<ide><path>docs/Manpage.md <ide> With `--verbose` or `-v`, many commands print extra debugging information. Note <ide> <ide> If `--cc=``compiler` is passed, attempt to compile using `compiler`. <ide> `compiler` should be the name of the compiler's executable, for instance <del> `gcc-8` for gcc 8, `gcc-4.2` for Apple's GCC 4.2, or `gcc-4.9` for a <del> Homebrew-provided GCC 4.9. In order to use LLVM's clang, use <del> `llvm_clang`. To specify the Apple-provided clang, use `clang`. This <add> `gcc-8` for gcc 8, `gcc-4.2` for Apple's GCC 4.2, or `gcc-4.9` for a <add> Homebrew-provided GCC 4.9. In order to use LLVM's clang, use <add> `llvm_clang`. To specify the Apple-provided clang, use `clang`. This <ide> parameter will only accept compilers that are provided by Homebrew or <ide> bundled with MacOS. Please do not file issues if you encounter errors <ide> while using this flag.
1
Text
Text
update deployment documentation.
748c8e8002987a68396858f4b5ca3eda9bd6d0d2
<ide><path>docs/deployment.md <ide> If you need to use different Environment Variables across multiple environments, <ide> <ide> If you’d like to do a static HTML export of your Next.js app, follow the directions on our [Static HTML Export documentation](/docs/advanced-features/static-html-export.md). <ide> <add>## Other Services <add> <add>The following services support Next.js `v12+`. Below, you’ll find examples or guides to deploy Next.js to each service. <add> <add>### Managed Server <add> <add>- [AWS Copilot](https://aws.github.io/copilot-cli/) <add>- [Digital Ocean App Platform](https://docs.digitalocean.com/tutorials/app-nextjs-deploy/) <add>- [Google Cloud Run](https://github.com/vercel/next.js/tree/canary/examples/with-docker) <add>- [Heroku](https://elements.heroku.com/buildpacks/mars/heroku-nextjs) <add>- [Railway](https://railway.app/new/starters/nextjs-prisma) <add>- [Render](https://render.com/docs/deploy-nextjs-app) <add> <add>> **Note:** There are also managed platforms that allow you to use a Dockerfile as shown in the [example above](/docs/deployment.md#docker-image). <add> <add>### Static Only <add> <add>The following services support deploying Next.js using [`next export`](/docs/advanced-features/static-html-export.md). <add> <add>- [Azure Static Web Apps](https://docs.microsoft.com/en-us/azure/static-web-apps/deploy-nextjs) <add>- [Cloudflare Pages](https://developers.cloudflare.com/pages/framework-guides/deploy-a-nextjs-site/) <add>- [Firebase](https://github.com/vercel/next.js/tree/canary/examples/with-firebase-hosting) <add>- [GitHub Pages](https://github.com/vercel/next.js/tree/canary/examples/github-pages) <add> <add>You can also manually deploy the [`next export`](/docs/advanced-features/static-html-export.md) output to any static hosting provider, often through your CI/CD pipeline like GitHub Actions, Jenkins, AWS CodeBuild, Circle CI, Azure Pipelines, and more. <add> <add>### Serverless <add> <add>- [AWS Serverless](https://github.com/serverless-nextjs/serverless-next.js) <add>- [Terraform](https://github.com/milliHQ/terraform-aws-next-js) <add>- [Netlify](https://docs.netlify.com/integrations/frameworks/next-js) <add> <add>> **Note:** Not all serverless providers implement the [Next.js Build API](/docs/deployment.md#nextjs-build-api) from `next start`. Please check with the provider to see what features are supported. <add> <ide> ## Automatic Updates <ide> <ide> When you deploy your Next.js application, you want to see the latest version without needing to reload.
1
Javascript
Javascript
allow creation of gcm ciphers with createcipher
ce56dccb99db128c8973642dfd0b47958c30010e
<ide><path>lib/crypto.js <ide> Cipher.prototype.setAutoPadding = function(ap) { <ide> return this; <ide> }; <ide> <add>Cipher.prototype.getAuthTag = function() { <add> return this._handle.getAuthTag(); <add>}; <add> <add> <add>Cipher.prototype.setAuthTag = function(tagbuf) { <add> this._handle.setAuthTag(tagbuf); <add>}; <ide> <add>Cipher.prototype.setAAD = function(aadbuf) { <add> this._handle.setAAD(aadbuf); <add>}; <ide> <ide> exports.createCipheriv = exports.Cipheriv = Cipheriv; <ide> function Cipheriv(cipher, key, iv, options) { <ide> Cipheriv.prototype._flush = Cipher.prototype._flush; <ide> Cipheriv.prototype.update = Cipher.prototype.update; <ide> Cipheriv.prototype.final = Cipher.prototype.final; <ide> Cipheriv.prototype.setAutoPadding = Cipher.prototype.setAutoPadding; <del> <del>Cipheriv.prototype.getAuthTag = function() { <del> return this._handle.getAuthTag(); <del>}; <del> <del> <del>Cipheriv.prototype.setAuthTag = function(tagbuf) { <del> this._handle.setAuthTag(tagbuf); <del>}; <del> <del>Cipheriv.prototype.setAAD = function(aadbuf) { <del> this._handle.setAAD(aadbuf); <del>}; <del> <add>Cipheriv.prototype.getAuthTag = Cipher.prototype.getAuthTag; <add>Cipheriv.prototype.setAuthTag = Cipher.prototype.setAuthTag; <add>Cipheriv.prototype.setAAD = Cipher.prototype.setAAD; <ide> <ide> exports.createDecipher = exports.Decipher = Decipher; <ide> function Decipher(cipher, password, options) { <ide> Decipher.prototype.update = Cipher.prototype.update; <ide> Decipher.prototype.final = Cipher.prototype.final; <ide> Decipher.prototype.finaltol = Cipher.prototype.final; <ide> Decipher.prototype.setAutoPadding = Cipher.prototype.setAutoPadding; <del> <add>Decipher.prototype.getAuthTag = Cipher.prototype.getAuthTag; <add>Decipher.prototype.setAuthTag = Cipher.prototype.setAuthTag; <add>Decipher.prototype.setAAD = Cipher.prototype.setAAD; <ide> <ide> <ide> exports.createDecipheriv = exports.Decipheriv = Decipheriv; <ide> Decipheriv.prototype.update = Cipher.prototype.update; <ide> Decipheriv.prototype.final = Cipher.prototype.final; <ide> Decipheriv.prototype.finaltol = Cipher.prototype.final; <ide> Decipheriv.prototype.setAutoPadding = Cipher.prototype.setAutoPadding; <del>Decipheriv.prototype.getAuthTag = Cipheriv.prototype.getAuthTag; <del>Decipheriv.prototype.setAuthTag = Cipheriv.prototype.setAuthTag; <del>Decipheriv.prototype.setAAD = Cipheriv.prototype.setAAD; <add>Decipheriv.prototype.getAuthTag = Cipher.prototype.getAuthTag; <add>Decipheriv.prototype.setAuthTag = Cipher.prototype.setAuthTag; <add>Decipheriv.prototype.setAAD = Cipher.prototype.setAAD; <ide> <ide> <ide> <ide><path>test/simple/test-crypto-authenticated.js <ide> crypto.DEFAULT_ENCODING = 'buffer'; <ide> // <ide> <ide> var TEST_CASES = [ <del> { algo: 'aes-128-gcm', key: 'ipxp9a6i1Mb4USb4', <del> iv: 'X6sIq117H0vR', plain: 'Hello World!', <add> { algo: 'aes-128-gcm', key: '6970787039613669314d623455536234', <add> iv: '583673497131313748307652', plain: 'Hello World!', <ide> ct: '4BE13896F64DFA2C2D0F2C76', <ide> tag: '272B422F62EB545EAA15B5FF84092447', tampered: false }, <del> { algo: 'aes-128-gcm', key: 'ipxp9a6i1Mb4USb4', <del> iv: 'X6sIq117H0vR', plain: 'Hello World!', <add> { algo: 'aes-128-gcm', key: '6970787039613669314d623455536234', <add> iv: '583673497131313748307652', plain: 'Hello World!', <ide> ct: '4BE13896F64DFA2C2D0F2C76', aad: '000000FF', <ide> tag: 'BA2479F66275665A88CB7B15F43EB005', tampered: false }, <del> { algo: 'aes-128-gcm', key: 'ipxp9a6i1Mb4USb4', <del> iv: 'X6sIq117H0vR', plain: 'Hello World!', <add> { algo: 'aes-128-gcm', key: '6970787039613669314d623455536234', <add> iv: '583673497131313748307652', plain: 'Hello World!', <ide> ct: '4BE13596F64DFA2C2D0FAC76', <ide> tag: '272B422F62EB545EAA15B5FF84092447', tampered: true }, <del> { algo: 'aes-256-gcm', key: '3zTvzr3p67VC61jmV54rIYu1545x4TlY', <del> iv: '60iP0h6vJoEa', plain: 'Hello node.js world!', <add> { algo: 'aes-256-gcm', key: '337a54767a7233703637564336316a6d56353472495975313534357834546c59', <add> iv: '36306950306836764a6f4561', plain: 'Hello node.js world!', <ide> ct: '58E62CFE7B1D274111A82267EBB93866E72B6C2A', <ide> tag: '9BB44F663BADABACAE9720881FB1EC7A', tampered: false }, <del> { algo: 'aes-256-gcm', key: '3zTvzr3p67VC61jmV54rIYu1545x4TlY', <del> iv: '60iP0h6vJoEa', plain: 'Hello node.js world!', <add> { algo: 'aes-256-gcm', key: '337a54767a7233703637564336316a6d56353472495975313534357834546c59', <add> iv: '36306950306836764a6f4561', plain: 'Hello node.js world!', <ide> ct: '58E62CFF7B1D274011A82267EBB93866E72B6C2B', <ide> tag: '9BB44F663BADABACAE9720881FB1EC7A', tampered: true }, <add> { algo: 'aes-192-gcm', key: '1ed2233fa2223ef5d7df08546049406c7305220bca40d4c9', <add> iv: '0e1791e9db3bd21a9122c416', plain: 'Hello node.js world!', <add> password: 'very bad password', aad: '63616c76696e', <add> ct: 'DDA53A4059AA17B88756984995F7BBA3C636CC44', <add> tag: 'D2A35E5C611E5E3D2258360241C5B045', tampered: false } <ide> ]; <ide> <ide> var ciphers = crypto.getCiphers(); <ide> for (var i in TEST_CASES) { <ide> } <ide> <ide> (function() { <del> var encrypt = crypto.createCipheriv(test.algo, test.key, test.iv); <add> var encrypt = crypto.createCipheriv(test.algo, <add> new Buffer(test.key, 'hex'), new Buffer(test.iv, 'hex')); <ide> if (test.aad) <ide> encrypt.setAAD(new Buffer(test.aad, 'hex')); <ide> var hex = encrypt.update(test.plain, 'ascii', 'hex'); <ide> for (var i in TEST_CASES) { <ide> })(); <ide> <ide> (function() { <del> var decrypt = crypto.createDecipheriv(test.algo, test.key, test.iv); <add> var decrypt = crypto.createDecipheriv(test.algo, <add> new Buffer(test.key, 'hex'), new Buffer(test.iv, 'hex')); <add> decrypt.setAuthTag(new Buffer(test.tag, 'hex')); <add> if (test.aad) <add> decrypt.setAAD(new Buffer(test.aad, 'hex')); <add> var msg = decrypt.update(test.ct, 'hex', 'ascii'); <add> if (!test.tampered) { <add> msg += decrypt.final('ascii'); <add> assert.equal(msg, test.plain); <add> } else { <add> // assert that final throws if input data could not be verified! <add> assert.throws(function() { decrypt.final('ascii'); }, / auth/); <add> } <add> })(); <add> <add> (function() { <add> if (!test.password) return; <add> var encrypt = crypto.createCipher(test.algo, test.password); <add> if (test.aad) <add> encrypt.setAAD(new Buffer(test.aad, 'hex')); <add> var hex = encrypt.update(test.plain, 'ascii', 'hex'); <add> hex += encrypt.final('hex'); <add> var auth_tag = encrypt.getAuthTag(); <add> // only test basic encryption run if output is marked as tampered. <add> if (!test.tampered) { <add> assert.equal(hex.toUpperCase(), test.ct); <add> assert.equal(auth_tag.toString('hex').toUpperCase(), test.tag); <add> } <add> })(); <add> <add> (function() { <add> if (!test.password) return; <add> var decrypt = crypto.createDecipher(test.algo, test.password); <ide> decrypt.setAuthTag(new Buffer(test.tag, 'hex')); <ide> if (test.aad) <ide> decrypt.setAAD(new Buffer(test.aad, 'hex')); <ide> for (var i in TEST_CASES) { <ide> <ide> (function() { <ide> // trying to get tag before inputting all data: <del> var encrypt = crypto.createCipheriv(test.algo, test.key, test.iv); <add> var encrypt = crypto.createCipheriv(test.algo, <add> new Buffer(test.key, 'hex'), new Buffer(test.iv, 'hex')); <ide> encrypt.update('blah', 'ascii'); <ide> assert.throws(function() { encrypt.getAuthTag(); }, / state/); <ide> })(); <ide> <ide> (function() { <ide> // trying to set tag on encryption object: <del> var encrypt = crypto.createCipheriv(test.algo, test.key, test.iv); <add> var encrypt = crypto.createCipheriv(test.algo, <add> new Buffer(test.key, 'hex'), new Buffer(test.iv, 'hex')); <ide> assert.throws(function() { <ide> encrypt.setAuthTag(new Buffer(test.tag, 'hex')); }, / state/); <ide> })(); <ide> <ide> (function() { <ide> // trying to read tag from decryption object: <del> var decrypt = crypto.createDecipheriv(test.algo, test.key, test.iv); <add> var decrypt = crypto.createDecipheriv(test.algo, <add> new Buffer(test.key, 'hex'), new Buffer(test.iv, 'hex')); <ide> assert.throws(function() { decrypt.getAuthTag(); }, / state/); <ide> })(); <ide> }
2
Javascript
Javascript
move common schema functions to util
b50d4cf7c370dc0f9fa2c39ea0e73e28ca8918ac
<ide><path>lib/WebpackOptionsValidationError.js <ide> const WebpackError = require("./WebpackError"); <ide> const webpackOptionsSchema = require("../schemas/webpackOptionsSchema.json"); <ide> <del>const getSchemaPart = (path, parents, additionalPath) => { <del> parents = parents || 0; <del> path = path.split("/"); <del> path = path.slice(0, path.length - parents); <del> if(additionalPath) { <del> additionalPath = additionalPath.split("/"); <del> path = path.concat(additionalPath); <del> } <del> let schemaPart = webpackOptionsSchema; <del> for(let i = 1; i < path.length; i++) { <del> const inner = schemaPart[path[i]]; <del> if(inner) <del> schemaPart = inner; <del> } <del> return schemaPart; <del>}; <del> <del>const getSchemaPartText = (schemaPart, additionalPath) => { <del> if(additionalPath) { <del> for(let i = 0; i < additionalPath.length; i++) { <del> const inner = schemaPart[additionalPath[i]]; <del> if(inner) <del> schemaPart = inner; <del> } <del> } <del> while(schemaPart.$ref) schemaPart = getSchemaPart(schemaPart.$ref); <del> let schemaText = WebpackOptionsValidationError.formatSchema(schemaPart); <del> if(schemaPart.description) <del> schemaText += `\n${schemaPart.description}`; <del> return schemaText; <del>}; <add>const indent = require("./util/indent"); <add>const getSchemaPartText = require("./util/getSchemaPartText"); <ide> <del>const indent = (str, prefix, firstLine) => { <del> if(firstLine) { <del> return prefix + str.replace(/\n(?!$)/g, "\n" + prefix); <del> } else { <del> return str.replace(/\n(?!$)/g, `\n${prefix}`); <del> } <del>}; <add>const getOptionsSchemaPartText = (schema, additionalPath) => <add> getSchemaPartText(webpackOptionsSchema, schema, additionalPath); <ide> <ide> class WebpackOptionsValidationError extends WebpackError { <ide> constructor(validationErrors) { <ide> class WebpackOptionsValidationError extends WebpackError { <ide> Error.captureStackTrace(this, this.constructor); <ide> } <ide> <del> static formatSchema(schema, prevSchemas) { <del> prevSchemas = prevSchemas || []; <del> <del> const formatInnerSchema = (innerSchema, addSelf) => { <del> if(!addSelf) return WebpackOptionsValidationError.formatSchema(innerSchema, prevSchemas); <del> if(prevSchemas.indexOf(innerSchema) >= 0) return "(recursive)"; <del> return WebpackOptionsValidationError.formatSchema(innerSchema, prevSchemas.concat(schema)); <del> }; <del> <del> if(schema.type === "string") { <del> if(schema.minLength === 1) <del> return "non-empty string"; <del> else if(schema.minLength > 1) <del> return `string (min length ${schema.minLength})`; <del> return "string"; <del> } else if(schema.type === "boolean") { <del> return "boolean"; <del> } else if(schema.type === "number") { <del> return "number"; <del> } else if(schema.type === "object") { <del> if(schema.properties) { <del> const required = schema.required || []; <del> return `object { ${Object.keys(schema.properties).map(property => { <del> if(required.indexOf(property) < 0) return property + "?"; <del> return property; <del> }).concat(schema.additionalProperties ? ["..."] : []).join(", ")} }`; <del> } <del> if(schema.additionalProperties) { <del> return `object { <key>: ${formatInnerSchema(schema.additionalProperties)} }`; <del> } <del> return "object"; <del> } else if(schema.type === "array") { <del> return `[${formatInnerSchema(schema.items)}]`; <del> } <del> <del> switch(schema.instanceof) { <del> case "Function": <del> return "function"; <del> case "RegExp": <del> return "RegExp"; <del> } <del> if(schema.$ref) return formatInnerSchema(getSchemaPart(schema.$ref), true); <del> if(schema.allOf) return schema.allOf.map(formatInnerSchema).join(" & "); <del> if(schema.oneOf) return schema.oneOf.map(formatInnerSchema).join(" | "); <del> if(schema.anyOf) return schema.anyOf.map(formatInnerSchema).join(" | "); <del> if(schema.enum) return schema.enum.map(item => JSON.stringify(item)).join(" | "); <del> return JSON.stringify(schema, 0, 2); <del> } <del> <ide> static formatValidationError(err) { <ide> const dataPath = `configuration${err.dataPath}`; <ide> if(err.keyword === "additionalProperties") { <del> const baseMessage = `${dataPath} has an unknown property '${err.params.additionalProperty}'. These properties are valid:\n${getSchemaPartText(err.parentSchema)}`; <add> const baseMessage = `${dataPath} has an unknown property '${err.params.additionalProperty}'. These properties are valid:\n${getOptionsSchemaPartText(err.parentSchema)}`; <ide> if(!err.dataPath) { <ide> switch(err.params.additionalProperty) { <ide> case "debug": <ide> class WebpackOptionsValidationError extends WebpackError { <ide> return baseMessage; <ide> } else if(err.keyword === "oneOf" || err.keyword === "anyOf") { <ide> if(err.children && err.children.length > 0) { <del> return `${dataPath} should be one of these:\n${getSchemaPartText(err.parentSchema)}\n` + <add> return `${dataPath} should be one of these:\n${getOptionsSchemaPartText(err.parentSchema)}\n` + <ide> `Details:\n${err.children.map(err => " * " + indent(WebpackOptionsValidationError.formatValidationError(err), " ", false)).join("\n")}`; <ide> } <del> return `${dataPath} should be one of these:\n${getSchemaPartText(err.parentSchema)}`; <add> return `${dataPath} should be one of these:\n${getOptionsSchemaPartText(err.parentSchema)}`; <ide> <ide> } else if(err.keyword === "enum") { <ide> if(err.parentSchema && err.parentSchema.enum && err.parentSchema.enum.length === 1) { <del> return `${dataPath} should be ${getSchemaPartText(err.parentSchema)}`; <add> return `${dataPath} should be ${getOptionsSchemaPartText(err.parentSchema)}`; <ide> } <del> return `${dataPath} should be one of these:\n${getSchemaPartText(err.parentSchema)}`; <add> return `${dataPath} should be one of these:\n${getOptionsSchemaPartText(err.parentSchema)}`; <ide> } else if(err.keyword === "allOf") { <del> return `${dataPath} should be:\n${getSchemaPartText(err.parentSchema)}`; <add> return `${dataPath} should be:\n${getOptionsSchemaPartText(err.parentSchema)}`; <ide> } else if(err.keyword === "type") { <ide> switch(err.params.type) { <ide> case "object": <ide> class WebpackOptionsValidationError extends WebpackError { <ide> case "number": <ide> return `${dataPath} should be a number.`; <ide> case "array": <del> return `${dataPath} should be an array:\n${getSchemaPartText(err.parentSchema)}`; <add> return `${dataPath} should be an array:\n${getOptionsSchemaPartText(err.parentSchema)}`; <ide> } <del> return `${dataPath} should be ${err.params.type}:\n${getSchemaPartText(err.parentSchema)}`; <add> return `${dataPath} should be ${err.params.type}:\n${getOptionsSchemaPartText(err.parentSchema)}`; <ide> } else if(err.keyword === "instanceof") { <del> return `${dataPath} should be an instance of ${getSchemaPartText(err.parentSchema)}.`; <add> return `${dataPath} should be an instance of ${getOptionsSchemaPartText(err.parentSchema)}.`; <ide> } else if(err.keyword === "required") { <ide> const missingProperty = err.params.missingProperty.replace(/^\./, ""); <del> return `${dataPath} misses the property '${missingProperty}'.\n${getSchemaPartText(err.parentSchema, ["properties", missingProperty])}`; <add> return `${dataPath} misses the property '${missingProperty}'.\n${getOptionsSchemaPartText(err.parentSchema, ["properties", missingProperty])}`; <ide> } else if(err.keyword === "minLength" || err.keyword === "minItems") { <ide> if(err.params.limit === 1) <ide> return `${dataPath} should not be empty.`; <ide> class WebpackOptionsValidationError extends WebpackError { <ide> return baseMessage; <ide> } else { <ide> // eslint-disable-line no-fallthrough <del> return `${dataPath} ${err.message} (${JSON.stringify(err, 0, 2)}).\n${getSchemaPartText(err.parentSchema)}`; <add> return `${dataPath} ${err.message} (${JSON.stringify(err, 0, 2)}).\n${getOptionsSchemaPartText(err.parentSchema)}`; <ide> } <ide> } <ide> } <ide><path>lib/util/formatSchema.js <add>"use strict"; <add> <add>const getSchemaPart = require("./getSchemaPart"); <add> <add>const formatSchema = (rootSchema, schema, prevSchemas) => { <add> prevSchemas = prevSchemas || []; <add> <add> const formatInnerSchema = (innerSchema, addSelf) => { <add> if(!addSelf) return formatSchema(rootSchema, innerSchema, prevSchemas); <add> if(prevSchemas.indexOf(innerSchema) >= 0) return "(recursive)"; <add> return formatSchema(rootSchema, innerSchema, prevSchemas.concat(schema)); <add> }; <add> <add> if(schema.type === "string") { <add> if(schema.minLength === 1) <add> return "non-empty string"; <add> else if(schema.minLength > 1) <add> return `string (min length ${schema.minLength})`; <add> return "string"; <add> } else if(schema.type === "boolean") { <add> return "boolean"; <add> } else if(schema.type === "number") { <add> return "number"; <add> } else if(schema.type === "object") { <add> if(schema.properties) { <add> const required = schema.required || []; <add> return `object { ${Object.keys(schema.properties).map(property => { <add> if(required.indexOf(property) < 0) return property + "?"; <add> return property; <add> }).concat(schema.additionalProperties ? ["..."] : []).join(", ")} }`; <add> } <add> if(schema.additionalProperties) { <add> return `object { <key>: ${formatInnerSchema(schema.additionalProperties)} }`; <add> } <add> return "object"; <add> } else if(schema.type === "array") { <add> return `[${formatInnerSchema(schema.items)}]`; <add> } <add> <add> switch(schema.instanceof) { <add> case "Function": <add> return "function"; <add> case "RegExp": <add> return "RegExp"; <add> } <add> if(schema.$ref) return formatInnerSchema(getSchemaPart(rootSchema, schema.$ref), true); <add> if(schema.allOf) return schema.allOf.map(formatInnerSchema).join(" & "); <add> if(schema.oneOf) return schema.oneOf.map(formatInnerSchema).join(" | "); <add> if(schema.anyOf) return schema.anyOf.map(formatInnerSchema).join(" | "); <add> if(schema.enum) return schema.enum.map(item => JSON.stringify(item)).join(" | "); <add> return JSON.stringify(schema, 0, 2); <add>}; <add> <add>module.exports = formatSchema; <ide><path>lib/util/getSchemaPart.js <add>"use strict"; <add> <add>const getSchemaPart = (schema, path, parents, additionalPath) => { <add> parents = parents || 0; <add> path = path.split("/"); <add> path = path.slice(0, path.length - parents); <add> if(additionalPath) { <add> additionalPath = additionalPath.split("/"); <add> path = path.concat(additionalPath); <add> } <add> let schemaPart = schema; <add> for(let i = 1; i < path.length; i++) { <add> const inner = schemaPart[path[i]]; <add> if(inner) <add> schemaPart = inner; <add> } <add> return schemaPart; <add>}; <add> <add>module.exports = getSchemaPart; <ide><path>lib/util/getSchemaPartText.js <add>"use strict"; <add> <add>const formatSchema = require("./formatSchema"); <add>const getSchemaPart = require("./getSchemaPart"); <add> <add>const getSchemaPartText = (rootSchema, schemaPart, additionalPath) => { <add> if(additionalPath) { <add> for(let i = 0; i < additionalPath.length; i++) { <add> const inner = schemaPart[additionalPath[i]]; <add> if(inner) <add> schemaPart = inner; <add> } <add> } <add> while(schemaPart.$ref) schemaPart = getSchemaPart(rootSchema, schemaPart.$ref); <add> let schemaText = formatSchema(rootSchema, schemaPart); <add> if(schemaPart.description) <add> schemaText += `\n${schemaPart.description}`; <add> return schemaText; <add>}; <add> <add>module.exports = getSchemaPartText; <ide><path>lib/util/indent.js <add>"use strict"; <add> <add>const indent = (str, prefix, firstLine) => { <add> if(firstLine) { <add> return prefix + str.replace(/\n(?!$)/g, "\n" + prefix); <add> } else { <add> return str.replace(/\n(?!$)/g, `\n${prefix}`); <add> } <add>}; <add> <add>module.exports = indent;
5
Go
Go
implement docker save with standalone client lib
373f55eecd39625f9f2751d8f940e83a056b6261
<ide><path>api/client/lib/image_save.go <add>package lib <add> <add>import ( <add> "io" <add> "net/url" <add>) <add> <add>// ImageSave retrieves one or more images from the docker host as a io.ReadCloser. <add>// It's up to the caller to store the images and close the stream. <add>func (cli *Client) ImageSave(imageIDs []string) (io.ReadCloser, error) { <add> query := url.Values{ <add> "names": imageIDs, <add> } <add> <add> resp, err := cli.GET("/images/get", query, nil) <add> if err != nil { <add> return nil, err <add> } <add> return resp.body, nil <add>} <ide><path>api/client/save.go <ide> package client <ide> <ide> import ( <ide> "errors" <del> "net/url" <add> "io" <ide> "os" <ide> <ide> Cli "github.com/docker/docker/cli" <ide> func (cli *DockerCli) CmdSave(args ...string) error { <ide> } <ide> } <ide> <del> sopts := &streamOpts{ <del> rawTerminal: true, <del> out: output, <del> } <del> <del> v := url.Values{} <del> for _, arg := range cmd.Args() { <del> v.Add("names", arg) <del> } <del> if _, err := cli.stream("GET", "/images/get?"+v.Encode(), sopts); err != nil { <add> responseBody, err := cli.client.ImageSave(cmd.Args()) <add> if err != nil { <ide> return err <ide> } <add> defer responseBody.Close() <ide> <del> return nil <add> _, err = io.Copy(output, responseBody) <add> return err <ide> }
2
Javascript
Javascript
remove unnecessary bind
fea1f1cb9a766e93027374ac0b934ec5448639b1
<ide><path>lib/_http_client.js <ide> ClientRequest.prototype._implicitHeader = function _implicitHeader() { <ide> <ide> ClientRequest.prototype.abort = function abort() { <ide> if (!this.aborted) { <del> process.nextTick(emitAbortNT.bind(this)); <add> process.nextTick(emitAbortNT, this); <ide> } <ide> this.aborted = true; <ide> <ide> ClientRequest.prototype.abort = function abort() { <ide> }; <ide> <ide> <del>function emitAbortNT() { <del> this.emit('abort'); <add>function emitAbortNT(req) { <add> req.emit('abort'); <ide> } <ide> <ide> function ondrain() {
1
Ruby
Ruby
remove extra newline from applicationjob template
655273cad1e623025581dfa3f84e9b12c3edc182
<ide><path>railties/lib/rails/generators/rails/app/templates/app/jobs/application_job.rb <ide> class ApplicationJob < ActiveJob::Base <del> <ide> end
1
PHP
PHP
increase range for comparing now
7f64c34c654676cd24f4f0397b0a0384a906dfe3
<ide><path>tests/TestCase/Database/QueryTest.php <ide> function ($q) { <ide> $this->assertWithinRange( <ide> date('U'), <ide> (new DateTime($result->fetchAll('assoc')[0]['d']))->format('U'), <del> 5 <add> 10 <ide> ); <ide> <ide> $query = new Query($this->connection);
1
PHP
PHP
simplify router code
dc49a4aaebb6b9e079693c4a8a3916ae61eaed72
<ide><path>system/router.php <ide> private static function translate_wildcards($key) <ide> // Now, to properly close the regular expression, we need to append a ")?" for each optional segment in the route. <ide> if ($replacements > 0) <ide> { <del> $key .= implode('', array_fill(0, $replacements, ')?')); <add> $key .= str_repeat(')?', $replacements); <ide> } <ide> <ide> return str_replace(array(':num', ':any'), array('[0-9]+', '[a-zA-Z0-9\-_]+'), $key);
1
Javascript
Javascript
show default `activeopacity` value in docs
5e5cbda682bd4874e2cc79b59972d8855357125e
<ide><path>Libraries/Components/Touchable/TouchableOpacity.js <ide> var TouchableOpacity = React.createClass({ <ide> ...TouchableWithoutFeedback.propTypes, <ide> /** <ide> * Determines what the opacity of the wrapped view should be when touch is <del> * active. <add> * active. Defaults to 0.2. <ide> */ <ide> activeOpacity: React.PropTypes.number, <ide> },
1
Javascript
Javascript
add warnings to react module
c04d02e5e8de18436ac95037ab856ac5ba7d29b9
<ide><path>packages/react/react.js <del>/* eslint-disable comma-dangle */ <ide> 'use strict'; <ide> <del>var React = require('./lib/React'); <del> <del>var assign = require('./lib/Object.assign'); <del>var deprecated = require('./lib/deprecated'); <del> <del>// We want to warn once when any of these methods are used. <del>if (process.env.NODE_ENV !== 'production') { <del> var deprecations = { <del> // ReactDOM <del> findDOMNode: deprecated( <del> 'findDOMNode', <del> 'react-dom', <del> React, <del> React.findDOMNode <del> ), <del> render: deprecated( <del> 'render', <del> 'react-dom', <del> React, <del> React.render <del> ), <del> unmountComponentAtNode: deprecated( <del> 'unmountComponentAtNode', <del> 'react-dom', <del> React, <del> React.unmountComponentAtNode <del> ), <del> // ReactDOMServer <del> renderToString: deprecated( <del> 'renderToString', <del> 'react-dom/server', <del> React, <del> React.renderToString <del> ), <del> renderToStaticMarkup: deprecated( <del> 'renderToStaticMarkup', <del> 'react-dom/server', <del> React, <del> React.renderToStaticMarkup <del> ) <del> }; <del> // Export a wrapped object. We'll use assign and take advantage of the fact <del> // that this will override the original methods in React. <del> module.exports = assign( <del> {}, <del> React, <del> deprecations <del> ); <del>} else { <del> module.exports = React; <del>} <add>module.exports = require('./lib/React'); <ide><path>src/React.js <ide> var ReactDOMServer = require('ReactDOMServer'); <ide> var ReactIsomorphic = require('ReactIsomorphic'); <ide> <ide> var assign = require('Object.assign'); <add>var deprecated = require('deprecated'); <ide> <ide> var React = {}; <ide> <ide> assign(React, ReactIsomorphic); <del>assign(React, ReactDOM); <del>assign(React, ReactDOMServer); <add> <add>assign(React, { <add> // ReactDOM <add> findDOMNode: deprecated( <add> 'findDOMNode', <add> 'ReactDOM', <add> 'react-dom', <add> ReactDOM, <add> ReactDOM.findDOMNode <add> ), <add> render: deprecated( <add> 'render', <add> 'ReactDOM', <add> 'react-dom', <add> ReactDOM, <add> ReactDOM.render <add> ), <add> unmountComponentAtNode: deprecated( <add> 'unmountComponentAtNode', <add> 'ReactDOM', <add> 'react-dom', <add> ReactDOM, <add> ReactDOM.unmountComponentAtNode <add> ), <add> <add> // ReactDOMServer <add> renderToString: deprecated( <add> 'renderToString', <add> 'ReactDOMServer', <add> 'react-dom/server', <add> ReactDOMServer, <add> ReactDOMServer.renderToString <add> ), <add> renderToStaticMarkup: deprecated( <add> 'renderToStaticMarkup', <add> 'ReactDOMServer', <add> 'react-dom/server', <add> ReactDOMServer, <add> ReactDOMServer.renderToStaticMarkup <add> ), <add>}); <ide> <ide> React.version = '0.14.0-beta3'; <ide> <ide><path>src/shared/utils/deprecated.js <ide> var warning = require('warning'); <ide> * <ide> * @param {string} fnName The name of the function <ide> * @param {string} newModule The module that fn will exist in <add> * @param {string} newPackage The module that fn will exist in <ide> * @param {*} ctx The context this forwarded call should run in <ide> * @param {function} fn The function to forward on to <ide> * @return {function} The function that will warn once and then call fn <ide> */ <del>function deprecated(fnName, newModule, ctx, fn) { <add>function deprecated(fnName, newModule, newPackage, ctx, fn) { <ide> var warned = false; <ide> if (__DEV__) { <ide> var newFn = function() { <ide> function deprecated(fnName, newModule, ctx, fn) { <ide> // Require examples in this string must be split to prevent React's <ide> // build tools from mistaking them for real requires. <ide> // Otherwise the build tools will attempt to build a '%s' module. <del> '`require' + '("react").%s` is deprecated. Please use `require' + '("%s").%s` ' + <add> 'React.%s is deprecated. Please use %s.%s from require' + '(\'%s\') ' + <ide> 'instead.', <ide> fnName, <ide> newModule, <del> fnName <add> fnName, <add> newPackage <ide> ); <ide> warned = true; <ide> return fn.apply(ctx, arguments);
3
PHP
PHP
add hasmanythrough tests
46ec7a4a370a190baa870ccd21a9f6e17d9131a8
<ide><path>tests/Database/DatabaseEloquentHasManyThroughTest.php <add><?php <add> <add>use Mockery as m; <add>use Illuminate\Database\Eloquent\Collection; <add>use Illuminate\Database\Eloquent\Relations\HasManyThrough; <add> <add>class DatabaseEloquentHasManyTest extends PHPUnit_Framework_TestCase { <add> <add> public function tearDown() <add> { <add> m::close(); <add> } <add> <add> <add> public function testRelationIsProperlyInitialized() <add> { <add> $relation = $this->getRelation(); <add> $model = m::mock('Illuminate\Database\Eloquent\Model'); <add> $relation->getRelated()->shouldReceive('newCollection')->andReturnUsing(function($array = array()) { return new Collection($array); }); <add> $model->shouldReceive('setRelation')->once()->with('foo', m::type('Illuminate\Database\Eloquent\Collection')); <add> $models = $relation->initRelation(array($model), 'foo'); <add> <add> $this->assertEquals(array($model), $models); <add> } <add> <add> <add> public function testEagerConstraintsAreProperlyAdded() <add> { <add> $relation = $this->getRelation(); <add> $relation->getQuery()->shouldReceive('whereIn')->once()->with('users.country_id', array(1, 2)); <add> $model1 = new EloquentHasManyThroughModelStub; <add> $model1->id = 1; <add> $model2 = new EloquentHasManyThroughModelStub; <add> $model2->id = 2; <add> $relation->addEagerConstraints(array($model1, $model2)); <add> } <add> <add> <add> public function testModelsAreProperlyMatchedToParents() <add> { <add> $relation = $this->getRelation(); <add> <add> $result1 = new EloquentHasManyThroughModelStub; <add> $result1->country_id = 1; <add> $result2 = new EloquentHasManyThroughModelStub; <add> $result2->country_id = 2; <add> $result3 = new EloquentHasManyThroughModelStub; <add> $result3->country_id = 2; <add> <add> $model1 = new EloquentHasManyThroughModelStub; <add> $model1->id = 1; <add> $model2 = new EloquentHasManyThroughModelStub; <add> $model2->id = 2; <add> $model3 = new EloquentHasManyThroughModelStub; <add> $model3->id = 3; <add> <add> $relation->getRelated()->shouldReceive('newCollection')->andReturnUsing(function($array) { return new Collection($array); }); <add> $models = $relation->match(array($model1, $model2, $model3), new Collection(array($result1, $result2, $result3)), 'foo'); <add> <add> $this->assertEquals(1, $models[0]->foo[0]->country_id); <add> $this->assertEquals(1, count($models[0]->foo)); <add> $this->assertEquals(2, $models[1]->foo[0]->country_id); <add> $this->assertEquals(2, $models[1]->foo[1]->country_id); <add> $this->assertEquals(2, count($models[1]->foo)); <add> $this->assertEquals(0, count($models[2]->foo)); <add> } <add> <add> <add> protected function getRelation() <add> { <add> $builder = m::mock('Illuminate\Database\Eloquent\Builder'); <add> $builder->shouldReceive('join')->once()->with('users', 'users.id', '=', 'posts.user_id'); <add> $builder->shouldReceive('where')->with('users.country_id', '=', 1); <add> <add> $country = m::mock('Illuminate\Database\Eloquent\Model'); <add> $country->shouldReceive('getKey')->andReturn(1); <add> $country->shouldReceive('getForeignKey')->andReturn('country_id'); <add> $user = m::mock('Illuminate\Database\Eloquent\Model'); <add> $user->shouldReceive('getTable')->andReturn('users'); <add> $user->shouldReceive('getQualifiedKeyName')->andReturn('users.id'); <add> $post = m::mock('Illuminate\Database\Eloquent\Model'); <add> $post->shouldReceive('getTable')->andReturn('posts'); <add> <add> $builder->shouldReceive('getModel')->andReturn($post); <add> <add> $user->shouldReceive('getKey')->andReturn(1); <add> $user->shouldReceive('getCreatedAtColumn')->andReturn('created_at'); <add> $user->shouldReceive('getUpdatedAtColumn')->andReturn('updated_at'); <add> return new HasManyThrough($builder, $country, $user, 'country_id', 'user_id'); <add> } <add> <add>} <add> <add>class EloquentHasManyThroughModelStub extends Illuminate\Database\Eloquent\Model { <add> public $country_id = 'foreign.value'; <add>} <ide>\ No newline at end of file
1
Javascript
Javascript
fix warning in flatlistexample
7104c1f3ce5b751bf1af71aceba5c6d410a964f6
<ide><path>RNTester/js/components/RNTesterExampleContainer.js <ide> const RNTesterBlock = require('./RNTesterBlock'); <ide> const RNTesterExampleFilter = require('./RNTesterExampleFilter'); <ide> const RNTesterPage = require('./RNTesterPage'); <ide> <add>const invariant = require('invariant'); <add> <ide> class RNTesterExampleContainer extends React.Component { <ide> renderExample(example, i) { <ide> // Filter platform-specific examples <ide> class RNTesterExampleContainer extends React.Component { <ide> } <ide> <ide> render(): React.Element<any> { <del> if (this.props.module.examples.length === 1) { <add> const {module} = this.props; <add> if (module.simpleExampleContainer) { <add> invariant( <add> module.examples.length === 1, <add> 'If noExampleContainer is specified, only one example is allowed', <add> ); <add> return module.examples[0].render(); <add> } <add> if (module.examples.length === 1) { <ide> return ( <ide> <RNTesterPage title={this.props.title}> <del> {this.renderExample(this.props.module.examples[0])} <add> {this.renderExample(module.examples[0])} <ide> </RNTesterPage> <ide> ); <ide> } <ide> class RNTesterExampleContainer extends React.Component { <ide> <ide> const sections = [ <ide> { <del> data: this.props.module.examples, <add> data: module.examples, <ide> title: 'EXAMPLES', <ide> key: 'e', <ide> }, <ide><path>RNTester/js/examples/FlatList/FlatListExample.js <ide> class FlatListExample extends React.PureComponent<Props, State> { <ide> const filteredData = this.state.data.filter(filter); <ide> const flatListItemRendererProps = this._renderItemComponent(); <ide> return ( <del> <RNTesterPage noSpacer={true} noScroll={true}> <add> <RNTesterPage <add> noSpacer={true} <add> noScroll={true} <add> title="Simple list of items"> <ide> <View style={styles.container}> <ide> <View style={styles.searchRow}> <ide> <View style={styles.options}> <ide> const styles = StyleSheet.create({ <ide> <ide> exports.title = '<FlatList>'; <ide> exports.description = 'Performant, scrollable list of data.'; <add>exports.simpleExampleContainer = true; <ide> exports.examples = [ <ide> { <ide> title: 'Simple list of items', <ide><path>RNTester/js/types/RNTesterTypes.js <ide> export type RNTesterExampleModule = $ReadOnly<{| <ide> displayName?: ?string, <ide> framework?: string, <ide> examples: Array<RNTesterExampleModuleItem>, <add> simpleExampleContainer?: ?boolean, <ide> |}>; <ide> <ide> export type RNTesterExample = $ReadOnly<{|
3
PHP
PHP
add options to sort (and order) routes
8ebfc02b24ec8b59cd12f879e7d28d0aadfbbe91
<ide><path>src/Illuminate/Foundation/Console/RouteListCommand.php <ide> protected function getRoutes() <ide> $results[] = $this->getRouteInformation($route); <ide> } <ide> <add> if ($sort = $this->option('sort')) { <add> $results = array_sort($results, function ($value) use ($sort) { <add> return $value[$sort]; <add> }); <add> } <add> <add> if ($this->option('reverse')) { <add> $results = array_reverse($results); <add> } <add> <ide> return array_filter($results); <ide> } <ide> <ide> protected function getOptions() <ide> ['name', null, InputOption::VALUE_OPTIONAL, 'Filter the routes by name.'], <ide> <ide> ['path', null, InputOption::VALUE_OPTIONAL, 'Filter the routes by path.'], <add> <add> ['reverse', 'r', InputOption::VALUE_NONE, 'Order descending alphabetically.'], <add> <add> ['sort', null, InputOption::VALUE_OPTIONAL, 'The column (domain, method, uri, name, action, middleware) to sort by.', 'uri'], <ide> ]; <ide> } <ide> }
1
Python
Python
raise error on complex input to i0
a2b9c2d5b6637b040917c0a2ef393dae83f09ee3
<ide><path>numpy/lib/function_base.py <ide> def i0(x): <ide> """ <ide> Modified Bessel function of the first kind, order 0. <ide> <del> Usually denoted :math:`I_0`. This function does broadcast, but will *not* <del> "up-cast" int dtype arguments unless accompanied by at least one float or <del> complex dtype argument (see Raises below). <add> Usually denoted :math:`I_0`. <ide> <ide> Parameters <ide> ---------- <del> x : array_like, dtype float or complex <add> x : array_like of float <ide> Argument of the Bessel function. <ide> <ide> Returns <ide> ------- <del> out : ndarray, shape = x.shape, dtype = x.dtype <add> out : ndarray, shape = x.shape, dtype = float <ide> The modified Bessel function evaluated at each of the elements of `x`. <ide> <del> Raises <del> ------ <del> TypeError: array cannot be safely cast to required type <del> If argument consists exclusively of int dtypes. <del> <ide> See Also <ide> -------- <ide> scipy.special.i0, scipy.special.iv, scipy.special.ive <ide> def i0(x): <ide> Examples <ide> -------- <ide> >>> np.i0(0.) <del> array(1.0) # may vary <del> >>> np.i0([0., 1. + 2j]) <del> array([ 1.00000000+0.j , 0.18785373+0.64616944j]) # may vary <add> array(1.0) <add> >>> np.i0([0, 1, 2, 3]) <add> array([1. , 1.26606588, 2.2795853 , 4.88079259]) <ide> <ide> """ <ide> x = np.asanyarray(x) <add> if x.dtype.kind == 'c': <add> raise TypeError("i0 not supported for complex values") <add> if x.dtype.kind != 'f': <add> x = x.astype(float) <ide> x = np.abs(x) <ide> return piecewise(x, [x <= 8.0], [_i0_1, _i0_2]) <ide> <ide><path>numpy/lib/tests/test_function_base.py <ide> def test_simple(self): <ide> i0(0.5), <ide> np.array(1.0634833707413234)) <ide> <del> A = np.array([0.49842636, 0.6969809, 0.22011976, 0.0155549]) <del> expected = np.array([1.06307822, 1.12518299, 1.01214991, 1.00006049]) <add> # need at least one test above 8, as the implementation is piecewise <add> A = np.array([0.49842636, 0.6969809, 0.22011976, 0.0155549, 10.0]) <add> expected = np.array([1.06307822, 1.12518299, 1.01214991, 1.00006049, 2815.71662847]) <ide> assert_almost_equal(i0(A), expected) <ide> assert_almost_equal(i0(-A), expected) <ide> <ide> def __array_wrap__(self, arr): <ide> <ide> assert_array_equal(exp, res) <ide> <add> def test_complex(self): <add> a = np.array([0, 1 + 2j]) <add> with pytest.raises(TypeError, match="i0 not supported for complex values"): <add> res = i0(a) <ide> <ide> class TestKaiser: <ide>
2
Ruby
Ruby
fix unsubscribe callbacks
568599dd206301b8fde9b75f4913de4caed65967
<ide><path>lib/action_cable/channel/base.rb <ide> def subscribe <ide> end <ide> <ide> def unsubscribe <del> self.class.on_unsubscribe.each do |callback| <add> self.class.on_unsubscribe_callbacks.each do |callback| <ide> EM.next_tick { send(callback) } <ide> end <ide> end
1
Javascript
Javascript
treat nodes with empty children arrays as leaves
d024c3f82c620681187ab15ed23e3cba28e54e11
<ide><path>d3.layout.js <ide> d3.layout.hierarchy = function() { <ide> // Also converts the data representation into a standard hierarchy structure. <ide> function recurse(data, depth, nodes) { <ide> var childs = children.call(hierarchy, data, depth), <add> n, <ide> node = d3_layout_hierarchyInline ? data : {data: data}; <ide> node.depth = depth; <ide> nodes.push(node); <del> if (childs) { <add> if (childs && (n = childs.length)) { <ide> var i = -1, <del> n = childs.length, <ide> c = node.children = [], <ide> v = 0, <ide> j = depth + 1; <ide><path>d3.layout.min.js <del>(function(){function bc(a,b){var c=a.x+b[3],d=a.y+b[0],e=a.dx-b[1]-b[3],f=a.dy-b[0]-b[2];e<0&&(c+=e/2,e=0),f<0&&(d+=f/2,f=0);return{x:c,y:d,dx:e,dy:f}}function bb(a){return{x:a.x,y:a.y,dx:a.dx,dy:a.dy}}function ba(a,b,c){return a._tree.ancestor.parent==b.parent?a._tree.ancestor:c}function _(a,b,c){a=a._tree,b=b._tree;var d=c/(b.number-a.number);a.change+=d,b.change-=d,b.shift+=c,b.prelim+=c,b.mod+=c}function $(a){var b=0,c=0,d=a.children,e=d.length,f;while(--e>=0)f=d[e]._tree,f.prelim+=b,f.mod+=b,b+=f.shift+(c+=f.change)}function Z(a,b){function c(a,d){var e=a.children;if(e){var f,g=null,h=-1,i=e.length;while(++h<i)f=e[h],c(f,g),g=f}b(a,d)}c(a,null)}function Y(a,b){return a.depth-b.depth}function X(a,b){return b.x-a.x}function W(a,b){return a.x-b.x}function V(a,b){var c=a.children;if(c){var d,e=c.length,f=-1;while(++f<e)b(d=V(c[f],b),a)>0&&(a=d)}return a}function U(a){return a.children?a.children[a.children.length-1]:a._tree.thread}function T(a){return a.children?a.children[0]:a._tree.thread}function S(a,b){return a.parent==b.parent?1:2}function R(a){var b=a.children;return b?R(b[b.length-1]):a}function Q(a){var b=a.children;return b?Q(b[0]):a}function P(a){return a.reduce(function(a,b){return a+b.x},0)/a.length}function O(a){return 1+d3.max(a,function(a){return a.y})}function N(a,b,c){var d=b.r+c.r,e=a.r+c.r,f=b.x-a.x,g=b.y-a.y,h=Math.sqrt(f*f+g*g),i=(e*e+h*h-d*d)/(2*e*h),j=Math.acos(i),k=i*e,l=Math.sin(j)*e;f/=h,g/=h,c.x=a.x+k*f+l*g,c.y=a.y+k*g-l*f}function M(a,b,c,d){var e=a.children;a.x=b+=d*a.x,a.y=c+=d*a.y,a.r*=d;if(e){var f=-1,g=e.length;while(++f<g)M(e[f],b,c,d)}}function L(a){var b=a.children;b?(b.forEach(L),a.r=I(b)):a.r=Math.sqrt(a.value)}function K(a){delete a._pack_next,delete a._pack_prev}function J(a){a._pack_next=a._pack_prev=a}function I(a){function l(a){b=Math.min(a.x-a.r,b),c=Math.max(a.x+a.r,c),d=Math.min(a.y-a.r,d),e=Math.max(a.y+a.r,e)}var b=Infinity,c=-Infinity,d=Infinity,e=-Infinity,f=a.length,g,h,i,j,k;a.forEach(J),g=a[0],g.x=-g.r,g.y=0,l(g);if(f>1){h=a[1],h.x=h.r,h.y=0,l(h);if(f>2){i=a[2],N(g,h,i),l(i),F(g,i),g._pack_prev=i,F(i,h),h=g._pack_next;for(var m=3;m<f;m++){N(g,h,i=a[m]);var n=0,o=1,p=1;for(j=h._pack_next;j!==h;j=j._pack_next,o++)if(H(j,i)){n=1;break}if(n==1)for(k=g._pack_prev;k!==j._pack_prev;k=k._pack_prev,p++)if(H(k,i)){p<o&&(n=-1,j=k);break}n==0?(F(g,i),h=i,l(i)):n>0?(G(g,j),h=j,m--):(G(j,h),g=j,m--)}}}var q=(b+c)/2,r=(d+e)/2,s=0;for(var m=0;m<f;m++){var t=a[m];t.x-=q,t.y-=r,s=Math.max(s,t.r+Math.sqrt(t.x*t.x+t.y*t.y))}a.forEach(K);return s}function H(a,b){var c=b.x-a.x,d=b.y-a.y,e=a.r+b.r;return e*e-c*c-d*d>.001}function G(a,b){a._pack_next=b,b._pack_prev=a}function F(a,b){var c=a._pack_next;a._pack_next=b,b._pack_prev=a,b._pack_next=c,c._pack_prev=b}function E(a,b){return a.value-b.value}function C(a){return d3.merge(a.map(function(a){return(a.children||[]).map(function(b){return{source:a,target:b}})}))}function B(a,b){return b.value-a.value}function A(a){return a.value}function z(a){return a.children}function y(a,b){a.sort=d3.rebind(a,b.sort),a.children=d3.rebind(a,b.children),a.links=C,a.value=d3.rebind(a,b.value),a.nodes=function(b){D=!0;return(a.nodes=a)(b)};return a}function x(a){return[d3.min(a),d3.max(a)]}function w(a,b){var c=-1,d=+a[0],e=(a[1]-d)/b,f=[];while(++c<=b)f[c]=e*c+d;return f}function v(a,b){return w(a,Math.ceil(Math.log(b.length)/Math.LN2+1))}function u(a,b){return a+b[1]}function t(a){return a.reduce(u,0)}function s(a){var b=1,c=0,d=a[0][1],e,f=a.length;for(;b<f;++b)(e=a[b][1])>d&&(c=b,d=e);return c}function p(a,b,c){a.y0=b,a.y=c}function o(a){return a.y}function n(a){return a.x}function m(a){return 1}function l(a){return 20}function k(a){var b=0,c=0;a.count=0;if(!a.leaf){var d=a.nodes,e=d.length,f=-1,g;while(++f<e){g=d[f];if(g==null)continue;k(g),a.count+=g.count,b+=g.count*g.cx,c+=g.count*g.cy}}a.point&&(a.leaf||(a.point.x+=Math.random()-.5,a.point.y+=Math.random()-.5),a.count++,b+=a.point.x,c+=a.point.y),a.cx=b/a.count,a.cy=c/a.count}function j(){f.px+=d3.event.dx,f.py+=d3.event.dy,e.resume()}function i(){j(),f.fixed&=1,e=f=null}function h(a){a!==f&&(a.fixed&=1)}function g(a){a.fixed|=2}function c(a,c){if(a===c)return a;var d=b(a),e=b(c),f=d.pop(),g=e.pop(),h=null;while(f===g)h=f,f=d.pop(),g=e.pop();return h}function b(a){var b=[],c=a.parent;while(c!=null)b.push(a),a=c,c=c.parent;b.push(a);return b}function a(a){var b=a.source,d=a.target,e=c(b,d),f=[b];while(b!==e)b=b.parent,f.push(b);var g=f.length;while(d!==e)f.splice(g,0,d),d=d.parent;return f}d3.layout={},d3.layout.bundle=function(){return function(b){var c=[],d=-1,e=b.length;while(++d<e)c.push(a(b[d]));return c}},d3.layout.chord=function(){function k(){b.sort(function(a,b){return i(a.target.value,b.target.value)})}function j(){var a={},j=[],l=d3.range(e),m=[],n,o,p,q,r;b=[],c=[],n=0,q=-1;while(++q<e){o=0,r=-1;while(++r<e)o+=d[q][r];j.push(o),m.push(d3.range(e)),n+=o}g&&l.sort(function(a,b){return g(j[a],j[b])}),h&&m.forEach(function(a,b){a.sort(function(a,c){return h(d[b][a],d[b][c])})}),n=(2*Math.PI-f*e)/n,o=0,q=-1;while(++q<e){p=o,r=-1;while(++r<e){var s=l[q],t=m[q][r],u=d[s][t];a[s+"-"+t]={index:s,subindex:t,startAngle:o,endAngle:o+=u*n,value:u}}c.push({index:s,startAngle:p,endAngle:o,value:(o-p)/n}),o+=f}q=-1;while(++q<e){r=q-1;while(++r<e){var v=a[q+"-"+r],w=a[r+"-"+q];(v.value||w.value)&&b.push(v.value<w.value?{source:w,target:v}:{source:v,target:w})}}i&&k()}var a={},b,c,d,e,f=0,g,h,i;a.matrix=function(f){if(!arguments.length)return d;e=(d=f)&&d.length,b=c=null;return a},a.padding=function(d){if(!arguments.length)return f;f=d,b=c=null;return a},a.sortGroups=function(d){if(!arguments.length)return g;g=d,b=c=null;return a},a.sortSubgroups=function(c){if(!arguments.length)return h;h=c,b=null;return a},a.sortChords=function(c){if(!arguments.length)return i;i=c,b&&k();return a},a.chords=function(){b||j();return b},a.groups=function(){c||j();return c};return a},d3.layout.force=function(){function B(b){g(f=b),e=a}function A(){var a=v.length,d=w.length,e,f,g,h,i,j,l,m,p;for(f=0;f<d;++f){g=w[f],h=g.source,i=g.target,m=i.x-h.x,p=i.y-h.y;if(j=m*m+p*p)j=n*y[f]*((j=Math.sqrt(j))-x[f])/j,m*=j,p*=j,i.x-=m*(l=h.weight/(i.weight+h.weight)),i.y-=p*l,h.x+=m*(l=1-l),h.y+=p*l}if(l=n*s){m=c[0]/2,p=c[1]/2,f=-1;if(l)while(++f<a)g=v[f],g.x+=(m-g.x)*l,g.y+=(p-g.y)*l}if(l=n*r){k(e=d3.geom.quadtree(v)),f=-1;while(++f<a)(g=v[f]).fixed||e.visit(z(g,l))}f=-1;while(++f<a)g=v[f],g.fixed?(g.x=g.px,g.y=g.py):(g.x-=(g.px-(g.px=g.x))*o,g.y-=(g.py-(g.py=g.y))*o);b.tick.dispatch({type:"tick",alpha:n});return(n*=.99)<.005}function z(a,b){return function(c,d,e,f,g){if(c.point!==a){var h=c.cx-a.x,i=c.cy-a.y,j=1/Math.sqrt(h*h+i*i);if((f-d)*j<t){var k=b*c.count*j*j;a.px-=h*k,a.py-=i*k;return!0}if(c.point&&isFinite(j)){var k=b*j*j;a.px-=h*k,a.py-=i*k}}}}var a={},b=d3.dispatch("tick"),c=[1,1],d,n,o=.9,p=l,q=m,r=-30,s=.1,t=.8,u,v=[],w=[],x,y;a.on=function(c,d){b[c].add(d);return a},a.nodes=function(b){if(!arguments.length)return v;v=b;return a},a.links=function(b){if(!arguments.length)return w;w=b;return a},a.size=function(b){if(!arguments.length)return c;c=b;return a},a.linkDistance=function(b){if(!arguments.length)return p;p=d3.functor(b);return a},a.distance=a.linkDistance,a.linkStrength=function(b){if(!arguments.length)return q;q=d3.functor(b);return a},a.friction=function(b){if(!arguments.length)return o;o=b;return a},a.charge=function(b){if(!arguments.length)return r;r=b;return a},a.gravity=function(b){if(!arguments.length)return s;s=b;return a},a.theta=function(b){if(!arguments.length)return t;t=b;return a},a.start=function(){function l(){if(!i){i=[];for(d=0;d<e;++d)i[d]=[];for(d=0;d<f;++d){var a=w[d];i[a.source.index].push(a.target),i[a.target.index].push(a.source)}}return i[b]}function k(a,c){var d=l(b),e=-1,f=d.length,g;while(++e<f)if(!isNaN(g=d[e][a]))return g;return Math.random()*c}var b,d,e=v.length,f=w.length,g=c[0],h=c[1],i,j;for(b=0;b<e;++b)(j=v[b]).index=b,j.weight=0;x=[],y=[];for(b=0;b<f;++b)j=w[b],typeof j.source=="number"&&(j.source=v[j.source]),typeof j.target=="number"&&(j.target=v[j.target]),x[b]=p.call(this,j,b),y[b]=q.call(this,j,b),++j.source.weight,++j.target.weight;for(b=0;b<e;++b)j=v[b],isNaN(j.x)&&(j.x=k("x",g)),isNaN(j.y)&&(j.y=k("y",h)),isNaN(j.px)&&(j.px=j.x),isNaN(j.py)&&(j.py=j.y);return a.resume()},a.resume=function(){n=.1,d3.timer(A);return a},a.stop=function(){n=0;return a},a.drag=function(){d||(d=d3.behavior.drag().on("dragstart",B).on("drag",j).on("dragend",i)),this.on("mouseover.force",g).on("mouseout.force",h).call(d)};return a};var e,f;d3.layout.partition=function(){function e(e,f){var g=a.call(this,e,f);c(g[0],0,b[0],b[1]/d(g[0]));return g}function d(a){var b=a.children,c=0;if(b){var e=-1,f=b.length;while(++e<f)c=Math.max(c,d(b[e]))}return 1+c}function c(a,b,d,e){var f=a.children;a.x=b,a.y=a.depth*e,a.dx=d,a.dy=e;if(f){var g=-1,h=f.length,i,j;d=a.value?d/a.value:0;while(++g<h)c(i=f[g],b,j=i.value*d,e),b+=j}}var a=d3.layout.hierarchy(),b=[1,1];e.size=function(a){if(!arguments.length)return b;b=a;return e};return y(e,a)},d3.layout.pie=function(){function f(f,g){var h=+(typeof c=="function"?c.apply(this,arguments):c),i=(typeof e=="function"?e.apply(this,arguments):e)-c,j=d3.range(f.length);b!=null&&j.sort(function(a,c){return b(f[a],f[c])});var k=f.map(a);i/=k.reduce(function(a,b){return a+b},0);var l=j.map(function(a){return{data:f[a],value:d=k[a],startAngle:h,endAngle:h+=d*i}});return f.map(function(a,b){return l[j[b]]})}var a=Number,b=null,c=0,e=2*Math.PI;f.value=function(b){if(!arguments.length)return a;a=b;return f},f.sort=function(a){if(!arguments.length)return b;b=a;return f},f.startAngle=function(a){if(!arguments.length)return c;c=a;return f},f.endAngle=function(a){if(!arguments.length)return e;e=a;return f};return f},d3.layout.stack=function(){function g(h,i){var j=h.map(function(b,c){return a.call(g,b,c)}),k=j.map(function(a,b){return a.map(function(a,b){return[e.call(g,a,b),f.call(g,a,b)]})}),l=b.call(g,k,i);j=d3.permute(j,l),k=d3.permute(k,l);var m=c.call(g,k,i),n=j.length,o=j[0].length,p,q,r;for(q=0;q<o;++q){d.call(g,j[0][q],r=m[q],k[0][q][1]);for(p=1;p<n;++p)d.call(g,j[p][q],r+=k[p-1][q][1],k[p][q][1])}return h}var a=Object,b=q["default"],c=r.zero,d=p,e=n,f=o;g.values=function(b){if(!arguments.length)return a;a=b;return g},g.order=function(a){if(!arguments.length)return b;b=typeof a=="function"?a:q[a];return g},g.offset=function(a){if(!arguments.length)return c;c=typeof a=="function"?a:r[a];return g},g.x=function(a){if(!arguments.length)return e;e=a;return g},g.y=function(a){if(!arguments.length)return f;f=a;return g},g.out=function(a){if(!arguments.length)return d;d=a;return g};return g};var q={"inside-out":function(a){var b=a.length,c,d,e=a.map(s),f=a.map(t),g=d3.range(b).sort(function(a,b){return e[a]-e[b]}),h=0,i=0,j=[],k=[];for(c=0;c<b;++c)d=g[c],h<i?(h+=f[d],j.push(d)):(i+=f[d],k.push(d));return k.reverse().concat(j)},reverse:function(a){return d3.range(a.length).reverse()},"default":function(a){return d3.range(a.length)}},r={silhouette:function(a){var b=a.length,c=a[0].length,d=[],e=0,f,g,h,i=[];for(g=0;g<c;++g){for(f=0,h=0;f<b;f++)h+=a[f][g][1];h>e&&(e=h),d.push(h)}for(g=0;g<c;++g)i[g]=(e-d[g])/2;return i},wiggle:function(a){var b=a.length,c=a[0],d=c.length,e=0,f,g,h,i,j,k,l,m,n,o=[];o[0]=m=n=0;for(g=1;g<d;++g){for(f=0,i=0;f<b;++f)i+=a[f][g][1];for(f=0,j=0,l=c[g][0]-c[g-1][0];f<b;++f){for(h=0,k=(a[f][g][1]-a[f][g-1][1])/(2*l);h<f;++h)k+=(a[h][g][1]-a[h][g-1][1])/l;j+=k*a[f][g][1]}o[g]=m-=i?j/i*l:0,m<n&&(n=m)}for(g=0;g<d;++g)o[g]-=n;return o},expand:function(a){var b=a.length,c=a[0].length,d=1/b,e,f,g,h=[];for(f=0;f<c;++f){for(e=0,g=0;e<b;e++)g+=a[e][f][1];if(g)for(e=0;e<b;e++)a[e][f][1]/=g;else for(e=0;e<b;e++)a[e][f][1]=d}for(f=0;f<c;++f)h[f]=0;return h},zero:function(a){var b=-1,c=a[0].length,d=[];while(++b<c)d[b]=0;return d}};d3.layout.histogram=function(){function e(e,f){var g=[],h=e.map(b,this),i=c.call(this,h,f),j=d.call(this,i,h,f),k,f=-1,l=h.length,m=j.length-1,n=a?1:1/l,o;while(++f<m)k=g[f]=[],k.dx=j[f+1]-(k.x=j[f]),k.y=0;f=-1;while(++f<l)o=h[f],o>=i[0]&&o<=i[1]&&(k=g[d3.bisect(j,o,1,m)-1],k.y+=n,k.push(e[f]));return g}var a=!0,b=Number,c=x,d=v;e.value=function(a){if(!arguments.length)return b;b=a;return e},e.range=function(a){if(!arguments.length)return c;c=d3.functor(a);return e},e.bins=function(a){if(!arguments.length)return d;d=typeof a=="number"?function(b){return w(b,a)}:d3.functor(a);return e},e.frequency=function(b){if(!arguments.length)return a;a=!!b;return e};return e},d3.layout.hierarchy=function(){function g(a){var b=[];e(a,0,b);return b}function f(a,b){var d=a.children,e=0;if(d){var h=-1,i=d.length,j=b+1;while(++h<i)e+=f(d[h],j)}else c&&(e=+c.call(g,D?a:a.data,b)||0);c&&(a.value=e);return e}function e(f,h,i){var j=b.call(g,f,h),k=D?f:{data:f};k.depth=h,i.push(k);if(j){var l=-1,m=j.length,n=k.children=[],o=0,p=h+1;while(++l<m)d=e(j[l],p,i),d.parent=k,n.push(d),o+=d.value;a&&n.sort(a),c&&(k.value=o)}else c&&(k.value=+c.call(g,f,h)||0);return k}var a=B,b=z,c=A;g.sort=function(b){if(!arguments.length)return a;a=b;return g},g.children=function(a){if(!arguments.length)return b;b=a;return g},g.value=function(a){if(!arguments.length)return c;c=a;return g},g.revalue=function(a){f(a,0);return a};return g};var D=!1;d3.layout.pack=function(){function c(c,d){var e=a.call(this,c,d),f=e[0];f.x=0,f.y=0,L(f);var g=b[0],h=b[1],i=1/Math.max(2*f.r/g,2*f.r/h);M(f,g/2,h/2,i);return e}var a=d3.layout.hierarchy().sort(E),b=[1,1];c.size=function(a){if(!arguments.length)return b;b=a;return c};return y(c,a)},d3.layout.cluster=function(){function d(d,e){var f=a.call(this,d,e),g=f[0],h,i=0,j,k;Z(g,function(a){a.children?(a.x=P(a.children),a.y=O(a.children)):(a.x=h?i+=b(a,h):0,a.y=0,h=a)});var l=Q(g),m=R(g),n=l.x-b(l,m)/2,o=m.x+b(m,l)/2;Z(g,function(a){a.x=(a.x-n)/(o-n)*c[0],a.y=(1-a.y/g.y)*c[1]});return f}var a=d3.layout.hierarchy().sort(null).value(null),b=S,c=[1,1];d.separation=function(a){if(!arguments.length)return b;b=a;return d},d.size=function(a){if(!arguments.length)return c;c=a;return d};return y(d,a)},d3.layout.tree=function(){function d(d,e){function j(a,c,d){if(c){var e=a,f=a,g=c,h=a.parent.children[0],i=e._tree.mod,j=f._tree.mod,k=g._tree.mod,l=h._tree.mod,m;while(g=U(g),e=T(e),g&&e)h=T(h),f=U(f),f._tree.ancestor=a,m=g._tree.prelim+k-e._tree.prelim-i+b(g,e),m>0&&(_(ba(g,a,d),a,m),i+=m,j+=m),k+=g._tree.mod,i+=e._tree.mod,l+=h._tree.mod,j+=f._tree.mod;g&&!U(f)&&(f._tree.thread=g,f._tree.mod+=k-j),e&&!T(h)&&(h._tree.thread=e,h._tree.mod+=i-l,d=a)}return d}function i(a,b){a.x=a._tree.prelim+b;var c=a.children;if(c){var d=-1,e=c.length;b+=a._tree.mod;while(++d<e)i(c[d],b)}}function h(a,c){var d=a.children,e=a._tree;if(d&&(f=d.length)){var f,g=d[0],i,k=g,l,m=-1;while(++m<f)l=d[m],h(l,i),k=j(l,i,k),i=l;$(a);var n=.5*(g._tree.prelim+l._tree.prelim);c?(e.prelim=c._tree.prelim+b(a,c),e.mod=e.prelim-n):e.prelim=n}else c&&(e.prelim=c._tree.prelim+b(a,c))}var f=a.call(this,d,e),g=f[0];Z(g,function(a,b){a._tree={ancestor:a,prelim:0,mod:0,change:0,shift:0,number:b?b._tree.number+1:0}}),h(g),i(g,-g._tree.prelim);var k=V(g,X),l=V(g,W),m=V(g,Y),n=k.x-b(k,l)/2,o=l.x+b(l,k)/2,p=m.depth||1;Z(g,function(a){a.x=(a.x-n)/(o-n)*c[0],a.y=a.depth/p*c[1],delete a._tree});return f}var a=d3.layout.hierarchy().sort(null).value(null),b=S,c=[1,1];d.separation=function(a){if(!arguments.length)return b;b=a;return d},d.size=function(a){if(!arguments.length)return c;c=a;return d};return y(d,a)},d3.layout.treemap=function(){function n(b){var d=g||a(b),e=d[0];e.x=0,e.y=0,e.dx=c[0],e.dy=c[1],g&&a.revalue(e),i([e],e.dx*e.dy/e.value),(g?k:j)(e),f&&(g=d);return d}function m(a,c,d,e){var f=-1,g=a.length,h=d.x,i=d.y,j=c?b(a.area/c):0,k;if(c==d.dx){if(e||j>d.dy)j=j?d.dy:0;while(++f<g)k=a[f],k.x=h,k.y=i,k.dy=j,h+=k.dx=j?b(k.area/j):0;k.z=!0,k.dx+=d.x+d.dx-h,d.y+=j,d.dy-=j}else{if(e||j>d.dx)j=j?d.dx:0;while(++f<g)k=a[f],k.x=h,k.y=i,k.dx=j,i+=k.dy=j?b(k.area/j):0;k.z=!1,k.dy+=d.y+d.dy-i,d.x+=j,d.dx-=j}}function l(a,b){var c=a.area,d,e=0,f=Infinity,g=-1,i=a.length;while(++g<i){if(!(d=a[g].area))continue;d<f&&(f=d),d>e&&(e=d)}c*=c,b*=b;return c?Math.max(b*e*h/c,c/(b*f*h)):Infinity}function k(a){if(!!a.children){var b=e(a),c=a.children.slice(),d,f=[];i(c,b.dx*b.dy/a.value),f.area=0;while(d=c.pop())f.push(d),f.area+=d.area,d.z!=null&&(m(f,d.z?b.dx:b.dy,b,!c.length),f.length=f.area=0);a.children.forEach(k)}}function j(a){if(!!a.children){var b=e(a),c=[],d=a.children.slice(),f,g=Infinity,h,k=Math.min(b.dx,b.dy),n;i(d,b.dx*b.dy/a.value),c.area=0;while((n=d.length)>0)c.push(f=d[n-1]),c.area+=f.area,(h=l(c,k))<=g?(d.pop(),g=h):(c.area-=c.pop().area,m(c,k,b,!1),k=Math.min(b.dx,b.dy),c.length=c.area=0,g=Infinity);c.length&&(m(c,k,b,!0),c.length=c.area=0),a.children.forEach(j)}}function i(a,b){var c=-1,d=a.length,e,f;while(++c<d)f=(e=a[c]).value*(b<0?0:b),e.area=isNaN(f)||f<=0?0:f}var a=d3.layout.hierarchy(),b=Math.round,c=[1,1],d=null,e=bb,f=!1,g,h=.5*(1+Math.sqrt(5));n.size=function(a){if(!arguments.length)return c;c=a;return n},n.padding=function(a){function c(b){return bc(b,a)}function b(b){var c=a.call(n,b,b.depth);return c==null?bb(b):bc(b,typeof c=="number"?[c,c,c,c]:c)}if(!arguments.length)return d;var f;e=(d=a)==null?bb:(f=typeof a)==="function"?b:f==="number"?(a=[a,a,a,a],c):c;return n},n.round=function(a){if(!arguments.length)return b!=Number;b=a?Math.round:Number;return n},n.sticky=function(a){if(!arguments.length)return f;f=a,g=null;return n},n.ratio=function(a){if(!arguments.length)return h;h=a;return n};return y(n,a)}})() <ide>\ No newline at end of file <add>(function(){function bc(a,b){var c=a.x+b[3],d=a.y+b[0],e=a.dx-b[1]-b[3],f=a.dy-b[0]-b[2];e<0&&(c+=e/2,e=0),f<0&&(d+=f/2,f=0);return{x:c,y:d,dx:e,dy:f}}function bb(a){return{x:a.x,y:a.y,dx:a.dx,dy:a.dy}}function ba(a,b,c){return a._tree.ancestor.parent==b.parent?a._tree.ancestor:c}function _(a,b,c){a=a._tree,b=b._tree;var d=c/(b.number-a.number);a.change+=d,b.change-=d,b.shift+=c,b.prelim+=c,b.mod+=c}function $(a){var b=0,c=0,d=a.children,e=d.length,f;while(--e>=0)f=d[e]._tree,f.prelim+=b,f.mod+=b,b+=f.shift+(c+=f.change)}function Z(a,b){function c(a,d){var e=a.children;if(e){var f,g=null,h=-1,i=e.length;while(++h<i)f=e[h],c(f,g),g=f}b(a,d)}c(a,null)}function Y(a,b){return a.depth-b.depth}function X(a,b){return b.x-a.x}function W(a,b){return a.x-b.x}function V(a,b){var c=a.children;if(c){var d,e=c.length,f=-1;while(++f<e)b(d=V(c[f],b),a)>0&&(a=d)}return a}function U(a){return a.children?a.children[a.children.length-1]:a._tree.thread}function T(a){return a.children?a.children[0]:a._tree.thread}function S(a,b){return a.parent==b.parent?1:2}function R(a){var b=a.children;return b?R(b[b.length-1]):a}function Q(a){var b=a.children;return b?Q(b[0]):a}function P(a){return a.reduce(function(a,b){return a+b.x},0)/a.length}function O(a){return 1+d3.max(a,function(a){return a.y})}function N(a,b,c){var d=b.r+c.r,e=a.r+c.r,f=b.x-a.x,g=b.y-a.y,h=Math.sqrt(f*f+g*g),i=(e*e+h*h-d*d)/(2*e*h),j=Math.acos(i),k=i*e,l=Math.sin(j)*e;f/=h,g/=h,c.x=a.x+k*f+l*g,c.y=a.y+k*g-l*f}function M(a,b,c,d){var e=a.children;a.x=b+=d*a.x,a.y=c+=d*a.y,a.r*=d;if(e){var f=-1,g=e.length;while(++f<g)M(e[f],b,c,d)}}function L(a){var b=a.children;b?(b.forEach(L),a.r=I(b)):a.r=Math.sqrt(a.value)}function K(a){delete a._pack_next,delete a._pack_prev}function J(a){a._pack_next=a._pack_prev=a}function I(a){function l(a){b=Math.min(a.x-a.r,b),c=Math.max(a.x+a.r,c),d=Math.min(a.y-a.r,d),e=Math.max(a.y+a.r,e)}var b=Infinity,c=-Infinity,d=Infinity,e=-Infinity,f=a.length,g,h,i,j,k;a.forEach(J),g=a[0],g.x=-g.r,g.y=0,l(g);if(f>1){h=a[1],h.x=h.r,h.y=0,l(h);if(f>2){i=a[2],N(g,h,i),l(i),F(g,i),g._pack_prev=i,F(i,h),h=g._pack_next;for(var m=3;m<f;m++){N(g,h,i=a[m]);var n=0,o=1,p=1;for(j=h._pack_next;j!==h;j=j._pack_next,o++)if(H(j,i)){n=1;break}if(n==1)for(k=g._pack_prev;k!==j._pack_prev;k=k._pack_prev,p++)if(H(k,i)){p<o&&(n=-1,j=k);break}n==0?(F(g,i),h=i,l(i)):n>0?(G(g,j),h=j,m--):(G(j,h),g=j,m--)}}}var q=(b+c)/2,r=(d+e)/2,s=0;for(var m=0;m<f;m++){var t=a[m];t.x-=q,t.y-=r,s=Math.max(s,t.r+Math.sqrt(t.x*t.x+t.y*t.y))}a.forEach(K);return s}function H(a,b){var c=b.x-a.x,d=b.y-a.y,e=a.r+b.r;return e*e-c*c-d*d>.001}function G(a,b){a._pack_next=b,b._pack_prev=a}function F(a,b){var c=a._pack_next;a._pack_next=b,b._pack_prev=a,b._pack_next=c,c._pack_prev=b}function E(a,b){return a.value-b.value}function C(a){return d3.merge(a.map(function(a){return(a.children||[]).map(function(b){return{source:a,target:b}})}))}function B(a,b){return b.value-a.value}function A(a){return a.value}function z(a){return a.children}function y(a,b){a.sort=d3.rebind(a,b.sort),a.children=d3.rebind(a,b.children),a.links=C,a.value=d3.rebind(a,b.value),a.nodes=function(b){D=!0;return(a.nodes=a)(b)};return a}function x(a){return[d3.min(a),d3.max(a)]}function w(a,b){var c=-1,d=+a[0],e=(a[1]-d)/b,f=[];while(++c<=b)f[c]=e*c+d;return f}function v(a,b){return w(a,Math.ceil(Math.log(b.length)/Math.LN2+1))}function u(a,b){return a+b[1]}function t(a){return a.reduce(u,0)}function s(a){var b=1,c=0,d=a[0][1],e,f=a.length;for(;b<f;++b)(e=a[b][1])>d&&(c=b,d=e);return c}function p(a,b,c){a.y0=b,a.y=c}function o(a){return a.y}function n(a){return a.x}function m(a){return 1}function l(a){return 20}function k(a){var b=0,c=0;a.count=0;if(!a.leaf){var d=a.nodes,e=d.length,f=-1,g;while(++f<e){g=d[f];if(g==null)continue;k(g),a.count+=g.count,b+=g.count*g.cx,c+=g.count*g.cy}}a.point&&(a.leaf||(a.point.x+=Math.random()-.5,a.point.y+=Math.random()-.5),a.count++,b+=a.point.x,c+=a.point.y),a.cx=b/a.count,a.cy=c/a.count}function j(){f.px+=d3.event.dx,f.py+=d3.event.dy,e.resume()}function i(){j(),f.fixed&=1,e=f=null}function h(a){a!==f&&(a.fixed&=1)}function g(a){a.fixed|=2}function c(a,c){if(a===c)return a;var d=b(a),e=b(c),f=d.pop(),g=e.pop(),h=null;while(f===g)h=f,f=d.pop(),g=e.pop();return h}function b(a){var b=[],c=a.parent;while(c!=null)b.push(a),a=c,c=c.parent;b.push(a);return b}function a(a){var b=a.source,d=a.target,e=c(b,d),f=[b];while(b!==e)b=b.parent,f.push(b);var g=f.length;while(d!==e)f.splice(g,0,d),d=d.parent;return f}d3.layout={},d3.layout.bundle=function(){return function(b){var c=[],d=-1,e=b.length;while(++d<e)c.push(a(b[d]));return c}},d3.layout.chord=function(){function k(){b.sort(function(a,b){return i(a.target.value,b.target.value)})}function j(){var a={},j=[],l=d3.range(e),m=[],n,o,p,q,r;b=[],c=[],n=0,q=-1;while(++q<e){o=0,r=-1;while(++r<e)o+=d[q][r];j.push(o),m.push(d3.range(e)),n+=o}g&&l.sort(function(a,b){return g(j[a],j[b])}),h&&m.forEach(function(a,b){a.sort(function(a,c){return h(d[b][a],d[b][c])})}),n=(2*Math.PI-f*e)/n,o=0,q=-1;while(++q<e){p=o,r=-1;while(++r<e){var s=l[q],t=m[q][r],u=d[s][t];a[s+"-"+t]={index:s,subindex:t,startAngle:o,endAngle:o+=u*n,value:u}}c.push({index:s,startAngle:p,endAngle:o,value:(o-p)/n}),o+=f}q=-1;while(++q<e){r=q-1;while(++r<e){var v=a[q+"-"+r],w=a[r+"-"+q];(v.value||w.value)&&b.push(v.value<w.value?{source:w,target:v}:{source:v,target:w})}}i&&k()}var a={},b,c,d,e,f=0,g,h,i;a.matrix=function(f){if(!arguments.length)return d;e=(d=f)&&d.length,b=c=null;return a},a.padding=function(d){if(!arguments.length)return f;f=d,b=c=null;return a},a.sortGroups=function(d){if(!arguments.length)return g;g=d,b=c=null;return a},a.sortSubgroups=function(c){if(!arguments.length)return h;h=c,b=null;return a},a.sortChords=function(c){if(!arguments.length)return i;i=c,b&&k();return a},a.chords=function(){b||j();return b},a.groups=function(){c||j();return c};return a},d3.layout.force=function(){function B(b){g(f=b),e=a}function A(){var a=v.length,d=w.length,e,f,g,h,i,j,l,m,p;for(f=0;f<d;++f){g=w[f],h=g.source,i=g.target,m=i.x-h.x,p=i.y-h.y;if(j=m*m+p*p)j=n*y[f]*((j=Math.sqrt(j))-x[f])/j,m*=j,p*=j,i.x-=m*(l=h.weight/(i.weight+h.weight)),i.y-=p*l,h.x+=m*(l=1-l),h.y+=p*l}if(l=n*s){m=c[0]/2,p=c[1]/2,f=-1;if(l)while(++f<a)g=v[f],g.x+=(m-g.x)*l,g.y+=(p-g.y)*l}if(l=n*r){k(e=d3.geom.quadtree(v)),f=-1;while(++f<a)(g=v[f]).fixed||e.visit(z(g,l))}f=-1;while(++f<a)g=v[f],g.fixed?(g.x=g.px,g.y=g.py):(g.x-=(g.px-(g.px=g.x))*o,g.y-=(g.py-(g.py=g.y))*o);b.tick.dispatch({type:"tick",alpha:n});return(n*=.99)<.005}function z(a,b){return function(c,d,e,f,g){if(c.point!==a){var h=c.cx-a.x,i=c.cy-a.y,j=1/Math.sqrt(h*h+i*i);if((f-d)*j<t){var k=b*c.count*j*j;a.px-=h*k,a.py-=i*k;return!0}if(c.point&&isFinite(j)){var k=b*j*j;a.px-=h*k,a.py-=i*k}}}}var a={},b=d3.dispatch("tick"),c=[1,1],d,n,o=.9,p=l,q=m,r=-30,s=.1,t=.8,u,v=[],w=[],x,y;a.on=function(c,d){b[c].add(d);return a},a.nodes=function(b){if(!arguments.length)return v;v=b;return a},a.links=function(b){if(!arguments.length)return w;w=b;return a},a.size=function(b){if(!arguments.length)return c;c=b;return a},a.linkDistance=function(b){if(!arguments.length)return p;p=d3.functor(b);return a},a.distance=a.linkDistance,a.linkStrength=function(b){if(!arguments.length)return q;q=d3.functor(b);return a},a.friction=function(b){if(!arguments.length)return o;o=b;return a},a.charge=function(b){if(!arguments.length)return r;r=b;return a},a.gravity=function(b){if(!arguments.length)return s;s=b;return a},a.theta=function(b){if(!arguments.length)return t;t=b;return a},a.start=function(){function l(){if(!i){i=[];for(d=0;d<e;++d)i[d]=[];for(d=0;d<f;++d){var a=w[d];i[a.source.index].push(a.target),i[a.target.index].push(a.source)}}return i[b]}function k(a,c){var d=l(b),e=-1,f=d.length,g;while(++e<f)if(!isNaN(g=d[e][a]))return g;return Math.random()*c}var b,d,e=v.length,f=w.length,g=c[0],h=c[1],i,j;for(b=0;b<e;++b)(j=v[b]).index=b,j.weight=0;x=[],y=[];for(b=0;b<f;++b)j=w[b],typeof j.source=="number"&&(j.source=v[j.source]),typeof j.target=="number"&&(j.target=v[j.target]),x[b]=p.call(this,j,b),y[b]=q.call(this,j,b),++j.source.weight,++j.target.weight;for(b=0;b<e;++b)j=v[b],isNaN(j.x)&&(j.x=k("x",g)),isNaN(j.y)&&(j.y=k("y",h)),isNaN(j.px)&&(j.px=j.x),isNaN(j.py)&&(j.py=j.y);return a.resume()},a.resume=function(){n=.1,d3.timer(A);return a},a.stop=function(){n=0;return a},a.drag=function(){d||(d=d3.behavior.drag().on("dragstart",B).on("drag",j).on("dragend",i)),this.on("mouseover.force",g).on("mouseout.force",h).call(d)};return a};var e,f;d3.layout.partition=function(){function e(e,f){var g=a.call(this,e,f);c(g[0],0,b[0],b[1]/d(g[0]));return g}function d(a){var b=a.children,c=0;if(b){var e=-1,f=b.length;while(++e<f)c=Math.max(c,d(b[e]))}return 1+c}function c(a,b,d,e){var f=a.children;a.x=b,a.y=a.depth*e,a.dx=d,a.dy=e;if(f){var g=-1,h=f.length,i,j;d=a.value?d/a.value:0;while(++g<h)c(i=f[g],b,j=i.value*d,e),b+=j}}var a=d3.layout.hierarchy(),b=[1,1];e.size=function(a){if(!arguments.length)return b;b=a;return e};return y(e,a)},d3.layout.pie=function(){function f(f,g){var h=+(typeof c=="function"?c.apply(this,arguments):c),i=(typeof e=="function"?e.apply(this,arguments):e)-c,j=d3.range(f.length);b!=null&&j.sort(function(a,c){return b(f[a],f[c])});var k=f.map(a);i/=k.reduce(function(a,b){return a+b},0);var l=j.map(function(a){return{data:f[a],value:d=k[a],startAngle:h,endAngle:h+=d*i}});return f.map(function(a,b){return l[j[b]]})}var a=Number,b=null,c=0,e=2*Math.PI;f.value=function(b){if(!arguments.length)return a;a=b;return f},f.sort=function(a){if(!arguments.length)return b;b=a;return f},f.startAngle=function(a){if(!arguments.length)return c;c=a;return f},f.endAngle=function(a){if(!arguments.length)return e;e=a;return f};return f},d3.layout.stack=function(){function g(h,i){var j=h.map(function(b,c){return a.call(g,b,c)}),k=j.map(function(a,b){return a.map(function(a,b){return[e.call(g,a,b),f.call(g,a,b)]})}),l=b.call(g,k,i);j=d3.permute(j,l),k=d3.permute(k,l);var m=c.call(g,k,i),n=j.length,o=j[0].length,p,q,r;for(q=0;q<o;++q){d.call(g,j[0][q],r=m[q],k[0][q][1]);for(p=1;p<n;++p)d.call(g,j[p][q],r+=k[p-1][q][1],k[p][q][1])}return h}var a=Object,b=q["default"],c=r.zero,d=p,e=n,f=o;g.values=function(b){if(!arguments.length)return a;a=b;return g},g.order=function(a){if(!arguments.length)return b;b=typeof a=="function"?a:q[a];return g},g.offset=function(a){if(!arguments.length)return c;c=typeof a=="function"?a:r[a];return g},g.x=function(a){if(!arguments.length)return e;e=a;return g},g.y=function(a){if(!arguments.length)return f;f=a;return g},g.out=function(a){if(!arguments.length)return d;d=a;return g};return g};var q={"inside-out":function(a){var b=a.length,c,d,e=a.map(s),f=a.map(t),g=d3.range(b).sort(function(a,b){return e[a]-e[b]}),h=0,i=0,j=[],k=[];for(c=0;c<b;++c)d=g[c],h<i?(h+=f[d],j.push(d)):(i+=f[d],k.push(d));return k.reverse().concat(j)},reverse:function(a){return d3.range(a.length).reverse()},"default":function(a){return d3.range(a.length)}},r={silhouette:function(a){var b=a.length,c=a[0].length,d=[],e=0,f,g,h,i=[];for(g=0;g<c;++g){for(f=0,h=0;f<b;f++)h+=a[f][g][1];h>e&&(e=h),d.push(h)}for(g=0;g<c;++g)i[g]=(e-d[g])/2;return i},wiggle:function(a){var b=a.length,c=a[0],d=c.length,e=0,f,g,h,i,j,k,l,m,n,o=[];o[0]=m=n=0;for(g=1;g<d;++g){for(f=0,i=0;f<b;++f)i+=a[f][g][1];for(f=0,j=0,l=c[g][0]-c[g-1][0];f<b;++f){for(h=0,k=(a[f][g][1]-a[f][g-1][1])/(2*l);h<f;++h)k+=(a[h][g][1]-a[h][g-1][1])/l;j+=k*a[f][g][1]}o[g]=m-=i?j/i*l:0,m<n&&(n=m)}for(g=0;g<d;++g)o[g]-=n;return o},expand:function(a){var b=a.length,c=a[0].length,d=1/b,e,f,g,h=[];for(f=0;f<c;++f){for(e=0,g=0;e<b;e++)g+=a[e][f][1];if(g)for(e=0;e<b;e++)a[e][f][1]/=g;else for(e=0;e<b;e++)a[e][f][1]=d}for(f=0;f<c;++f)h[f]=0;return h},zero:function(a){var b=-1,c=a[0].length,d=[];while(++b<c)d[b]=0;return d}};d3.layout.histogram=function(){function e(e,f){var g=[],h=e.map(b,this),i=c.call(this,h,f),j=d.call(this,i,h,f),k,f=-1,l=h.length,m=j.length-1,n=a?1:1/l,o;while(++f<m)k=g[f]=[],k.dx=j[f+1]-(k.x=j[f]),k.y=0;f=-1;while(++f<l)o=h[f],o>=i[0]&&o<=i[1]&&(k=g[d3.bisect(j,o,1,m)-1],k.y+=n,k.push(e[f]));return g}var a=!0,b=Number,c=x,d=v;e.value=function(a){if(!arguments.length)return b;b=a;return e},e.range=function(a){if(!arguments.length)return c;c=d3.functor(a);return e},e.bins=function(a){if(!arguments.length)return d;d=typeof a=="number"?function(b){return w(b,a)}:d3.functor(a);return e},e.frequency=function(b){if(!arguments.length)return a;a=!!b;return e};return e},d3.layout.hierarchy=function(){function g(a){var b=[];e(a,0,b);return b}function f(a,b){var d=a.children,e=0;if(d){var h=-1,i=d.length,j=b+1;while(++h<i)e+=f(d[h],j)}else c&&(e=+c.call(g,D?a:a.data,b)||0);c&&(a.value=e);return e}function e(f,h,i){var j=b.call(g,f,h),k,l=D?f:{data:f};l.depth=h,i.push(l);if(j&&(k=j.length)){var m=-1,n=l.children=[],o=0,p=h+1;while(++m<k)d=e(j[m],p,i),d.parent=l,n.push(d),o+=d.value;a&&n.sort(a),c&&(l.value=o)}else c&&(l.value=+c.call(g,f,h)||0);return l}var a=B,b=z,c=A;g.sort=function(b){if(!arguments.length)return a;a=b;return g},g.children=function(a){if(!arguments.length)return b;b=a;return g},g.value=function(a){if(!arguments.length)return c;c=a;return g},g.revalue=function(a){f(a,0);return a};return g};var D=!1;d3.layout.pack=function(){function c(c,d){var e=a.call(this,c,d),f=e[0];f.x=0,f.y=0,L(f);var g=b[0],h=b[1],i=1/Math.max(2*f.r/g,2*f.r/h);M(f,g/2,h/2,i);return e}var a=d3.layout.hierarchy().sort(E),b=[1,1];c.size=function(a){if(!arguments.length)return b;b=a;return c};return y(c,a)},d3.layout.cluster=function(){function d(d,e){var f=a.call(this,d,e),g=f[0],h,i=0,j,k;Z(g,function(a){a.children?(a.x=P(a.children),a.y=O(a.children)):(a.x=h?i+=b(a,h):0,a.y=0,h=a)});var l=Q(g),m=R(g),n=l.x-b(l,m)/2,o=m.x+b(m,l)/2;Z(g,function(a){a.x=(a.x-n)/(o-n)*c[0],a.y=(1-a.y/g.y)*c[1]});return f}var a=d3.layout.hierarchy().sort(null).value(null),b=S,c=[1,1];d.separation=function(a){if(!arguments.length)return b;b=a;return d},d.size=function(a){if(!arguments.length)return c;c=a;return d};return y(d,a)},d3.layout.tree=function(){function d(d,e){function j(a,c,d){if(c){var e=a,f=a,g=c,h=a.parent.children[0],i=e._tree.mod,j=f._tree.mod,k=g._tree.mod,l=h._tree.mod,m;while(g=U(g),e=T(e),g&&e)h=T(h),f=U(f),f._tree.ancestor=a,m=g._tree.prelim+k-e._tree.prelim-i+b(g,e),m>0&&(_(ba(g,a,d),a,m),i+=m,j+=m),k+=g._tree.mod,i+=e._tree.mod,l+=h._tree.mod,j+=f._tree.mod;g&&!U(f)&&(f._tree.thread=g,f._tree.mod+=k-j),e&&!T(h)&&(h._tree.thread=e,h._tree.mod+=i-l,d=a)}return d}function i(a,b){a.x=a._tree.prelim+b;var c=a.children;if(c){var d=-1,e=c.length;b+=a._tree.mod;while(++d<e)i(c[d],b)}}function h(a,c){var d=a.children,e=a._tree;if(d&&(f=d.length)){var f,g=d[0],i,k=g,l,m=-1;while(++m<f)l=d[m],h(l,i),k=j(l,i,k),i=l;$(a);var n=.5*(g._tree.prelim+l._tree.prelim);c?(e.prelim=c._tree.prelim+b(a,c),e.mod=e.prelim-n):e.prelim=n}else c&&(e.prelim=c._tree.prelim+b(a,c))}var f=a.call(this,d,e),g=f[0];Z(g,function(a,b){a._tree={ancestor:a,prelim:0,mod:0,change:0,shift:0,number:b?b._tree.number+1:0}}),h(g),i(g,-g._tree.prelim);var k=V(g,X),l=V(g,W),m=V(g,Y),n=k.x-b(k,l)/2,o=l.x+b(l,k)/2,p=m.depth||1;Z(g,function(a){a.x=(a.x-n)/(o-n)*c[0],a.y=a.depth/p*c[1],delete a._tree});return f}var a=d3.layout.hierarchy().sort(null).value(null),b=S,c=[1,1];d.separation=function(a){if(!arguments.length)return b;b=a;return d},d.size=function(a){if(!arguments.length)return c;c=a;return d};return y(d,a)},d3.layout.treemap=function(){function n(b){var d=g||a(b),e=d[0];e.x=0,e.y=0,e.dx=c[0],e.dy=c[1],g&&a.revalue(e),i([e],e.dx*e.dy/e.value),(g?k:j)(e),f&&(g=d);return d}function m(a,c,d,e){var f=-1,g=a.length,h=d.x,i=d.y,j=c?b(a.area/c):0,k;if(c==d.dx){if(e||j>d.dy)j=j?d.dy:0;while(++f<g)k=a[f],k.x=h,k.y=i,k.dy=j,h+=k.dx=j?b(k.area/j):0;k.z=!0,k.dx+=d.x+d.dx-h,d.y+=j,d.dy-=j}else{if(e||j>d.dx)j=j?d.dx:0;while(++f<g)k=a[f],k.x=h,k.y=i,k.dx=j,i+=k.dy=j?b(k.area/j):0;k.z=!1,k.dy+=d.y+d.dy-i,d.x+=j,d.dx-=j}}function l(a,b){var c=a.area,d,e=0,f=Infinity,g=-1,i=a.length;while(++g<i){if(!(d=a[g].area))continue;d<f&&(f=d),d>e&&(e=d)}c*=c,b*=b;return c?Math.max(b*e*h/c,c/(b*f*h)):Infinity}function k(a){if(!!a.children){var b=e(a),c=a.children.slice(),d,f=[];i(c,b.dx*b.dy/a.value),f.area=0;while(d=c.pop())f.push(d),f.area+=d.area,d.z!=null&&(m(f,d.z?b.dx:b.dy,b,!c.length),f.length=f.area=0);a.children.forEach(k)}}function j(a){if(!!a.children){var b=e(a),c=[],d=a.children.slice(),f,g=Infinity,h,k=Math.min(b.dx,b.dy),n;i(d,b.dx*b.dy/a.value),c.area=0;while((n=d.length)>0)c.push(f=d[n-1]),c.area+=f.area,(h=l(c,k))<=g?(d.pop(),g=h):(c.area-=c.pop().area,m(c,k,b,!1),k=Math.min(b.dx,b.dy),c.length=c.area=0,g=Infinity);c.length&&(m(c,k,b,!0),c.length=c.area=0),a.children.forEach(j)}}function i(a,b){var c=-1,d=a.length,e,f;while(++c<d)f=(e=a[c]).value*(b<0?0:b),e.area=isNaN(f)||f<=0?0:f}var a=d3.layout.hierarchy(),b=Math.round,c=[1,1],d=null,e=bb,f=!1,g,h=.5*(1+Math.sqrt(5));n.size=function(a){if(!arguments.length)return c;c=a;return n},n.padding=function(a){function c(b){return bc(b,a)}function b(b){var c=a.call(n,b,b.depth);return c==null?bb(b):bc(b,typeof c=="number"?[c,c,c,c]:c)}if(!arguments.length)return d;var f;e=(d=a)==null?bb:(f=typeof a)==="function"?b:f==="number"?(a=[a,a,a,a],c):c;return n},n.round=function(a){if(!arguments.length)return b!=Number;b=a?Math.round:Number;return n},n.sticky=function(a){if(!arguments.length)return f;f=a,g=null;return n},n.ratio=function(a){if(!arguments.length)return h;h=a;return n};return y(n,a)}})() <ide>\ No newline at end of file <ide><path>src/layout/hierarchy.js <ide> d3.layout.hierarchy = function() { <ide> // Also converts the data representation into a standard hierarchy structure. <ide> function recurse(data, depth, nodes) { <ide> var childs = children.call(hierarchy, data, depth), <add> n, <ide> node = d3_layout_hierarchyInline ? data : {data: data}; <ide> node.depth = depth; <ide> nodes.push(node); <del> if (childs) { <add> if (childs && (n = childs.length)) { <ide> var i = -1, <del> n = childs.length, <ide> c = node.children = [], <ide> v = 0, <ide> j = depth + 1; <ide><path>test/layout/hierarchy-test.js <add>require("../env"); <add>require("../../d3"); <add>require("../../d3.layout"); <add> <add>var vows = require("vows"), <add> assert = require("assert"); <add> <add>var suite = vows.describe("d3.layout.hierarchy"); <add> <add>suite.addBatch({ <add> "hierarchy": { <add> topic: d3.layout.hierarchy, <add> "doesn't overwrite the value of a node that has an empty children array": function(hierarchy) { <add> assert.deepEqual(hierarchy({value: 1, children: []}), [ <add> {data: {value: 1, children: []}, depth: 0, value: 1} <add> ]); <add> } <add> } <add>}); <add> <add>suite.export(module);
4
Python
Python
simplify underscore tests
abdb853ebf74ef241340216852cd779c23c2b422
<ide><path>spacy/tests/test_underscore.py <ide> from mock import Mock <ide> <ide> from ..vocab import Vocab <del>from ..tokens.doc import Doc <add>from ..tokens import Doc, Span, Token <ide> from ..tokens.underscore import Underscore <ide> <ide> <ide> def test_token_underscore_method(): <ide> assert token._.hello() == 'cheese' <ide> <ide> <del>@pytest.mark.parametrize('obj', [ <del> Doc(Vocab(), words=['hello', 'world']), <del> Doc(Vocab(), words=['hello', 'world'])[1], <del> Doc(Vocab(), words=['hello', 'world'])[0:2]]) <add>@pytest.mark.parametrize('obj', [Doc, Span, Token]) <ide> def test_underscore_raises_for_dup(obj): <ide> obj.set_extension('test', default=None) <ide> with pytest.raises(ValueError): <ide> def test_underscore_raises_for_dup(obj): <ide> {'getter': True}]) <ide> def test_underscore_raises_for_invalid(invalid_kwargs): <ide> invalid_kwargs['force'] = True <del> doc = Doc(Vocab(), words=['hello', 'world']) <ide> with pytest.raises(ValueError): <del> doc.set_extension('test', **invalid_kwargs) <add> Doc.set_extension('test', **invalid_kwargs) <ide> <ide> <ide> @pytest.mark.parametrize('valid_kwargs', [ <ide> def test_underscore_raises_for_invalid(invalid_kwargs): <ide> {'method': lambda: None}]) <ide> def test_underscore_accepts_valid(valid_kwargs): <ide> valid_kwargs['force'] = True <del> doc = Doc(Vocab(), words=['hello', 'world']) <del> doc.set_extension('test', **valid_kwargs) <add> Doc.set_extension('test', **valid_kwargs)
1
Mixed
Python
update cifar input following data change
6515a419aad7ecce38cb00656ebe7517997d0a0a
<ide><path>resnet/README.md <ide> curl -o cifar-100-binary.tar.gz https://www.cs.toronto.edu/~kriz/cifar-100-binar <ide> ```shell <ide> # cd to the your workspace. <ide> # It contains an empty WORKSPACE file, resnet codes and cifar10 dataset. <add># Note: User can split 5k from train set for eval set. <ide> ls -R <ide> .: <ide> cifar10 resnet WORKSPACE <ide> <ide> ./cifar10: <del> test.bin train.bin validation.bin <add> data_batch_1.bin data_batch_2.bin data_batch_3.bin data_batch_4.bin <add> data_batch_5.bin test_batch.bin <ide> <ide> ./resnet: <ide> BUILD cifar_input.py g3doc README.md resnet_main.py resnet_model.py <ide> ls -R <ide> bazel build -c opt --config=cuda resnet/... <ide> <ide> # Train the model. <del>bazel-bin/resnet/resnet_main --train_data_path=cifar10/train.bin \ <add>bazel-bin/resnet/resnet_main --train_data_path=cifar10/data_batch* \ <ide> --log_root=/tmp/resnet_model \ <ide> --train_dir=/tmp/resnet_model/train \ <ide> --dataset='cifar10' \ <ide> bazel-bin/resnet/resnet_main --train_data_path=cifar10/train.bin \ <ide> # Evaluate the model. <ide> # Avoid running on the same GPU as the training job at the same time, <ide> # otherwise, you might run out of memory. <del>bazel-bin/resnet/resnet_main --eval_data_path=cifar10/test.bin \ <add>bazel-bin/resnet/resnet_main --eval_data_path=cifar10/test_batch.bin \ <ide> --log_root=/tmp/resnet_model \ <ide> --eval_dir=/tmp/resnet_model/test \ <ide> --mode=eval \ <ide><path>resnet/cifar_input.py <ide> def build_input(dataset, data_path, batch_size, mode): <ide> image_bytes = image_size * image_size * depth <ide> record_bytes = label_bytes + label_offset + image_bytes <ide> <del> file_queue = tf.train.string_input_producer([data_path], shuffle=True) <add> data_files = tf.gfile.Glob(data_path) <add> file_queue = tf.train.string_input_producer(data_files, shuffle=True) <ide> # Read examples from files in the filename queue. <ide> reader = tf.FixedLengthRecordReader(record_bytes=record_bytes) <ide> _, value = reader.read(file_queue) <ide><path>resnet/resnet_main.py <ide> FLAGS = tf.app.flags.FLAGS <ide> tf.app.flags.DEFINE_string('dataset', 'cifar10', 'cifar10 or cifar100.') <ide> tf.app.flags.DEFINE_string('mode', 'train', 'train or eval.') <del>tf.app.flags.DEFINE_string('train_data_path', '', 'Filename for training data.') <del>tf.app.flags.DEFINE_string('eval_data_path', '', 'Filename for eval data') <add>tf.app.flags.DEFINE_string('train_data_path', '', 'Filepattern for training data.') <add>tf.app.flags.DEFINE_string('eval_data_path', '', 'Filepattern for eval data') <ide> tf.app.flags.DEFINE_integer('image_size', 32, 'Image side length.') <ide> tf.app.flags.DEFINE_string('train_dir', '', <ide> 'Directory to keep training outputs.')
3
Javascript
Javascript
remove internal files in `blueprints-js` folder
2a06e7dc1895b78759522dda062d1897b016172d
<ide><path>blueprints-js/-addon-import.js <del>'use strict'; <del> <del>const stringUtil = require('ember-cli-string-utils'); <del>const path = require('path'); <del>const inflector = require('inflection'); <del> <del>module.exports = { <del> description: 'Generates an import wrapper.', <del> <del> fileMapTokens: function () { <del> return { <del> __name__: function (options) { <del> return options.dasherizedModuleName; <del> }, <del> __path__: function (options) { <del> return inflector.pluralize(options.locals.blueprintName); <del> }, <del> __root__: function (options) { <del> if (options.inRepoAddon) { <del> return path.join('lib', options.inRepoAddon, 'app'); <del> } <del> return 'app'; <del> }, <del> }; <del> }, <del> <del> locals: function (options) { <del> let addonRawName = options.inRepoAddon ? options.inRepoAddon : options.project.name(); <del> let addonName = stringUtil.dasherize(addonRawName); <del> let fileName = stringUtil.dasherize(options.entity.name); <del> let blueprintName = options.originBlueprintName; <del> let modulePathSegments = [ <del> addonName, <del> inflector.pluralize(options.originBlueprintName), <del> fileName, <del> ]; <del> <del> if (blueprintName.match(/-addon/)) { <del> blueprintName = blueprintName.substr(0, blueprintName.indexOf('-addon')); <del> modulePathSegments = [addonName, inflector.pluralize(blueprintName), fileName]; <del> } <del> <del> return { <del> modulePath: modulePathSegments.join('/'), <del> blueprintName: blueprintName, <del> }; <del> }, <del>}; <ide><path>blueprints-js/test-framework-detector.js <del>'use strict'; <del> <del>const fs = require('fs'); <del>const path = require('path'); <del>const VersionChecker = require('ember-cli-version-checker'); <del> <del>module.exports = function (blueprint) { <del> blueprint.supportsAddon = function () { <del> return false; <del> }; <del> <del> blueprint.filesPath = function () { <del> let type; <del> const qunitRfcVersion = 'qunit-rfc-232'; <del> const mochaRfcVersion = 'mocha-rfc-232'; <del> const mochaVersion = 'mocha-0.12'; <del> <del> let dependencies = this.project.dependencies(); <del> if ('ember-qunit' in dependencies) { <del> type = qunitRfcVersion; <del> } else if ('ember-cli-qunit' in dependencies) { <del> let checker = new VersionChecker(this.project); <del> if ( <del> fs.existsSync(`${this.path}/${qunitRfcVersion}-files`) && <del> checker.for('ember-cli-qunit', 'npm').gte('4.2.0') <del> ) { <del> type = qunitRfcVersion; <del> } else { <del> type = 'qunit'; <del> } <del> } else if ('ember-mocha' in dependencies) { <del> let checker = new VersionChecker(this.project); <del> if ( <del> fs.existsSync(`${this.path}/${mochaRfcVersion}-files`) && <del> checker.for('ember-mocha', 'npm').gte('0.14.0') <del> ) { <del> type = mochaRfcVersion; <del> } else { <del> type = mochaVersion; <del> } <del> } else if ('ember-cli-mocha' in dependencies) { <del> let checker = new VersionChecker(this.project); <del> if ( <del> fs.existsSync(`${this.path}/${mochaVersion}-files`) && <del> checker.for('ember-cli-mocha', 'npm').gte('0.12.0') <del> ) { <del> type = mochaVersion; <del> } else { <del> type = 'mocha'; <del> } <del> } else { <del> this.ui.writeLine("Couldn't determine test style - using QUnit"); <del> type = 'qunit'; <del> } <del> <del> return path.join(this.path, type + '-files'); <del> }; <del> <del> return blueprint; <del>};
2
Text
Text
update version in readme code
6beb0eb29930e4b42d84c1663b4434fba525ebb1
<ide><path>README.md <ide> Thanks to the awesome folks over at [Fastly](http://www.fastly.com/), there's a <ide> `<head>`: <ide> <ide> ```html <del><link href="http://vjs.zencdn.net/4.12/video-js.css" rel="stylesheet"> <del><script src="http://vjs.zencdn.net/4.12/video.js"></script> <add><link href="http://vjs.zencdn.net/5.0/video-js.min.css" rel="stylesheet"> <add><script src="http://vjs.zencdn.net/5.0/video.min.js"></script> <ide> ``` <ide> <ide> Then, whenever you want to use Video.js you can simply use the `<video>` element as your normally would, but with an additional `data-setup` attribute containing any Video.js options. These options
1
Java
Java
fix race condition in writeresultpublisher
c35b3e5c822d9ffc57893393603866468ce24c80
<ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/WriteResultPublisher.java <ide> void subscribe(WriteResultPublisher publisher, Subscriber<? super Void> subscrib <ide> @Override <ide> void publishComplete(WriteResultPublisher publisher) { <ide> publisher.completedBeforeSubscribed = true; <add> if(State.SUBSCRIBED.equals(publisher.state.get())) { <add> publisher.state.get().publishComplete(publisher); <add> } <ide> } <ide> @Override <ide> void publishError(WriteResultPublisher publisher, Throwable ex) { <ide> void request(WriteResultPublisher publisher, long n) { <ide> @Override <ide> void publishComplete(WriteResultPublisher publisher) { <ide> publisher.completedBeforeSubscribed = true; <add> if(State.SUBSCRIBED.equals(publisher.state.get())) { <add> publisher.state.get().publishComplete(publisher); <add> } <ide> } <ide> @Override <ide> void publishError(WriteResultPublisher publisher, Throwable ex) {
1
Text
Text
simplify section on adequate record [ci skip]
56f2b70db1210f63e972a8755551cc6eb95dc497
<ide><path>guides/source/4_2_release_notes.md <ide> then deserialized again at run time. <ide> <ide> ### Adequate Record <ide> <del>Adequate Record is a set of refactorings that make Active Record `find` and <del>`find_by` methods and some association queries up to 2x faster. <add>Adequate Record is a set of performance improvements in Active Record that makes <add>common `find` and `find_by` calls and some association queries up to 2x faster. <ide> <del>It works by caching SQL query patterns while executing the Active Record calls. <del>The cache helps skip parts of the computation involved in the transformation of <del>the calls into SQL queries. More details in [Aaron Patterson's <del>post](http://tenderlovemaking.com/2014/02/19/adequaterecord-pro-like-activerecord.html). <add>It works by caching common SQL queries as prepared statements and reusing them <add>on similar calls, skipping most of the query-generation work on subsequent <add>calls. For more details, please refer to [Aaron Patterson's blog post](http://tenderlovemaking.com/2014/02/19/adequaterecord-pro-like-activerecord.html). <ide> <del>Nothing special has to be done to activate this feature. Most `find` and <del>`find_by` calls and association queries will use it automatically. Examples: <add>Active Record will automatically take advantage of this feature on the supported <add>operations without any user involvement and code changes. Here are some examples <add>of the supported operations: <ide> <ide> ```ruby <del>Post.find 1 # caches query pattern <del>Post.find 2 # uses the cached pattern <add>Post.find 1 # First call will generate and cache the prepared statement <add>Post.find 2 # Second call will reuse the cached statement <ide> <del>Post.find_by_title 'first post' # caches query pattern <del>Post.find_by_title 'second post' # uses the cached pattern <add>Post.find_by_title 'first post' <add>Post.find_by_title 'second post' <ide> <del>post.comments # caches query pattern <del>post.comments(true) # uses cached pattern <add>post.comments <add>post.comments(true) <ide> ``` <ide> <ide> The caching is not used in the following scenarios:
1
PHP
PHP
remove unneeded use calls
a17aabea13b23119ac843bf32898cc385ac8f06b
<ide><path>src/View/StringTemplate.php <ide> <ide> use Cake\Configure\Engine\PhpConfig; <ide> use Cake\Core\InstanceConfigTrait; <del>use Cake\Core\Plugin; <del>use Cake\Error; <ide> <ide> /** <ide> * Provides an interface for registering and inserting
1
Ruby
Ruby
use standardloader when we know the path already
caaa32325cf7bcf03d07f7525da082f53217cceb
<ide><path>Library/Homebrew/formulary.rb <ide> def self.loader_for(ref) <ide> <ide> possible_cached_formula = Pathname.new("#{HOMEBREW_CACHE_FORMULA}/#{ref}.rb") <ide> if possible_cached_formula.file? <del> return FromPathLoader.new(possible_cached_formula.to_s) <add> return StandardLoader.new(ref, possible_cached_formula) <ide> end <ide> <ide> return StandardLoader.new(ref)
1
Python
Python
fix error message and format with python/black
2fb3beeaf1215a1be4a7bc97097ef6a33fd65aeb
<ide><path>dynamic_programming/climbing_stairs.py <add>#!/usr/bin/env python3 <add> <add> <ide> def climb_stairs(n: int) -> int: <del> """ <del> LeetCdoe No.70: Climbing Stairs <del> Distinct ways to climb a n step staircase where <del> each time you can either climb 1 or 2 steps. <del> <del> Args: <del> n: number of steps of staircase <del> <del> Returns: <del> Distinct ways to climb a n step staircase <del> <del> Raises: <del> AssertionError: n not positive integer <del> <del> >>> climb_stairs(3) <del> 3 <del> >>> climb_stairs(1) <del> 1 <del> """ <del> assert isinstance(n,int) and n > 0, "n needs to be positive integer, your input {0}".format(0) <del> if n == 1: return 1 <del> dp = [0]*(n+1) <del> dp[0], dp[1] = (1, 1) <del> for i in range(2,n+1): <del> dp[i] = dp[i-1] + dp[i-2] <del> return dp[n] <add> """ <add> LeetCdoe No.70: Climbing Stairs <add> Distinct ways to climb a n step staircase where <add> each time you can either climb 1 or 2 steps. <add> <add> Args: <add> n: number of steps of staircase <add> <add> Returns: <add> Distinct ways to climb a n step staircase <add> <add> Raises: <add> AssertionError: n not positive integer <add> <add> >>> climb_stairs(3) <add> 3 <add> >>> climb_stairs(1) <add> 1 <add> >>> climb_stairs(-7) # doctest: +ELLIPSIS <add> Traceback (most recent call last): <add> ... <add> AssertionError: n needs to be positive integer, your input -7 <add> """ <add> fmt = "n needs to be positive integer, your input {}" <add> assert isinstance(n, int) and n > 0, fmt.format(n) <add> if n == 1: <add> return 1 <add> dp = [0] * (n + 1) <add> dp[0], dp[1] = (1, 1) <add> for i in range(2, n + 1): <add> dp[i] = dp[i - 1] + dp[i - 2] <add> return dp[n] <add> <add> <add>if __name__ == "__main__": <add> import doctest <add> <add> doctest.testmod()
1
Javascript
Javascript
add a feature flag to disable legacy context
0c1ec049f8832d1c27f876844666fda393036800
<ide><path>packages/react-dom/src/__tests__/ReactDOMServerIntegrationLegacyContextDisabled-test.internal.js <add>/** <add> * Copyright (c) Facebook, Inc. and its affiliates. <add> * <add> * This source code is licensed under the MIT license found in the <add> * LICENSE file in the root directory of this source tree. <add> * <add> * @emails react-core <add> */ <add> <add>'use strict'; <add> <add>const ReactDOMServerIntegrationUtils = require('./utils/ReactDOMServerIntegrationTestUtils'); <add> <add>let React; <add>let ReactDOM; <add>let ReactFeatureFlags; <add>let ReactDOMServer; <add>let ReactTestUtils; <add> <add>function initModules() { <add> // Reset warning cache. <add> jest.resetModuleRegistry(); <add> React = require('react'); <add> ReactDOM = require('react-dom'); <add> ReactDOMServer = require('react-dom/server'); <add> ReactTestUtils = require('react-dom/test-utils'); <add> <add> ReactFeatureFlags = require('shared/ReactFeatureFlags'); <add> ReactFeatureFlags.disableLegacyContext = true; <add> <add> // Make them available to the helpers. <add> return { <add> ReactDOM, <add> ReactDOMServer, <add> ReactTestUtils, <add> }; <add>} <add> <add>const {resetModules, itRenders} = ReactDOMServerIntegrationUtils(initModules); <add> <add>function formatValue(val) { <add> if (val === null) { <add> return 'null'; <add> } <add> if (val === undefined) { <add> return 'undefined'; <add> } <add> if (typeof val === 'string') { <add> return val; <add> } <add> return JSON.stringify(val); <add>} <add> <add>describe('ReactDOMServerIntegrationLegacyContextDisabled', () => { <add> beforeEach(() => { <add> resetModules(); <add> }); <add> <add> itRenders('undefined legacy context with warning', async render => { <add> class LegacyProvider extends React.Component { <add> static childContextTypes = { <add> foo() {}, <add> }; <add> getChildContext() { <add> return {foo: 10}; <add> } <add> render() { <add> return this.props.children; <add> } <add> } <add> <add> let lifecycleContextLog = []; <add> class LegacyClsConsumer extends React.Component { <add> static contextTypes = { <add> foo() {}, <add> }; <add> shouldComponentUpdate(nextProps, nextState, nextContext) { <add> lifecycleContextLog.push(nextContext); <add> return true; <add> } <add> UNSAFE_componentWillReceiveProps(nextProps, nextContext) { <add> lifecycleContextLog.push(nextContext); <add> } <add> UNSAFE_componentWillUpdate(nextProps, nextState, nextContext) { <add> lifecycleContextLog.push(nextContext); <add> } <add> render() { <add> return formatValue(this.context); <add> } <add> } <add> <add> function LegacyFnConsumer(props, context) { <add> return formatValue(context); <add> } <add> LegacyFnConsumer.contextTypes = {foo() {}}; <add> <add> function RegularFn(props, context) { <add> return formatValue(context); <add> } <add> <add> const e = await render( <add> <LegacyProvider> <add> <span> <add> <LegacyClsConsumer /> <add> <LegacyFnConsumer /> <add> <RegularFn /> <add> </span> <add> </LegacyProvider>, <add> 3, <add> ); <add> expect(e.textContent).toBe('{}undefinedundefined'); <add> expect(lifecycleContextLog).toEqual([]); <add> }); <add> <add> itRenders('modern context', async render => { <add> let Ctx = React.createContext(); <add> <add> class Provider extends React.Component { <add> render() { <add> return ( <add> <Ctx.Provider value={this.props.value}> <add> {this.props.children} <add> </Ctx.Provider> <add> ); <add> } <add> } <add> <add> class RenderPropConsumer extends React.Component { <add> render() { <add> return <Ctx.Consumer>{value => formatValue(value)}</Ctx.Consumer>; <add> } <add> } <add> <add> let lifecycleContextLog = []; <add> class ContextTypeConsumer extends React.Component { <add> static contextType = Ctx; <add> shouldComponentUpdate(nextProps, nextState, nextContext) { <add> lifecycleContextLog.push(nextContext); <add> return true; <add> } <add> UNSAFE_componentWillReceiveProps(nextProps, nextContext) { <add> lifecycleContextLog.push(nextContext); <add> } <add> UNSAFE_componentWillUpdate(nextProps, nextState, nextContext) { <add> lifecycleContextLog.push(nextContext); <add> } <add> render() { <add> return formatValue(this.context); <add> } <add> } <add> <add> function FnConsumer() { <add> return formatValue(React.useContext(Ctx)); <add> } <add> <add> const e = await render( <add> <Provider value="a"> <add> <span> <add> <RenderPropConsumer /> <add> <ContextTypeConsumer /> <add> <FnConsumer /> <add> </span> <add> </Provider>, <add> ); <add> expect(e.textContent).toBe('aaa'); <add> expect(lifecycleContextLog).toEqual([]); <add> }); <add>}); <ide><path>packages/react-dom/src/__tests__/ReactLegacyContextDisabled-test.internal.js <add>/** <add> * Copyright (c) Facebook, Inc. and its affiliates. <add> * <add> * This source code is licensed under the MIT license found in the <add> * LICENSE file in the root directory of this source tree. <add> * <add> * @emails react-core <add> */ <add> <add>'use strict'; <add> <add>let React; <add>let ReactDOM; <add>let ReactFeatureFlags; <add> <add>describe('ReactLegacyContextDisabled', () => { <add> beforeEach(() => { <add> jest.resetModules(); <add> <add> React = require('react'); <add> ReactDOM = require('react-dom'); <add> ReactFeatureFlags = require('shared/ReactFeatureFlags'); <add> ReactFeatureFlags.disableLegacyContext = true; <add> }); <add> <add> function formatValue(val) { <add> if (val === null) { <add> return 'null'; <add> } <add> if (val === undefined) { <add> return 'undefined'; <add> } <add> if (typeof val === 'string') { <add> return val; <add> } <add> return JSON.stringify(val); <add> } <add> <add> it('warns for legacy context', () => { <add> class LegacyProvider extends React.Component { <add> static childContextTypes = { <add> foo() {}, <add> }; <add> getChildContext() { <add> return {foo: 10}; <add> } <add> render() { <add> return this.props.children; <add> } <add> } <add> <add> let lifecycleContextLog = []; <add> class LegacyClsConsumer extends React.Component { <add> static contextTypes = { <add> foo() {}, <add> }; <add> shouldComponentUpdate(nextProps, nextState, nextContext) { <add> lifecycleContextLog.push(nextContext); <add> return true; <add> } <add> UNSAFE_componentWillReceiveProps(nextProps, nextContext) { <add> lifecycleContextLog.push(nextContext); <add> } <add> UNSAFE_componentWillUpdate(nextProps, nextState, nextContext) { <add> lifecycleContextLog.push(nextContext); <add> } <add> render() { <add> return formatValue(this.context); <add> } <add> } <add> <add> function LegacyFnConsumer(props, context) { <add> return formatValue(context); <add> } <add> LegacyFnConsumer.contextTypes = {foo() {}}; <add> <add> function RegularFn(props, context) { <add> return formatValue(context); <add> } <add> <add> const container = document.createElement('div'); <add> expect(() => { <add> ReactDOM.render( <add> <LegacyProvider> <add> <span> <add> <LegacyClsConsumer /> <add> <LegacyFnConsumer /> <add> <RegularFn /> <add> </span> <add> </LegacyProvider>, <add> container, <add> ); <add> }).toWarnDev( <add> [ <add> 'LegacyProvider uses the legacy childContextTypes API which is no longer supported. ' + <add> 'Use React.createContext() instead.', <add> 'LegacyClsConsumer uses the legacy contextTypes API which is no longer supported. ' + <add> 'Use React.createContext() with static contextType instead.', <add> 'LegacyFnConsumer uses the legacy contextTypes API which is no longer supported. ' + <add> 'Use React.createContext() with React.useContext() instead.', <add> ], <add> {withoutStack: true}, <add> ); <add> expect(container.textContent).toBe('{}undefinedundefined'); <add> expect(lifecycleContextLog).toEqual([]); <add> <add> // Test update path. <add> ReactDOM.render( <add> <LegacyProvider> <add> <span> <add> <LegacyClsConsumer /> <add> <LegacyFnConsumer /> <add> <RegularFn /> <add> </span> <add> </LegacyProvider>, <add> container, <add> ); <add> expect(container.textContent).toBe('{}undefinedundefined'); <add> expect(lifecycleContextLog).toEqual([{}, {}, {}]); <add> ReactDOM.unmountComponentAtNode(container); <add> }); <add> <add> it('renders a tree with modern context', () => { <add> let Ctx = React.createContext(); <add> <add> class Provider extends React.Component { <add> render() { <add> return ( <add> <Ctx.Provider value={this.props.value}> <add> {this.props.children} <add> </Ctx.Provider> <add> ); <add> } <add> } <add> <add> class RenderPropConsumer extends React.Component { <add> render() { <add> return <Ctx.Consumer>{value => formatValue(value)}</Ctx.Consumer>; <add> } <add> } <add> <add> let lifecycleContextLog = []; <add> class ContextTypeConsumer extends React.Component { <add> static contextType = Ctx; <add> shouldComponentUpdate(nextProps, nextState, nextContext) { <add> lifecycleContextLog.push(nextContext); <add> return true; <add> } <add> UNSAFE_componentWillReceiveProps(nextProps, nextContext) { <add> lifecycleContextLog.push(nextContext); <add> } <add> UNSAFE_componentWillUpdate(nextProps, nextState, nextContext) { <add> lifecycleContextLog.push(nextContext); <add> } <add> render() { <add> return formatValue(this.context); <add> } <add> } <add> <add> function FnConsumer() { <add> return formatValue(React.useContext(Ctx)); <add> } <add> <add> const container = document.createElement('div'); <add> ReactDOM.render( <add> <Provider value="a"> <add> <span> <add> <RenderPropConsumer /> <add> <ContextTypeConsumer /> <add> <FnConsumer /> <add> </span> <add> </Provider>, <add> container, <add> ); <add> expect(container.textContent).toBe('aaa'); <add> expect(lifecycleContextLog).toEqual([]); <add> <add> // Test update path <add> ReactDOM.render( <add> <Provider value="a"> <add> <span> <add> <RenderPropConsumer /> <add> <ContextTypeConsumer /> <add> <FnConsumer /> <add> </span> <add> </Provider>, <add> container, <add> ); <add> expect(container.textContent).toBe('aaa'); <add> expect(lifecycleContextLog).toEqual(['a', 'a', 'a']); <add> lifecycleContextLog.length = 0; <add> <add> ReactDOM.render( <add> <Provider value="b"> <add> <span> <add> <RenderPropConsumer /> <add> <ContextTypeConsumer /> <add> <FnConsumer /> <add> </span> <add> </Provider>, <add> container, <add> ); <add> expect(container.textContent).toBe('bbb'); <add> expect(lifecycleContextLog).toEqual(['b', 'b']); // sCU skipped due to changed context value. <add> ReactDOM.unmountComponentAtNode(container); <add> }); <add>}); <ide><path>packages/react-dom/src/server/ReactPartialRenderer.js <ide> import describeComponentFrame from 'shared/describeComponentFrame'; <ide> import ReactSharedInternals from 'shared/ReactSharedInternals'; <ide> import { <ide> warnAboutDeprecatedLifecycles, <add> disableLegacyContext, <ide> enableSuspenseServerRenderer, <ide> enableFundamentalAPI, <ide> enableFlareAPI, <ide> function resolve( <ide> <ide> // Extra closure so queue and replace can be captured properly <ide> function processChild(element, Component) { <del> let publicContext = processContext(Component, context, threadID); <add> const isClass = shouldConstruct(Component); <add> const publicContext = processContext(Component, context, threadID, isClass); <ide> <ide> let queue = []; <ide> let replace = false; <ide> function resolve( <ide> }; <ide> <ide> let inst; <del> if (shouldConstruct(Component)) { <add> if (isClass) { <ide> inst = new Component(element.props, publicContext, updater); <ide> <ide> if (typeof Component.getDerivedStateFromProps === 'function') { <ide> function resolve( <ide> validateRenderResult(child, Component); <ide> <ide> let childContext; <del> if (typeof inst.getChildContext === 'function') { <del> let childContextTypes = Component.childContextTypes; <del> if (typeof childContextTypes === 'object') { <del> childContext = inst.getChildContext(); <del> for (let contextKey in childContext) { <del> invariant( <del> contextKey in childContextTypes, <del> '%s.getChildContext(): key "%s" is not defined in childContextTypes.', <add> if (disableLegacyContext) { <add> if (__DEV__) { <add> let childContextTypes = Component.childContextTypes; <add> if (childContextTypes !== undefined) { <add> warningWithoutStack( <add> false, <add> '%s uses the legacy childContextTypes API which is no longer supported. ' + <add> 'Use React.createContext() instead.', <ide> getComponentName(Component) || 'Unknown', <del> contextKey, <ide> ); <ide> } <del> } else { <del> warningWithoutStack( <del> false, <del> '%s.getChildContext(): childContextTypes must be defined in order to ' + <del> 'use getChildContext().', <del> getComponentName(Component) || 'Unknown', <del> ); <ide> } <del> } <del> if (childContext) { <del> context = Object.assign({}, context, childContext); <add> } else { <add> if (typeof inst.getChildContext === 'function') { <add> let childContextTypes = Component.childContextTypes; <add> if (typeof childContextTypes === 'object') { <add> childContext = inst.getChildContext(); <add> for (let contextKey in childContext) { <add> invariant( <add> contextKey in childContextTypes, <add> '%s.getChildContext(): key "%s" is not defined in childContextTypes.', <add> getComponentName(Component) || 'Unknown', <add> contextKey, <add> ); <add> } <add> } else { <add> warningWithoutStack( <add> false, <add> '%s.getChildContext(): childContextTypes must be defined in order to ' + <add> 'use getChildContext().', <add> getComponentName(Component) || 'Unknown', <add> ); <add> } <add> } <add> if (childContext) { <add> context = Object.assign({}, context, childContext); <add> } <ide> } <ide> } <ide> return {child, context}; <ide><path>packages/react-dom/src/server/ReactPartialRendererContext.js <ide> import type {ThreadID} from './ReactThreadIDAllocator'; <ide> import type {ReactContext} from 'shared/ReactTypes'; <ide> <add>import {disableLegacyContext} from 'shared/ReactFeatureFlags'; <ide> import {REACT_CONTEXT_TYPE, REACT_PROVIDER_TYPE} from 'shared/ReactSymbols'; <ide> import ReactSharedInternals from 'shared/ReactSharedInternals'; <ide> import getComponentName from 'shared/getComponentName'; <ide> export function processContext( <ide> type: Function, <ide> context: Object, <ide> threadID: ThreadID, <add> isClass: boolean, <ide> ) { <del> const contextType = type.contextType; <del> if (__DEV__) { <del> if ('contextType' in (type: any)) { <del> let isValid = <del> // Allow null for conditional declaration <del> contextType === null || <del> (contextType !== undefined && <del> contextType.$$typeof === REACT_CONTEXT_TYPE && <del> contextType._context === undefined); // Not a <Context.Consumer> <add> if (isClass) { <add> const contextType = type.contextType; <add> if (__DEV__) { <add> if ('contextType' in (type: any)) { <add> let isValid = <add> // Allow null for conditional declaration <add> contextType === null || <add> (contextType !== undefined && <add> contextType.$$typeof === REACT_CONTEXT_TYPE && <add> contextType._context === undefined); // Not a <Context.Consumer> <ide> <del> if (!isValid && !didWarnAboutInvalidateContextType.has(type)) { <del> didWarnAboutInvalidateContextType.add(type); <add> if (!isValid && !didWarnAboutInvalidateContextType.has(type)) { <add> didWarnAboutInvalidateContextType.add(type); <ide> <del> let addendum = ''; <del> if (contextType === undefined) { <del> addendum = <del> ' However, it is set to undefined. ' + <del> 'This can be caused by a typo or by mixing up named and default imports. ' + <del> 'This can also happen due to a circular dependency, so ' + <del> 'try moving the createContext() call to a separate file.'; <del> } else if (typeof contextType !== 'object') { <del> addendum = ' However, it is set to a ' + typeof contextType + '.'; <del> } else if (contextType.$$typeof === REACT_PROVIDER_TYPE) { <del> addendum = ' Did you accidentally pass the Context.Provider instead?'; <del> } else if (contextType._context !== undefined) { <del> // <Context.Consumer> <del> addendum = ' Did you accidentally pass the Context.Consumer instead?'; <del> } else { <del> addendum = <del> ' However, it is set to an object with keys {' + <del> Object.keys(contextType).join(', ') + <del> '}.'; <add> let addendum = ''; <add> if (contextType === undefined) { <add> addendum = <add> ' However, it is set to undefined. ' + <add> 'This can be caused by a typo or by mixing up named and default imports. ' + <add> 'This can also happen due to a circular dependency, so ' + <add> 'try moving the createContext() call to a separate file.'; <add> } else if (typeof contextType !== 'object') { <add> addendum = ' However, it is set to a ' + typeof contextType + '.'; <add> } else if (contextType.$$typeof === REACT_PROVIDER_TYPE) { <add> addendum = <add> ' Did you accidentally pass the Context.Provider instead?'; <add> } else if (contextType._context !== undefined) { <add> // <Context.Consumer> <add> addendum = <add> ' Did you accidentally pass the Context.Consumer instead?'; <add> } else { <add> addendum = <add> ' However, it is set to an object with keys {' + <add> Object.keys(contextType).join(', ') + <add> '}.'; <add> } <add> warningWithoutStack( <add> false, <add> '%s defines an invalid contextType. ' + <add> 'contextType should point to the Context object returned by React.createContext().%s', <add> getComponentName(type) || 'Component', <add> addendum, <add> ); <ide> } <del> warningWithoutStack( <del> false, <del> '%s defines an invalid contextType. ' + <del> 'contextType should point to the Context object returned by React.createContext().%s', <del> getComponentName(type) || 'Component', <del> addendum, <del> ); <ide> } <ide> } <del> } <del> if (typeof contextType === 'object' && contextType !== null) { <del> validateContextBounds(contextType, threadID); <del> return contextType[threadID]; <add> if (typeof contextType === 'object' && contextType !== null) { <add> validateContextBounds(contextType, threadID); <add> return contextType[threadID]; <add> } <add> if (disableLegacyContext) { <add> if (__DEV__) { <add> if (type.contextTypes) { <add> warningWithoutStack( <add> false, <add> '%s uses the legacy contextTypes API which is no longer supported. ' + <add> 'Use React.createContext() with static contextType instead.', <add> getComponentName(type) || 'Unknown', <add> ); <add> } <add> } <add> return emptyObject; <add> } else { <add> const maskedContext = maskContext(type, context); <add> if (__DEV__) { <add> if (type.contextTypes) { <add> checkContextTypes(type.contextTypes, maskedContext, 'context'); <add> } <add> } <add> return maskedContext; <add> } <ide> } else { <del> const maskedContext = maskContext(type, context); <del> if (__DEV__) { <del> if (type.contextTypes) { <del> checkContextTypes(type.contextTypes, maskedContext, 'context'); <add> if (disableLegacyContext) { <add> if (__DEV__) { <add> if (type.contextTypes) { <add> warningWithoutStack( <add> false, <add> '%s uses the legacy contextTypes API which is no longer supported. ' + <add> 'Use React.createContext() with React.useContext() instead.', <add> getComponentName(type) || 'Unknown', <add> ); <add> } <add> } <add> return undefined; <add> } else { <add> const maskedContext = maskContext(type, context); <add> if (__DEV__) { <add> if (type.contextTypes) { <add> checkContextTypes(type.contextTypes, maskedContext, 'context'); <add> } <ide> } <add> return maskedContext; <ide> } <del> return maskedContext; <ide> } <ide> } <ide><path>packages/react-reconciler/src/ReactFiberBeginWork.js <ide> import ReactSharedInternals from 'shared/ReactSharedInternals'; <ide> import { <ide> debugRenderPhaseSideEffects, <ide> debugRenderPhaseSideEffectsForStrictMode, <add> disableLegacyContext, <ide> enableProfilerTimer, <ide> enableSchedulerTracing, <ide> enableSuspenseServerRenderer, <ide> function updateFunctionComponent( <ide> } <ide> } <ide> <del> const unmaskedContext = getUnmaskedContext(workInProgress, Component, true); <del> const context = getMaskedContext(workInProgress, unmaskedContext); <add> let context; <add> if (!disableLegacyContext) { <add> const unmaskedContext = getUnmaskedContext(workInProgress, Component, true); <add> context = getMaskedContext(workInProgress, unmaskedContext); <add> } <ide> <ide> let nextChildren; <ide> prepareToReadContext(workInProgress, renderExpirationTime); <ide> function mountIndeterminateComponent( <ide> } <ide> <ide> const props = workInProgress.pendingProps; <del> const unmaskedContext = getUnmaskedContext(workInProgress, Component, false); <del> const context = getMaskedContext(workInProgress, unmaskedContext); <add> let context; <add> if (!disableLegacyContext) { <add> const unmaskedContext = getUnmaskedContext( <add> workInProgress, <add> Component, <add> false, <add> ); <add> context = getMaskedContext(workInProgress, unmaskedContext); <add> } <ide> <ide> prepareToReadContext(workInProgress, renderExpirationTime); <ide> let value; <ide> function mountIndeterminateComponent( <ide> // Proceed under the assumption that this is a function component <ide> workInProgress.tag = FunctionComponent; <ide> if (__DEV__) { <add> if (disableLegacyContext && Component.contextTypes) { <add> warningWithoutStack( <add> false, <add> '%s uses the legacy contextTypes API which is no longer supported. ' + <add> 'Use React.createContext() with React.useContext() instead.', <add> getComponentName(Component) || 'Unknown', <add> ); <add> } <add> <ide> if ( <ide> debugRenderPhaseSideEffects || <ide> (debugRenderPhaseSideEffectsForStrictMode && <ide><path>packages/react-reconciler/src/ReactFiberClassComponent.js <ide> import {Update, Snapshot} from 'shared/ReactSideEffectTags'; <ide> import { <ide> debugRenderPhaseSideEffects, <ide> debugRenderPhaseSideEffectsForStrictMode, <add> disableLegacyContext, <ide> warnAboutDeprecatedLifecycles, <ide> } from 'shared/ReactFeatureFlags'; <ide> import ReactStrictModeWarnings from './ReactStrictModeWarnings'; <ide> function checkClassInstance(workInProgress: Fiber, ctor: any, newProps: any) { <ide> 'property to define contextType instead.', <ide> name, <ide> ); <del> const noInstanceContextTypes = !instance.contextTypes; <del> warningWithoutStack( <del> noInstanceContextTypes, <del> 'contextTypes was defined as an instance property on %s. Use a static ' + <del> 'property to define contextTypes instead.', <del> name, <del> ); <ide> <del> if ( <del> ctor.contextType && <del> ctor.contextTypes && <del> !didWarnAboutContextTypeAndContextTypes.has(ctor) <del> ) { <del> didWarnAboutContextTypeAndContextTypes.add(ctor); <add> if (disableLegacyContext) { <add> if (ctor.childContextTypes) { <add> warningWithoutStack( <add> false, <add> '%s uses the legacy childContextTypes API which is no longer supported. ' + <add> 'Use React.createContext() instead.', <add> name, <add> ); <add> } <add> if (ctor.contextTypes) { <add> warningWithoutStack( <add> false, <add> '%s uses the legacy contextTypes API which is no longer supported. ' + <add> 'Use React.createContext() with static contextType instead.', <add> name, <add> ); <add> } <add> } else { <add> const noInstanceContextTypes = !instance.contextTypes; <ide> warningWithoutStack( <del> false, <del> '%s declares both contextTypes and contextType static properties. ' + <del> 'The legacy contextTypes property will be ignored.', <add> noInstanceContextTypes, <add> 'contextTypes was defined as an instance property on %s. Use a static ' + <add> 'property to define contextTypes instead.', <ide> name, <ide> ); <add> <add> if ( <add> ctor.contextType && <add> ctor.contextTypes && <add> !didWarnAboutContextTypeAndContextTypes.has(ctor) <add> ) { <add> didWarnAboutContextTypeAndContextTypes.add(ctor); <add> warningWithoutStack( <add> false, <add> '%s declares both contextTypes and contextType static properties. ' + <add> 'The legacy contextTypes property will be ignored.', <add> name, <add> ); <add> } <ide> } <ide> <ide> const noComponentShouldUpdate = <ide> function constructClassInstance( <ide> ): any { <ide> let isLegacyContextConsumer = false; <ide> let unmaskedContext = emptyContextObject; <del> let context = null; <add> let context = emptyContextObject; <ide> const contextType = ctor.contextType; <ide> <ide> if (__DEV__) { <ide> function constructClassInstance( <ide> <ide> if (typeof contextType === 'object' && contextType !== null) { <ide> context = readContext((contextType: any)); <del> } else { <add> } else if (!disableLegacyContext) { <ide> unmaskedContext = getUnmaskedContext(workInProgress, ctor, true); <ide> const contextTypes = ctor.contextTypes; <ide> isLegacyContextConsumer = <ide> function mountClassInstance( <ide> const contextType = ctor.contextType; <ide> if (typeof contextType === 'object' && contextType !== null) { <ide> instance.context = readContext(contextType); <add> } else if (disableLegacyContext) { <add> instance.context = emptyContextObject; <ide> } else { <ide> const unmaskedContext = getUnmaskedContext(workInProgress, ctor, true); <ide> instance.context = getMaskedContext(workInProgress, unmaskedContext); <ide> function resumeMountClassInstance( <ide> <ide> const oldContext = instance.context; <ide> const contextType = ctor.contextType; <del> let nextContext; <add> let nextContext = emptyContextObject; <ide> if (typeof contextType === 'object' && contextType !== null) { <ide> nextContext = readContext(contextType); <del> } else { <add> } else if (!disableLegacyContext) { <ide> const nextLegacyUnmaskedContext = getUnmaskedContext( <ide> workInProgress, <ide> ctor, <ide> function updateClassInstance( <ide> <ide> const oldContext = instance.context; <ide> const contextType = ctor.contextType; <del> let nextContext; <add> let nextContext = emptyContextObject; <ide> if (typeof contextType === 'object' && contextType !== null) { <ide> nextContext = readContext(contextType); <del> } else { <add> } else if (!disableLegacyContext) { <ide> const nextUnmaskedContext = getUnmaskedContext(workInProgress, ctor, true); <ide> nextContext = getMaskedContext(workInProgress, nextUnmaskedContext); <ide> } <ide><path>packages/react-reconciler/src/ReactFiberContext.js <ide> import type {Fiber} from './ReactFiber'; <ide> import type {StackCursor} from './ReactFiberStack'; <ide> <ide> import {isFiberMounted} from 'react-reconciler/reflection'; <add>import {disableLegacyContext} from 'shared/ReactFeatureFlags'; <ide> import {ClassComponent, HostRoot} from 'shared/ReactWorkTags'; <ide> import getComponentName from 'shared/getComponentName'; <ide> import invariant from 'shared/invariant'; <ide> function getUnmaskedContext( <ide> Component: Function, <ide> didPushOwnContextIfProvider: boolean, <ide> ): Object { <del> if (didPushOwnContextIfProvider && isContextProvider(Component)) { <del> // If the fiber is a context provider itself, when we read its context <del> // we may have already pushed its own child context on the stack. A context <del> // provider should not "see" its own child context. Therefore we read the <del> // previous (parent) context instead for a context provider. <del> return previousContext; <add> if (disableLegacyContext) { <add> return emptyContextObject; <add> } else { <add> if (didPushOwnContextIfProvider && isContextProvider(Component)) { <add> // If the fiber is a context provider itself, when we read its context <add> // we may have already pushed its own child context on the stack. A context <add> // provider should not "see" its own child context. Therefore we read the <add> // previous (parent) context instead for a context provider. <add> return previousContext; <add> } <add> return contextStackCursor.current; <ide> } <del> return contextStackCursor.current; <ide> } <ide> <ide> function cacheContext( <ide> workInProgress: Fiber, <ide> unmaskedContext: Object, <ide> maskedContext: Object, <ide> ): void { <del> const instance = workInProgress.stateNode; <del> instance.__reactInternalMemoizedUnmaskedChildContext = unmaskedContext; <del> instance.__reactInternalMemoizedMaskedChildContext = maskedContext; <add> if (disableLegacyContext) { <add> return; <add> } else { <add> const instance = workInProgress.stateNode; <add> instance.__reactInternalMemoizedUnmaskedChildContext = unmaskedContext; <add> instance.__reactInternalMemoizedMaskedChildContext = maskedContext; <add> } <ide> } <ide> <ide> function getMaskedContext( <ide> workInProgress: Fiber, <ide> unmaskedContext: Object, <ide> ): Object { <del> const type = workInProgress.type; <del> const contextTypes = type.contextTypes; <del> if (!contextTypes) { <add> if (disableLegacyContext) { <ide> return emptyContextObject; <del> } <add> } else { <add> const type = workInProgress.type; <add> const contextTypes = type.contextTypes; <add> if (!contextTypes) { <add> return emptyContextObject; <add> } <ide> <del> // Avoid recreating masked context unless unmasked context has changed. <del> // Failing to do this will result in unnecessary calls to componentWillReceiveProps. <del> // This may trigger infinite loops if componentWillReceiveProps calls setState. <del> const instance = workInProgress.stateNode; <del> if ( <del> instance && <del> instance.__reactInternalMemoizedUnmaskedChildContext === unmaskedContext <del> ) { <del> return instance.__reactInternalMemoizedMaskedChildContext; <del> } <add> // Avoid recreating masked context unless unmasked context has changed. <add> // Failing to do this will result in unnecessary calls to componentWillReceiveProps. <add> // This may trigger infinite loops if componentWillReceiveProps calls setState. <add> const instance = workInProgress.stateNode; <add> if ( <add> instance && <add> instance.__reactInternalMemoizedUnmaskedChildContext === unmaskedContext <add> ) { <add> return instance.__reactInternalMemoizedMaskedChildContext; <add> } <ide> <del> const context = {}; <del> for (let key in contextTypes) { <del> context[key] = unmaskedContext[key]; <del> } <add> const context = {}; <add> for (let key in contextTypes) { <add> context[key] = unmaskedContext[key]; <add> } <ide> <del> if (__DEV__) { <del> const name = getComponentName(type) || 'Unknown'; <del> checkPropTypes( <del> contextTypes, <del> context, <del> 'context', <del> name, <del> getCurrentFiberStackInDev, <del> ); <del> } <add> if (__DEV__) { <add> const name = getComponentName(type) || 'Unknown'; <add> checkPropTypes( <add> contextTypes, <add> context, <add> 'context', <add> name, <add> getCurrentFiberStackInDev, <add> ); <add> } <ide> <del> // Cache unmasked context so we can avoid recreating masked context unless necessary. <del> // Context is created before the class component is instantiated so check for instance. <del> if (instance) { <del> cacheContext(workInProgress, unmaskedContext, context); <del> } <add> // Cache unmasked context so we can avoid recreating masked context unless necessary. <add> // Context is created before the class component is instantiated so check for instance. <add> if (instance) { <add> cacheContext(workInProgress, unmaskedContext, context); <add> } <ide> <del> return context; <add> return context; <add> } <ide> } <ide> <ide> function hasContextChanged(): boolean { <del> return didPerformWorkStackCursor.current; <add> if (disableLegacyContext) { <add> return false; <add> } else { <add> return didPerformWorkStackCursor.current; <add> } <ide> } <ide> <ide> function isContextProvider(type: Function): boolean { <del> const childContextTypes = type.childContextTypes; <del> return childContextTypes !== null && childContextTypes !== undefined; <add> if (disableLegacyContext) { <add> return false; <add> } else { <add> const childContextTypes = type.childContextTypes; <add> return childContextTypes !== null && childContextTypes !== undefined; <add> } <ide> } <ide> <ide> function popContext(fiber: Fiber): void { <del> pop(didPerformWorkStackCursor, fiber); <del> pop(contextStackCursor, fiber); <add> if (disableLegacyContext) { <add> return; <add> } else { <add> pop(didPerformWorkStackCursor, fiber); <add> pop(contextStackCursor, fiber); <add> } <ide> } <ide> <ide> function popTopLevelContextObject(fiber: Fiber): void { <del> pop(didPerformWorkStackCursor, fiber); <del> pop(contextStackCursor, fiber); <add> if (disableLegacyContext) { <add> return; <add> } else { <add> pop(didPerformWorkStackCursor, fiber); <add> pop(contextStackCursor, fiber); <add> } <ide> } <ide> <ide> function pushTopLevelContextObject( <ide> fiber: Fiber, <ide> context: Object, <ide> didChange: boolean, <ide> ): void { <del> invariant( <del> contextStackCursor.current === emptyContextObject, <del> 'Unexpected context found on stack. ' + <del> 'This error is likely caused by a bug in React. Please file an issue.', <del> ); <del> <del> push(contextStackCursor, context, fiber); <del> push(didPerformWorkStackCursor, didChange, fiber); <add> if (disableLegacyContext) { <add> return; <add> } else { <add> invariant( <add> contextStackCursor.current === emptyContextObject, <add> 'Unexpected context found on stack. ' + <add> 'This error is likely caused by a bug in React. Please file an issue.', <add> ); <add> <add> push(contextStackCursor, context, fiber); <add> push(didPerformWorkStackCursor, didChange, fiber); <add> } <ide> } <ide> <ide> function processChildContext( <ide> fiber: Fiber, <ide> type: any, <ide> parentContext: Object, <ide> ): Object { <del> const instance = fiber.stateNode; <del> const childContextTypes = type.childContextTypes; <add> if (disableLegacyContext) { <add> return parentContext; <add> } else { <add> const instance = fiber.stateNode; <add> const childContextTypes = type.childContextTypes; <add> <add> // TODO (bvaughn) Replace this behavior with an invariant() in the future. <add> // It has only been added in Fiber to match the (unintentional) behavior in Stack. <add> if (typeof instance.getChildContext !== 'function') { <add> if (__DEV__) { <add> const componentName = getComponentName(type) || 'Unknown'; <add> <add> if (!warnedAboutMissingGetChildContext[componentName]) { <add> warnedAboutMissingGetChildContext[componentName] = true; <add> warningWithoutStack( <add> false, <add> '%s.childContextTypes is specified but there is no getChildContext() method ' + <add> 'on the instance. You can either define getChildContext() on %s or remove ' + <add> 'childContextTypes from it.', <add> componentName, <add> componentName, <add> ); <add> } <add> } <add> return parentContext; <add> } <ide> <del> // TODO (bvaughn) Replace this behavior with an invariant() in the future. <del> // It has only been added in Fiber to match the (unintentional) behavior in Stack. <del> if (typeof instance.getChildContext !== 'function') { <add> let childContext; <ide> if (__DEV__) { <del> const componentName = getComponentName(type) || 'Unknown'; <del> <del> if (!warnedAboutMissingGetChildContext[componentName]) { <del> warnedAboutMissingGetChildContext[componentName] = true; <del> warningWithoutStack( <del> false, <del> '%s.childContextTypes is specified but there is no getChildContext() method ' + <del> 'on the instance. You can either define getChildContext() on %s or remove ' + <del> 'childContextTypes from it.', <del> componentName, <del> componentName, <del> ); <del> } <add> setCurrentPhase('getChildContext'); <add> } <add> startPhaseTimer(fiber, 'getChildContext'); <add> childContext = instance.getChildContext(); <add> stopPhaseTimer(); <add> if (__DEV__) { <add> setCurrentPhase(null); <add> } <add> for (let contextKey in childContext) { <add> invariant( <add> contextKey in childContextTypes, <add> '%s.getChildContext(): key "%s" is not defined in childContextTypes.', <add> getComponentName(type) || 'Unknown', <add> contextKey, <add> ); <add> } <add> if (__DEV__) { <add> const name = getComponentName(type) || 'Unknown'; <add> checkPropTypes( <add> childContextTypes, <add> childContext, <add> 'child context', <add> name, <add> // In practice, there is one case in which we won't get a stack. It's when <add> // somebody calls unstable_renderSubtreeIntoContainer() and we process <add> // context from the parent component instance. The stack will be missing <add> // because it's outside of the reconciliation, and so the pointer has not <add> // been set. This is rare and doesn't matter. We'll also remove that API. <add> getCurrentFiberStackInDev, <add> ); <ide> } <del> return parentContext; <del> } <ide> <del> let childContext; <del> if (__DEV__) { <del> setCurrentPhase('getChildContext'); <add> return {...parentContext, ...childContext}; <ide> } <del> startPhaseTimer(fiber, 'getChildContext'); <del> childContext = instance.getChildContext(); <del> stopPhaseTimer(); <del> if (__DEV__) { <del> setCurrentPhase(null); <del> } <del> for (let contextKey in childContext) { <del> invariant( <del> contextKey in childContextTypes, <del> '%s.getChildContext(): key "%s" is not defined in childContextTypes.', <del> getComponentName(type) || 'Unknown', <del> contextKey, <del> ); <del> } <del> if (__DEV__) { <del> const name = getComponentName(type) || 'Unknown'; <del> checkPropTypes( <del> childContextTypes, <del> childContext, <del> 'child context', <del> name, <del> // In practice, there is one case in which we won't get a stack. It's when <del> // somebody calls unstable_renderSubtreeIntoContainer() and we process <del> // context from the parent component instance. The stack will be missing <del> // because it's outside of the reconciliation, and so the pointer has not <del> // been set. This is rare and doesn't matter. We'll also remove that API. <del> getCurrentFiberStackInDev, <del> ); <del> } <del> <del> return {...parentContext, ...childContext}; <ide> } <ide> <ide> function pushContextProvider(workInProgress: Fiber): boolean { <del> const instance = workInProgress.stateNode; <del> // We push the context as early as possible to ensure stack integrity. <del> // If the instance does not exist yet, we will push null at first, <del> // and replace it on the stack later when invalidating the context. <del> const memoizedMergedChildContext = <del> (instance && instance.__reactInternalMemoizedMergedChildContext) || <del> emptyContextObject; <del> <del> // Remember the parent context so we can merge with it later. <del> // Inherit the parent's did-perform-work value to avoid inadvertently blocking updates. <del> previousContext = contextStackCursor.current; <del> push(contextStackCursor, memoizedMergedChildContext, workInProgress); <del> push( <del> didPerformWorkStackCursor, <del> didPerformWorkStackCursor.current, <del> workInProgress, <del> ); <del> <del> return true; <add> if (disableLegacyContext) { <add> return false; <add> } else { <add> const instance = workInProgress.stateNode; <add> // We push the context as early as possible to ensure stack integrity. <add> // If the instance does not exist yet, we will push null at first, <add> // and replace it on the stack later when invalidating the context. <add> const memoizedMergedChildContext = <add> (instance && instance.__reactInternalMemoizedMergedChildContext) || <add> emptyContextObject; <add> <add> // Remember the parent context so we can merge with it later. <add> // Inherit the parent's did-perform-work value to avoid inadvertently blocking updates. <add> previousContext = contextStackCursor.current; <add> push(contextStackCursor, memoizedMergedChildContext, workInProgress); <add> push( <add> didPerformWorkStackCursor, <add> didPerformWorkStackCursor.current, <add> workInProgress, <add> ); <add> <add> return true; <add> } <ide> } <ide> <ide> function invalidateContextProvider( <ide> workInProgress: Fiber, <ide> type: any, <ide> didChange: boolean, <ide> ): void { <del> const instance = workInProgress.stateNode; <del> invariant( <del> instance, <del> 'Expected to have an instance by this point. ' + <del> 'This error is likely caused by a bug in React. Please file an issue.', <del> ); <del> <del> if (didChange) { <del> // Merge parent and own context. <del> // Skip this if we're not updating due to sCU. <del> // This avoids unnecessarily recomputing memoized values. <del> const mergedContext = processChildContext( <del> workInProgress, <del> type, <del> previousContext, <del> ); <del> instance.__reactInternalMemoizedMergedChildContext = mergedContext; <del> <del> // Replace the old (or empty) context with the new one. <del> // It is important to unwind the context in the reverse order. <del> pop(didPerformWorkStackCursor, workInProgress); <del> pop(contextStackCursor, workInProgress); <del> // Now push the new context and mark that it has changed. <del> push(contextStackCursor, mergedContext, workInProgress); <del> push(didPerformWorkStackCursor, didChange, workInProgress); <add> if (disableLegacyContext) { <add> return; <ide> } else { <del> pop(didPerformWorkStackCursor, workInProgress); <del> push(didPerformWorkStackCursor, didChange, workInProgress); <add> const instance = workInProgress.stateNode; <add> invariant( <add> instance, <add> 'Expected to have an instance by this point. ' + <add> 'This error is likely caused by a bug in React. Please file an issue.', <add> ); <add> <add> if (didChange) { <add> // Merge parent and own context. <add> // Skip this if we're not updating due to sCU. <add> // This avoids unnecessarily recomputing memoized values. <add> const mergedContext = processChildContext( <add> workInProgress, <add> type, <add> previousContext, <add> ); <add> instance.__reactInternalMemoizedMergedChildContext = mergedContext; <add> <add> // Replace the old (or empty) context with the new one. <add> // It is important to unwind the context in the reverse order. <add> pop(didPerformWorkStackCursor, workInProgress); <add> pop(contextStackCursor, workInProgress); <add> // Now push the new context and mark that it has changed. <add> push(contextStackCursor, mergedContext, workInProgress); <add> push(didPerformWorkStackCursor, didChange, workInProgress); <add> } else { <add> pop(didPerformWorkStackCursor, workInProgress); <add> push(didPerformWorkStackCursor, didChange, workInProgress); <add> } <ide> } <ide> } <ide> <ide> function findCurrentUnmaskedContext(fiber: Fiber): Object { <del> // Currently this is only used with renderSubtreeIntoContainer; not sure if it <del> // makes sense elsewhere <del> invariant( <del> isFiberMounted(fiber) && fiber.tag === ClassComponent, <del> 'Expected subtree parent to be a mounted class component. ' + <del> 'This error is likely caused by a bug in React. Please file an issue.', <del> ); <del> <del> let node = fiber; <del> do { <del> switch (node.tag) { <del> case HostRoot: <del> return node.stateNode.context; <del> case ClassComponent: { <del> const Component = node.type; <del> if (isContextProvider(Component)) { <del> return node.stateNode.__reactInternalMemoizedMergedChildContext; <add> if (disableLegacyContext) { <add> return emptyContextObject; <add> } else { <add> // Currently this is only used with renderSubtreeIntoContainer; not sure if it <add> // makes sense elsewhere <add> invariant( <add> isFiberMounted(fiber) && fiber.tag === ClassComponent, <add> 'Expected subtree parent to be a mounted class component. ' + <add> 'This error is likely caused by a bug in React. Please file an issue.', <add> ); <add> <add> let node = fiber; <add> do { <add> switch (node.tag) { <add> case HostRoot: <add> return node.stateNode.context; <add> case ClassComponent: { <add> const Component = node.type; <add> if (isContextProvider(Component)) { <add> return node.stateNode.__reactInternalMemoizedMergedChildContext; <add> } <add> break; <ide> } <del> break; <ide> } <del> } <del> node = node.return; <del> } while (node !== null); <del> invariant( <del> false, <del> 'Found unexpected detached subtree parent. ' + <del> 'This error is likely caused by a bug in React. Please file an issue.', <del> ); <add> node = node.return; <add> } while (node !== null); <add> invariant( <add> false, <add> 'Found unexpected detached subtree parent. ' + <add> 'This error is likely caused by a bug in React. Please file an issue.', <add> ); <add> } <ide> } <ide> <ide> export { <ide><path>packages/shared/ReactFeatureFlags.js <ide> export const enableSuspenseCallback = false; <ide> // from React.createElement to React.jsx <ide> // https://github.com/reactjs/rfcs/blob/createlement-rfc/text/0000-create-element-changes.md <ide> export const warnAboutDefaultPropsOnFunctionComponents = false; <add> <add>export const disableLegacyContext = false; <ide><path>packages/shared/forks/ReactFeatureFlags.native-fb.js <ide> export const flushSuspenseFallbacksInTests = true; <ide> export const enableUserBlockingEvents = false; <ide> export const enableSuspenseCallback = false; <ide> export const warnAboutDefaultPropsOnFunctionComponents = false; <add>export const disableLegacyContext = false; <ide> <ide> // Only used in www builds. <ide> export function addUserTimingListener() { <ide><path>packages/shared/forks/ReactFeatureFlags.native-oss.js <ide> export const flushSuspenseFallbacksInTests = true; <ide> export const enableUserBlockingEvents = false; <ide> export const enableSuspenseCallback = false; <ide> export const warnAboutDefaultPropsOnFunctionComponents = false; <add>export const disableLegacyContext = false; <ide> <ide> // Only used in www builds. <ide> export function addUserTimingListener() { <ide><path>packages/shared/forks/ReactFeatureFlags.persistent.js <ide> export const flushSuspenseFallbacksInTests = true; <ide> export const enableUserBlockingEvents = false; <ide> export const enableSuspenseCallback = false; <ide> export const warnAboutDefaultPropsOnFunctionComponents = false; <add>export const disableLegacyContext = false; <ide> <ide> // Only used in www builds. <ide> export function addUserTimingListener() { <ide><path>packages/shared/forks/ReactFeatureFlags.test-renderer.js <ide> export const flushSuspenseFallbacksInTests = true; <ide> export const enableUserBlockingEvents = false; <ide> export const enableSuspenseCallback = false; <ide> export const warnAboutDefaultPropsOnFunctionComponents = false; <add>export const disableLegacyContext = false; <ide> <ide> // Only used in www builds. <ide> export function addUserTimingListener() { <ide><path>packages/shared/forks/ReactFeatureFlags.test-renderer.www.js <ide> export const flushSuspenseFallbacksInTests = true; <ide> export const enableUserBlockingEvents = false; <ide> export const enableSuspenseCallback = true; <ide> export const warnAboutDefaultPropsOnFunctionComponents = false; <add>export const disableLegacyContext = false; <ide> <ide> // Only used in www builds. <ide> export function addUserTimingListener() { <ide><path>packages/shared/forks/ReactFeatureFlags.www.js <ide> export const { <ide> warnAboutDeprecatedSetNativeProps, <ide> revertPassiveEffectsChange, <ide> enableUserBlockingEvents, <add> disableLegacyContext, <ide> } = require('ReactFeatureFlags'); <ide> <ide> // In www, we have experimental support for gathering data
14
Text
Text
expand propositional logic stub
fb32d44c54dd1f47dba3789f73b8759b8bf9b1c6
<ide><path>guide/english/mathematics/propositional-logic/index.md <ide> title: Propositional Logic <ide> --- <ide> ## Propositional Logic Intro <ide> <del>This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/mathematics/propositional-logic/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>. <add>Propositional logic is a branch of logic that uses propositions, logical connectives and inference rules to reach conclusions. Propositions are statements or assertions that only be either false or true. These statements are the basic building blocks of propositional logic. Logical connectives bring propositions together to define argument and reach conclusions. Inference rules dictate how arguments are structured. <ide> <del><a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>. <add>Propositions are simple statements that can be represented by simple symbols. Those symbols can then be used with logical connectives to reach conclusions. <add>For example take the following argument: <ide> <del><!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds --> <add>First Premise: If it is snowing, then it is winter. <add> <add>Second Premise: It is snowing. <add> <add>Conclusion: Therefore, it is winter. <add> <add>This argument can be rewritten in the form: <add> <add>First Premise: P -> Q <add> <add>Second Premise: P <add> <add>Conclusion: Q <add> <add>## Modus Ponens <add> <add>The following argument illustrates one of the most basic inference rules of propositional logic: Modus Ponens also known as implication elimination. <add> <add>The rule for modus ponens takes the simple form: If P is true then Q is true. P is true therefore Q is true. <add> <add>P and Q can be replaced with any statement and the argument will be valid meaning if the premises are true, then the conclusion must be true by necessity. However, the argument is not sound unless it is both valid and the premises are true. For example, <add> <add>The following argument is valid but not sound: <add> <add>First Premise: If it is raining, it is a Thursday. <add> <add>Second Premise: It is raining. <add> <add>Conclusion: It is Thursday. <ide> <ide> #### More Information: <del><!-- Please add any articles you think might be helpful to read before writing the article --> <add>- [Wikipedia: Propositional Calclulus]( https://en.wikipedia.org/wiki/Propositional_calculus) <add> <add> <ide> <ide>
1
Javascript
Javascript
use global.eventtarget instead of internals
36fbbe0b86131fa2dcca558872b02335586e0089
<ide><path>test/parallel/test-abortcontroller.js <del>// Flags: --no-warnings --expose-internals <add>// Flags: --no-warnings <ide> 'use strict'; <ide> <ide> const common = require('../common'); <ide> <ide> const { ok, strictEqual } = require('assert'); <del>const { Event } = require('internal/event_target'); <ide> <ide> { <ide> // Tests that abort is fired with the correct event type on AbortControllers <ide><path>test/parallel/test-eventtarget-once-twice.js <del>// Flags: --expose-internals --no-warnings <ide> 'use strict'; <ide> const common = require('../common'); <del>const { <del> Event, <del> EventTarget, <del>} = require('internal/event_target'); <ide> const { once } = require('events'); <ide> <ide> const et = new EventTarget(); <ide><path>test/parallel/test-eventtarget-whatwg-once.js <del>// Flags: --expose-internals --no-warnings <ide> 'use strict'; <ide> <ide> const common = require('../common'); <ide> <del>const { <del> Event, <del> EventTarget, <del>} = require('internal/event_target'); <del> <ide> const { <ide> strictEqual, <ide> } = require('assert'); <ide><path>test/parallel/test-eventtarget.js <ide> 'use strict'; <ide> <ide> const common = require('../common'); <del>const { <del> Event, <del> EventTarget, <del> defineEventHandler <del>} = require('internal/event_target'); <add>const { defineEventHandler } = require('internal/event_target'); <ide> <ide> const { <ide> ok, <ide><path>test/parallel/test-nodeeventtarget.js <ide> 'use strict'; <ide> <ide> const common = require('../common'); <del>const { <del> Event, <del> NodeEventTarget, <del>} = require('internal/event_target'); <add>const { NodeEventTarget } = require('internal/event_target'); <ide> <ide> const { <ide> deepStrictEqual,
5
Javascript
Javascript
change renderfinish event to complete
26a2dcb516d8687b2e0b4c1056be95e0b2e517c2
<ide><path>examples/js/renderers/RaytracingRenderer.js <ide> THREE.RaytracingRenderer = function ( parameters ) { <ide> <ide> if ( blockY >= canvasHeight ) { <ide> <del> dispatch( { type: "renderfinish" } ); <add> dispatch( { type: "complete" } ); <ide> <ide> return; <ide>
1