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
Text
Text
remove react devtools from debugging docs
fa638c79971298bc88cccfe13657faf23cd249f0
<ide><path>docs/Debugging.md <ide> To debug on a real device: <ide> 1. On iOS - open the file `RCTWebSocketExecutor.m` and change `localhost` to the IP address of your computer. Shake the device to open the development menu with the option to start debugging. <ide> 2. On Android, if you're running Android 5.0+ device connected via USB you can use `adb` command line tool to setup port forwarding from the device to your computer. For that run: `adb reverse tcp:8081 tcp:8081` (see [this link](http://developer.android.com/tools/help/adb.html) for help on `adb` command). Alternatively, you can [open dev menu](#debugging-react-native-apps) on the device and select `Dev Settings`, then update `Debug server host for device` setting to the IP address of your computer. <ide> <del>#### React Developer Tools (optional) <del>Install the [React Developer Tools](https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi?hl=en) extension for Google Chrome. This will allow you to navigate the component hierarchy via the `React` in the developer tools (see [facebook/react-devtools](https://github.com/facebook/react-devtools) for more information). <del> <ide> ### Live Reload <ide> This option allows for your JS changes to trigger automatic reload on the connected device/emulator. To enable this option: <ide>
1
Javascript
Javascript
improve constant inlining, add `process.platform`
e6bafca39ed7105579daf9aba29a65f8dfc3c48b
<ide><path>Libraries/JavaScriptAppEngine/Initialization/InitializeJavaScriptAppEngine.js <ide> function polyfillLazyGlobal(name, valueFn, scope = GLOBAL) { <ide> configurable: true, <ide> enumerable: true, <ide> get() { <del> return this[name] = valueFn(); <add> return (this[name] = valueFn()); <ide> }, <ide> set(value) { <ide> Object.defineProperty(this, name, { <ide> function setUpProfile() { <ide> } <ide> } <ide> <del>function setUpProcessEnv() { <add>function setUpProcess() { <ide> GLOBAL.process = GLOBAL.process || {}; <ide> GLOBAL.process.env = GLOBAL.process.env || {}; <ide> if (!GLOBAL.process.env.NODE_ENV) { <ide> GLOBAL.process.env.NODE_ENV = __DEV__ ? 'development' : 'production'; <ide> } <add> <add> polyfillLazyGlobal('platform', () => require('Platform').OS, GLOBAL.process); <ide> } <ide> <ide> function setUpDevTools() { <ide> function setUpDevTools() { <ide> } <ide> } <ide> <del>setUpProcessEnv(); <add>setUpProcess(); <ide> setUpConsole(); <ide> setUpTimers(); <ide> setUpAlert(); <ide><path>packager/react-packager/src/JSTransformer/worker/__tests__/inline-test.js <ide> describe('inline constants', () => { <ide> var a = __DEV__ ? 1 : 2; <ide> var b = a.__DEV__; <ide> var c = function __DEV__(__DEV__) {}; <del> }` <add> }`; <ide> const {ast} = inline('arbitrary.js', {code}, {dev: true}); <ide> expect(toString(ast)).toEqual(normalize(code.replace(/__DEV__/, 'true'))); <ide> }); <ide> describe('inline constants', () => { <ide> const code = `function a() { <ide> var a = Platform.OS; <ide> var b = a.Platform.OS; <del> }` <add> }`; <ide> const {ast} = inline('arbitrary.js', {code}, {platform: 'ios'}); <ide> expect(toString(ast)).toEqual(normalize(code.replace(/Platform\.OS/, '"ios"'))); <ide> }); <ide> describe('inline constants', () => { <ide> function a() { <ide> if (Platform.OS === 'android') a = function() {}; <ide> var b = a.Platform.OS; <del> }` <add> }`; <add> const {ast} = inline('arbitrary.js', {code}, {platform: 'ios'}); <add> expect(toString(ast)).toEqual(normalize(code.replace(/Platform\.OS/, '"ios"'))); <add> }); <add> <add> it('replaces Platform.OS in the code if Platform is a top level import from react-native', () => { <add> const code = ` <add> var Platform = require('react-native').Platform; <add> function a() { <add> if (Platform.OS === 'android') a = function() {}; <add> var b = a.Platform.OS; <add> }`; <ide> const {ast} = inline('arbitrary.js', {code}, {platform: 'ios'}); <ide> expect(toString(ast)).toEqual(normalize(code.replace(/Platform\.OS/, '"ios"'))); <ide> }); <ide> describe('inline constants', () => { <ide> const code = `function a() { <ide> var a = require('Platform').OS; <ide> var b = a.require('Platform').OS; <del> }` <add> }`; <ide> const {ast} = inline('arbitrary.js', {code}, {platform: 'android'}); <ide> expect(toString(ast)).toEqual( <ide> normalize(code.replace(/require\('Platform'\)\.OS/, '"android"'))); <ide> describe('inline constants', () => { <ide> const code = `function a() { <ide> var a = React.Platform.OS; <ide> var b = a.React.Platform.OS; <del> }` <add> }`; <ide> const {ast} = inline('arbitrary.js', {code}, {platform: 'ios'}); <ide> expect(toString(ast)).toEqual(normalize(code.replace(/React\.Platform\.OS/, '"ios"'))); <ide> }); <ide> <add> it('replaces ReactNative.Platform.OS in the code if ReactNative is a global', () => { <add> const code = `function a() { <add> var a = ReactNative.Platform.OS; <add> var b = a.ReactNative.Platform.OS; <add> }`; <add> const {ast} = inline('arbitrary.js', {code}, {platform: 'ios'}); <add> expect(toString(ast)).toEqual(normalize(code.replace(/ReactNative\.Platform\.OS/, '"ios"'))); <add> }); <add> <ide> it('replaces React.Platform.OS in the code if React is a top level import', () => { <ide> const code = ` <ide> var React = require('React'); <ide> function a() { <ide> if (React.Platform.OS === 'android') a = function() {}; <ide> var b = a.React.Platform.OS; <del> }` <add> }`; <ide> const {ast} = inline('arbitrary.js', {code}, {platform: 'ios'}); <ide> expect(toString(ast)).toEqual(normalize(code.replace(/React.Platform\.OS/, '"ios"'))); <ide> }); <ide> describe('inline constants', () => { <ide> const code = `function a() { <ide> var a = require('React').Platform.OS; <ide> var b = a.require('React').Platform.OS; <del> }` <add> }`; <ide> const {ast} = inline('arbitrary.js', {code}, {platform: 'android'}); <ide> expect(toString(ast)).toEqual( <ide> normalize(code.replace(/require\('React'\)\.Platform\.OS/, '"android"'))); <ide> }); <ide> <add> it('replaces ReactNative.Platform.OS in the code if ReactNative is a top level import', () => { <add> const code = ` <add> var ReactNative = require('react-native'); <add> function a() { <add> if (ReactNative.Platform.OS === 'android') a = function() {}; <add> var b = a.ReactNative.Platform.OS; <add> }`; <add> const {ast} = inline('arbitrary.js', {code}, {platform: 'android'}); <add> expect(toString(ast)).toEqual(normalize(code.replace(/ReactNative.Platform\.OS/, '"android"'))); <add> }); <add> <add> it('replaces require("react-native").Platform.OS in the code', () => { <add> const code = `function a() { <add> var a = require('react-native').Platform.OS; <add> var b = a.require('react-native').Platform.OS; <add> }`; <add> const {ast} = inline('arbitrary.js', {code}, {platform: 'android'}); <add> expect(toString(ast)).toEqual( <add> normalize(code.replace(/require\('react-native'\)\.Platform\.OS/, '"android"'))); <add> }); <add> <ide> it('replaces process.env.NODE_ENV in the code', () => { <ide> const code = `function a() { <ide> if (process.env.NODE_ENV === 'production') { <ide> return require('Prod'); <ide> } <ide> return require('Dev'); <del> }` <add> }`; <ide> const {ast} = inline('arbitrary.js', {code}, {dev: false}); <ide> expect(toString(ast)).toEqual( <ide> normalize(code.replace(/process\.env\.NODE_ENV/, '"production"'))); <ide> describe('inline constants', () => { <ide> return require('Prod'); <ide> } <ide> return require('Dev'); <del> }` <add> }`; <ide> const {ast} = inline('arbitrary.js', {code}, {dev: true}); <ide> expect(toString(ast)).toEqual( <ide> normalize(code.replace(/process\.env\.NODE_ENV/, '"development"'))); <ide> }); <ide> <add> it('replaces process.platform in the code', () => { <add> const code = `function a() { <add> if (process.platform === 'android') { <add> return require('./android'); <add> } <add> return require('./ios'); <add> }`; <add> const {ast} = inline('arbitrary.js', {code}, {platform: 'ios'}); <add> expect(toString(ast)).toEqual( <add> normalize(code.replace(/process\.platform\b/, '"ios"'))); <add> }); <add> <ide> it('accepts an AST as input', function() { <del> const code = `function ifDev(a,b){return __DEV__?a:b;}`; <add> const code = 'function ifDev(a,b){return __DEV__?a:b;}'; <ide> const {ast} = inline('arbitrary.hs', {ast: toAst(code)}, {dev: false}); <del> expect(toString(ast)).toEqual(code.replace(/__DEV__/, 'false')) <add> expect(toString(ast)).toEqual(code.replace(/__DEV__/, 'false')); <ide> }); <ide> }); <ide> <ide><path>packager/react-packager/src/JSTransformer/worker/inline.js <ide> const babel = require('babel-core'); <ide> const t = babel.types; <ide> <del>const react = {name: 'React'}; <add>const React = {name: 'React'}; <add>const ReactNative = {name: 'ReactNative'}; <ide> const platform = {name: 'Platform'}; <ide> const os = {name: 'OS'}; <ide> const requirePattern = {name: 'require'}; <ide> <ide> const env = {name: 'env'}; <ide> const nodeEnv = {name: 'NODE_ENV'}; <ide> const processId = {name: 'process'}; <add>const platformId = {name: 'platform'}; <ide> <ide> const dev = {name: '__DEV__'}; <ide> <add>const importMap = new Map([['ReactNative', 'react-native']]); <add> <ide> const isGlobal = (binding) => !binding; <ide> <ide> const isToplevelBinding = (binding) => isGlobal(binding) || !binding.scope.parent; <ide> const isRequireCall = (node, dependencyId, scope) => <ide> t.isIdentifier(node.callee, requirePattern) && <ide> t.isStringLiteral(node.arguments[0], t.stringLiteral(dependencyId)); <ide> <del>const isImport = (node, scope, pattern) => <del> t.isIdentifier(node, pattern) && <del> isToplevelBinding(scope.getBinding(pattern.name)) || <del> isRequireCall(node, pattern.name, scope); <add>const isImport = (node, scope, patterns) => <add> patterns.some(pattern => { <add> const importName = importMap.get(pattern.name) || pattern.name; <add> return isRequireCall(node, importName, scope); <add> }); <add> <add>function isImportOrGlobal(node, scope, patterns) { <add> const identifier = patterns.find(pattern => t.isIdentifier(node, pattern)); <add> return identifier && isToplevelBinding(scope.getBinding(identifier.name)) || <add> isImport(node, scope, patterns); <add>} <ide> <ide> const isPlatformOS = (node, scope) => <ide> t.isIdentifier(node.property, os) && <del> isImport(node.object, scope, platform); <add> isImportOrGlobal(node.object, scope, [platform]); <ide> <ide> const isReactPlatformOS = (node, scope) => <ide> t.isIdentifier(node.property, os) && <ide> t.isMemberExpression(node.object) && <ide> t.isIdentifier(node.object.property, platform) && <del> isImport(node.object.object, scope, react); <add> isImportOrGlobal(node.object.object, scope, [React, ReactNative]); <ide> <ide> const isProcessEnvNodeEnv = (node, scope) => <ide> t.isIdentifier(node.property, nodeEnv) && <ide> const isProcessEnvNodeEnv = (node, scope) => <ide> t.isIdentifier(node.object.object, processId) && <ide> isGlobal(scope.getBinding(processId.name)); <ide> <add>const isProcessPlatform = (node, scope) => <add> t.isIdentifier(node.property, platformId) && <add> t.isIdentifier(node.object, processId) && <add> isGlobal(scope.getBinding(processId.name)); <add> <ide> const isDev = (node, parent, scope) => <ide> t.isIdentifier(node, dev) && <ide> isGlobal(scope.getBinding(dev.name)) && <ide> const inlinePlugin = { <ide> <ide> if (isPlatformOS(node, scope) || isReactPlatformOS(node, scope)) { <ide> path.replaceWith(t.stringLiteral(state.opts.platform)); <del> } <del> <del> if(isProcessEnvNodeEnv(node, scope)) { <add> } else if (isProcessEnvNodeEnv(node, scope)) { <ide> path.replaceWith( <ide> t.stringLiteral(state.opts.dev ? 'development' : 'production')); <add> } else if (isProcessPlatform(node, scope)) { <add> path.replaceWith( <add> t.stringLiteral(state.opts.platform)); <ide> } <ide> }, <ide> },
3
PHP
PHP
add doc block for deprecation
3a4c90769f40c2e722d6e2e6e590fbdc090afbee
<ide><path>src/Illuminate/Pagination/Environment.php <ide> use Illuminate\View\Factory as ViewFactory; <ide> use Symfony\Component\Translation\TranslatorInterface; <ide> <add>/** <add> * DEPRECATED: Please use Illuminate\Pagination\Factory instead! <add> */ <ide> class Environment extends Factory { <ide> <ide> /**
1
PHP
PHP
fix suffix check
2b951e43a042f1931d2253ed4749207366556cb6
<ide><path>src/Illuminate/View/Factory.php <ide> protected function getExtension($path) <ide> $extensions = array_keys($this->extensions); <ide> <ide> return Arr::first($extensions, function ($value) use ($path) { <del> return Str::endsWith($path, $value); <add> return Str::endsWith($path, '.'.$value); <ide> }); <ide> } <ide>
1
Go
Go
remove waitandassert and type casts
649201dc4429fa8f734eaf6cd89cccd7eb2d9119
<ide><path>integration-cli/docker_api_swarm_test.go <ide> func (s *DockerSwarmSuite) TestAPISwarmLeaderElection(c *testing.T) { <ide> followers []*daemon.Daemon // keep track of followers <ide> ) <ide> var lastErr error <del> checkLeader := func(nodes ...*daemon.Daemon) interface{} { <add> checkLeader := func(nodes ...*daemon.Daemon) checkF { <ide> return func(c *testing.T) (interface{}, string) { <ide> // clear these out before each run <ide> leader = nil <ide><path>integration-cli/docker_utils_test.go <ide> func getErrorMessage(c *testing.T, body []byte) string { <ide> return strings.TrimSpace(resp.Message) <ide> } <ide> <del>func waitAndAssert(t *testing.T, timeout time.Duration, f interface{}, comparison interface{}, args ...interface{}) { <del> t1 := time.Now() <del> defer func() { <del> t2 := time.Now() <del> t.Logf("waited for %v (out of %v)", t2.Sub(t1), timeout) <del> }() <del> <del> after := time.After(timeout) <del> for { <del> v, comment := f.(checkF)(t) <del> args = append([]interface{}{v}, args...) <del> shouldAssert := assert.Check(t, comparison, args...) <del> select { <del> case <-after: <del> shouldAssert = true <del> default: <del> } <del> if shouldAssert { <del> if len(comment) > 0 { <del> args = append(args, comment) <del> } <del> assert.Assert(t, comparison, args...) <del> return <del> } <del> time.Sleep(100 * time.Millisecond) <del> } <del>} <del> <ide> type checkF func(*testing.T) (interface{}, string) <ide> type reducer func(...interface{}) interface{} <ide> <del>func pollCheck(t *testing.T, f interface{}, compare func(x interface{}) assert.BoolOrComparison) poll.Check { <add>func pollCheck(t *testing.T, f checkF, compare func(x interface{}) assert.BoolOrComparison) poll.Check { <ide> return func(poll.LogT) poll.Result { <del> ff := f.(checkF) <del> v, comment := ff(t) <add> v, comment := f(t) <ide> if assert.Check(t, compare(v)) { <ide> return poll.Success() <ide> } <ide> return poll.Continue(comment) <ide> } <ide> } <ide> <del>func reducedCheck(r reducer, funcs ...interface{}) checkF { <add>func reducedCheck(r reducer, funcs ...checkF) checkF { <ide> return func(c *testing.T) (interface{}, string) { <ide> var values []interface{} <ide> var comments []string <ide> for _, f := range funcs { <del> v, comment := f.(checkF)(c) <add> v, comment := f(c) <ide> values = append(values, v) <ide> if len(comment) > 0 { <ide> comments = append(comments, comment)
2
Javascript
Javascript
add save as support for firefox
3f4f056665b1bdc2b4a2b9aaf65f8783613442ee
<ide><path>extensions/firefox/components/PdfStreamConverter.js <ide> PdfStreamConverter.prototype = { <ide> onStartRequest: function(aRequest, aContext) { <ide> // Setup the request so we can use it below. <ide> aRequest.QueryInterface(Ci.nsIChannel); <add> aRequest.QueryInterface(Ci.nsIWritablePropertyBag); <ide> // Creating storage for PDF data <ide> var contentLength = aRequest.contentLength; <ide> var dataListener = new PdfDataListener(contentLength); <ide> PdfStreamConverter.prototype = { <ide> .createInstance(Ci.nsIBinaryInputStream); <ide> <ide> // Change the content type so we don't get stuck in a loop. <add> aRequest.setProperty('contentType', aRequest.contentType); <ide> aRequest.contentType = 'text/html'; <ide> <ide> // Create a new channel that is viewer loaded as a resource.
1
Javascript
Javascript
fix typo in `headersgetter`
26a6a9b624ee85ce51381ab0449f6cd775c445fb
<ide><path>src/ng/http.js <ide> function parseHeaders(headers) { <ide> * @param {(string|Object)} headers Headers to provide access to. <ide> * @returns {function(string=)} Returns a getter function which if called with: <ide> * <del> * - if called with single an argument returns a single header value or null <add> * - if called with an argument returns a single header value or null <ide> * - if called with no arguments returns an object containing all headers. <ide> */ <ide> function headersGetter(headers) {
1
Ruby
Ruby
remove duplicated conflicts unlinking
8755e91675dbe615b7792a77061627eb089abbfc
<ide><path>Library/Homebrew/cmd/test-bot.rb <ide> def formula(formula_name) <ide> <ide> formula = Formulary.factory(canonical_formula_name) <ide> <del> formula.conflicts.map { |c| Formulary.factory(c.name) }. <del> select(&:installed?).each do |conflict| <del> test "brew", "unlink", conflict.name <del> end <del> <ide> installed_gcc = false <ide> <ide> deps = []
1
PHP
PHP
remove uninstantiable seeder class
92b34069c1c36aef1e298174b2c3fbbe8511f28d
<ide><path>src/Illuminate/Database/SeedServiceProvider.php <ide> class SeedServiceProvider extends ServiceProvider <ide> */ <ide> public function register() <ide> { <del> $this->app->singleton('seeder', function () { <del> return new Seeder; <del> }); <del> <ide> $this->registerSeedCommand(); <ide> <ide> $this->commands('command.seed');
1
Go
Go
remove some intermediate variables
1483905024879a3da6ba4c5beb4fa45ef408e9f8
<ide><path>cmd/dockerd/config.go <ide> const defaultTrustKeyFile = "key.json" <ide> // installCommonConfigFlags adds flags to the pflag.FlagSet to configure the daemon <ide> func installCommonConfigFlags(conf *config.Config, flags *pflag.FlagSet) error { <ide> var maxConcurrentDownloads, maxConcurrentUploads, maxDownloadAttempts int <del> defaultPidFile, err := getDefaultPidFile() <add> var err error <add> conf.Pidfile, err = getDefaultPidFile() <ide> if err != nil { <ide> return err <ide> } <del> defaultDataRoot, err := getDefaultDataRoot() <add> conf.Root, err = getDefaultDataRoot() <ide> if err != nil { <ide> return err <ide> } <del> defaultExecRoot, err := getDefaultExecRoot() <add> conf.ExecRoot, err = getDefaultExecRoot() <ide> if err != nil { <ide> return err <ide> } <ide> func installCommonConfigFlags(conf *config.Config, flags *pflag.FlagSet) error { <ide> flags.Var(opts.NewNamedListOptsRef("storage-opts", &conf.GraphOptions, nil), "storage-opt", "Storage driver options") <ide> flags.Var(opts.NewNamedListOptsRef("authorization-plugins", &conf.AuthorizationPlugins, nil), "authorization-plugin", "Authorization plugins to load") <ide> flags.Var(opts.NewNamedListOptsRef("exec-opts", &conf.ExecOptions, nil), "exec-opt", "Runtime execution options") <del> flags.StringVarP(&conf.Pidfile, "pidfile", "p", defaultPidFile, "Path to use for daemon PID file") <del> flags.StringVar(&conf.Root, "data-root", defaultDataRoot, "Root directory of persistent Docker state") <del> flags.StringVar(&conf.ExecRoot, "exec-root", defaultExecRoot, "Root directory for execution state files") <add> flags.StringVarP(&conf.Pidfile, "pidfile", "p", conf.Pidfile, "Path to use for daemon PID file") <add> flags.StringVar(&conf.Root, "data-root", conf.Root, "Root directory of persistent Docker state") <add> flags.StringVar(&conf.ExecRoot, "exec-root", conf.ExecRoot, "Root directory for execution state files") <ide> flags.StringVar(&conf.ContainerdAddr, "containerd", "", "containerd grpc address") <ide> flags.BoolVar(&conf.CriContainerd, "cri-containerd", false, "start containerd with cri") <ide> <ide> func installCommonConfigFlags(conf *config.Config, flags *pflag.FlagSet) error { <ide> <ide> // "--graph" is "soft-deprecated" in favor of "data-root". This flag was added <ide> // before Docker 1.0, so won't be removed, only hidden, to discourage its usage. <del> flags.StringVarP(&conf.Root, "graph", "g", defaultDataRoot, "Root of the Docker runtime") <add> flags.StringVarP(&conf.Root, "graph", "g", conf.Root, "Root of the Docker runtime") <ide> _ = flags.MarkHidden("graph") <ide> flags.BoolVarP(&conf.AutoRestart, "restart", "r", true, "--restart on the daemon has been deprecated in favor of --restart policies on docker run") <ide> _ = flags.MarkDeprecated("restart", "Please use a restart policy on docker run")
1
Go
Go
fix typos in function comments
4a98f9ef7fdb6f6f77516fb030293fbc0ff659dc
<ide><path>client/config_update.go <ide> import ( <ide> "golang.org/x/net/context" <ide> ) <ide> <del>// ConfigUpdate attempts to updates a Config <add>// ConfigUpdate attempts to update a Config <ide> func (cli *Client) ConfigUpdate(ctx context.Context, id string, version swarm.Version, config swarm.ConfigSpec) error { <ide> query := url.Values{} <ide> query.Set("version", strconv.FormatUint(version.Index, 10)) <ide><path>client/secret_update.go <ide> import ( <ide> "golang.org/x/net/context" <ide> ) <ide> <del>// SecretUpdate attempts to updates a Secret <add>// SecretUpdate attempts to update a Secret <ide> func (cli *Client) SecretUpdate(ctx context.Context, id string, version swarm.Version, secret swarm.SecretSpec) error { <ide> query := url.Values{} <ide> query.Set("version", strconv.FormatUint(version.Index, 10))
2
Javascript
Javascript
use javascript functions for component templates
3848f48943d0530c3712394b9e405ebddf21cf3b
<ide><path>packages/react-native-codegen/src/generators/components/GenerateComponentDescriptorH.js <ide> import type {SchemaType} from '../../CodegenSchema'; <ide> // File path -> contents <ide> type FilesOutput = Map<string, string>; <ide> <del>const template = ` <add>const FileTemplate = ({ <add> componentDescriptors, <add> libraryName, <add>}: { <add> componentDescriptors: string, <add> libraryName: string, <add>}) => ` <ide> /** <ide> * ${'C'}opyright (c) Facebook, Inc. and its affiliates. <ide> * <ide> const template = ` <ide> <ide> #pragma once <ide> <del>#include <react/renderer/components/::_LIBRARY_::/ShadowNodes.h> <add>#include <react/renderer/components/${libraryName}/ShadowNodes.h> <ide> #include <react/renderer/core/ConcreteComponentDescriptor.h> <ide> <ide> namespace facebook { <ide> namespace react { <ide> <del>::_COMPONENT_DESCRIPTORS_:: <add>${componentDescriptors} <ide> <ide> } // namespace react <ide> } // namespace facebook <ide> `; <ide> <del>const componentTemplate = ` <del>using ::_CLASSNAME_::ComponentDescriptor = ConcreteComponentDescriptor<::_CLASSNAME_::ShadowNode>; <add>const ComponentTemplate = ({className}: {className: string}) => <add> ` <add>using ${className}ComponentDescriptor = ConcreteComponentDescriptor<${className}ShadowNode>; <ide> `.trim(); <ide> <ide> module.exports = { <ide> module.exports = { <ide> if (components[componentName].interfaceOnly === true) { <ide> return; <ide> } <del> return componentTemplate.replace(/::_CLASSNAME_::/g, componentName); <add> <add> return ComponentTemplate({className: componentName}); <ide> }) <ide> .join('\n'); <ide> }) <ide> .filter(Boolean) <ide> .join('\n'); <ide> <del> const replacedTemplate = template <del> .replace(/::_COMPONENT_DESCRIPTORS_::/g, componentDescriptors) <del> .replace('::_LIBRARY_::', libraryName); <add> const replacedTemplate = FileTemplate({ <add> componentDescriptors, <add> libraryName, <add> }); <ide> <ide> return new Map([[fileName, replacedTemplate]]); <ide> }, <ide><path>packages/react-native-codegen/src/generators/components/GenerateComponentHObjCpp.js <ide> function getOrdinalNumber(num: number): string { <ide> return 'unknown'; <ide> } <ide> <del>const protocolTemplate = ` <del>@protocol RCT::_COMPONENT_NAME_::ViewProtocol <NSObject> <del>::_METHODS_:: <add>const ProtocolTemplate = ({ <add> componentName, <add> methods, <add>}: { <add> componentName: string, <add> methods: string, <add>}) => <add> ` <add>@protocol RCT${componentName}ViewProtocol <NSObject> <add>${methods} <ide> @end <ide> `.trim(); <ide> <del>const commandHandlerIfCaseConvertArgTemplate = ` <del> NSObject *arg::_ARG_NUMBER_:: = args[::_ARG_NUMBER_::]; <add>const CommandHandlerIfCaseConvertArgTemplate = ({ <add> componentName, <add> expectedKind, <add> argNumber, <add> argNumberString, <add> expectedKindString, <add> argConversion, <add>}: { <add> componentName: string, <add> expectedKind: string, <add> argNumber: number, <add> argNumberString: string, <add> expectedKindString: string, <add> argConversion: string, <add>}) => <add> ` <add> NSObject *arg${argNumber} = args[${argNumber}]; <ide> #if RCT_DEBUG <del> if (!RCTValidateTypeOfViewCommandArgument(arg::_ARG_NUMBER_::, ::_EXPECTED_KIND_::, @"::_EXPECTED_KIND_STRING_::", @"::_COMPONENT_NAME_::", commandName, @"::_ARG_NUMBER_STR_::")) { <add> if (!RCTValidateTypeOfViewCommandArgument(arg${argNumber}, ${expectedKind}, @"${expectedKindString}", @"${componentName}", commandName, @"${argNumberString}")) { <ide> return; <ide> } <ide> #endif <del> ::_ARG_CONVERSION_:: <add> ${argConversion} <ide> `.trim(); <ide> <del>const commandHandlerIfCaseTemplate = ` <del>if ([commandName isEqualToString:@"::_COMMAND_NAME_::"]) { <add>const CommandHandlerIfCaseTemplate = ({ <add> componentName, <add> commandName, <add> numArgs, <add> convertArgs, <add> commandCall, <add>}: { <add> componentName: string, <add> commandName: string, <add> numArgs: number, <add> convertArgs: string, <add> commandCall: string, <add>}) => <add> ` <add>if ([commandName isEqualToString:@"${commandName}"]) { <ide> #if RCT_DEBUG <del> if ([args count] != ::_NUM_ARGS_::) { <del> RCTLogError(@"%@ command %@ received %d arguments, expected %d.", @"::_COMPONENT_NAME_::", commandName, (int)[args count], ::_NUM_ARGS_::); <add> if ([args count] != ${numArgs}) { <add> RCTLogError(@"%@ command %@ received %d arguments, expected %d.", @"${componentName}", commandName, (int)[args count], ${numArgs}); <ide> return; <ide> } <ide> #endif <ide> <del> ::_CONVERT_ARGS_:: <add> ${convertArgs} <ide> <del> ::_COMMAND_CALL_:: <add> ${commandCall} <ide> return; <ide> } <ide> `.trim(); <ide> <del>const commandHandlerTemplate = ` <del>RCT_EXTERN inline void RCT::_COMPONENT_NAME_::HandleCommand( <del> id<RCT::_COMPONENT_NAME_::ViewProtocol> componentView, <add>const CommandHandlerTemplate = ({ <add> componentName, <add> ifCases, <add>}: { <add> componentName: string, <add> ifCases: string, <add>}) => <add> ` <add>RCT_EXTERN inline void RCT${componentName}HandleCommand( <add> id<RCT${componentName}ViewProtocol> componentView, <ide> NSString const *commandName, <ide> NSArray const *args) <ide> { <del> ::_IF_CASES_:: <add> ${ifCases} <ide> <ide> #if RCT_DEBUG <del> RCTLogError(@"%@ received command %@, which is not a supported command.", @"::_COMPONENT_NAME_::", commandName); <add> RCTLogError(@"%@ received command %@, which is not a supported command.", @"${componentName}", commandName); <ide> #endif <ide> } <ide> `.trim(); <ide> <del>const template = ` <add>const FileTemplate = ({componentContent}: {componentContent: string}) => <add> ` <ide> /** <ide> * ${'C'}opyright (c) Facebook, Inc. and its affiliates. <ide> * <ide> const template = ` <ide> <ide> NS_ASSUME_NONNULL_BEGIN <ide> <del>::_COMPONENT_CONTENT_:: <add>${componentContent} <ide> <ide> NS_ASSUME_NONNULL_END <ide> `.trim(); <ide> function generateProtocol( <ide> component: ComponentShape, <ide> componentName: string, <ide> ): string { <del> const commands = component.commands <add> const methods = component.commands <ide> .map(command => { <ide> const params = command.typeAnnotation.params; <ide> const paramString = <ide> function generateProtocol( <ide> .join('\n') <ide> .trim(); <ide> <del> return protocolTemplate <del> .replace(/::_COMPONENT_NAME_::/g, componentName) <del> .replace('::_METHODS_::', commands); <add> return ProtocolTemplate({ <add> componentName, <add> methods, <add> }); <ide> } <ide> <ide> function generateConvertAndValidateParam( <ide> function generateConvertAndValidateParam( <ide> param.name <ide> } = ${getObjCRightHandAssignmentParamType(param, index)};`; <ide> <del> return commandHandlerIfCaseConvertArgTemplate <del> .replace(/::_COMPONENT_NAME_::/g, componentName) <del> .replace('::_ARG_CONVERSION_::', argConversion) <del> .replace(/::_ARG_NUMBER_::/g, '' + index) <del> .replace('::_ARG_NUMBER_STR_::', getOrdinalNumber(index + 1)) <del> .replace('::_EXPECTED_KIND_::', expectedKind) <del> .replace('::_EXPECTED_KIND_STRING_::', expectedKindString); <add> return CommandHandlerIfCaseConvertArgTemplate({ <add> componentName, <add> argConversion, <add> argNumber: index, <add> argNumberString: getOrdinalNumber(index + 1), <add> expectedKind, <add> expectedKindString, <add> }); <ide> } <ide> <ide> function generateCommandIfCase( <ide> function generateCommandIfCase( <ide> .join(' '); <ide> const commandCall = `[componentView ${command.name}${commandCallArgs}];`; <ide> <del> return commandHandlerIfCaseTemplate <del> .replace(/::_COMPONENT_NAME_::/g, componentName) <del> .replace(/::_COMMAND_NAME_::/g, command.name) <del> .replace(/::_NUM_ARGS_::/g, '' + params.length) <del> .replace('::_CONVERT_ARGS_::', convertArgs) <del> .replace('::_COMMAND_CALL_::', commandCall); <add> return CommandHandlerIfCaseTemplate({ <add> componentName, <add> commandName: command.name, <add> numArgs: params.length, <add> convertArgs, <add> commandCall, <add> }); <ide> } <ide> <ide> function generateCommandHandler( <ide> function generateCommandHandler( <ide> .map(command => generateCommandIfCase(command, componentName)) <ide> .join('\n\n'); <ide> <del> return commandHandlerTemplate <del> .replace(/::_COMPONENT_NAME_::/g, componentName) <del> .replace('::_IF_CASES_::', ifCases); <add> return CommandHandlerTemplate({ <add> componentName, <add> ifCases, <add> }); <ide> } <ide> <ide> module.exports = { <ide> module.exports = { <ide> .filter(Boolean) <ide> .join('\n\n'); <ide> <del> const replacedTemplate = template.replace( <del> '::_COMPONENT_CONTENT_::', <add> const replacedTemplate = FileTemplate({ <ide> componentContent, <del> ); <add> }); <ide> <ide> return new Map([[fileName, replacedTemplate]]); <ide> }, <ide><path>packages/react-native-codegen/src/generators/components/GenerateEventEmitterCpp.js <ide> type ComponentCollection = $ReadOnly<{ <ide> ..., <ide> }>; <ide> <del>const template = ` <add>const FileTemplate = ({ <add> events, <add> libraryName, <add>}: { <add> events: string, <add> libraryName: string, <add>}) => ` <ide> /** <ide> * ${'C'}opyright (c) Facebook, Inc. and its affiliates. <ide> * <ide> const template = ` <ide> * ${'@'}generated by codegen project: GenerateEventEmitterCpp.js <ide> */ <ide> <del>#include <react/renderer/components/::_LIBRARY_::/EventEmitters.h> <add>#include <react/renderer/components/${libraryName}/EventEmitters.h> <ide> <ide> namespace facebook { <ide> namespace react { <ide> <del>::_EVENTS_:: <add>${events} <ide> <ide> } // namespace react <ide> } // namespace facebook <ide> `; <ide> <del>const componentTemplate = ` <del>void ::_CLASSNAME_::EventEmitter::::_EVENT_NAME_::(::_STRUCT_NAME_:: event) const { <del> dispatchEvent("::_DISPATCH_EVENT_NAME_::", [event=std::move(event)](jsi::Runtime &runtime) { <del> ::_IMPLEMENTATION_:: <add>const ComponentTemplate = ({ <add> className, <add> eventName, <add> structName, <add> dispatchEventName, <add> implementation, <add>}: { <add> className: string, <add> eventName: string, <add> structName: string, <add> dispatchEventName: string, <add> implementation: string, <add>}) => <add> ` <add>void ${className}EventEmitter::${eventName}(${structName} event) const { <add> dispatchEvent("${dispatchEventName}", [event=std::move(event)](jsi::Runtime &runtime) { <add> ${implementation} <ide> }); <ide> } <ide> `.trim(); <ide> <del>const basicComponentTemplate = ` <del>void ::_CLASSNAME_::EventEmitter::::_EVENT_NAME_::() const { <del> dispatchEvent("::_DISPATCH_EVENT_NAME_::"); <add>const BasicComponentTemplate = ({ <add> className, <add> eventName, <add> dispatchEventName, <add>}: { <add> className: string, <add> eventName: string, <add> dispatchEventName: string, <add>}) => <add> ` <add>void ${className}EventEmitter::${eventName}() const { <add> dispatchEvent("${dispatchEventName}"); <ide> } <ide> `.trim(); <ide> <ide> function generateEvent(componentName: string, event): string { <ide> throw new Error('Expected the event name to start with `on`'); <ide> } <ide> <del> return componentTemplate <del> .replace(/::_CLASSNAME_::/g, componentName) <del> .replace(/::_EVENT_NAME_::/g, event.name) <del> .replace(/::_DISPATCH_EVENT_NAME_::/g, dispatchEventName) <del> .replace('::_STRUCT_NAME_::', generateEventStructName([event.name])) <del> .replace('::_IMPLEMENTATION_::', implementation); <add> return ComponentTemplate({ <add> className: componentName, <add> eventName: event.name, <add> dispatchEventName, <add> structName: generateEventStructName([event.name]), <add> implementation, <add> }); <ide> } <ide> <del> return basicComponentTemplate <del> .replace(/::_CLASSNAME_::/g, componentName) <del> .replace(/::_EVENT_NAME_::/g, event.name) <del> .replace(/::_DISPATCH_EVENT_NAME_::/g, dispatchEventName); <add> return BasicComponentTemplate({ <add> className: componentName, <add> eventName: event.name, <add> dispatchEventName, <add> }); <ide> } <ide> <ide> module.exports = { <ide> module.exports = { <ide> }) <ide> .join('\n'); <ide> <del> const replacedTemplate = template <del> .replace(/::_COMPONENT_EMITTERS_::/g, componentEmitters) <del> .replace('::_LIBRARY_::', libraryName) <del> .replace('::_EVENTS_::', componentEmitters); <add> const replacedTemplate = FileTemplate({ <add> libraryName, <add> events: componentEmitters, <add> }); <ide> <ide> return new Map([[fileName, replacedTemplate]]); <ide> }, <ide><path>packages/react-native-codegen/src/generators/components/GenerateEventEmitterH.js <ide> type ComponentCollection = $ReadOnly<{ <ide> ..., <ide> }>; <ide> <del>const template = ` <add>const FileTemplate = ({componentEmitters}: {componentEmitters: string}) => ` <ide> /** <ide> * ${'C'}opyright (c) Facebook, Inc. and its affiliates. <ide> * <ide> const template = ` <ide> namespace facebook { <ide> namespace react { <ide> <del>::_COMPONENT_EMITTERS_:: <add>${componentEmitters} <ide> <ide> } // namespace react <ide> } // namespace facebook <ide> `; <ide> <del>const componentTemplate = ` <del>class ::_CLASSNAME_::EventEmitter : public ViewEventEmitter { <add>const ComponentTemplate = ({ <add> className, <add> structs, <add> events, <add>}: { <add> className: string, <add> structs: string, <add> events: string, <add>}) => <add> ` <add>class ${className}EventEmitter : public ViewEventEmitter { <ide> public: <ide> using ViewEventEmitter::ViewEventEmitter; <ide> <del> ::_STRUCTS_:: <add> ${structs} <ide> <del> ::_EVENTS_:: <add> ${events} <ide> }; <ide> `.trim(); <ide> <del>const structTemplate = ` <del> struct ::_STRUCT_NAME_:: { <del> ::_FIELDS_:: <add>const StructTemplate = ({ <add> structName, <add> fields, <add>}: { <add> structName: string, <add> fields: string, <add>}) => <add> ` <add> struct ${structName} { <add> ${fields} <ide> }; <ide> `.trim(); <ide> <del>const enumTemplate = `enum class ::_ENUM_NAME_:: { <del> ::_VALUES_:: <add>const EnumTemplate = ({ <add> enumName, <add> values, <add> toCases, <add>}: { <add> enumName: string, <add> values: string, <add> toCases: string, <add>}) => <add> `enum class ${enumName} { <add> ${values} <ide> }; <ide> <del>static char const *toString(const ::_ENUM_NAME_:: value) { <add>static char const *toString(const ${enumName} value) { <ide> switch (value) { <del> ::_TO_CASES_:: <add> ${toCases} <ide> } <ide> } <ide> `.trim(); <ide> function generateEnum(structs, options, nameParts) { <ide> <ide> structs.set( <ide> structName, <del> enumTemplate <del> .replace(/::_ENUM_NAME_::/g, structName) <del> .replace('::_VALUES_::', fields) <del> .replace('::_TO_CASES_::', toCases), <add> EnumTemplate({ <add> enumName: structName, <add> values: fields, <add> toCases: toCases, <add> }), <ide> ); <ide> } <ide> <ide> function generateStruct( <ide> <ide> structs.set( <ide> structName, <del> structTemplate <del> .replace('::_STRUCT_NAME_::', structName) <del> .replace('::_FIELDS_::', fields), <add> StructTemplate({ <add> structName, <add> fields, <add> }), <ide> ); <ide> } <ide> <ide> module.exports = { <ide> .map(componentName => { <ide> const component = moduleComponents[componentName]; <ide> <del> const replacedTemplate = componentTemplate <del> .replace(/::_CLASSNAME_::/g, componentName) <del> .replace( <del> '::_STRUCTS_::', <del> indent(generateStructs(componentName, component), 2), <del> ) <del> .replace( <del> '::_EVENTS_::', <del> generateEvents(componentName, component), <del> ) <del> .trim(); <add> const replacedTemplate = ComponentTemplate({ <add> className: componentName, <add> structs: indent(generateStructs(componentName, component), 2), <add> events: generateEvents(componentName, component), <add> }); <ide> <ide> return replacedTemplate; <ide> }) <ide> .join('\n') <ide> : ''; <ide> <del> const replacedTemplate = template.replace( <del> /::_COMPONENT_EMITTERS_::/g, <add> const replacedTemplate = FileTemplate({ <ide> componentEmitters, <del> ); <add> }); <ide> <ide> return new Map([[fileName, replacedTemplate]]); <ide> }, <ide><path>packages/react-native-codegen/src/generators/components/GeneratePropsCpp.js <ide> const {convertDefaultTypeToString, getImports} = require('./CppHelpers'); <ide> // File path -> contents <ide> type FilesOutput = Map<string, string>; <ide> <del>const template = ` <add>const FileTemplate = ({ <add> libraryName, <add> imports, <add> componentClasses, <add>}: { <add> libraryName: string, <add> imports: string, <add> componentClasses: string, <add>}) => ` <ide> /** <ide> * ${'C'}opyright (c) Facebook, Inc. and its affiliates. <ide> * <ide> const template = ` <ide> * ${'@'}generated by codegen project: GeneratePropsCpp.js <ide> */ <ide> <del>#include <react/renderer/components/::_LIBRARY_::/Props.h> <del>::_IMPORTS_:: <add>#include <react/renderer/components/${libraryName}/Props.h> <add>${imports} <ide> <ide> namespace facebook { <ide> namespace react { <ide> <del>::_COMPONENT_CLASSES_:: <add>${componentClasses} <ide> <ide> } // namespace react <ide> } // namespace facebook <ide> `; <ide> <del>const componentTemplate = ` <del>::_CLASSNAME_::::::_CLASSNAME_::( <add>const ComponentTemplate = ({ <add> className, <add> extendClasses, <add> props, <add>}: { <add> className: string, <add> extendClasses: string, <add> props: string, <add>}) => <add> ` <add>${className}::${className}( <ide> const PropsParserContext &context, <del> const ::_CLASSNAME_:: &sourceProps, <del> const RawProps &rawProps):::_EXTEND_CLASSES_:: <add> const ${className} &sourceProps, <add> const RawProps &rawProps):${extendClasses} <ide> <del> ::_PROPS_:: <add> ${props} <ide> {} <ide> `.trim(); <ide> <ide> module.exports = { <ide> // $FlowFixMe[method-unbinding] added when improving typing for this parameters <ide> imports.forEach(allImports.add, allImports); <ide> <del> const replacedTemplate = componentTemplate <del> .replace(/::_CLASSNAME_::/g, newName) <del> .replace('::_EXTEND_CLASSES_::', extendString) <del> .replace('::_PROPS_::', propsString); <add> const replacedTemplate = ComponentTemplate({ <add> className: newName, <add> extendClasses: extendString, <add> props: propsString, <add> }); <ide> <ide> return replacedTemplate; <ide> }) <ide> module.exports = { <ide> .filter(Boolean) <ide> .join('\n'); <ide> <del> const replacedTemplate = template <del> .replace(/::_COMPONENT_CLASSES_::/g, componentProps) <del> .replace('::_LIBRARY_::', libraryName) <del> .replace( <del> '::_IMPORTS_::', <del> <del> Array.from(allImports) <del> .sort() <del> .join('\n') <del> .trim(), <del> ); <add> const replacedTemplate = FileTemplate({ <add> componentClasses: componentProps, <add> libraryName, <add> imports: Array.from(allImports) <add> .sort() <add> .join('\n') <add> .trim(), <add> }); <ide> <ide> return new Map([[fileName, replacedTemplate]]); <ide> }, <ide><path>packages/react-native-codegen/src/generators/components/GeneratePropsH.js <ide> import type { <ide> type FilesOutput = Map<string, string>; <ide> type StructsMap = Map<string, string>; <ide> <del>const template = ` <add>const FileTemplate = ({ <add> imports, <add> componentClasses, <add>}: { <add> imports: string, <add> componentClasses: string, <add>}) => ` <ide> /** <ide> * ${'C'}opyright (c) Facebook, Inc. and its affiliates. <ide> * <ide> const template = ` <ide> */ <ide> #pragma once <ide> <del>::_IMPORTS_:: <add>${imports} <ide> <ide> namespace facebook { <ide> namespace react { <ide> <del>::_COMPONENT_CLASSES_:: <add>${componentClasses} <ide> <ide> } // namespace react <ide> } // namespace facebook <ide> `; <ide> <del>const classTemplate = ` <del>::_ENUMS_:: <del>::_STRUCTS_:: <del>class ::_CLASSNAME_:: final::_EXTEND_CLASSES_:: { <add>const ClassTemplate = ({ <add> enums, <add> structs, <add> className, <add> props, <add> extendClasses, <add>}: { <add> enums: string, <add> structs: string, <add> className: string, <add> props: string, <add> extendClasses: string, <add>}) => <add> ` <add>${enums} <add>${structs} <add>class ${className} final${extendClasses} { <ide> public: <del> ::_CLASSNAME_::() = default; <del> ::_CLASSNAME_::(const PropsParserContext& context, const ::_CLASSNAME_:: &sourceProps, const RawProps &rawProps); <add> ${className}() = default; <add> ${className}(const PropsParserContext& context, const ${className} &sourceProps, const RawProps &rawProps); <ide> <ide> #pragma mark - Props <ide> <del> ::_PROPS_:: <add> ${props} <ide> }; <ide> `.trim(); <ide> <del>const enumTemplate = ` <del>enum class ::_ENUM_NAME_:: { ::_VALUES_:: }; <del> <del>static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, ::_ENUM_NAME_:: &result) { <add>const EnumTemplate = ({ <add> enumName, <add> values, <add> fromCases, <add> toCases, <add>}: { <add> enumName: string, <add> values: string, <add> fromCases: string, <add> toCases: string, <add>}) => <add> ` <add>enum class ${enumName} { ${values} }; <add> <add>static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, ${enumName} &result) { <ide> auto string = (std::string)value; <del> ::_FROM_CASES_:: <add> ${fromCases} <ide> abort(); <ide> } <ide> <del>static inline std::string toString(const ::_ENUM_NAME_:: &value) { <add>static inline std::string toString(const ${enumName} &value) { <ide> switch (value) { <del> ::_TO_CASES_:: <add> ${toCases} <ide> } <ide> } <ide> `.trim(); <ide> <del>const intEnumTemplate = ` <del>enum class ::_ENUM_NAME_:: { ::_VALUES_:: }; <del> <del>static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, ::_ENUM_NAME_:: &result) { <add>const IntEnumTemplate = ({ <add> enumName, <add> values, <add> fromCases, <add> toCases, <add>}: { <add> enumName: string, <add> values: string, <add> fromCases: string, <add> toCases: string, <add>}) => <add> ` <add>enum class ${enumName} { ${values} }; <add> <add>static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, ${enumName} &result) { <ide> assert(value.hasType<int>()); <ide> auto integerValue = (int)value; <del> switch (integerValue) {::_FROM_CASES_:: <add> switch (integerValue) {${fromCases} <ide> } <ide> abort(); <ide> } <ide> <del>static inline std::string toString(const ::_ENUM_NAME_:: &value) { <add>static inline std::string toString(const ${enumName} &value) { <ide> switch (value) { <del> ::_TO_CASES_:: <add> ${toCases} <ide> } <ide> } <ide> `.trim(); <ide> <del>const structTemplate = `struct ::_STRUCT_NAME_:: { <del> ::_FIELDS_:: <add>const StructTemplate = ({ <add> structName, <add> fields, <add> fromCases, <add>}: { <add> structName: string, <add> fields: string, <add> fromCases: string, <add>}) => <add> `struct ${structName} { <add> ${fields} <ide> }; <ide> <del>static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, ::_STRUCT_NAME_:: &result) { <add>static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, ${structName} &result) { <ide> auto map = (better::map<std::string, RawValue>)value; <ide> <del> ::_FROM_CASES_:: <add> ${fromCases} <ide> } <ide> <del>static inline std::string toString(const ::_STRUCT_NAME_:: &value) { <del> return "[Object ::_STRUCT_NAME_::]"; <add>static inline std::string toString(const ${structName} &value) { <add> return "[Object ${structName}]"; <ide> } <ide> `.trim(); <ide> <del>const arrayConversionFunction = `static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, std::vector<::_STRUCT_NAME_::> &result) { <add>const ArrayConversionFunctionTemplate = ({ <add> structName, <add>}: { <add> structName: string, <add>}) => `static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, std::vector<${structName}> &result) { <ide> auto items = (std::vector<RawValue>)value; <ide> for (const auto &item : items) { <del> ::_STRUCT_NAME_:: newItem; <add> ${structName} newItem; <ide> fromRawValue(context, item, newItem); <ide> result.emplace_back(newItem); <ide> } <ide> } <ide> `; <ide> <del>const doubleArrayConversionFunction = `static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, std::vector<std::vector<::_STRUCT_NAME_::>> &result) { <add>const DoubleArrayConversionFunctionTemplate = ({ <add> structName, <add>}: { <add> structName: string, <add>}) => `static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, std::vector<std::vector<${structName}>> &result) { <ide> auto items = (std::vector<std::vector<RawValue>>)value; <ide> for (const std::vector<RawValue> &item : items) { <del> auto nestedArray = std::vector<::_STRUCT_NAME_::>{}; <add> auto nestedArray = std::vector<${structName}>{}; <ide> for (const RawValue &nestedItem : item) { <del> ::_STRUCT_NAME_:: newItem; <add> ${structName} newItem; <ide> fromRawValue(context, nestedItem, newItem); <ide> nestedArray.emplace_back(newItem); <ide> } <ide> const doubleArrayConversionFunction = `static inline void fromRawValue(const Pro <ide> } <ide> `; <ide> <del>const arrayEnumTemplate = ` <del>using ::_ENUM_MASK_:: = uint32_t; <del> <del>enum class ::_ENUM_NAME_::: ::_ENUM_MASK_:: { <del> ::_VALUES_:: <add>const ArrayEnumTemplate = ({ <add> enumName, <add> enumMask, <add> values, <add> fromCases, <add> toCases, <add>}: { <add> enumName: string, <add> enumMask: string, <add> values: string, <add> fromCases: string, <add> toCases: string, <add>}) => <add> ` <add>using ${enumMask} = uint32_t; <add> <add>enum class ${enumName}: ${enumMask} { <add> ${values} <ide> }; <ide> <ide> constexpr bool operator&( <del> ::_ENUM_MASK_:: const lhs, <del> enum ::_ENUM_NAME_:: const rhs) { <del> return lhs & static_cast<::_ENUM_MASK_::>(rhs); <add> ${enumMask} const lhs, <add> enum ${enumName} const rhs) { <add> return lhs & static_cast<${enumMask}>(rhs); <ide> } <ide> <del>constexpr ::_ENUM_MASK_:: operator|( <del> ::_ENUM_MASK_:: const lhs, <del> enum ::_ENUM_NAME_:: const rhs) { <del> return lhs | static_cast<::_ENUM_MASK_::>(rhs); <add>constexpr ${enumMask} operator|( <add> ${enumMask} const lhs, <add> enum ${enumName} const rhs) { <add> return lhs | static_cast<${enumMask}>(rhs); <ide> } <ide> <ide> constexpr void operator|=( <del> ::_ENUM_MASK_:: &lhs, <del> enum ::_ENUM_NAME_:: const rhs) { <del> lhs = lhs | static_cast<::_ENUM_MASK_::>(rhs); <add> ${enumMask} &lhs, <add> enum ${enumName} const rhs) { <add> lhs = lhs | static_cast<${enumMask}>(rhs); <ide> } <ide> <del>static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, ::_ENUM_MASK_:: &result) { <add>static inline void fromRawValue(const PropsParserContext& context, const RawValue &value, ${enumMask} &result) { <ide> auto items = std::vector<std::string>{value}; <ide> for (const auto &item : items) { <del> ::_FROM_CASES_:: <add> ${fromCases} <ide> abort(); <ide> } <ide> } <ide> <del>static inline std::string toString(const ::_ENUM_MASK_:: &value) { <add>static inline std::string toString(const ${enumMask} &value) { <ide> auto result = std::string{}; <ide> auto separator = std::string{", "}; <ide> <del> ::_TO_CASES_:: <add> ${toCases} <ide> if (!result.empty()) { <ide> result.erase(result.length() - separator.length()); <ide> } <ide> function generateArrayEnumString( <ide> ) <ide> .join('\n' + ' '); <ide> <del> return arrayEnumTemplate <del> .replace(/::_ENUM_NAME_::/g, enumName) <del> .replace(/::_ENUM_MASK_::/g, getEnumMaskName(enumName)) <del> .replace('::_VALUES_::', values) <del> .replace('::_FROM_CASES_::', fromCases) <del> .replace('::_TO_CASES_::', toCases); <add> return ArrayEnumTemplate({ <add> enumName, <add> enumMask: getEnumMaskName(enumName), <add> values, <add> fromCases, <add> toCases, <add> }); <ide> } <ide> <ide> function generateStringEnum(componentName, prop) { <ide> function generateStringEnum(componentName, prop) { <ide> ) <ide> .join('\n' + ' '); <ide> <del> return enumTemplate <del> .replace(/::_ENUM_NAME_::/g, enumName) <del> .replace('::_VALUES_::', values.map(toSafeCppString).join(', ')) <del> .replace('::_FROM_CASES_::', fromCases) <del> .replace('::_TO_CASES_::', toCases); <add> return EnumTemplate({ <add> enumName, <add> values: values.map(toSafeCppString).join(', '), <add> fromCases: fromCases, <add> toCases: toCases, <add> }); <ide> } <ide> <ide> return ''; <ide> function generateIntEnum(componentName, prop) { <ide> .map(val => `${toIntEnumValueName(prop.name, val)} = ${val}`) <ide> .join(', '); <ide> <del> return intEnumTemplate <del> .replace(/::_ENUM_NAME_::/g, enumName) <del> .replace('::_VALUES_::', valueVariables) <del> .replace('::_FROM_CASES_::', fromCases) <del> .replace('::_TO_CASES_::', toCases); <add> return IntEnumTemplate({ <add> enumName, <add> values: valueVariables, <add> fromCases, <add> toCases, <add> }); <ide> } <ide> <ide> return ''; <ide> function generateStructs( <ide> `${[componentName, ...nameParts.concat([prop.name])].join( <ide> '', <ide> )}ArrayStruct`, <del> arrayConversionFunction.replace( <del> /::_STRUCT_NAME_::/g, <del> generateStructName(componentName, nameParts.concat([prop.name])), <del> ), <add> ArrayConversionFunctionTemplate({ <add> structName: generateStructName( <add> componentName, <add> nameParts.concat([prop.name]), <add> ), <add> }), <ide> ); <ide> } <ide> if ( <ide> function generateStructs( <ide> `${[componentName, ...nameParts.concat([prop.name])].join( <ide> '', <ide> )}ArrayArrayStruct`, <del> doubleArrayConversionFunction.replace( <del> /::_STRUCT_NAME_::/g, <del> generateStructName(componentName, nameParts.concat([prop.name])), <del> ), <add> DoubleArrayConversionFunctionTemplate({ <add> structName: generateStructName( <add> componentName, <add> nameParts.concat([prop.name]), <add> ), <add> }), <ide> ); <ide> } <ide> }); <ide> function generateStruct( <ide> <ide> structs.set( <ide> structName, <del> structTemplate <del> .replace(/::_STRUCT_NAME_::/g, structName) <del> .replace('::_FIELDS_::', fields) <del> .replace('::_FROM_CASES_::', fromCases), <add> StructTemplate({ <add> structName, <add> fields, <add> fromCases, <add> }), <ide> ); <ide> } <ide> <ide> module.exports = { <ide> // $FlowFixMe[method-unbinding] added when improving typing for this parameters <ide> imports.forEach(allImports.add, allImports); <ide> <del> const replacedTemplate = classTemplate <del> .replace('::_ENUMS_::', enumString) <del> .replace('::_STRUCTS_::', structString) <del> .replace(/::_CLASSNAME_::/g, newName) <del> .replace('::_EXTEND_CLASSES_::', extendString) <del> .replace('::_PROPS_::', propsString) <del> .trim(); <add> const replacedTemplate = ClassTemplate({ <add> enums: enumString, <add> structs: structString, <add> className: newName, <add> extendClasses: extendString, <add> props: propsString, <add> }); <ide> <ide> return replacedTemplate; <ide> }) <ide> module.exports = { <ide> .filter(Boolean) <ide> .join('\n\n'); <ide> <del> const replacedTemplate = template <del> .replace(/::_COMPONENT_CLASSES_::/g, componentClasses) <del> .replace( <del> '::_IMPORTS_::', <del> Array.from(allImports) <del> .sort() <del> .join('\n'), <del> ); <add> const replacedTemplate = FileTemplate({ <add> componentClasses, <add> imports: Array.from(allImports) <add> .sort() <add> .join('\n'), <add> }); <ide> <ide> return new Map([[fileName, replacedTemplate]]); <ide> }, <ide><path>packages/react-native-codegen/src/generators/components/GeneratePropsJavaDelegate.js <ide> const { <ide> // File path -> contents <ide> type FilesOutput = Map<string, string>; <ide> <del>const template = `/** <add>const FileTemplate = ({ <add> packageName, <add> imports, <add> className, <add> extendClasses, <add> interfaceClassName, <add> methods, <add>}: { <add> packageName: string, <add> imports: string, <add> className: string, <add> extendClasses: string, <add> interfaceClassName: string, <add> methods: string, <add>}) => `/** <ide> * ${'C'}opyright (c) Facebook, Inc. and its affiliates. <ide> * <ide> * This source code is licensed under the MIT license found in the <ide> const template = `/** <ide> * ${'@'}generated by codegen project: GeneratePropsJavaDelegate.js <ide> */ <ide> <del>package ::_PACKAGE_NAME_::; <add>package ${packageName}; <ide> <del>::_IMPORTS_:: <add>${imports} <ide> <del>public class ::_CLASSNAME_::<T extends ::_EXTEND_CLASSES_::, U extends BaseViewManagerInterface<T> & ::_INTERFACE_CLASSNAME_::<T>> extends BaseViewManagerDelegate<T, U> { <del> public ::_CLASSNAME_::(U viewManager) { <add>public class ${className}<T extends ${extendClasses}, U extends BaseViewManagerInterface<T> & ${interfaceClassName}<T>> extends BaseViewManagerDelegate<T, U> { <add> public ${className}(U viewManager) { <ide> super(viewManager); <ide> } <del> ::_METHODS_:: <add> ${methods} <ide> } <ide> `; <ide> <del>const propSetterTemplate = ` <add>const PropSetterTemplate = ({propCases}: {propCases: string}) => <add> ` <ide> @Override <ide> public void setProperty(T view, String propName, @Nullable Object value) { <del> ::_PROP_CASES_:: <add> ${propCases} <ide> } <del>`; <add>`.trim(); <ide> <del>const commandsTemplate = ` <add>const CommandsTemplate = ({commandCases}: {commandCases: string}) => <add> ` <ide> @Override <ide> public void receiveCommand(T view, String commandName, ReadableArray args) { <ide> switch (commandName) { <del> ::_COMMAND_CASES_:: <add> ${commandCases} <ide> } <ide> } <del>`; <add>`.trim(); <ide> <ide> function getJavaValueForProp( <ide> prop: NamedShape<PropTypeAnnotation>, <ide> function getDelegateImports(component) { <ide> <ide> function generateMethods(propsString, commandsString): string { <ide> return [ <del> propSetterTemplate.trim().replace('::_PROP_CASES_::', propsString), <add> PropSetterTemplate({propCases: propsString}), <ide> commandsString != null <del> ? commandsTemplate.trim().replace('::_COMMAND_CASES_::', commandsString) <add> ? CommandsTemplate({commandCases: commandsString}) <ide> : '', <ide> ] <ide> .join('\n\n ') <ide> module.exports = { <ide> ); <ide> const extendString = getClassExtendString(component); <ide> <del> const replacedTemplate = template <del> .replace( <del> /::_IMPORTS_::/g, <del> Array.from(imports) <del> .sort() <del> .join('\n'), <del> ) <del> .replace(/::_PACKAGE_NAME_::/g, normalizedPackageName) <del> .replace(/::_CLASSNAME_::/g, className) <del> .replace('::_EXTEND_CLASSES_::', extendString) <del> .replace('::_PROP_CASES_::', propsString) <del> .replace( <del> '::_METHODS_::', <del> generateMethods(propsString, commandsString), <del> ) <del> .replace(/::_INTERFACE_CLASSNAME_::/g, interfaceClassName); <add> const replacedTemplate = FileTemplate({ <add> imports: Array.from(imports) <add> .sort() <add> .join('\n'), <add> packageName: normalizedPackageName, <add> className, <add> extendClasses: extendString, <add> methods: generateMethods(propsString, commandsString), <add> interfaceClassName: interfaceClassName, <add> }); <ide> <ide> files.set(`${outputDir}/${className}.java`, replacedTemplate); <ide> }); <ide><path>packages/react-native-codegen/src/generators/components/GeneratePropsJavaInterface.js <ide> const { <ide> // File path -> contents <ide> type FilesOutput = Map<string, string>; <ide> <del>const template = `/** <add>const FileTemplate = ({ <add> packageName, <add> imports, <add> className, <add> extendClasses, <add> methods, <add>}: { <add> packageName: string, <add> imports: string, <add> className: string, <add> extendClasses: string, <add> methods: string, <add>}) => `/** <ide> * ${'C'}opyright (c) Facebook, Inc. and its affiliates. <ide> * <ide> * This source code is licensed under the MIT license found in the <ide> const template = `/** <ide> * ${'@'}generated by codegen project: GeneratePropsJavaInterface.js <ide> */ <ide> <del>package ::_PACKAGE_NAME_::; <add>package ${packageName}; <ide> <del>::_IMPORTS_:: <add>${imports} <ide> <del>public interface ::_CLASSNAME_::<T extends ::_EXTEND_CLASSES_::> { <del> ::_METHODS_:: <add>public interface ${className}<T extends ${extendClasses}> { <add> ${methods} <ide> } <ide> `; <ide> <ide> module.exports = { <ide> ); <ide> const extendString = getClassExtendString(component); <ide> <del> const replacedTemplate = template <del> .replace( <del> /::_IMPORTS_::/g, <del> Array.from(imports) <del> .sort() <del> .join('\n'), <del> ) <del> .replace(/::_PACKAGE_NAME_::/g, normalizedPackageName) <del> .replace(/::_CLASSNAME_::/g, className) <del> .replace('::_EXTEND_CLASSES_::', extendString) <del> .replace( <del> '::_METHODS_::', <del> [propsString, commandsString].join('\n' + ' ').trimRight(), <del> ) <del> .replace('::_COMMAND_HANDLERS_::', commandsString); <add> const replacedTemplate = FileTemplate({ <add> imports: Array.from(imports) <add> .sort() <add> .join('\n'), <add> packageName: normalizedPackageName, <add> className, <add> extendClasses: extendString, <add> methods: [propsString, commandsString] <add> .join('\n' + ' ') <add> .trimRight(), <add> }); <ide> <ide> files.set(`${outputDir}/${className}.java`, replacedTemplate); <ide> }); <ide><path>packages/react-native-codegen/src/generators/components/GenerateShadowNodeCpp.js <ide> import type {SchemaType} from '../../CodegenSchema'; <ide> // File path -> contents <ide> type FilesOutput = Map<string, string>; <ide> <del>const template = ` <add>const FileTemplate = ({ <add> libraryName, <add> componentNames, <add>}: { <add> libraryName: string, <add> componentNames: string, <add>}) => ` <ide> /** <ide> * ${'C'}opyright (c) Facebook, Inc. and its affiliates. <ide> * <ide> const template = ` <ide> * ${'@'}generated by codegen project: GenerateShadowNodeCpp.js <ide> */ <ide> <del>#include <react/renderer/components/::_LIBRARY_::/ShadowNodes.h> <add>#include <react/renderer/components/${libraryName}/ShadowNodes.h> <ide> <ide> namespace facebook { <ide> namespace react { <ide> <del>::_COMPONENT_NAMES_:: <add>${componentNames} <ide> <ide> } // namespace react <ide> } // namespace facebook <ide> `; <ide> <del>const componentTemplate = ` <del>extern const char ::_CLASSNAME_::ComponentName[] = "::_CLASSNAME_::"; <add>const ComponentTemplate = ({className}: {className: string}) => <add> ` <add>extern const char ${className}ComponentName[] = "${className}"; <ide> `.trim(); <ide> <ide> module.exports = { <ide> module.exports = { <ide> if (components[componentName].interfaceOnly === true) { <ide> return; <ide> } <del> const replacedTemplate = componentTemplate.replace( <del> /::_CLASSNAME_::/g, <del> componentName, <del> ); <add> const replacedTemplate = ComponentTemplate({ <add> className: componentName, <add> }); <ide> <ide> return replacedTemplate; <ide> }) <ide> module.exports = { <ide> .filter(Boolean) <ide> .join('\n'); <ide> <del> const replacedTemplate = template <del> .replace(/::_COMPONENT_NAMES_::/g, componentNames) <del> .replace('::_LIBRARY_::', libraryName); <add> const replacedTemplate = FileTemplate({ <add> componentNames, <add> libraryName, <add> }); <ide> <ide> return new Map([[fileName, replacedTemplate]]); <ide> }, <ide><path>packages/react-native-codegen/src/generators/components/GenerateShadowNodeH.js <ide> import type {SchemaType} from '../../CodegenSchema'; <ide> // File path -> contents <ide> type FilesOutput = Map<string, string>; <ide> <del>const template = ` <add>const FileTemplate = ({ <add> imports, <add> libraryName, <add> componentClasses, <add>}: { <add> imports: string, <add> libraryName: string, <add> componentClasses: string, <add>}) => ` <ide> /** <ide> * ${'C'}opyright (c) Facebook, Inc. and its affiliates. <ide> * <ide> const template = ` <ide> <ide> #pragma once <ide> <del>::_IMPORTS_::#include <react/renderer/components/::_LIBRARY_::/Props.h> <add>${imports}#include <react/renderer/components/${libraryName}/Props.h> <ide> #include <react/renderer/components/view/ConcreteViewShadowNode.h> <ide> <ide> namespace facebook { <ide> namespace react { <ide> <del>::_COMPONENT_CLASSES_:: <add>${componentClasses} <ide> <ide> } // namespace react <ide> } // namespace facebook <ide> `; <ide> <del>const componentTemplate = ` <del>extern const char ::_CLASSNAME_::ComponentName[]; <add>const ComponentTemplate = ({ <add> className, <add> eventEmitter, <add>}: { <add> className: string, <add> eventEmitter: string, <add>}) => <add> ` <add>extern const char ${className}ComponentName[]; <ide> <ide> /* <del> * \`ShadowNode\` for <::_CLASSNAME_::> component. <add> * \`ShadowNode\` for <${className}> component. <ide> */ <del>using ::_CLASSNAME_::ShadowNode = ConcreteViewShadowNode< <del> ::_CLASSNAME_::ComponentName, <del> ::_CLASSNAME_::Props::_EVENT_EMITTER_::>; <add>using ${className}ShadowNode = ConcreteViewShadowNode< <add> ${className}ComponentName, <add> ${className}Props${eventEmitter}>; <ide> `.trim(); <ide> <ide> module.exports = { <ide> module.exports = { <ide> ? `,\n${componentName}EventEmitter` <ide> : ''; <ide> <del> const replacedTemplate = componentTemplate <del> .replace(/::_CLASSNAME_::/g, componentName) <del> .replace('::_EVENT_EMITTER_::', eventEmitter); <add> const replacedTemplate = ComponentTemplate({ <add> className: componentName, <add> eventEmitter, <add> }); <ide> <ide> return replacedTemplate; <ide> }) <ide> module.exports = { <ide> <ide> const eventEmitterImport = `#include <react/renderer/components/${libraryName}/EventEmitters.h>\n`; <ide> <del> const replacedTemplate = template <del> .replace(/::_COMPONENT_CLASSES_::/g, moduleResults) <del> .replace('::_LIBRARY_::', libraryName) <del> .replace('::_IMPORTS_::', hasAnyEvents ? eventEmitterImport : ''); <add> const replacedTemplate = FileTemplate({ <add> componentClasses: moduleResults, <add> libraryName, <add> imports: hasAnyEvents ? eventEmitterImport : '', <add> }); <ide> <ide> return new Map([[fileName, replacedTemplate]]); <ide> }, <ide><path>packages/react-native-codegen/src/generators/components/GenerateTests.js <ide> type TestCase = $ReadOnly<{ <ide> raw?: boolean, <ide> }>; <ide> <del>const fileTemplate = ` <add>const FileTemplate = ({ <add> libraryName, <add> imports, <add> componentTests, <add>}: { <add> libraryName: string, <add> imports: string, <add> componentTests: string, <add>}) => <add> ` <ide> /** <ide> * ${'C'}opyright (c) Facebook, Inc. and its affiliates. <ide> * <ide> const fileTemplate = ` <ide> <ide> #include <gtest/gtest.h> <ide> #include <react/renderer/core/PropsParserContext.h> <del>#include <react/renderer/components/::_LIBRARY_NAME_::/Props.h> <del>::_IMPORTS_:: <add>#include <react/renderer/components/${libraryName}/Props.h> <add>${imports} <ide> <ide> using namespace facebook::react; <del>::_COMPONENT_TESTS_:: <del>`; <del> <del>const testTemplate = ` <del>TEST(::_COMPONENT_NAME_::_::_TEST_NAME_::, etc) { <add>${componentTests} <add>`.trim(); <add> <add>const TestTemplate = ({ <add> componentName, <add> testName, <add> propName, <add> propValue, <add>}: { <add> componentName: string, <add> testName: string, <add> propName: string, <add> propValue: string, <add>}) => ` <add>TEST(${componentName}_${testName}, etc) { <ide> auto propParser = RawPropsParser(); <del> propParser.prepare<::_COMPONENT_NAME_::>(); <del> auto const &sourceProps = ::_COMPONENT_NAME_::(); <del> auto const &rawProps = RawProps(folly::dynamic::object("::_PROP_NAME_::", ::_PROP_VALUE_::)); <add> propParser.prepare<${componentName}>(); <add> auto const &sourceProps = ${componentName}(); <add> auto const &rawProps = RawProps(folly::dynamic::object("${propName}", ${propValue})); <ide> <ide> ContextContainer contextContainer{}; <ide> PropsParserContext parserContext{-1, contextContainer}; <ide> <ide> rawProps.parse(propParser, parserContext); <del> ::_COMPONENT_NAME_::(parserContext, sourceProps, rawProps); <add> ${componentName}(parserContext, sourceProps, rawProps); <ide> } <ide> `; <ide> <ide> function generateTestsString(name, component) { <ide> const value = <ide> !raw && typeof propValue === 'string' ? `"${propValue}"` : propValue; <ide> <del> return testTemplate <del> .replace(/::_COMPONENT_NAME_::/g, name) <del> .replace(/::_TEST_NAME_::/g, testName != null ? testName : propName) <del> .replace(/::_PROP_NAME_::/g, propName) <del> .replace(/::_PROP_VALUE_::/g, String(value)); <add> return TestTemplate({ <add> componentName: name, <add> testName: testName != null ? testName : propName, <add> propName, <add> propValue: String(value), <add> }); <ide> } <ide> <ide> const testCases = component.props.reduce((cases, prop) => { <ide> module.exports = { <ide> .join('\n') <ide> .trim(); <ide> <del> const replacedTemplate = fileTemplate <del> .replace(/::_IMPORTS_::/g, imports) <del> .replace(/::_LIBRARY_NAME_::/g, libraryName) <del> .replace(/::_COMPONENT_TESTS_::/g, componentTests) <del> .trim(); <add> const replacedTemplate = FileTemplate({ <add> imports, <add> libraryName, <add> componentTests, <add> }); <ide> <ide> return new Map([[fileName, replacedTemplate]]); <ide> }, <ide><path>packages/react-native-codegen/src/generators/components/GenerateViewConfigJs.js <ide> import type {SchemaType} from '../../CodegenSchema'; <ide> // File path -> contents <ide> type FilesOutput = Map<string, string>; <ide> <del>const template = ` <add>const FileTemplate = ({ <add> imports, <add> componentConfig, <add>}: { <add> imports: string, <add> componentConfig: string, <add>}) => ` <ide> /** <ide> * ${'C'}opyright (c) Facebook, Inc. and its affiliates. <ide> * <ide> const template = ` <ide> <ide> 'use strict'; <ide> <del>::_IMPORTS_:: <add>${imports} <ide> <del>::_COMPONENT_CONFIG_:: <add>${componentConfig} <ide> `; <ide> <ide> // We use this to add to a set. Need to make sure we aren't importing <ide> function getReactDiffProcessValue(typeAnnotation) { <ide> } <ide> } <ide> <del>const componentTemplate = ` <del>let nativeComponentName = '::_COMPONENT_NAME_WITH_COMPAT_SUPPORT_::'; <del>::_DEPRECATION_CHECK_:: <add>const ComponentTemplate = ({ <add> componentNameWithCompatSupport, <add> deprecationCheck, <add>}: { <add> componentNameWithCompatSupport: string, <add> deprecationCheck: string, <add>}) => <add> ` <add>let nativeComponentName = '${componentNameWithCompatSupport}'; <add>${deprecationCheck} <ide> export default NativeComponentRegistry.get(nativeComponentName, () => VIEW_CONFIG); <ide> `.trim(); <ide> <del>const deprecatedComponentTemplate = ` <del>if (UIManager.getViewManagerConfig('::_COMPONENT_NAME_::')) { <del> nativeComponentName = '::_COMPONENT_NAME_::'; <del>} else if (UIManager.getViewManagerConfig('::_COMPONENT_NAME_DEPRECATED_::')) { <del> nativeComponentName = '::_COMPONENT_NAME_DEPRECATED_::'; <add>const DeprecatedComponentTemplate = ({ <add> componentName, <add> componentNameDeprecated, <add>}: { <add> componentName: string, <add> componentNameDeprecated: string, <add>}) => <add> ` <add>if (UIManager.getViewManagerConfig('${componentName}')) { <add> nativeComponentName = '${componentName}'; <add>} else if (UIManager.getViewManagerConfig('${componentNameDeprecated}')) { <add> nativeComponentName = '${componentNameDeprecated}'; <ide> } else { <del> throw new Error('Failed to find native component for either "::_COMPONENT_NAME_::" or "::_COMPONENT_NAME_DEPRECATED_::"'); <add> throw new Error('Failed to find native component for either "${componentName}" or "${componentNameDeprecated}"'); <ide> } <ide> `.trim(); <ide> <ide> module.exports = { <ide> } <ide> <ide> const deprecatedCheckBlock = component.paperComponentNameDeprecated <del> ? deprecatedComponentTemplate <del> .replace(/::_COMPONENT_NAME_::/g, componentName) <del> .replace( <del> /::_COMPONENT_NAME_DEPRECATED_::/g, <add> ? DeprecatedComponentTemplate({ <add> componentName, <add> componentNameDeprecated: <ide> component.paperComponentNameDeprecated || '', <del> ) <add> }) <ide> : ''; <ide> <del> const replacedTemplate = componentTemplate <del> .replace(/::_COMPONENT_NAME_::/g, componentName) <del> .replace( <del> /::_COMPONENT_NAME_WITH_COMPAT_SUPPORT_::/g, <del> paperComponentName, <del> ) <del> .replace(/::_DEPRECATION_CHECK_::/, deprecatedCheckBlock); <add> const replacedTemplate = ComponentTemplate({ <add> componentNameWithCompatSupport: paperComponentName, <add> deprecationCheck: deprecatedCheckBlock, <add> }); <ide> <ide> const replacedSourceRoot = j.withParser('flow')(replacedTemplate); <ide> <ide> module.exports = { <ide> .filter(Boolean) <ide> .join('\n\n'); <ide> <del> const replacedTemplate = template <del> .replace(/::_COMPONENT_CONFIG_::/g, moduleResults) <del> .replace( <del> '::_IMPORTS_::', <del> Array.from(imports) <del> .sort() <del> .join('\n'), <del> ); <add> const replacedTemplate = FileTemplate({ <add> componentConfig: moduleResults, <add> imports: Array.from(imports) <add> .sort() <add> .join('\n'), <add> }); <ide> <ide> return new Map([[fileName, replacedTemplate]]); <ide> } catch (error) {
12
Text
Text
move james back onto tsc
4206e7c2c4d8571029bf3c6e194f979f24910498
<ide><path>README.md <ide> For information about the governance of the Node.js project, see <ide> **Gabriel Schulhof** &lt;gabriel.schulhof@intel.com&gt; <ide> * [gireeshpunathil](https://github.com/gireeshpunathil) - <ide> **Gireesh Punathil** &lt;gpunathi@in.ibm.com&gt; (he/him) <add>* [jasnell](https://github.com/jasnell) - <add>**James M Snell** &lt;jasnell@gmail.com&gt; (he/him) <ide> * [joyeecheung](https://github.com/joyeecheung) - <ide> **Joyee Cheung** &lt;joyeec9h3@gmail.com&gt; (she/her) <ide> * [mcollina](https://github.com/mcollina) - <ide> For information about the governance of the Node.js project, see <ide> **Fedor Indutny** &lt;fedor.indutny@gmail.com&gt; <ide> * [isaacs](https://github.com/isaacs) - <ide> **Isaac Z. Schlueter** &lt;i@izs.me&gt; <del>* [jasnell](https://github.com/jasnell) - <del>**James M Snell** &lt;jasnell@gmail.com&gt; (he/him) <ide> * [joshgav](https://github.com/joshgav) - <ide> **Josh Gavant** &lt;josh.gavant@outlook.com&gt; <ide> * [mscdex](https://github.com/mscdex) -
1
Javascript
Javascript
throw error to object mode in socket
46446623f511c0d8c7d8d0e87db9f3ad8e8bc77d
<ide><path>lib/net.js <ide> const { <ide> NumberIsNaN, <ide> NumberParseInt, <ide> ObjectDefineProperty, <add> ObjectKeys, <ide> ObjectSetPrototypeOf, <ide> Symbol, <ide> } = primordials; <ide> const kSetNoDelay = Symbol('kSetNoDelay'); <ide> <ide> function Socket(options) { <ide> if (!(this instanceof Socket)) return new Socket(options); <add> const invalidKeys = [ <add> 'objectMode', <add> 'readableObjectMode', <add> 'writableObjectMode', <add> ]; <add> invalidKeys.forEach((invalidKey) => { <add> if (ObjectKeys(options).includes(invalidKey)) { <add> throw new ERR_INVALID_ARG_VALUE( <add> `options.${invalidKey}`, <add> options[invalidKey], <add> 'is not supported' <add> ); <add> } <add> }); <ide> <ide> this.connecting = false; <ide> // Problem with this is that users can supply their own handle, that may not <ide><path>test/parallel/test-net-connect-options-invalid.js <add>'use strict'; <add>const common = require('../common'); <add>const assert = require('assert'); <add>const net = require('net'); <add> <add>{ <add> const invalidKeys = [ <add> 'objectMode', <add> 'readableObjectMode', <add> 'writableObjectMode', <add> ]; <add> invalidKeys.forEach((invalidKey) => { <add> const option = { <add> ...common.localhostIPv4, <add> [invalidKey]: true <add> }; <add> const message = `The property 'options.${invalidKey}' is not supported. Received true`; <add> <add> assert.throws(() => { <add> net.createConnection(option); <add> }, { <add> code: 'ERR_INVALID_ARG_VALUE', <add> name: 'TypeError', <add> message: new RegExp(message) <add> }); <add> }); <add>} <ide><path>test/parallel/test-socket-options-invalid.js <add>'use strict'; <add>const common = require('../common'); <add>const assert = require('assert'); <add>const net = require('net'); <add> <add>{ <add> const invalidKeys = [ <add> 'objectMode', <add> 'readableObjectMode', <add> 'writableObjectMode', <add> ]; <add> invalidKeys.forEach((invalidKey) => { <add> const option = { <add> ...common.localhostIPv4, <add> [invalidKey]: true <add> }; <add> const message = `The property 'options.${invalidKey}' is not supported. Received true`; <add> <add> assert.throws(() => { <add> const socket = new net.Socket(option); <add> socket.connect({ port: 8080 }); <add> }, { <add> code: 'ERR_INVALID_ARG_VALUE', <add> name: 'TypeError', <add> message: new RegExp(message) <add> }); <add> }); <add>}
3
Java
Java
add interceptors for async processing
57c36dd39500654caeea124519257696d98f9f14
<ide><path>spring-orm/src/main/java/org/springframework/orm/hibernate3/support/OpenSessionInViewFilter.java <ide> package org.springframework.orm.hibernate3.support; <ide> <ide> import java.io.IOException; <add>import java.util.concurrent.Callable; <ide> <ide> import javax.servlet.FilterChain; <ide> import javax.servlet.ServletException; <ide> import org.springframework.transaction.support.TransactionSynchronizationManager; <ide> import org.springframework.util.Assert; <ide> import org.springframework.web.context.WebApplicationContext; <del>import org.springframework.web.context.request.async.WebAsyncUtils; <add>import org.springframework.web.context.request.NativeWebRequest; <add>import org.springframework.web.context.request.async.CallableProcessingInterceptor; <ide> import org.springframework.web.context.request.async.WebAsyncManager; <del>import org.springframework.web.context.request.async.WebAsyncManager.WebAsyncThreadInitializer; <add>import org.springframework.web.context.request.async.WebAsyncUtils; <ide> import org.springframework.web.context.support.WebApplicationContextUtils; <ide> import org.springframework.web.filter.OncePerRequestFilter; <ide> <ide> protected void doFilterInternal( <ide> participate = true; <ide> } <ide> else { <del> if (isFirstRequest || !asyncManager.initializeAsyncThread(key)) { <add> if (isFirstRequest || !applySessionBindingInterceptor(asyncManager, key)) { <ide> logger.debug("Opening single Hibernate Session in OpenSessionInViewFilter"); <ide> Session session = getSession(sessionFactory); <ide> SessionHolder sessionHolder = new SessionHolder(session); <ide> TransactionSynchronizationManager.bindResource(sessionFactory, sessionHolder); <ide> <del> WebAsyncThreadInitializer initializer = createAsyncThreadInitializer(sessionFactory, sessionHolder); <del> asyncManager.registerAsyncThreadInitializer(key, initializer); <add> asyncManager.registerCallableInterceptor(key, <add> new SessionBindingCallableInterceptor(sessionFactory, sessionHolder)); <ide> } <ide> } <ide> } <ide> protected void closeSession(Session session, SessionFactory sessionFactory) { <ide> SessionFactoryUtils.closeSession(session); <ide> } <ide> <del> private WebAsyncThreadInitializer createAsyncThreadInitializer(final SessionFactory sessionFactory, <del> final SessionHolder sessionHolder) { <add> private boolean applySessionBindingInterceptor(WebAsyncManager asyncManager, String key) { <add> if (asyncManager.getCallableInterceptor(key) == null) { <add> return false; <add> } <add> ((SessionBindingCallableInterceptor) asyncManager.getCallableInterceptor(key)).initializeThread(); <add> return true; <add> } <add> <ide> <del> return new WebAsyncThreadInitializer() { <del> public void initialize() { <del> TransactionSynchronizationManager.bindResource(sessionFactory, sessionHolder); <del> } <del> public void reset() { <del> TransactionSynchronizationManager.unbindResource(sessionFactory); <del> } <del> }; <add> /** <add> * Bind and unbind the Hibernate {@code Session} to the current thread. <add> */ <add> private static class SessionBindingCallableInterceptor implements CallableProcessingInterceptor { <add> <add> private final SessionFactory sessionFactory; <add> <add> private final SessionHolder sessionHolder; <add> <add> public SessionBindingCallableInterceptor(SessionFactory sessionFactory, SessionHolder sessionHolder) { <add> this.sessionFactory = sessionFactory; <add> this.sessionHolder = sessionHolder; <add> } <add> <add> public void preProcess(NativeWebRequest request, Callable<?> task) { <add> initializeThread(); <add> } <add> <add> private void initializeThread() { <add> TransactionSynchronizationManager.bindResource(this.sessionFactory, this.sessionHolder); <add> } <add> <add> public void postProcess(NativeWebRequest request, Callable<?> task, Object concurrentResult) { <add> TransactionSynchronizationManager.unbindResource(this.sessionFactory); <add> } <ide> } <ide> <ide> } <ide><path>spring-orm/src/main/java/org/springframework/orm/hibernate3/support/OpenSessionInViewInterceptor.java <ide> <ide> package org.springframework.orm.hibernate3.support; <ide> <add>import java.util.concurrent.Callable; <add> <ide> import org.hibernate.HibernateException; <ide> import org.hibernate.Session; <ide> import org.springframework.dao.DataAccessException; <ide> import org.springframework.transaction.support.TransactionSynchronizationManager; <ide> import org.springframework.ui.ModelMap; <ide> import org.springframework.web.context.request.AsyncWebRequestInterceptor; <add>import org.springframework.web.context.request.NativeWebRequest; <ide> import org.springframework.web.context.request.WebRequest; <del>import org.springframework.web.context.request.async.WebAsyncUtils; <add>import org.springframework.web.context.request.async.CallableProcessingInterceptor; <ide> import org.springframework.web.context.request.async.WebAsyncManager; <del>import org.springframework.web.context.request.async.WebAsyncManager.WebAsyncThreadInitializer; <add>import org.springframework.web.context.request.async.WebAsyncUtils; <ide> <ide> /** <ide> * Spring web request interceptor that binds a Hibernate <code>Session</code> to the <ide> public void preHandle(WebRequest request) throws DataAccessException { <ide> String participateAttributeName = getParticipateAttributeName(); <ide> <ide> if (asyncManager.hasConcurrentResult()) { <del> if (asyncManager.initializeAsyncThread(participateAttributeName)) { <add> if (applySessionBindingInterceptor(asyncManager, participateAttributeName)) { <ide> return; <ide> } <ide> } <ide> public void preHandle(WebRequest request) throws DataAccessException { <ide> SessionHolder sessionHolder = new SessionHolder(session); <ide> TransactionSynchronizationManager.bindResource(getSessionFactory(), sessionHolder); <ide> <del> WebAsyncThreadInitializer asyncThreadInitializer = createThreadInitializer(sessionHolder); <del> asyncManager.registerAsyncThreadInitializer(participateAttributeName, asyncThreadInitializer); <add> asyncManager.registerCallableInterceptor(participateAttributeName, <add> new SessionBindingCallableInterceptor(sessionHolder)); <ide> } <ide> else { <ide> // deferred close mode <ide> protected String getParticipateAttributeName() { <ide> return getSessionFactory().toString() + PARTICIPATE_SUFFIX; <ide> } <ide> <del> private WebAsyncThreadInitializer createThreadInitializer(final SessionHolder sessionHolder) { <del> return new WebAsyncThreadInitializer() { <del> public void initialize() { <del> TransactionSynchronizationManager.bindResource(getSessionFactory(), sessionHolder); <del> } <del> public void reset() { <del> TransactionSynchronizationManager.unbindResource(getSessionFactory()); <del> } <del> }; <add> private boolean applySessionBindingInterceptor(WebAsyncManager asyncManager, String key) { <add> if (asyncManager.getCallableInterceptor(key) == null) { <add> return false; <add> } <add> ((SessionBindingCallableInterceptor) asyncManager.getCallableInterceptor(key)).initializeThread(); <add> return true; <ide> } <ide> <add> <add> /** <add> * Bind and unbind the Hibernate {@code Session} to the current thread. <add> */ <add> private class SessionBindingCallableInterceptor implements CallableProcessingInterceptor { <add> <add> private final SessionHolder sessionHolder; <add> <add> public SessionBindingCallableInterceptor(SessionHolder sessionHolder) { <add> this.sessionHolder = sessionHolder; <add> } <add> <add> public void preProcess(NativeWebRequest request, Callable<?> task) { <add> initializeThread(); <add> } <add> <add> private void initializeThread() { <add> TransactionSynchronizationManager.bindResource(getSessionFactory(), this.sessionHolder); <add> } <add> <add> public void postProcess(NativeWebRequest request, Callable<?> task, Object concurrentResult) { <add> TransactionSynchronizationManager.unbindResource(getSessionFactory()); <add> } <add> } <ide> } <ide><path>spring-orm/src/main/java/org/springframework/orm/hibernate4/support/OpenSessionInViewFilter.java <ide> package org.springframework.orm.hibernate4.support; <ide> <ide> import java.io.IOException; <add>import java.util.concurrent.Callable; <ide> <ide> import javax.servlet.FilterChain; <ide> import javax.servlet.ServletException; <ide> import org.springframework.orm.hibernate4.SessionHolder; <ide> import org.springframework.transaction.support.TransactionSynchronizationManager; <ide> import org.springframework.web.context.WebApplicationContext; <del>import org.springframework.web.context.request.async.WebAsyncUtils; <add>import org.springframework.web.context.request.NativeWebRequest; <add>import org.springframework.web.context.request.async.CallableProcessingInterceptor; <ide> import org.springframework.web.context.request.async.WebAsyncManager; <del>import org.springframework.web.context.request.async.WebAsyncManager.WebAsyncThreadInitializer; <add>import org.springframework.web.context.request.async.WebAsyncUtils; <ide> import org.springframework.web.context.support.WebApplicationContextUtils; <ide> import org.springframework.web.filter.OncePerRequestFilter; <ide> <ide> protected void doFilterInternal( <ide> participate = true; <ide> } <ide> else { <del> if (isFirstRequest || !asyncManager.initializeAsyncThread(key)) { <add> if (isFirstRequest || !applySessionBindingInterceptor(asyncManager, key)) { <ide> logger.debug("Opening Hibernate Session in OpenSessionInViewFilter"); <ide> Session session = openSession(sessionFactory); <ide> SessionHolder sessionHolder = new SessionHolder(session); <ide> TransactionSynchronizationManager.bindResource(sessionFactory, sessionHolder); <ide> <del> WebAsyncThreadInitializer initializer = createAsyncThreadInitializer(sessionFactory, sessionHolder); <del> asyncManager.registerAsyncThreadInitializer(key, initializer); <add> asyncManager.registerCallableInterceptor(key, <add> new SessionBindingCallableInterceptor(sessionFactory, sessionHolder)); <ide> } <ide> } <ide> <ide> protected Session openSession(SessionFactory sessionFactory) throws DataAccessRe <ide> } <ide> } <ide> <del> private WebAsyncThreadInitializer createAsyncThreadInitializer(final SessionFactory sessionFactory, <del> final SessionHolder sessionHolder) { <del> <del> return new WebAsyncThreadInitializer() { <del> public void initialize() { <del> TransactionSynchronizationManager.bindResource(sessionFactory, sessionHolder); <del> } <del> public void reset() { <del> TransactionSynchronizationManager.unbindResource(sessionFactory); <del> } <del> }; <add> private boolean applySessionBindingInterceptor(WebAsyncManager asyncManager, String key) { <add> if (asyncManager.getCallableInterceptor(key) == null) { <add> return false; <add> } <add> ((SessionBindingCallableInterceptor) asyncManager.getCallableInterceptor(key)).initializeThread(); <add> return true; <ide> } <ide> <add> <add> /** <add> * Bind and unbind the Hibernate {@code Session} to the current thread. <add> */ <add> private static class SessionBindingCallableInterceptor implements CallableProcessingInterceptor { <add> <add> private final SessionFactory sessionFactory; <add> <add> private final SessionHolder sessionHolder; <add> <add> public SessionBindingCallableInterceptor(SessionFactory sessionFactory, SessionHolder sessionHolder) { <add> this.sessionFactory = sessionFactory; <add> this.sessionHolder = sessionHolder; <add> } <add> <add> public void preProcess(NativeWebRequest request, Callable<?> task) { <add> initializeThread(); <add> } <add> <add> private void initializeThread() { <add> TransactionSynchronizationManager.bindResource(this.sessionFactory, this.sessionHolder); <add> } <add> <add> public void postProcess(NativeWebRequest request, Callable<?> task, Object concurrentResult) { <add> TransactionSynchronizationManager.unbindResource(this.sessionFactory); <add> } <add> } <ide> } <ide><path>spring-orm/src/main/java/org/springframework/orm/hibernate4/support/OpenSessionInViewInterceptor.java <ide> <ide> package org.springframework.orm.hibernate4.support; <ide> <add>import java.util.concurrent.Callable; <add> <ide> import org.apache.commons.logging.Log; <ide> import org.apache.commons.logging.LogFactory; <ide> import org.hibernate.FlushMode; <ide> import org.springframework.transaction.support.TransactionSynchronizationManager; <ide> import org.springframework.ui.ModelMap; <ide> import org.springframework.web.context.request.AsyncWebRequestInterceptor; <add>import org.springframework.web.context.request.NativeWebRequest; <ide> import org.springframework.web.context.request.WebRequest; <del>import org.springframework.web.context.request.async.WebAsyncUtils; <add>import org.springframework.web.context.request.async.CallableProcessingInterceptor; <ide> import org.springframework.web.context.request.async.WebAsyncManager; <del>import org.springframework.web.context.request.async.WebAsyncManager.WebAsyncThreadInitializer; <add>import org.springframework.web.context.request.async.WebAsyncUtils; <ide> <ide> /** <ide> * Spring web request interceptor that binds a Hibernate <code>Session</code> to the <ide> public void preHandle(WebRequest request) throws DataAccessException { <ide> <ide> WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request); <ide> if (asyncManager.hasConcurrentResult()) { <del> if (asyncManager.initializeAsyncThread(participateAttributeName)) { <add> if (applySessionBindingInterceptor(asyncManager, participateAttributeName)) { <ide> return; <ide> } <ide> } <ide> public void preHandle(WebRequest request) throws DataAccessException { <ide> SessionHolder sessionHolder = new SessionHolder(session); <ide> TransactionSynchronizationManager.bindResource(getSessionFactory(), sessionHolder); <ide> <del> WebAsyncThreadInitializer asyncThreadInitializer = createThreadInitializer(sessionHolder); <del> asyncManager.registerAsyncThreadInitializer(participateAttributeName, asyncThreadInitializer); <add> asyncManager.registerCallableInterceptor(participateAttributeName, <add> new SessionBindingCallableInterceptor(sessionHolder)); <ide> } <ide> } <ide> <ide> protected String getParticipateAttributeName() { <ide> return getSessionFactory().toString() + PARTICIPATE_SUFFIX; <ide> } <ide> <del> private WebAsyncThreadInitializer createThreadInitializer(final SessionHolder sessionHolder) { <del> return new WebAsyncThreadInitializer() { <del> public void initialize() { <del> TransactionSynchronizationManager.bindResource(getSessionFactory(), sessionHolder); <del> } <del> public void reset() { <del> TransactionSynchronizationManager.unbindResource(getSessionFactory()); <del> } <del> }; <add> private boolean applySessionBindingInterceptor(WebAsyncManager asyncManager, String key) { <add> if (asyncManager.getCallableInterceptor(key) == null) { <add> return false; <add> } <add> ((SessionBindingCallableInterceptor) asyncManager.getCallableInterceptor(key)).initializeThread(); <add> return true; <add> } <add> <add> <add> /** <add> * Bind and unbind the Hibernate {@code Session} to the current thread. <add> */ <add> private class SessionBindingCallableInterceptor implements CallableProcessingInterceptor { <add> <add> private final SessionHolder sessionHolder; <add> <add> public SessionBindingCallableInterceptor(SessionHolder sessionHolder) { <add> this.sessionHolder = sessionHolder; <add> } <add> <add> public void preProcess(NativeWebRequest request, Callable<?> task) { <add> initializeThread(); <add> } <add> <add> private void initializeThread() { <add> TransactionSynchronizationManager.bindResource(getSessionFactory(), this.sessionHolder); <add> } <add> <add> public void postProcess(NativeWebRequest request, Callable<?> task, Object concurrentResult) { <add> TransactionSynchronizationManager.unbindResource(getSessionFactory()); <add> } <ide> } <ide> <ide> } <ide><path>spring-orm/src/main/java/org/springframework/orm/jpa/support/OpenEntityManagerInViewFilter.java <ide> package org.springframework.orm.jpa.support; <ide> <ide> import java.io.IOException; <add>import java.util.concurrent.Callable; <ide> <ide> import javax.persistence.EntityManager; <ide> import javax.persistence.EntityManagerFactory; <ide> import org.springframework.transaction.support.TransactionSynchronizationManager; <ide> import org.springframework.util.StringUtils; <ide> import org.springframework.web.context.WebApplicationContext; <del>import org.springframework.web.context.request.async.WebAsyncUtils; <add>import org.springframework.web.context.request.NativeWebRequest; <add>import org.springframework.web.context.request.async.CallableProcessingInterceptor; <ide> import org.springframework.web.context.request.async.WebAsyncManager; <del>import org.springframework.web.context.request.async.WebAsyncManager.WebAsyncThreadInitializer; <add>import org.springframework.web.context.request.async.WebAsyncUtils; <ide> import org.springframework.web.context.support.WebApplicationContextUtils; <ide> import org.springframework.web.filter.OncePerRequestFilter; <ide> <ide> protected void doFilterInternal( <ide> participate = true; <ide> } <ide> else { <del> if (isFirstRequest || !asyncManager.initializeAsyncThread(key)) { <add> if (isFirstRequest || !applyEntityManagerBindingInterceptor(asyncManager, key)) { <ide> logger.debug("Opening JPA EntityManager in OpenEntityManagerInViewFilter"); <ide> try { <ide> EntityManager em = createEntityManager(emf); <ide> EntityManagerHolder emHolder = new EntityManagerHolder(em); <ide> TransactionSynchronizationManager.bindResource(emf, emHolder); <ide> <del> WebAsyncThreadInitializer initializer = createAsyncThreadInitializer(emf, emHolder); <del> asyncManager.registerAsyncThreadInitializer(key, initializer); <add> asyncManager.registerCallableInterceptor(key, new EntityManagerBindingCallableInterceptor(emf, emHolder)); <ide> } <ide> catch (PersistenceException ex) { <ide> throw new DataAccessResourceFailureException("Could not create JPA EntityManager", ex); <ide> protected EntityManager createEntityManager(EntityManagerFactory emf) { <ide> return emf.createEntityManager(); <ide> } <ide> <del> private WebAsyncThreadInitializer createAsyncThreadInitializer(final EntityManagerFactory emFactory, <del> final EntityManagerHolder emHolder) { <add> private boolean applyEntityManagerBindingInterceptor(WebAsyncManager asyncManager, String key) { <add> if (asyncManager.getCallableInterceptor(key) == null) { <add> return false; <add> } <add> ((EntityManagerBindingCallableInterceptor) asyncManager.getCallableInterceptor(key)).initializeThread(); <add> return true; <add> } <add> <add> /** <add> * Bind and unbind the {@code EntityManager} to the current thread. <add> */ <add> private static class EntityManagerBindingCallableInterceptor implements CallableProcessingInterceptor { <ide> <del> return new WebAsyncThreadInitializer() { <del> public void initialize() { <del> TransactionSynchronizationManager.bindResource(emFactory, emHolder); <del> } <del> public void reset() { <del> TransactionSynchronizationManager.unbindResource(emFactory); <del> } <del> }; <add> private final EntityManagerFactory emFactory; <add> <add> private final EntityManagerHolder emHolder; <add> <add> <add> public EntityManagerBindingCallableInterceptor(EntityManagerFactory emFactory, EntityManagerHolder emHolder) { <add> this.emFactory = emFactory; <add> this.emHolder = emHolder; <add> } <add> <add> public void preProcess(NativeWebRequest request, Callable<?> task) { <add> initializeThread(); <add> } <add> <add> private void initializeThread() { <add> TransactionSynchronizationManager.bindResource(this.emFactory, this.emHolder); <add> } <add> <add> public void postProcess(NativeWebRequest request, Callable<?> task, Object concurrentResult) { <add> TransactionSynchronizationManager.unbindResource(this.emFactory); <add> } <ide> } <ide> <ide> } <ide><path>spring-orm/src/main/java/org/springframework/orm/jpa/support/OpenEntityManagerInViewInterceptor.java <ide> <ide> package org.springframework.orm.jpa.support; <ide> <add>import java.util.concurrent.Callable; <add> <ide> import javax.persistence.EntityManager; <ide> import javax.persistence.PersistenceException; <ide> <ide> import org.springframework.transaction.support.TransactionSynchronizationManager; <ide> import org.springframework.ui.ModelMap; <ide> import org.springframework.web.context.request.AsyncWebRequestInterceptor; <add>import org.springframework.web.context.request.NativeWebRequest; <ide> import org.springframework.web.context.request.WebRequest; <del>import org.springframework.web.context.request.async.WebAsyncUtils; <add>import org.springframework.web.context.request.async.CallableProcessingInterceptor; <ide> import org.springframework.web.context.request.async.WebAsyncManager; <del>import org.springframework.web.context.request.async.WebAsyncManager.WebAsyncThreadInitializer; <add>import org.springframework.web.context.request.async.WebAsyncUtils; <ide> <ide> /** <ide> * Spring web request interceptor that binds a JPA EntityManager to the <ide> public void preHandle(WebRequest request) throws DataAccessException { <ide> <ide> WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request); <ide> if (asyncManager.hasConcurrentResult()) { <del> if (asyncManager.initializeAsyncThread(participateAttributeName)) { <add> if (applyCallableInterceptor(asyncManager, participateAttributeName)) { <ide> return; <ide> } <ide> } <ide> public void preHandle(WebRequest request) throws DataAccessException { <ide> EntityManagerHolder emHolder = new EntityManagerHolder(em); <ide> TransactionSynchronizationManager.bindResource(getEntityManagerFactory(), emHolder); <ide> <del> WebAsyncThreadInitializer asyncThreadInitializer = createThreadInitializer(emHolder); <del> asyncManager.registerAsyncThreadInitializer(participateAttributeName, asyncThreadInitializer); <add> asyncManager.registerCallableInterceptor(participateAttributeName, <add> new EntityManagerBindingCallableInterceptor(emHolder)); <ide> } <ide> catch (PersistenceException ex) { <ide> throw new DataAccessResourceFailureException("Could not create JPA EntityManager", ex); <ide> protected String getParticipateAttributeName() { <ide> return getEntityManagerFactory().toString() + PARTICIPATE_SUFFIX; <ide> } <ide> <del> private WebAsyncThreadInitializer createThreadInitializer(final EntityManagerHolder emHolder) { <del> return new WebAsyncThreadInitializer() { <del> public void initialize() { <del> TransactionSynchronizationManager.bindResource(getEntityManagerFactory(), emHolder); <del> } <del> public void reset() { <del> TransactionSynchronizationManager.unbindResource(getEntityManagerFactory()); <del> } <del> }; <add> <add> private boolean applyCallableInterceptor(WebAsyncManager asyncManager, String key) { <add> if (asyncManager.getCallableInterceptor(key) == null) { <add> return false; <add> } <add> ((EntityManagerBindingCallableInterceptor) asyncManager.getCallableInterceptor(key)).initializeThread(); <add> return true; <add> } <add> <add> <add> /** <add> * Bind and unbind the Hibernate {@code Session} to the current thread. <add> */ <add> private class EntityManagerBindingCallableInterceptor implements CallableProcessingInterceptor { <add> <add> private final EntityManagerHolder emHolder; <add> <add> <add> public EntityManagerBindingCallableInterceptor(EntityManagerHolder emHolder) { <add> this.emHolder = emHolder; <add> } <add> <add> public void preProcess(NativeWebRequest request, Callable<?> task) { <add> initializeThread(); <add> } <add> <add> private void initializeThread() { <add> TransactionSynchronizationManager.bindResource(getEntityManagerFactory(), this.emHolder); <add> } <add> <add> public void postProcess(NativeWebRequest request, Callable<?> task, Object concurrentResult) { <add> TransactionSynchronizationManager.unbindResource(getEntityManagerFactory()); <add> } <ide> } <ide> <ide> } <ide><path>spring-orm/src/test/java/org/springframework/orm/hibernate3/support/OpenSessionInViewTests.java <ide> public void testOpenSessionInViewInterceptorAsyncScenario() throws Exception { <ide> replay(asyncWebRequest); <ide> <ide> WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(this.request); <add> asyncManager.setTaskExecutor(new SyncTaskExecutor()); <ide> asyncManager.setAsyncWebRequest(asyncWebRequest); <ide> <ide> asyncManager.startCallableProcessing(new Callable<String>() { <ide> public String call() throws Exception { <ide> <ide> // Async dispatch thread <ide> <del> reset(asyncWebRequest); <del> expect(asyncWebRequest.isDispatched()).andReturn(true); <del> replay(asyncWebRequest); <del> <ide> interceptor.preHandle(this.webRequest); <ide> assertTrue("Session not bound to async thread", TransactionSynchronizationManager.hasResource(sf)); <ide> <ide> public void doFilter(ServletRequest servletRequest, ServletResponse servletRespo <ide> asyncWebRequest.addCompletionHandler((Runnable) anyObject()); <ide> asyncWebRequest.startAsync(); <ide> expect(asyncWebRequest.isAsyncStarted()).andReturn(true).anyTimes(); <del> expect(asyncWebRequest.isDispatched()).andReturn(false).anyTimes(); <ide> replay(asyncWebRequest); <ide> <ide> WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(this.request); <add> asyncManager.setTaskExecutor(new SyncTaskExecutor()); <ide> asyncManager.setAsyncWebRequest(asyncWebRequest); <ide> asyncManager.startCallableProcessing(new Callable<String>() { <ide> public String call() throws Exception { <ide> public String call() throws Exception { <ide> <ide> expect(session.close()).andReturn(null); <ide> expect(asyncWebRequest.isAsyncStarted()).andReturn(false).anyTimes(); <del> expect(asyncWebRequest.isDispatched()).andReturn(true).anyTimes(); <ide> <ide> replay(sf); <ide> replay(session); <ide><path>spring-orm/src/test/java/org/springframework/orm/jpa/support/OpenEntityManagerInViewTests.java <ide> <ide> import junit.framework.TestCase; <ide> <add>import org.springframework.core.task.SimpleAsyncTaskExecutor; <ide> import org.springframework.mock.web.MockFilterConfig; <ide> import org.springframework.mock.web.MockHttpServletRequest; <ide> import org.springframework.mock.web.MockHttpServletResponse; <ide> public void testOpenEntityManagerInViewInterceptorAsyncScenario() throws Excepti <ide> replay(asyncWebRequest); <ide> <ide> WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(webRequest); <add> asyncManager.setTaskExecutor(new SyncTaskExecutor()); <ide> asyncManager.setAsyncWebRequest(asyncWebRequest); <ide> asyncManager.startCallableProcessing(new Callable<String>() { <ide> public String call() throws Exception { <ide> public String call() throws Exception { <ide> <ide> // Async dispatch thread <ide> <del> reset(asyncWebRequest); <del> expect(asyncWebRequest.isDispatched()).andReturn(true); <del> replay(asyncWebRequest); <del> <ide> reset(manager, factory); <ide> replay(manager, factory); <ide> <ide> public void doFilter(ServletRequest servletRequest, ServletResponse servletRespo <ide> asyncWebRequest.addCompletionHandler((Runnable) anyObject()); <ide> asyncWebRequest.startAsync(); <ide> expect(asyncWebRequest.isAsyncStarted()).andReturn(true).anyTimes(); <del> expect(asyncWebRequest.isDispatched()).andReturn(false).anyTimes(); <ide> replay(asyncWebRequest); <ide> <ide> WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request); <add> asyncManager.setTaskExecutor(new SyncTaskExecutor()); <ide> asyncManager.setAsyncWebRequest(asyncWebRequest); <ide> asyncManager.startCallableProcessing(new Callable<String>() { <ide> public String call() throws Exception { <ide> public String call() throws Exception { <ide> <ide> reset(asyncWebRequest); <ide> expect(asyncWebRequest.isAsyncStarted()).andReturn(false).anyTimes(); <del> expect(asyncWebRequest.isDispatched()).andReturn(true).anyTimes(); <ide> replay(asyncWebRequest); <ide> <ide> assertFalse(TransactionSynchronizationManager.hasResource(factory)); <ide> public String call() throws Exception { <ide> wac.close(); <ide> } <ide> <add> @SuppressWarnings("serial") <add> private static class SyncTaskExecutor extends SimpleAsyncTaskExecutor { <add> <add> @Override <add> public void execute(Runnable task, long startTimeout) { <add> task.run(); <add> } <add> } <ide> } <ide><path>spring-web/src/main/java/org/springframework/web/context/request/async/AsyncWebRequest.java <ide> public interface AsyncWebRequest extends NativeWebRequest { <ide> */ <ide> void setTimeoutHandler(Runnable runnable); <ide> <add> /** <add> * Add a Runnable to be invoked when request processing completes. <add> */ <add> void addCompletionHandler(Runnable runnable); <add> <ide> /** <ide> * Mark the start of asynchronous request processing so that when the main <ide> * processing thread exits, the response remains open for further processing <ide> public interface AsyncWebRequest extends NativeWebRequest { <ide> */ <ide> void dispatch(); <ide> <del> /** <del> * Whether the request was dispatched to the container in order to resume <del> * processing after concurrent execution in an application thread. <del> */ <del> boolean isDispatched(); <del> <del> /** <del> * Add a Runnable to be invoked when request processing completes. <del> */ <del> void addCompletionHandler(Runnable runnable); <del> <ide> /** <ide> * Whether asynchronous processing has completed. <ide> */ <ide><path>spring-web/src/main/java/org/springframework/web/context/request/async/CallableInterceptorChain.java <add>/* <add> * Copyright 2002-2012 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add>package org.springframework.web.context.request.async; <add> <add>import java.util.ArrayList; <add>import java.util.Collection; <add>import java.util.List; <add>import java.util.concurrent.Callable; <add> <add>import org.apache.commons.logging.Log; <add>import org.apache.commons.logging.LogFactory; <add>import org.springframework.web.context.request.NativeWebRequest; <add> <add>/** <add> * Assists with the invocation of {@link CallableProcessingInterceptor}'s. <add> * <add> * @author Rossen Stoyanchev <add> * @since 3.2 <add> */ <add>class CallableInterceptorChain { <add> <add> private static Log logger = LogFactory.getLog(CallableInterceptorChain.class); <add> <add> private final List<CallableProcessingInterceptor> interceptors; <add> <add> private int interceptorIndex = -1; <add> <add> <add> public CallableInterceptorChain(Collection<CallableProcessingInterceptor> interceptors) { <add> this.interceptors = new ArrayList<CallableProcessingInterceptor>(interceptors); <add> } <add> <add> public void applyPreProcess(NativeWebRequest request, Callable<?> task) throws Exception { <add> for (int i = 0; i < this.interceptors.size(); i++) { <add> this.interceptors.get(i).preProcess(request, task); <add> this.interceptorIndex = i; <add> } <add> } <add> <add> public void applyPostProcess(NativeWebRequest request, Callable<?> task, Object concurrentResult) { <add> for (int i = this.interceptorIndex; i >= 0; i--) { <add> try { <add> this.interceptors.get(i).postProcess(request, task, concurrentResult); <add> } <add> catch (Exception ex) { <add> logger.error("CallableProcessingInterceptor.postProcess threw exception", ex); <add> } <add> } <add> } <add> <add>} <ide><path>spring-web/src/main/java/org/springframework/web/context/request/async/CallableProcessingInterceptor.java <add>/* <add> * Copyright 2002-2012 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add>package org.springframework.web.context.request.async; <add> <add>import java.util.concurrent.Callable; <add> <add>import org.springframework.core.task.AsyncTaskExecutor; <add>import org.springframework.web.context.request.NativeWebRequest; <add>import org.springframework.web.context.request.WebRequestInterceptor; <add> <add>/** <add> * Intercepts concurrent request handling, where the concurrent result is <add> * obtained by executing a {@link Callable} on behalf of the application with an <add> * {@link AsyncTaskExecutor}. <add> * <p> <add> * A {@code CallableProcessingInterceptor} is invoked before and after the <add> * invocation of the {@code Callable} task in the asynchronous thread. <add> * <add> * <p>A {@code CallableProcessingInterceptor} may be registered as follows: <add> * <pre> <add> * CallableProcessingInterceptor interceptor = ... ; <add> * WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request); <add> * asyncManager.registerCallableInterceptor("key", interceptor); <add> * </pre> <add> * <add> * <p>To register an interceptor for every request, the above can be done through <add> * a {@link WebRequestInterceptor} during pre-handling. <add> * <add> * @author Rossen Stoyanchev <add> * @since 3.2 <add> */ <add>public interface CallableProcessingInterceptor { <add> <add> /** <add> * Invoked from the asynchronous thread in which the {@code Callable} is <add> * executed, before the {@code Callable} is invoked. <add> * <add> * @param request the current request <add> * @param task the task that will produce a result <add> */ <add> void preProcess(NativeWebRequest request, Callable<?> task) throws Exception; <add> <add> /** <add> * Invoked from the asynchronous thread in which the {@code Callable} is <add> * executed, after the {@code Callable} returned a result. <add> * <add> * @param request the current request <add> * @param task the task that produced the result <add> * @param concurrentResult the result of concurrent processing, which could <add> * be a {@link Throwable} if the {@code Callable} raised an exception <add> */ <add> void postProcess(NativeWebRequest request, Callable<?> task, Object concurrentResult) throws Exception; <add> <add>} <ide><path>spring-web/src/main/java/org/springframework/web/context/request/async/DeferredResult.java <ide> <ide> /** <ide> * {@code DeferredResult} provides an alternative to using a {@link Callable} <del> * for asynchronous request processing. While a Callable is executed concurrently <del> * on behalf of the application, with a DeferredResult the application can produce <del> * the result from a thread of its choice. <add> * for asynchronous request processing. While a {@code Callable} is executed <add> * concurrently on behalf of the application, with a {@code DeferredResult} the <add> * application can produce the result from a thread of its choice. <ide> * <ide> * @author Rossen Stoyanchev <ide> * @since 3.2 <ide> <ide> private DeferredResultHandler resultHandler; <ide> <del> private Object result = RESULT_NONE; <del> <ide> private final AtomicBoolean expired = new AtomicBoolean(false); <ide> <ide> private final Object lock = new Object(); <ide> public DeferredResult(Long timeout, Object timeoutResult) { <ide> this.timeout = timeout; <ide> } <ide> <del> <ide> /** <ide> * Return the configured timeout value in milliseconds. <ide> */ <ide> public Long getTimeoutMilliseconds() { <ide> } <ide> <ide> /** <del> * Set a handler to handle the result when set. Normally applications do not <del> * use this method at runtime but may do so during testing. <add> * Set a handler to handle the result when set. There can be only handler <add> * for a {@code DeferredResult}. At runtime it will be set by the framework. <add> * However applications may set it when unit testing. <add> * <add> * <p>If you need to be called back when a {@code DeferredResult} is set or <add> * expires, register a {@link DeferredResultProcessingInterceptor} instead. <ide> */ <ide> public void setResultHandler(DeferredResultHandler resultHandler) { <ide> this.resultHandler = resultHandler; <ide> public boolean setErrorResult(Object result) { <ide> } <ide> <ide> private boolean processResult(Object result) { <add> <ide> synchronized (this.lock) { <ide> <del> if (isSetOrExpired()) { <add> boolean wasExpired = getAndSetExpired(); <add> if (wasExpired) { <ide> return false; <ide> } <ide> <del> this.result = result; <del> <ide> if (!awaitResultHandler()) { <ide> throw new IllegalStateException("DeferredResultHandler not set"); <ide> } <ide> private boolean awaitResultHandler() { <ide> } <ide> <ide> /** <del> * Whether the DeferredResult can no longer be set either because the async <del> * request expired or because it was already set. <add> * Return {@code true} if this DeferredResult is no longer usable either <add> * because it was previously set or because the underlying request ended <add> * before it could be set. <add> * <p> <add> * The result may have been set with a call to {@link #setResult(Object)}, <add> * or {@link #setErrorResult(Object)}, or following a timeout, assuming a <add> * timeout result was provided to the constructor. The request may before <add> * the result set due to a timeout or network error. <ide> */ <ide> public boolean isSetOrExpired() { <del> return (this.expired.get() || (this.result != RESULT_NONE)); <add> return this.expired.get(); <ide> } <ide> <del> void setExpired() { <del> this.expired.set(true); <add> /** <add> * Atomically set the expired flag and return its previous value. <add> */ <add> boolean getAndSetExpired() { <add> return this.expired.getAndSet(true); <ide> } <ide> <ide> boolean hasTimeoutResult() { <ide><path>spring-web/src/main/java/org/springframework/web/context/request/async/DeferredResultInterceptorChain.java <add>/* <add> * Copyright 2002-2012 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add>package org.springframework.web.context.request.async; <add> <add>import java.util.ArrayList; <add>import java.util.Collection; <add>import java.util.List; <add> <add>import org.apache.commons.logging.Log; <add>import org.apache.commons.logging.LogFactory; <add>import org.springframework.web.context.request.NativeWebRequest; <add> <add>/** <add> * Assists with the invocation of {@link DeferredResultProcessingInterceptor}'s. <add> * <add> * @author Rossen Stoyanchev <add> * @since 3.2 <add> */ <add>class DeferredResultInterceptorChain { <add> <add> private static Log logger = LogFactory.getLog(DeferredResultInterceptorChain.class); <add> <add> private final List<DeferredResultProcessingInterceptor> interceptors; <add> <add> <add> public DeferredResultInterceptorChain(Collection<DeferredResultProcessingInterceptor> interceptors) { <add> this.interceptors = new ArrayList<DeferredResultProcessingInterceptor>(interceptors); <add> } <add> <add> public void applyPreProcess(NativeWebRequest request, DeferredResult<?> task) throws Exception { <add> for (DeferredResultProcessingInterceptor interceptor : this.interceptors) { <add> interceptor.preProcess(request, task); <add> } <add> } <add> <add> public void applyPostProcess(NativeWebRequest request, DeferredResult<?> task, Object concurrentResult) { <add> for (int i = this.interceptors.size()-1; i >= 0; i--) { <add> try { <add> this.interceptors.get(i).postProcess(request, task, concurrentResult); <add> } <add> catch (Exception ex) { <add> logger.error("DeferredResultProcessingInterceptor.postProcess threw exception", ex); <add> } <add> } <add> } <add> <add> public void triggerAfterExpiration(NativeWebRequest request, DeferredResult<?> task) { <add> for (int i = this.interceptors.size()-1; i >= 0; i--) { <add> try { <add> this.interceptors.get(i).afterExpiration(request, task); <add> } <add> catch (Exception ex) { <add> logger.error("DeferredResultProcessingInterceptor.afterExpiration threw exception", ex); <add> } <add> } <add> } <add> <add>} <ide><path>spring-web/src/main/java/org/springframework/web/context/request/async/DeferredResultProcessingInterceptor.java <add>/* <add> * Copyright 2002-2012 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add>package org.springframework.web.context.request.async; <add> <add>import org.springframework.web.context.request.NativeWebRequest; <add>import org.springframework.web.context.request.WebRequestInterceptor; <add> <add>/** <add> * Intercepts concurrent request handling, where the concurrent result is <add> * obtained by waiting for a {@link DeferredResult} to be set from a thread <add> * chosen by the application (e.g. in response to some external event). <add> * <add> * <p>A {@code DeferredResultProcessingInterceptor} is invoked before the start of <add> * asynchronous processing and either when the {@code DeferredResult} is set or <add> * when when the underlying request ends, whichever comes fist. <add> * <add> * <p>A {@code DeferredResultProcessingInterceptor} may be registered as follows: <add> * <pre> <add> * DeferredResultProcessingInterceptor interceptor = ... ; <add> * WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request); <add> * asyncManager.registerDeferredResultInterceptor("key", interceptor); <add> * </pre> <add> * <add> * <p>To register an interceptor for every request, the above can be done through <add> * a {@link WebRequestInterceptor} during pre-handling. <add> * <add> * @author Rossen Stoyanchev <add> * @since 3.2 <add> */ <add>public interface DeferredResultProcessingInterceptor { <add> <add> /** <add> * Invoked before the start of concurrent handling using a <add> * {@link DeferredResult}. The invocation occurs in the thread that <add> * initiated concurrent handling. <add> * <add> * @param request the current request <add> * @param deferredResult the DeferredResult instance <add> */ <add> void preProcess(NativeWebRequest request, DeferredResult<?> deferredResult) throws Exception; <add> <add> /** <add> * Invoked when a {@link DeferredResult} is set either with a normal value <add> * or with a {@link DeferredResult#DeferredResult(Long, Object) timeout <add> * result}. The invocation occurs in the thread that set the result. <add> * <p> <add> * If the request ends before the {@code DeferredResult} is set, then <add> * {@link #afterExpiration(NativeWebRequest, DeferredResult)} is called. <add> * <add> * @param request the current request <add> * @param deferredResult the DeferredResult that has been set <add> * @param concurrentResult the result to which the {@code DeferredResult} <add> * was set <add> */ <add> void postProcess(NativeWebRequest request, DeferredResult<?> deferredResult, <add> Object concurrentResult) throws Exception; <add> <add> <add> /** <add> * Invoked when a {@link DeferredResult} expires before a result has been <add> * set possibly due to a timeout or a network error. This invocation occurs <add> * in the thread where the timeout or network error notification is <add> * processed. <add> * <add> * @param request the current request <add> * @param deferredResult the DeferredResult that has been set <add> */ <add> void afterExpiration(NativeWebRequest request, DeferredResult<?> deferredResult) throws Exception; <add> <add>} <ide><path>spring-web/src/main/java/org/springframework/web/context/request/async/NoSupportAsyncWebRequest.java <ide> public boolean isAsyncStarted() { <ide> return false; <ide> } <ide> <del> public boolean isDispatched() { <del> return false; <del> } <del> <ide> // Not supported <ide> <ide> public void startAsync() { <ide><path>spring-web/src/main/java/org/springframework/web/context/request/async/StandardServletAsyncWebRequest.java <ide> import javax.servlet.AsyncContext; <ide> import javax.servlet.AsyncEvent; <ide> import javax.servlet.AsyncListener; <del>import javax.servlet.DispatcherType; <ide> import javax.servlet.http.HttpServletRequest; <ide> import javax.servlet.http.HttpServletResponse; <ide> <ide> public boolean isAsyncStarted() { <ide> return ((this.asyncContext != null) && getRequest().isAsyncStarted()); <ide> } <ide> <del> public boolean isDispatched() { <del> return (DispatcherType.ASYNC.equals(getRequest().getDispatcherType())); <del> } <del> <ide> /** <ide> * Whether async request processing has completed. <ide> * <p>It is important to avoid use of request and response objects after async <ide><path>spring-web/src/main/java/org/springframework/web/context/request/async/WebAsyncManager.java <ide> */ <ide> package org.springframework.web.context.request.async; <ide> <del>import java.util.ArrayList; <del>import java.util.Collections; <ide> import java.util.LinkedHashMap; <del>import java.util.List; <ide> import java.util.Map; <ide> import java.util.concurrent.Callable; <ide> <ide> public final class WebAsyncManager { <ide> <ide> private Object[] concurrentResultContext; <ide> <del> private final Map<Object, WebAsyncThreadInitializer> threadInitializers = new LinkedHashMap<Object, WebAsyncThreadInitializer>(); <add> private final Map<Object, CallableProcessingInterceptor> callableInterceptors = <add> new LinkedHashMap<Object, CallableProcessingInterceptor>(); <add> <add> private final Map<Object, DeferredResultProcessingInterceptor> deferredResultInterceptors = <add> new LinkedHashMap<Object, DeferredResultProcessingInterceptor>(); <ide> <ide> private static final UrlPathHelper urlPathHelper = new UrlPathHelper(); <ide> <ide> public final class WebAsyncManager { <ide> } <ide> <ide> /** <del> * Configure the {@link AsyncWebRequest} to use. This property may be <del> * set more than once during a single request to accurately reflect the <del> * current state of the request (e.g. following a forward, request/response <del> * wrapping, etc). However, it should not be set while concurrent handling is <del> * in progress, i.e. while {@link #isConcurrentHandlingStarted()} is {@code true}. <add> * Configure the {@link AsyncWebRequest} to use. This property may be set <add> * more than once during a single request to accurately reflect the current <add> * state of the request (e.g. following a forward, request/response <add> * wrapping, etc). However, it should not be set while concurrent handling <add> * is in progress, i.e. while {@link #isConcurrentHandlingStarted()} is <add> * {@code true}. <add> * <ide> * @param asyncWebRequest the web request to use <ide> */ <ide> public void setAsyncWebRequest(final AsyncWebRequest asyncWebRequest) { <ide> public boolean isConcurrentHandlingStarted() { <ide> } <ide> <ide> /** <del> * Whether the request has been dispatched to process the result of <del> * concurrent handling. <add> * Whether a result value exists as a result of concurrent handling. <ide> */ <ide> public boolean hasConcurrentResult() { <del> return ((this.concurrentResult != RESULT_NONE) && this.asyncWebRequest.isDispatched()); <add> return (this.concurrentResult != RESULT_NONE); <ide> } <ide> <ide> /** <ide> * Provides access to the result from concurrent handling. <add> * <ide> * @return an Object, possibly an {@code Exception} or {@code Throwable} if <del> * concurrent handling raised one. <add> * concurrent handling raised one. <add> * @see #clearConcurrentResult() <ide> */ <ide> public Object getConcurrentResult() { <ide> return this.concurrentResult; <ide> public Object getConcurrentResult() { <ide> /** <ide> * Provides access to additional processing context saved at the start of <ide> * concurrent handling. <add> * <add> * @see #clearConcurrentResult() <ide> */ <ide> public Object[] getConcurrentResultContext() { <ide> return this.concurrentResultContext; <ide> } <ide> <add> public CallableProcessingInterceptor getCallableInterceptor(Object key) { <add> return this.callableInterceptors.get(key); <add> } <add> <add> public DeferredResultProcessingInterceptor getDeferredResultInterceptor(Object key) { <add> return this.deferredResultInterceptors.get(key); <add> } <add> <add> /** <add> * Register a {@link CallableProcessingInterceptor} that will be applied <add> * when concurrent request handling with a {@link Callable} starts. <add> * <add> * @param key a unique the key under which to register the interceptor <add> * @param interceptor the interceptor to register <add> */ <add> public void registerCallableInterceptor(Object key, CallableProcessingInterceptor interceptor) { <add> Assert.notNull(interceptor, "interceptor is required"); <add> this.callableInterceptors.put(key, interceptor); <add> } <add> <add> /** <add> * Register a {@link DeferredResultProcessingInterceptor} that will be <add> * applied when concurrent request handling with a {@link DeferredResult} <add> * starts. <add> * <add> * @param key a unique the key under which to register the interceptor <add> * @param interceptor the interceptor to register <add> */ <add> public void registerDeferredResultInterceptor(Object key, DeferredResultProcessingInterceptor interceptor) { <add> Assert.notNull(interceptor, "interceptor is required"); <add> this.deferredResultInterceptors.put(key, interceptor); <add> } <add> <ide> /** <ide> * Clear {@linkplain #getConcurrentResult() concurrentResult} and <ide> * {@linkplain #getConcurrentResultContext() concurrentResultContext}. <ide> public void clearConcurrentResult() { <ide> * <ide> * @param callable a unit of work to be executed asynchronously <ide> * @param processingContext additional context to save that can be accessed <del> * via {@link #getConcurrentResultContext()} <add> * via {@link #getConcurrentResultContext()} <ide> * <ide> * @see #getConcurrentResult() <ide> * @see #getConcurrentResultContext() <ide> public void startCallableProcessing(final Callable<?> callable, Object... proces <ide> this.taskExecutor.submit(new Runnable() { <ide> <ide> public void run() { <del> List<WebAsyncThreadInitializer> initializers = <del> new ArrayList<WebAsyncThreadInitializer>(threadInitializers.values()); <add> <add> CallableInterceptorChain chain = <add> new CallableInterceptorChain(callableInterceptors.values()); <ide> <ide> try { <del> for (WebAsyncThreadInitializer initializer : initializers) { <del> initializer.initialize(); <del> } <add> chain.applyPreProcess(asyncWebRequest, callable); <ide> concurrentResult = callable.call(); <ide> } <ide> catch (Throwable t) { <ide> concurrentResult = t; <ide> } <ide> finally { <del> Collections.reverse(initializers); <del> for (WebAsyncThreadInitializer initializer : initializers) { <del> initializer.reset(); <del> } <add> chain.applyPostProcess(asyncWebRequest, callable, concurrentResult); <ide> } <ide> <ide> if (logger.isDebugEnabled()) { <ide> public void run() { <ide> * Use the given {@link AsyncTask} to configure the task executor as well as <ide> * the timeout value of the {@code AsyncWebRequest} before delegating to <ide> * {@link #startCallableProcessing(Callable, Object...)}. <add> * <ide> * @param asyncTask an asyncTask containing the target {@code Callable} <ide> * @param processingContext additional context to save that can be accessed <del> * via {@link #getConcurrentResultContext()} <add> * via {@link #getConcurrentResultContext()} <ide> */ <ide> public void startCallableProcessing(AsyncTask asyncTask, Object... processingContext) { <ide> Assert.notNull(asyncTask, "AsyncTask must not be null"); <ide> public void startCallableProcessing(AsyncTask asyncTask, Object... processingCon <ide> } <ide> <ide> /** <del> * Start concurrent request processing and initialize the given {@link DeferredResult} <del> * with a {@link DeferredResultHandler} that saves the result and dispatches <del> * the request to resume processing of that result. <del> * The {@code AsyncWebRequest} is also updated with a completion handler that <del> * expires the {@code DeferredResult} and a timeout handler assuming the <del> * {@code DeferredResult} has a default timeout result. <add> * Start concurrent request processing and initialize the given <add> * {@link DeferredResult} with a {@link DeferredResultHandler} that saves <add> * the result and dispatches the request to resume processing of that <add> * result. The {@code AsyncWebRequest} is also updated with a completion <add> * handler that expires the {@code DeferredResult} and a timeout handler <add> * assuming the {@code DeferredResult} has a default timeout result. <ide> * <ide> * @param deferredResult the DeferredResult instance to initialize <ide> * @param processingContext additional context to save that can be accessed <del> * via {@link #getConcurrentResultContext()} <add> * via {@link #getConcurrentResultContext()} <ide> * <ide> * @see #getConcurrentResult() <ide> * @see #getConcurrentResultContext() <ide> */ <del> public void startDeferredResultProcessing(final DeferredResult<?> deferredResult, Object... processingContext) { <add> public void startDeferredResultProcessing(final DeferredResult<?> deferredResult, <add> Object... processingContext) throws Exception { <add> <ide> Assert.notNull(deferredResult, "DeferredResult must not be null"); <ide> <ide> Long timeout = deferredResult.getTimeoutMilliseconds(); <ide> if (timeout != null) { <ide> this.asyncWebRequest.setTimeout(timeout); <ide> } <ide> <del> this.asyncWebRequest.addCompletionHandler(new Runnable() { <del> public void run() { <del> deferredResult.setExpired(); <del> } <del> }); <del> <ide> if (deferredResult.hasTimeoutResult()) { <ide> this.asyncWebRequest.setTimeoutHandler(new Runnable() { <ide> public void run() { <ide> public void run() { <ide> }); <ide> } <ide> <add> final DeferredResultInterceptorChain chain = <add> new DeferredResultInterceptorChain(this.deferredResultInterceptors.values()); <add> <add> chain.applyPreProcess(this.asyncWebRequest, deferredResult); <add> <add> this.asyncWebRequest.addCompletionHandler(new Runnable() { <add> public void run() { <add> if (!deferredResult.getAndSetExpired()) { <add> chain.triggerAfterExpiration(asyncWebRequest, deferredResult); <add> } <add> } <add> }); <add> <ide> startAsyncProcessing(processingContext); <ide> <ide> deferredResult.setResultHandler(new DeferredResultHandler() { <ide> public void handleResult(Object result) { <ide> logger.debug("Deferred result value [" + concurrentResult + "]"); <ide> } <ide> <del> Assert.state(!asyncWebRequest.isAsyncComplete(), <del> "Cannot handle DeferredResult [ " + deferredResult + " ] due to a timeout or network error"); <add> chain.applyPostProcess(asyncWebRequest, deferredResult, result); <ide> <ide> logger.debug("Dispatching request to complete processing"); <ide> asyncWebRequest.dispatch(); <ide> public void handleResult(Object result) { <ide> <ide> private void startAsyncProcessing(Object[] processingContext) { <ide> <add> clearConcurrentResult(); <add> this.concurrentResultContext = processingContext; <add> <ide> Assert.state(this.asyncWebRequest != null, "AsyncWebRequest must not be null"); <ide> this.asyncWebRequest.startAsync(); <ide> <del> this.concurrentResult = null; <del> this.concurrentResultContext = processingContext; <del> <ide> if (logger.isDebugEnabled()) { <ide> HttpServletRequest request = asyncWebRequest.getNativeRequest(HttpServletRequest.class); <ide> String requestUri = urlPathHelper.getRequestUri(request); <ide> logger.debug("Concurrent handling starting for " + request.getMethod() + " [" + requestUri + "]"); <ide> } <ide> } <ide> <del> /** <del> * Register an {@link WebAsyncThreadInitializer} for the current request. It may <del> * later be accessed and applied via {@link #initializeAsyncThread(String)} <del> * and will also be used to initialize and reset threads for concurrent handler execution. <del> * @param key a unique the key under which to keep the initializer <del> * @param initializer the initializer instance <del> */ <del> public void registerAsyncThreadInitializer(Object key, WebAsyncThreadInitializer initializer) { <del> Assert.notNull(initializer, "WebAsyncThreadInitializer must not be null"); <del> this.threadInitializers.put(key, initializer); <del> } <del> <del> /** <del> * Invoke the {@linkplain WebAsyncThreadInitializer#initialize() initialize()} <del> * method of the named {@link WebAsyncThreadInitializer}. <del> * @param key the key under which the initializer was registered <del> * @return whether an initializer was found and applied <del> */ <del> public boolean initializeAsyncThread(Object key) { <del> WebAsyncThreadInitializer initializer = this.threadInitializers.get(key); <del> if (initializer != null) { <del> initializer.initialize(); <del> return true; <del> } <del> return false; <del> } <del> <del> <del> /** <del> * Initialize and reset thread-bound variables. <del> */ <del> public interface WebAsyncThreadInitializer { <del> <del> void initialize(); <del> <del> void reset(); <del> <del> } <del> <ide> } <ide><path>spring-web/src/main/java/org/springframework/web/context/request/async/WebAsyncUtils.java <ide> public static WebAsyncManager getAsyncManager(WebRequest webRequest) { <ide> } <ide> <ide> /** <del> * Create an AsyncWebRequest instance. <del> * <p>By default an instance of {@link StandardServletAsyncWebRequest} is created <del> * if running in Servlet 3.0 (or higher) environment or as a fallback option an <del> * instance of {@link NoSupportAsyncWebRequest} is returned. <add> * Create an AsyncWebRequest instance. By default an instance of <add> * {@link StandardServletAsyncWebRequest} is created if running in Servlet <add> * 3.0 (or higher) environment or as a fallback, an instance of <add> * {@link NoSupportAsyncWebRequest} is returned. <add> * <ide> * @param request the current request <ide> * @param response the current response <ide> * @return an AsyncWebRequest instance, never {@code null} <ide><path>spring-web/src/test/java/org/springframework/web/context/request/async/DeferredResultTests.java <ide> public void setExpired() { <ide> DeferredResult<String> result = new DeferredResult<String>(); <ide> assertFalse(result.isSetOrExpired()); <ide> <del> result.setExpired(); <add> result.getAndSetExpired(); <ide> assertTrue(result.isSetOrExpired()); <ide> assertFalse(result.setResult("hello")); <ide> } <ide><path>spring-web/src/test/java/org/springframework/web/context/request/async/WebAsyncManagerTests.java <ide> import org.springframework.core.task.AsyncTaskExecutor; <ide> import org.springframework.core.task.SimpleAsyncTaskExecutor; <ide> import org.springframework.mock.web.MockHttpServletRequest; <del>import org.springframework.web.context.request.async.WebAsyncManager.WebAsyncThreadInitializer; <ide> <ide> <ide> /** <ide> public void setAsyncWebRequestAfterAsyncStarted() { <ide> @Test <ide> public void startCallableProcessing() throws Exception { <ide> <del> WebAsyncThreadInitializer initializer = createStrictMock(WebAsyncThreadInitializer.class); <del> initializer.initialize(); <del> initializer.reset(); <del> replay(initializer); <add> Callable<Object> task = new Callable<Object>() { <add> public Object call() throws Exception { <add> return 1; <add> } <add> }; <add> <add> CallableProcessingInterceptor interceptor = createStrictMock(CallableProcessingInterceptor.class); <add> interceptor.preProcess(this.asyncWebRequest, task); <add> interceptor.postProcess(this.asyncWebRequest, task, new Integer(1)); <add> replay(interceptor); <ide> <ide> this.asyncWebRequest.startAsync(); <ide> expect(this.asyncWebRequest.isAsyncComplete()).andReturn(false); <ide> this.asyncWebRequest.dispatch(); <ide> replay(this.asyncWebRequest); <ide> <del> this.asyncManager.registerAsyncThreadInitializer("testInitializer", initializer); <del> this.asyncManager.startCallableProcessing(new Callable<Object>() { <del> public Object call() throws Exception { <del> return 1; <del> } <del> }); <add> this.asyncManager.registerCallableInterceptor("interceptor", interceptor); <add> this.asyncManager.startCallableProcessing(task); <ide> <del> verify(initializer, this.asyncWebRequest); <add> verify(interceptor, this.asyncWebRequest); <ide> } <ide> <ide> @Test <ide> public Object call() throws Exception { <ide> @Test <ide> public void startDeferredResultProcessing() throws Exception { <ide> <add> DeferredResult<Integer> deferredResult = new DeferredResult<Integer>(1000L, 10); <add> <ide> this.asyncWebRequest.setTimeout(1000L); <del> this.asyncWebRequest.addCompletionHandler((Runnable) notNull()); <ide> this.asyncWebRequest.setTimeoutHandler((Runnable) notNull()); <add> this.asyncWebRequest.addCompletionHandler((Runnable) notNull()); <ide> this.asyncWebRequest.startAsync(); <ide> replay(this.asyncWebRequest); <ide> <del> DeferredResult<Integer> deferredResult = new DeferredResult<Integer>(1000L, 10); <add> DeferredResultProcessingInterceptor interceptor = createStrictMock(DeferredResultProcessingInterceptor.class); <add> interceptor.preProcess(this.asyncWebRequest, deferredResult); <add> replay(interceptor); <add> <add> this.asyncManager.registerDeferredResultInterceptor("interceptor", interceptor); <ide> this.asyncManager.startDeferredResultProcessing(deferredResult); <ide> <del> verify(this.asyncWebRequest); <del> reset(this.asyncWebRequest); <add> verify(this.asyncWebRequest, interceptor); <add> reset(this.asyncWebRequest, interceptor); <ide> <del> expect(this.asyncWebRequest.isAsyncComplete()).andReturn(false); <ide> this.asyncWebRequest.dispatch(); <ide> replay(this.asyncWebRequest); <ide> <add> interceptor.postProcess(asyncWebRequest, deferredResult, 25); <add> replay(interceptor); <add> <ide> deferredResult.setResult(25); <ide> <ide> assertEquals(25, this.asyncManager.getConcurrentResult()); <del> verify(this.asyncWebRequest); <add> verify(this.asyncWebRequest, interceptor); <ide> } <ide> <ide> <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/AsyncHandlerInterceptor.java <ide> import javax.servlet.http.HttpServletRequest; <ide> import javax.servlet.http.HttpServletResponse; <ide> <add>import org.springframework.web.method.HandlerMethod; <add> <ide> /** <ide> * Extends {@code HandlerInterceptor} with a callback method invoked during <ide> * asynchronous request handling. <ide> * <ide> * <p>When a handler starts asynchronous request handling, the DispatcherServlet <ide> * exits without invoking {@code postHandle} and {@code afterCompletion}, as it <del> * normally does, since the results of request handling (e.g. ModelAndView) are <del> * not available in the current thread and handling is not yet complete. <del> * In such scenarios, the <add> * normally does, since the results of request handling (e.g. ModelAndView) <add> * will. be produced concurrently in another thread. In such scenarios, <ide> * {@link #afterConcurrentHandlingStarted(HttpServletRequest, HttpServletResponse)} <del> * method is invoked instead allowing implementations to perform tasks such as <del> * cleaning up thread bound attributes. <add> * is invoked instead allowing implementations to perform tasks such as cleaning <add> * up thread bound attributes. <ide> * <ide> * <p>When asynchronous handling completes, the request is dispatched to the <ide> * container for further processing. At this stage the DispatcherServlet invokes <ide> * @since 3.2 <ide> * <ide> * @see org.springframework.web.context.request.async.WebAsyncManager <add> * @see org.springframework.web.context.request.async.CallableProcessingInterceptor <add> * @see org.springframework.web.context.request.async.DeferredResultProcessingInterceptor <ide> */ <ide> public interface AsyncHandlerInterceptor extends HandlerInterceptor { <ide> <ide> /** <del> * Called instead of {@code postHandle} and {@code afterCompletion}, when the <del> * a handler is being executed concurrently. Implementations may use the provided <del> * request and response but should avoid modifying them in ways that would <del> * conflict with the concurrent execution of the handler. A typical use of <del> * this method would be to clean thread local variables. <add> * Called instead of {@code postHandle} and {@code afterCompletion}, when <add> * the a handler is being executed concurrently. Implementations may use the <add> * provided request and response but should avoid modifying them in ways <add> * that would conflict with the concurrent execution of the handler. A <add> * typical use of this method would be to clean thread local variables. <ide> * <ide> * @param request the current request <ide> * @param response the current response <del> * @param handler handler that started async execution, for type and/or instance examination <add> * @param handler handler (or {@link HandlerMethod}) that started async <add> * execution, for type and/or instance examination <add> * @throws Exception in case of errors <ide> */ <del> void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler); <add> void afterConcurrentHandlingStarted( <add> HttpServletRequest request, HttpServletResponse response, Object handler) <add> throws Exception; <ide> <ide> } <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/FrameworkServlet.java <ide> import java.security.Principal; <ide> import java.util.ArrayList; <ide> import java.util.Collections; <add>import java.util.concurrent.Callable; <ide> <ide> import javax.servlet.ServletContext; <ide> import javax.servlet.ServletException; <ide> import org.springframework.web.bind.annotation.RequestMethod; <ide> import org.springframework.web.context.ConfigurableWebApplicationContext; <ide> import org.springframework.web.context.WebApplicationContext; <add>import org.springframework.web.context.request.NativeWebRequest; <ide> import org.springframework.web.context.request.RequestAttributes; <ide> import org.springframework.web.context.request.RequestContextHolder; <ide> import org.springframework.web.context.request.ServletRequestAttributes; <del>import org.springframework.web.context.request.async.WebAsyncUtils; <add>import org.springframework.web.context.request.async.CallableProcessingInterceptor; <ide> import org.springframework.web.context.request.async.WebAsyncManager; <del>import org.springframework.web.context.request.async.WebAsyncManager.WebAsyncThreadInitializer; <add>import org.springframework.web.context.request.async.WebAsyncUtils; <ide> import org.springframework.web.context.support.ServletRequestHandledEvent; <ide> import org.springframework.web.context.support.WebApplicationContextUtils; <ide> import org.springframework.web.context.support.XmlWebApplicationContext; <ide> protected final void processRequest(HttpServletRequest request, HttpServletRespo <ide> initContextHolders(request, localeContext, requestAttributes); <ide> <ide> WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request); <del> asyncManager.registerAsyncThreadInitializer(this.getClass().getName(), createAsyncThreadInitializer(request)); <add> asyncManager.registerCallableInterceptor(this.getClass().getName(), createRequestBindingInterceptor(request)); <ide> <ide> try { <ide> doService(request, response); <ide> private void resetContextHolders(HttpServletRequest request, <ide> } <ide> } <ide> <del> private WebAsyncThreadInitializer createAsyncThreadInitializer(final HttpServletRequest request) { <add> private CallableProcessingInterceptor createRequestBindingInterceptor(final HttpServletRequest request) { <ide> <del> return new WebAsyncThreadInitializer() { <del> public void initialize() { <add> return new CallableProcessingInterceptor() { <add> <add> public void preProcess(NativeWebRequest webRequest, Callable<?> task) { <ide> initContextHolders(request, buildLocaleContext(request), new ServletRequestAttributes(request)); <ide> } <del> public void reset() { <add> <add> public void postProcess(NativeWebRequest webRequest, Callable<?> task, Object concurrentResult) { <ide> resetContextHolders(request, null, null); <ide> } <ide> }; <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/HandlerInterceptor.java <ide> import javax.servlet.http.HttpServletRequest; <ide> import javax.servlet.http.HttpServletResponse; <ide> <add>import org.springframework.web.method.HandlerMethod; <add> <ide> /** <ide> * Workflow interface that allows for customized handler execution chains. <ide> * Applications can register any number of existing or custom interceptors <ide> * {@code postHandle} and {@code afterCompletion} callbacks. When concurrent <ide> * handler execution completes, the request is dispatched back in order to <ide> * proceed with rendering the model and all methods of this contract are invoked <del> * again. For further options and comments see <del> * {@code org.springframework.web.servlet.HandlerInterceptor} <add> * again. For further options and details see <add> * {@code org.springframework.web.servlet.AsyncHandlerInterceptor} <ide> * <ide> * <p>Typically an interceptor chain is defined per HandlerMapping bean, <ide> * sharing its granularity. To be able to apply a certain interceptor chain <ide> boolean preHandle(HttpServletRequest request, HttpServletResponse response, Obje <ide> * getting applied in inverse order of the execution chain. <ide> * @param request current HTTP request <ide> * @param response current HTTP response <del> * @param handler chosen handler to execute, for type and/or instance examination <add> * @param handler handler (or {@link HandlerMethod}) that started async <add> * execution, for type and/or instance examination <ide> * @param modelAndView the <code>ModelAndView</code> that the handler returned <ide> * (can also be <code>null</code>) <ide> * @throws Exception in case of errors <ide> void postHandle( <ide> * the last to be invoked. <ide> * @param request current HTTP request <ide> * @param response current HTTP response <del> * @param handler chosen handler to execute, for type and/or instance examination <add> * @param handler handler (or {@link HandlerMethod}) that started async <add> * execution, for type and/or instance examination <ide> * @param ex exception thrown on handler execution, if any <ide> * @throws Exception in case of errors <ide> */ <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/handler/HandlerInterceptorAdapter.java <ide> /* <del> * Copyright 2002-2006 the original author or authors. <add> * Copyright 2002-2012 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> import javax.servlet.http.HttpServletRequest; <ide> import javax.servlet.http.HttpServletResponse; <ide> <del>import org.springframework.web.servlet.HandlerInterceptor; <add>import org.springframework.web.servlet.AsyncHandlerInterceptor; <ide> import org.springframework.web.servlet.ModelAndView; <ide> <ide> /** <ide> * @author Juergen Hoeller <ide> * @since 05.12.2003 <ide> */ <del>public abstract class HandlerInterceptorAdapter implements HandlerInterceptor { <add>public abstract class HandlerInterceptorAdapter implements AsyncHandlerInterceptor { <ide> <ide> /** <ide> * This implementation always returns <code>true</code>. <ide> public void afterCompletion( <ide> throws Exception { <ide> } <ide> <add> /** <add> * This implementation is empty. <add> */ <add> public void afterConcurrentHandlingStarted( <add> HttpServletRequest request, HttpServletResponse response, Object handler) <add> throws Exception { <add> } <add> <ide> }
24
Text
Text
fix broken links in readme.md
f18fa4af5003190c8ab01a3908cd2fc0b7ee0834
<ide><path>README.md <ide> Keras is compatible with: <ide> <ide> ## Getting started: 30 seconds to Keras <ide> <del>The core datastructure of Keras is a __model__, a way to organize layers. There are two types of models: [`Sequential`](/models/#sequential) and [`Graph`](/models/#graph). <add>The core datastructure of Keras is a __model__, a way to organize layers. There are two types of models: [`Sequential`](http://keras.io/models/#sequential) and [`Graph`](http://keras.io/models/#graph). <ide> <ide> Here's the `Sequential` model (a linear pile of layers): <ide>
1
Text
Text
fix small grammatical error
38db4e2ca9902a57ae45422cba9cccbfc3e912b6
<ide><path>guides/source/action_controller_overview.md <ide> class DinnerController <ide> end <ide> ``` <ide> <del>Just like the filter, you could also passing `:only` and `:except` to enforce the secure connection only to specific actions: <add>Just like the filter, you could also pass `:only` and `:except` to enforce the secure connection only to specific actions: <ide> <ide> ```ruby <ide> class DinnerController
1
Python
Python
finalize streamlining of conv1d
305b3bed747bb8dd358cf82d11bcb1aee5b6e517
<ide><path>keras/engine/topology.py <ide> def load_weights_from_hdf5_group(self, f): <ide> # the old Conv1D weights format. <ide> w = weight_values[0] <ide> shape = w.shape <del> if shape[:2] != (1, layer.filter_length) or shape[3] != layer.nb_filter: <add> if shape[:2] != (layer.filter_length, 1) or shape[3] != layer.nb_filter: <ide> # legacy shape: (self.nb_filter, input_dim, self.filter_length, 1) <ide> assert shape[0] == layer.nb_filter and shape[2:] == (layer.filter_length, 1) <del> w = np.transpose(w, (3, 2, 1, 0)) <add> w = np.transpose(w, (2, 3, 1, 0)) <ide> weight_values[0] = w <ide> weight_value_tuples += zip(symbolic_weights, weight_values) <ide> K.batch_set_value(weight_value_tuples) <ide><path>keras/layers/convolutional.py <ide> def __init__(self, nb_filter, filter_length, <ide> <ide> def build(self, input_shape): <ide> input_dim = input_shape[2] <del> self.W_shape = (1, self.filter_length, input_dim, self.nb_filter) <add> self.W_shape = (self.filter_length, 1, input_dim, self.nb_filter) <ide> self.W = self.init(self.W_shape, name='{}_W'.format(self.name)) <ide> if self.bias: <ide> self.b = K.zeros((self.nb_filter,), name='{}_b'.format(self.name)) <ide> def get_output_shape_for(self, input_shape): <ide> return (input_shape[0], length, self.nb_filter) <ide> <ide> def call(self, x, mask=None): <del> x = K.expand_dims(x, 1) # add a dummy dimension <add> x = K.expand_dims(x, 2) # add a dummy dimension <ide> output = K.conv2d(x, self.W, strides=self.subsample, <ide> border_mode=self.border_mode, <ide> dim_ordering='tf') <del> output = K.squeeze(output, 1) # remove the dummy dimension <add> output = K.squeeze(output, 2) # remove the dummy dimension <ide> if self.bias: <ide> output += K.reshape(self.b, (1, 1, self.nb_filter)) <ide> output = self.activation(output) <ide> def get_output_shape_for(self, input_shape): <ide> return (input_shape[0], length, self.nb_filter) <ide> <ide> def call(self, x, mask=None): <del> x = K.expand_dims(x, 1) # add a dummy dimension <add> x = K.expand_dims(x, 2) # add a dummy dimension <ide> output = K.conv2d(x, self.W, strides=self.subsample, <ide> border_mode=self.border_mode, <ide> dim_ordering='tf', <ide> filter_dilation=(self.atrous_rate, self.atrous_rate)) <del> output = K.squeeze(output, 1) # remove the dummy dimension <add> output = K.squeeze(output, 2) # remove the dummy dimension <ide> if self.bias: <ide> output += K.reshape(self.b, (1, 1, self.nb_filter)) <ide> output = self.activation(output) <ide><path>tests/keras/layers/test_convolutional.py <ide> def test_convolution_1d(): <ide> nb_filter = 3 <ide> <ide> for border_mode in ['valid', 'same']: <del> for subsample_length in [1]: <add> for subsample_length in [1, 2]: <ide> if border_mode == 'same' and subsample_length != 1: <ide> continue <add> <ide> layer_test(convolutional.Convolution1D, <ide> kwargs={'nb_filter': nb_filter, <ide> 'filter_length': filter_length,
3
Ruby
Ruby
remove dead code
197dbe56011a656784e4c1dae734fabc3a3d512f
<ide><path>Library/Homebrew/download_strategy.rb <ide> require 'utils/json' <del>require 'erb' <ide> <ide> class AbstractDownloadStrategy <ide> attr_reader :name, :resource <ide> def extract_ref(specs) <ide> end <ide> <ide> def cache_filename(tag=cache_tag) <del> if name.empty? || name == '__UNKNOWN__' <del> "#{ERB::Util.url_encode(@url)}--#{tag}" <del> else <del> "#{name}--#{tag}" <del> end <add> "#{name}--#{tag}" <ide> end <ide> <ide> def cache_tag <ide> def mirrors <ide> end <ide> <ide> def tarball_path <del> @tarball_path ||= if name.empty? || name == '__UNKNOWN__' <del> Pathname.new("#{HOMEBREW_CACHE}/#{basename_without_params}") <del> else <del> Pathname.new("#{HOMEBREW_CACHE}/#{name}-#{resource.version}#{ext}") <del> end <add> @tarball_path ||= Pathname.new("#{HOMEBREW_CACHE}/#{name}-#{resource.version}#{ext}") <ide> end <ide> <ide> def temporary_path <ide><path>Library/Homebrew/test/test_download_strategies.rb <ide> def test_explicit_name <ide> downloader = @strategy.new("baz", @resource) <ide> assert_equal "baz--foo", downloader.cache_filename("foo") <ide> end <del> <del> def test_empty_name <del> downloader = @strategy.new("", @resource) <del> assert_equal escaped("foo"), downloader.cache_filename("foo") <del> end <del> <del> def test_unknown_name <del> downloader = @strategy.new("__UNKNOWN__", @resource) <del> assert_equal escaped("foo"), downloader.cache_filename("foo") <del> end <ide> end <ide> <ide> class DownloadStrategyDetectorTests < Homebrew::TestCase
2
Text
Text
check inline style for color
9a5ae756acf28dfcd66ddc9c149ec5a81b4b08f2
<ide><path>curriculum/challenges/english/01-responsive-web-design/basic-css/change-the-color-of-text.english.md <ide> Change your <code>h2</code> element's style so that its text color is red. <ide> tests: <ide> - text: Your <code>h2</code> element should have a <code>style</code> declaration. <ide> testString: assert($("h2").attr('style')); <del> - text: Your <code>h2</code> element should be red. <del> testString: assert($("h2").css("color") === "rgb(255, 0, 0)"); <add> - text: Your <code>h2</code> element should have color set to <code>red</code>. <add> testString: assert($("h2")[0].style.color === "red"); <ide> - text: Your <code>style</code> declaration should end with a <code>;</code> . <ide> testString: assert($("h2").attr('style') && $("h2").attr('style').endsWith(';')); <ide>
1
Text
Text
update mesteery email
44f8b4f506310acee316882ee533fec46588e4d0
<ide><path>README.md <ide> maintaining the Node.js project. <ide> * [marsonya](https://github.com/marsonya) - <ide> **Akhil Marsonya** <<akhil.marsonya27@gmail.com>> (he/him) <ide> * [Mesteery](https://github.com/Mesteery) - <del> **Mestery** <<mestery@pm.me>> <add> **Mestery** <<mestery@protonmail.com>> (he/him) <ide> * [PoojaDurgad](https://github.com/PoojaDurgad) - <ide> **Pooja Durgad** <<Pooja.D.P@ibm.com>> <ide> * [RaisinTen](https://github.com/RaisinTen) -
1
Python
Python
fix the missing types
5e23c6edfadcd46325eb954aa5357a21c9e1a474
<ide><path>benchmarks/benchmarks/bench_function_base.py <ide> class SortGenerator(object): <ide> BUBBLE_SIZE = 10 <ide> <ide> @staticmethod <del> def random(size, dtype): <add> def _random(size, dtype): <ide> arr = np.arange(size, dtype=dtype) <ide> np.random.shuffle(arr) <ide> return arr <ide> <ide> @staticmethod <del> def ordered(size, dtype): <add> def _ordered(size, dtype): <ide> return np.arange(size, dtype=dtype) <ide> <ide> @staticmethod <del> def reversed(size, dtype): <add> def _reversed(size, dtype): <ide> return np.arange(size-1, -1, -1, dtype=dtype) <ide> <ide> @staticmethod <del> def uniform(size, dtype): <add> def _uniform(size, dtype): <ide> return np.ones(size, dtype=dtype) <ide> <ide> @staticmethod <ide> def get_array(cls, array_type, size, dtype): <ide> import re <ide> import functools <ide> token_specification = [ <add> (r'random', <add> lambda match: cls._random(size, dtype)), <add> (r'ordered', <add> lambda match: cls._ordered(size, dtype)), <add> (r'reversed', <add> lambda match: cls._reversed(size, dtype)), <add> (r'uniform', <add> lambda match: cls._uniform(size, dtype)), <ide> (r'sorted\_block\_([0-9]+)', <del> lambda size, dtype, x: cls._type_sorted_block(size, dtype, x)), <add> lambda match: cls._type_sorted_block(size, dtype, int(match.group(1)))), <ide> (r'swapped\_pair\_([0-9]+)\_percent', <del> lambda size, dtype, x: cls._type_swapped_pair(size, dtype, x / 100.0)), <add> lambda match: cls._type_swapped_pair(size, dtype, int(match.group(1)) / 100.0)), <ide> (r'random\_unsorted\_area\_([0-9]+)\_percent', <del> lambda size, dtype, x: cls._type_random_unsorted_area(size, dtype, x / 100.0, cls.AREA_SIZE)), <add> lambda match: cls._type_random_unsorted_area(size, dtype, int(match.group(1)) / 100.0, cls.AREA_SIZE)), <ide> (r'random_bubble\_([0-9]+)\_fold', <del> lambda size, dtype, x: cls._type_random_unsorted_area(size, dtype, x * cls.BUBBLE_SIZE / size, cls.BUBBLE_SIZE)), <add> lambda match: cls._type_random_unsorted_area(size, dtype, int(match.group(1)) * cls.BUBBLE_SIZE / size, cls.BUBBLE_SIZE)), <ide> ] <ide> <ide> for pattern, function in token_specification: <ide> match = re.fullmatch(pattern, array_type) <ide> <ide> if match is not None: <del> return function(size, dtype, int(match.group(1))) <add> return function(match) <ide> <ide> raise ValueError("Incorrect array_type specified.") <ide>
1
Mixed
Java
expose screen metrics and window metrics
228a1fe7d48d57a0fbb2d852135ef94247198aaa
<ide><path>Libraries/Utilities/Dimensions.js <ide> */ <ide> 'use strict'; <ide> <add>var Platform = require('Platform'); <ide> var UIManager = require('UIManager'); <ide> <ide> var invariant = require('invariant'); <ide> if (dimensions && dimensions.windowPhysicalPixels) { <ide> scale: windowPhysicalPixels.scale, <ide> fontScale: windowPhysicalPixels.fontScale, <ide> }; <add> if (Platform.OS === 'android') { <add> // Screen and window dimensions are different on android <add> var screenPhysicalPixels = dimensions.screenPhysicalPixels; <add> dimensions.screen = { <add> width: screenPhysicalPixels.width / screenPhysicalPixels.scale, <add> height: screenPhysicalPixels.height / screenPhysicalPixels.scale, <add> scale: screenPhysicalPixels.scale, <add> fontScale: screenPhysicalPixels.fontScale, <add> }; <ide> <add> // delete so no callers rely on this existing <add> delete dimensions.screenPhysicalPixels; <add> } else { <add> dimensions.screen = dimensions.window; <add> } <ide> // delete so no callers rely on this existing <ide> delete dimensions.windowPhysicalPixels; <ide> } <ide><path>ReactAndroid/src/main/java/com/facebook/react/ReactInstanceManagerImpl.java <ide> private static void initializeSoLoaderIfNecessary(Context applicationContext) { <ide> } <ide> <ide> private static void setDisplayMetrics(Context context) { <del> DisplayMetrics displayMetrics = new DisplayMetrics(); <del> displayMetrics.setTo(context.getResources().getDisplayMetrics()); <add> DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics(); <add> DisplayMetricsHolder.setWindowDisplayMetrics(displayMetrics); <add> <add> DisplayMetrics screenDisplayMetrics = new DisplayMetrics(); <add> screenDisplayMetrics.setTo(displayMetrics); <ide> WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); <ide> Display display = wm.getDefaultDisplay(); <ide> <ide> // Get the real display metrics if we are using API level 17 or higher. <ide> // The real metrics include system decor elements (e.g. soft menu bar). <ide> // <ide> // See: http://developer.android.com/reference/android/view/Display.html#getRealMetrics(android.util.DisplayMetrics) <del> if (Build.VERSION.SDK_INT >= 17){ <del> display.getRealMetrics(displayMetrics); <del> <add> if (Build.VERSION.SDK_INT >= 17) { <add> display.getRealMetrics(screenDisplayMetrics); <ide> } else { <ide> // For 14 <= API level <= 16, we need to invoke getRawHeight and getRawWidth to get the real dimensions. <ide> // Since react-native only supports API level 16+ we don't have to worry about other cases. <ide> private static void setDisplayMetrics(Context context) { <ide> try { <ide> Method mGetRawH = Display.class.getMethod("getRawHeight"); <ide> Method mGetRawW = Display.class.getMethod("getRawWidth"); <del> displayMetrics.widthPixels = (Integer) mGetRawW.invoke(display); <del> displayMetrics.heightPixels = (Integer) mGetRawH.invoke(display); <add> screenDisplayMetrics.widthPixels = (Integer) mGetRawW.invoke(display); <add> screenDisplayMetrics.heightPixels = (Integer) mGetRawH.invoke(display); <ide> } catch (InvocationTargetException | IllegalAccessException | NoSuchMethodException e) { <ide> throw new RuntimeException("Error getting real dimensions for API level < 17", e); <ide> } <ide> } <del> DisplayMetricsHolder.setDisplayMetrics(displayMetrics); <add> DisplayMetricsHolder.setScreenDisplayMetrics(screenDisplayMetrics); <ide> } <ide> <ide> /** <ide><path>ReactAndroid/src/main/java/com/facebook/react/ReactRootView.java <ide> private KeyboardListener getKeyboardListener() { <ide> private class KeyboardListener implements ViewTreeObserver.OnGlobalLayoutListener { <ide> private final Rect mVisibleViewArea; <ide> private final int mMinKeyboardHeightDetected; <del> <add> <ide> private int mKeyboardHeight = 0; <ide> <ide> /* package */ KeyboardListener() { <ide> public void onGlobalLayout() { <ide> <ide> getRootView().getWindowVisibleDisplayFrame(mVisibleViewArea); <ide> final int heightDiff = <del> DisplayMetricsHolder.getDisplayMetrics().heightPixels - mVisibleViewArea.bottom; <add> DisplayMetricsHolder.getWindowDisplayMetrics().heightPixels - mVisibleViewArea.bottom; <ide> if (mKeyboardHeight != heightDiff && heightDiff > mMinKeyboardHeightDetected) { <ide> // keyboard is now showing, or the keyboard height has changed <ide> mKeyboardHeight = heightDiff; <ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/DisplayMetricsHolder.java <ide> /** <ide> * Holds an instance of the current DisplayMetrics so we don't have to thread it through all the <ide> * classes that need it. <add> * Note: windowDisplayMetrics are deprecated in favor of ScreenDisplayMetrics: window metrics <add> * are supposed to return the drawable area but there's no guarantee that they correspond to the <add> * actual size of the {@link ReactRootView}. Moreover, they are not consistent with what iOS <add> * returns. Screen metrics returns the metrics of the entire screen, is consistent with iOS and <add> * should be used instead. <ide> */ <ide> public class DisplayMetricsHolder { <ide> <del> private static DisplayMetrics sCurrentDisplayMetrics; <add> private static DisplayMetrics sWindowDisplayMetrics; <add> private static DisplayMetrics sScreenDisplayMetrics; <ide> <del> public static void setDisplayMetrics(DisplayMetrics displayMetrics) { <del> sCurrentDisplayMetrics = displayMetrics; <add> /** <add> * @deprecated Use {@link #setScreenDisplayMetrics(DisplayMetrics)} instead. See comment above as <add> * to why this is not correct to use. <add> */ <add> public static void setWindowDisplayMetrics(DisplayMetrics displayMetrics) { <add> sWindowDisplayMetrics = displayMetrics; <ide> } <ide> <del> public static DisplayMetrics getDisplayMetrics() { <del> return sCurrentDisplayMetrics; <add> /** <add> * @deprecated Use {@link #getScreenDisplayMetrics()} instead. See comment above as to why this <add> * is not correct to use. <add> */ <add> @Deprecated <add> public static DisplayMetrics getWindowDisplayMetrics() { <add> return sWindowDisplayMetrics; <add> } <add> <add> public static void setScreenDisplayMetrics(DisplayMetrics screenDisplayMetrics) { <add> sScreenDisplayMetrics = screenDisplayMetrics; <add> } <add> <add> public static DisplayMetrics getScreenDisplayMetrics() { <add> return sScreenDisplayMetrics; <ide> } <ide> } <ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/PixelUtil.java <ide> public static float toPixelFromDIP(float value) { <ide> return TypedValue.applyDimension( <ide> TypedValue.COMPLEX_UNIT_DIP, <ide> value, <del> DisplayMetricsHolder.getDisplayMetrics()); <add> DisplayMetricsHolder.getWindowDisplayMetrics()); <ide> } <ide> <ide> /** <ide> public static float toPixelFromSP(float value) { <ide> return TypedValue.applyDimension( <ide> TypedValue.COMPLEX_UNIT_SP, <ide> value, <del> DisplayMetricsHolder.getDisplayMetrics()); <add> DisplayMetricsHolder.getWindowDisplayMetrics()); <ide> } <ide> <ide> /** <ide> public static float toPixelFromSP(double value) { <ide> * Convert from PX to DP <ide> */ <ide> public static float toDIPFromPixel(float value) { <del> return value / DisplayMetricsHolder.getDisplayMetrics().density; <add> return value / DisplayMetricsHolder.getWindowDisplayMetrics().density; <ide> } <ide> <ide> } <ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/UIManagerModuleConstants.java <ide> public static Map<String, Object> getConstants() { <ide> "ScaleAspectFill", <ide> ImageView.ScaleType.CENTER_CROP.ordinal()))); <ide> <del> DisplayMetrics displayMetrics = DisplayMetricsHolder.getDisplayMetrics(); <add> DisplayMetrics displayMetrics = DisplayMetricsHolder.getWindowDisplayMetrics(); <add> DisplayMetrics screenDisplayMetrics = DisplayMetricsHolder.getScreenDisplayMetrics(); <ide> constants.put( <ide> "Dimensions", <ide> MapBuilder.of( <ide> public static Map<String, Object> getConstants() { <ide> "fontScale", <ide> displayMetrics.scaledDensity, <ide> "densityDpi", <del> displayMetrics.densityDpi))); <add> displayMetrics.densityDpi), <add> "screenPhysicalPixels", <add> MapBuilder.of( <add> "width", <add> screenDisplayMetrics.widthPixels, <add> "height", <add> screenDisplayMetrics.heightPixels, <add> "scale", <add> screenDisplayMetrics.density, <add> "fontScale", <add> screenDisplayMetrics.scaledDensity, <add> "densityDpi", <add> screenDisplayMetrics.densityDpi))); <ide> <ide> constants.put( <ide> "StyleConstants", <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/art/ARTVirtualNode.java <ide> <ide> import com.facebook.react.bridge.JSApplicationIllegalArgumentException; <ide> import com.facebook.react.bridge.ReadableArray; <del>import com.facebook.react.uimanager.ReactStylesDiffMap; <ide> import com.facebook.react.uimanager.DisplayMetricsHolder; <ide> import com.facebook.react.uimanager.annotations.ReactProp; <ide> import com.facebook.react.uimanager.ReactShadowNode; <ide> public abstract class ARTVirtualNode extends ReactShadowNode { <ide> protected final float mScale; <ide> <ide> public ARTVirtualNode() { <del> mScale = DisplayMetricsHolder.getDisplayMetrics().density; <add> mScale = DisplayMetricsHolder.getWindowDisplayMetrics().density; <ide> } <ide> <ide> @Override <ide><path>ReactAndroid/src/test/java/com/facebook/react/RootViewTest.java <ide> public Object answer(InvocationOnMock invocation) throws Throwable { <ide> mReactContext = new ReactApplicationContext(RuntimeEnvironment.application); <ide> mReactContext.initializeWithInstance(mCatalystInstanceMock); <ide> DisplayMetrics displayMetrics = mReactContext.getResources().getDisplayMetrics(); <del> DisplayMetricsHolder.setDisplayMetrics(displayMetrics); <add> DisplayMetricsHolder.setWindowDisplayMetrics(displayMetrics); <ide> <ide> UIManagerModule uiManagerModuleMock = mock(UIManagerModule.class); <ide> when(mCatalystInstanceMock.getNativeModule(UIManagerModule.class)) <ide><path>ReactAndroid/src/test/java/com/facebook/react/uimanager/LayoutPropertyApplicatorTest.java <ide> public class LayoutPropertyApplicatorTest { <ide> <ide> @Before <ide> public void setup() { <del> DisplayMetricsHolder.setDisplayMetrics(new DisplayMetrics()); <add> DisplayMetricsHolder.setWindowDisplayMetrics(new DisplayMetrics()); <add> DisplayMetricsHolder.setScreenDisplayMetrics(new DisplayMetrics()); <ide> } <ide> <ide> @After <ide> public void teardown() { <del> DisplayMetricsHolder.setDisplayMetrics(null); <add> DisplayMetricsHolder.setWindowDisplayMetrics(null); <add> DisplayMetricsHolder.setScreenDisplayMetrics(null); <ide> } <ide> <ide> public ReactStylesDiffMap buildStyles(Object... keysAndValues) { <ide> public void testEnumerations() { <ide> public void testPropertiesResetToDefault() { <ide> DisplayMetrics displayMetrics = new DisplayMetrics(); <ide> displayMetrics.density = 1.0f; <del> DisplayMetricsHolder.setDisplayMetrics(displayMetrics); <add> DisplayMetricsHolder.setWindowDisplayMetrics(displayMetrics); <ide> <ide> LayoutShadowNode reactShadowNode = spy(new LayoutShadowNode()); <ide> ReactStylesDiffMap map = buildStyles( <ide><path>ReactAndroid/src/test/java/com/facebook/react/uimanager/ReactPropConstantsTest.java <ide> public void testNativePropsIncludeCorrectTypes() { <ide> List<ViewManager> viewManagers = Arrays.<ViewManager>asList(new ViewManagerUnderTest()); <ide> ReactApplicationContext reactContext = new ReactApplicationContext(RuntimeEnvironment.application); <ide> DisplayMetrics displayMetrics = reactContext.getResources().getDisplayMetrics(); <del> DisplayMetricsHolder.setDisplayMetrics(displayMetrics); <add> DisplayMetricsHolder.setWindowDisplayMetrics(displayMetrics); <add> DisplayMetricsHolder.setScreenDisplayMetrics(displayMetrics); <ide> UIManagerModule uiManagerModule = new UIManagerModule( <ide> reactContext, <ide> viewManagers, <ide><path>ReactAndroid/src/test/java/com/facebook/react/uimanager/UIManagerModuleConstantsTest.java <ide> public void setUp() { <ide> mUIImplementation = mock(UIImplementation.class); <ide> <ide> DisplayMetrics displayMetrics = mReactContext.getResources().getDisplayMetrics(); <del> DisplayMetricsHolder.setDisplayMetrics(displayMetrics); <add> DisplayMetricsHolder.setWindowDisplayMetrics(displayMetrics); <add> DisplayMetricsHolder.setScreenDisplayMetrics(displayMetrics); <ide> } <ide> <ide> @Test <ide><path>ReactAndroid/src/test/java/com/facebook/react/uimanager/UIManagerModuleTest.java <ide> public Object answer(InvocationOnMock invocation) throws Throwable { <ide> mReactContext.initializeWithInstance(mCatalystInstanceMock); <ide> <ide> DisplayMetrics displayMetrics = mReactContext.getResources().getDisplayMetrics(); <del> DisplayMetricsHolder.setDisplayMetrics(displayMetrics); <add> DisplayMetricsHolder.setWindowDisplayMetrics(displayMetrics); <add> DisplayMetricsHolder.setScreenDisplayMetrics(displayMetrics); <ide> <ide> UIManagerModule uiManagerModuleMock = mock(UIManagerModule.class); <ide> when(mCatalystInstanceMock.getNativeModule(UIManagerModule.class)) <ide><path>ReactAndroid/src/test/java/com/facebook/react/views/image/ReactImagePropertyTest.java <ide> public void setup() { <ide> mContext.initializeWithInstance(mCatalystInstanceMock); <ide> mThemeContext = new ThemedReactContext(mContext, mContext); <ide> Fresco.initialize(mContext); <del> DisplayMetricsHolder.setDisplayMetrics(new DisplayMetrics()); <add> DisplayMetricsHolder.setWindowDisplayMetrics(new DisplayMetrics()); <ide> } <ide> <ide> @After <ide> public void teardown() { <del> DisplayMetricsHolder.setDisplayMetrics(null); <add> DisplayMetricsHolder.setWindowDisplayMetrics(null); <ide> } <ide> <ide> public ReactStylesDiffMap buildStyles(Object... keysAndValues) { <ide><path>ReactAndroid/src/test/java/com/facebook/react/views/text/ReactTextTest.java <ide> private void executePendingChoreographerCallbacks() { <ide> public UIManagerModule getUIManagerModule() { <ide> ReactApplicationContext reactContext = ReactTestHelper.createCatalystContextForTest(); <ide> DisplayMetrics displayMetrics = reactContext.getResources().getDisplayMetrics(); <del> DisplayMetricsHolder.setDisplayMetrics(displayMetrics); <add> DisplayMetricsHolder.setWindowDisplayMetrics(displayMetrics); <add> DisplayMetricsHolder.setScreenDisplayMetrics(displayMetrics); <ide> List<ViewManager> viewManagers = Arrays.asList( <ide> new ViewManager[] { <ide> new ReactTextViewManager(), <ide><path>ReactAndroid/src/test/java/com/facebook/react/views/textinput/ReactTextInputPropertyTest.java <ide> public void setup() { <ide> mContext.initializeWithInstance(mCatalystInstanceMock); <ide> mThemedContext = new ThemedReactContext(mContext, mContext); <ide> mManager = new ReactTextInputManager(); <del> DisplayMetricsHolder.setDisplayMetrics(new DisplayMetrics()); <add> DisplayMetricsHolder.setWindowDisplayMetrics(new DisplayMetrics()); <ide> } <ide> <ide> public ReactStylesDiffMap buildStyles(Object... keysAndValues) { <ide><path>ReactAndroid/src/test/java/com/facebook/react/views/textinput/TextInputTest.java <ide> public UIManagerModule getUIManagerModule() { <ide> new ReactTextInputManager(), <ide> }); <ide> DisplayMetrics displayMetrics = reactContext.getResources().getDisplayMetrics(); <del> DisplayMetricsHolder.setDisplayMetrics(displayMetrics); <add> DisplayMetricsHolder.setWindowDisplayMetrics(displayMetrics); <add> DisplayMetricsHolder.setScreenDisplayMetrics(displayMetrics); <ide> UIManagerModule uiManagerModule = new UIManagerModule( <ide> reactContext, <ide> viewManagers,
16
Javascript
Javascript
add missing bootstrap container
6a91f7c5b2ba8ea5203bd7d934e07555486ef746
<ide><path>client/src/templates/Introduction/Intro.js <ide> import React from 'react'; <ide> import PropTypes from 'prop-types'; <ide> import { Link, graphql } from 'gatsby'; <ide> import Helmet from 'react-helmet'; <del>import { ListGroup, ListGroupItem } from '@freecodecamp/react-bootstrap'; <add>import { Grid, ListGroup, ListGroupItem } from '@freecodecamp/react-bootstrap'; <ide> <ide> import LearnLayout from '../../components/layouts/Learn'; <ide> import FullWidthRow from '../../components/helpers/FullWidthRow'; <ide> function IntroductionPage({ data: { markdownRemark, allChallengeNode } }) { <ide> <Helmet> <ide> <title>{block} | freeCodeCamp.org</title> <ide> </Helmet> <del> <div className='intro-layout-container'> <add> <Grid className='intro-layout-container'> <ide> <FullWidthRow> <ide> <div <ide> className='intro-layout' <ide> function IntroductionPage({ data: { markdownRemark, allChallengeNode } }) { <ide> {allChallengeNode ? renderMenuItems(allChallengeNode) : null} <ide> </ListGroup> <ide> </FullWidthRow> <del> </div> <add> </Grid> <ide> </LearnLayout> <ide> ); <ide> }
1
PHP
PHP
add support for custom curl options
5e08596b7209d73c07a4807ec8d4d2fda1f9dde5
<ide><path>src/Http/Client/Adapter/Curl.php <ide> use Cake\Http\Exception\HttpException; <ide> <ide> /** <del> * Implements sending Cake\Http\Client\Request <del> * via ext/curl. <add> * Implements sending Cake\Http\Client\Request via ext/curl. <add> * <add> * In addition to the standard options documented in Cake\Http\Client, <add> * this adapter supports all available curl options. Additional curl options <add> * can be set via the `curl` option key when making requests or configuring <add> * a client. <ide> */ <ide> class Curl implements AdapterInterface <ide> { <ide> public function buildOptions(Request $request, array $options) <ide> 'timeout' => CURLOPT_TIMEOUT, <ide> 'ssl_verify_peer' => CURLOPT_SSL_VERIFYPEER, <ide> 'ssl_verify_host' => CURLOPT_SSL_VERIFYHOST, <del> 'ssl_verify_status' => CURLOPT_SSL_VERIFYSTATUS, <ide> 'ssl_cafile' => CURLOPT_CAINFO, <ide> 'ssl_local_cert' => CURLOPT_SSLCERT, <ide> 'ssl_passphrase' => CURLOPT_SSLCERTPASSWD, <ide> public function buildOptions(Request $request, array $options) <ide> if (isset($options['proxy']['proxy'])) { <ide> $out[CURLOPT_PROXY] = $options['proxy']['proxy']; <ide> } <add> if (isset($options['curl']) && is_array($options['curl'])) { <add> // Can't use array_merge() because keys will be re-ordered. <add> foreach ($options['curl'] as $key => $value) { <add> $out[$key] = $value; <add> } <add> } <ide> <ide> return $out; <ide> } <ide><path>tests/TestCase/Http/Client/Adapter/CurlTest.php <ide> public function testBuildOptionsProxy() <ide> ]; <ide> $this->assertSame($expected, $result); <ide> } <add> <add> /** <add> * Test converting client options into curl ones. <add> * <add> * @return void <add> */ <add> public function testBuildOptionsCurlOptions() <add> { <add> $options = [ <add> 'curl' => [ <add> CURLOPT_USERAGENT => 'Super-secret' <add> ] <add> ]; <add> $request = new Request('http://localhost/things', 'GET'); <add> $result = $this->curl->buildOptions($request, $options); <add> $expected = [ <add> CURLOPT_URL => 'http://localhost/things', <add> CURLOPT_HTTP_VERSION => '1.1', <add> CURLOPT_RETURNTRANSFER => true, <add> CURLOPT_HEADER => true, <add> CURLOPT_HTTPHEADER => [ <add> 'Connection: close', <add> 'User-Agent: CakePHP', <add> ], <add> CURLOPT_HTTPGET => true, <add> CURLOPT_CAINFO => $this->caFile, <add> CURLOPT_USERAGENT => 'Super-secret' <add> ]; <add> $this->assertSame($expected, $result); <add> } <ide> }
2
Python
Python
change default to override
3c63e402f8348e75363ff833d5dfd869e16db5be
<ide><path>numpy/distutils/environment.py <ide> def _get_var(self, name, conf_desc): <ide> if envvar is not None: <ide> envvar_contents = os.environ.get(envvar) <ide> if envvar_contents is not None: <del> if append and os.environ.get('NPY_DISTUTILS_APPEND_FLAGS', '1') == '1': <add> if append and os.environ.get('NPY_DISTUTILS_APPEND_FLAGS', '0') == '1': <ide> if var is None: <ide> var = '' <ide> try:
1
PHP
PHP
apply fixes from styleci
0d16818a7c1114b1d9b12975bcac820a21c35bcc
<ide><path>src/Illuminate/Http/Client/ResponseSequence.php <ide> <ide> namespace Illuminate\Http\Client; <ide> <del>use Closure; <ide> use OutOfBoundsException; <ide> <ide> class ResponseSequence
1
Go
Go
move convertnetworks to composetransform package
6b778c96336fe9c0bcfea477092aab8cdfc0c896
<ide><path>cli/command/stack/common.go <ide> import ( <ide> "github.com/docker/docker/client" <ide> ) <ide> <del>const ( <del> labelNamespace = "com.docker.stack.namespace" <del>) <del> <del>func getStackLabels(namespace string, labels map[string]string) map[string]string { <del> if labels == nil { <del> labels = make(map[string]string) <del> } <del> labels[labelNamespace] = namespace <del> return labels <del>} <del> <ide> func getStackFilter(namespace string) filters.Args { <ide> filter := filters.NewArgs() <ide> filter.Add("label", labelNamespace+"="+namespace) <ide> func getStackNetworks( <ide> ctx, <ide> types.NetworkListOptions{Filters: getStackFilter(namespace)}) <ide> } <del> <del>type namespace struct { <del> name string <del>} <del> <del>func (n namespace) scope(name string) string { <del> return n.name + "_" + name <del>} <ide><path>cli/command/stack/deploy.go <ide> func getConfigFile(filename string) (*composetypes.ConfigFile, error) { <ide> }, nil <ide> } <ide> <del>func convertNetworks( <del> namespace namespace, <del> networks map[string]composetypes.NetworkConfig, <del>) (map[string]types.NetworkCreate, []string) { <del> if networks == nil { <del> networks = make(map[string]composetypes.NetworkConfig) <del> } <del> <del> // TODO: only add default network if it's used <del> networks["default"] = composetypes.NetworkConfig{} <del> <del> externalNetworks := []string{} <del> result := make(map[string]types.NetworkCreate) <del> <del> for internalName, network := range networks { <del> if network.External.External { <del> externalNetworks = append(externalNetworks, network.External.Name) <del> continue <del> } <del> <del> createOpts := types.NetworkCreate{ <del> Labels: getStackLabels(namespace.name, network.Labels), <del> Driver: network.Driver, <del> Options: network.DriverOpts, <del> } <del> <del> if network.Ipam.Driver != "" || len(network.Ipam.Config) > 0 { <del> createOpts.IPAM = &networktypes.IPAM{} <del> } <del> <del> if network.Ipam.Driver != "" { <del> createOpts.IPAM.Driver = network.Ipam.Driver <del> } <del> for _, ipamConfig := range network.Ipam.Config { <del> config := networktypes.IPAMConfig{ <del> Subnet: ipamConfig.Subnet, <del> } <del> createOpts.IPAM.Config = append(createOpts.IPAM.Config, config) <del> } <del> result[internalName] = createOpts <del> } <del> <del> return result, externalNetworks <del>} <del> <ide> func validateExternalNetworks( <ide> ctx context.Context, <ide> dockerCli *command.DockerCli, <ide><path>pkg/composetransform/compose.go <add>package composetransform <add> <add>import ( <add> composetypes "github.com/aanand/compose-file/types" <add> "github.com/docker/docker/api/types" <add> networktypes "github.com/docker/docker/api/types/network" <add>) <add> <add>const ( <add> labelNamespace = "com.docker.stack.namespace" <add>) <add> <add>// Namespace mangles names by prepending the name <add>type Namespace struct { <add> name string <add>} <add> <add>// Scope prepends the namespace to a name <add>func (n Namespace) Scope(name string) string { <add> return n.name + "_" + name <add>} <add> <add>// AddStackLabel returns labels with the namespace label added <add>func AddStackLabel(namespace Namespace, labels map[string]string) map[string]string { <add> if labels == nil { <add> labels = make(map[string]string) <add> } <add> labels[labelNamespace] = namespace.name <add> return labels <add>} <add> <add>type networks map[string]composetypes.NetworkConfig <add> <add>// ConvertNetworks from the compose-file type to the engine API type <add>func ConvertNetworks(namespace Namespace, networks networks) (map[string]types.NetworkCreate, []string) { <add> if networks == nil { <add> networks = make(map[string]composetypes.NetworkConfig) <add> } <add> <add> // TODO: only add default network if it's used <add> networks["default"] = composetypes.NetworkConfig{} <add> <add> externalNetworks := []string{} <add> result := make(map[string]types.NetworkCreate) <add> <add> for internalName, network := range networks { <add> if network.External.External { <add> externalNetworks = append(externalNetworks, network.External.Name) <add> continue <add> } <add> <add> createOpts := types.NetworkCreate{ <add> Labels: AddStackLabel(namespace, network.Labels), <add> Driver: network.Driver, <add> Options: network.DriverOpts, <add> } <add> <add> if network.Ipam.Driver != "" || len(network.Ipam.Config) > 0 { <add> createOpts.IPAM = &networktypes.IPAM{} <add> } <add> <add> if network.Ipam.Driver != "" { <add> createOpts.IPAM.Driver = network.Ipam.Driver <add> } <add> for _, ipamConfig := range network.Ipam.Config { <add> config := networktypes.IPAMConfig{ <add> Subnet: ipamConfig.Subnet, <add> } <add> createOpts.IPAM.Config = append(createOpts.IPAM.Config, config) <add> } <add> result[internalName] = createOpts <add> } <add> <add> return result, externalNetworks <add>} <ide><path>pkg/composetransform/compose_test.go <add>package composetransform <add> <add>import ( <add> "testing" <add> <add> composetypes "github.com/aanand/compose-file/types" <add> "github.com/docker/docker/api/types" <add> "github.com/docker/docker/api/types/network" <add> "github.com/docker/docker/pkg/testutil/assert" <add>) <add> <add>func TestNamespaceScope(t *testing.T) { <add> scoped := Namespace{name: "foo"}.Scope("bar") <add> assert.Equal(t, scoped, "foo_bar") <add>} <add> <add>func TestAddStackLabel(t *testing.T) { <add> labels := map[string]string{ <add> "something": "labeled", <add> } <add> actual := AddStackLabel(Namespace{name: "foo"}, labels) <add> expected := map[string]string{ <add> "something": "labeled", <add> labelNamespace: "foo", <add> } <add> assert.DeepEqual(t, actual, expected) <add>} <add> <add>func TestConvertNetworks(t *testing.T) { <add> namespace := Namespace{name: "foo"} <add> source := networks{ <add> "normal": composetypes.NetworkConfig{ <add> Driver: "overlay", <add> DriverOpts: map[string]string{ <add> "opt": "value", <add> }, <add> Ipam: composetypes.IPAMConfig{ <add> Driver: "driver", <add> Config: []*composetypes.IPAMPool{ <add> { <add> Subnet: "10.0.0.0", <add> }, <add> }, <add> }, <add> Labels: map[string]string{ <add> "something": "labeled", <add> }, <add> }, <add> "outside": composetypes.NetworkConfig{ <add> External: composetypes.External{ <add> External: true, <add> Name: "special", <add> }, <add> }, <add> } <add> expected := map[string]types.NetworkCreate{ <add> "default": { <add> Labels: map[string]string{ <add> labelNamespace: "foo", <add> }, <add> }, <add> "normal": { <add> Driver: "overlay", <add> IPAM: &network.IPAM{ <add> Driver: "driver", <add> Config: []network.IPAMConfig{ <add> { <add> Subnet: "10.0.0.0", <add> }, <add> }, <add> }, <add> Options: map[string]string{ <add> "opt": "value", <add> }, <add> Labels: map[string]string{ <add> labelNamespace: "foo", <add> "something": "labeled", <add> }, <add> }, <add> } <add> <add> networks, externals := ConvertNetworks(namespace, source) <add> assert.DeepEqual(t, networks, expected) <add> assert.DeepEqual(t, externals, []string{"special"}) <add>} <ide><path>pkg/testutil/assert/assert.go <ide> import ( <ide> "reflect" <ide> "runtime" <ide> "strings" <add> <add> "github.com/davecgh/go-spew/spew" <ide> ) <ide> <ide> // TestingT is an interface which defines the methods of testing.T that are <ide> func NilError(t TestingT, err error) { <ide> // they are not "deeply equal". <ide> func DeepEqual(t TestingT, actual, expected interface{}) { <ide> if !reflect.DeepEqual(actual, expected) { <del> fatal(t, "Expected '%v' (%T) got '%v' (%T)", expected, expected, actual, actual) <add> fatal(t, "Expected (%T):\n%v\n\ngot (%T):\n%s\n", <add> expected, spew.Sdump(expected), actual, spew.Sdump(actual)) <ide> } <ide> } <ide>
5
Javascript
Javascript
add error handling
4e5da238449f113930ba97e206c5c7ae675923d0
<ide><path>client/index.js <ide> app$({ history, location: appLocation }) <ide> .doOnNext(title => document.title = title) <ide> .subscribe(() => {}); <ide> <add> appStore$ <add> .pluck('err') <add> .filter(err => !!err) <add> .distinctUntilChanged() <add> .subscribe(err => console.error(err)); <add> <ide> synchroniseHistory( <ide> history, <ide> updateLocation, <ide><path>common/app/routes/Hikes/flux/Actions.js <ide> export default Actions({ <ide> } <ide> }; <ide> }) <del> .catch(err => { <del> console.error(err); <del> }); <add> .catch(err => Observable.just({ <add> transform(state) { return { ...state, err }; } <add> })); <ide> }, <ide> <ide> toggleQuestions() { <ide> export default Actions({ <ide> }) <ide> .delay(300) <ide> .startWith(correctAnswer) <del> .catch(err => { <del> console.error(err); <del> return Observable.just({ <del> set: { <del> error: err <del> } <del> }); <del> }); <add> .catch(err => Observable.just({ <add> transform(state) { return { ...state, err }; } <add> })); <ide> } <ide> }); <ide><path>common/app/routes/Jobs/flux/Actions.js <ide> import { Actions } from 'thundercats'; <ide> import store from 'store'; <add>import { Observable } from 'rx'; <add> <ide> import { nameSpacedTransformer } from '../../../../utils'; <ide> <ide> const assign = Object.assign; <ide> export default Actions({ <ide> }; <ide> } <ide> })) <del> .catch(err => ({ <add> .catch(err => Observable.just({ <ide> transform(state) { <ide> return { ...state, err }; <ide> } <ide> export default Actions({ <ide> return { ...state, currentJob: job }; <ide> }) <ide> })) <del> .catch(err => ({ <add> .catch(err => Observable.just({ <ide> transform(state) { <ide> return { ...state, err }; <ide> } <ide> export default Actions({ <ide> return { ...state, jobs }; <ide> }) <ide> })) <del> .catch(err => ({ <add> .catch(err => Observable.just({ <ide> transform(state) { <del> return { state, err }; <add> return { ...state, err }; <ide> } <ide> })); <ide> }, <ide> export default Actions({ <ide> })) <ide> }; <ide> }) <del> .catch(err => ({ <add> .catch(err => Observable.just({ <ide> transform(state) { <ide> return { ...state, err }; <ide> }
3
Javascript
Javascript
fix typo in resolutionrequest.js
f521e992ccbcf684f88dcf6b3de25edc3df7cbfe
<ide><path>packager/react-packager/src/node-haste/DependencyGraph/ResolutionRequest.js <ide> class ResolutionRequest { <ide> `To resolve try the following:\n` + <ide> ` 1. Clear watchman watches: \`watchman watch-del-all\`.\n` + <ide> ` 2. Delete the \`node_modules\` folder: \`rm -rf node_modules && npm install\`.\n` + <del> ' 3. Reset packager cache: `rm -fr $TMPDIR/react-*` or `npm start -- --reset-cache`.' <add> ' 3. Reset packager cache: `rm -fr $TMPDIR/react-*` or `npm start --reset-cache`.' <ide> ); <ide> }); <ide> });
1
Javascript
Javascript
allow identifiers containing `$`
4e1b36c21686ad0ca4930d1d81f77a7d9cc35851
<ide><path>src/ng/controller.js <ide> var $controllerMinErr = minErr('$controller'); <ide> <ide> <del>var CNTRL_REG = /^(\S+)(\s+as\s+(\w+))?$/; <add>var CNTRL_REG = /^(\S+)(\s+as\s+([\w$]+))?$/; <ide> function identifierForController(controller, ident) { <ide> if (ident && isString(ident)) return ident; <ide> if (isString(controller)) { <ide><path>test/ng/controllerSpec.js <ide> describe('$controller', function() { <ide> "Badly formed controller string 'ctrl as'. " + <ide> "Must match `__name__ as __id__` or `__name__`."); <ide> }); <add> <add> <add> it('should allow identifiers containing `$`', function() { <add> var scope = {}; <add> <add> $controllerProvider.register('FooCtrl', function() { this.mark = 'foo'; }); <add> <add> var foo = $controller('FooCtrl as $foo', {$scope: scope}); <add> expect(scope.$foo).toBe(foo); <add> expect(scope.$foo.mark).toBe('foo'); <add> }); <ide> }); <ide> });
2
Javascript
Javascript
add usage example for `--port`
302cc9e92c2e9a2154bef568d4fa2e7e9f64e05e
<ide><path>lib/internal/inspector/_inspect.js <ide> function startInspect(argv = process.argv.slice(2), <ide> <ide> console.error(`Usage: ${invokedAs} script.js`); <ide> console.error(` ${invokedAs} <host>:<port>`); <add> console.error(` ${invokedAs} --port=<port>`); <ide> console.error(` ${invokedAs} -p <pid>`); <ide> process.exit(1); <ide> }
1
Text
Text
add another sudo
4706a1ad76ed9bc6c0555499d0bd8b8eea3b3604
<ide><path>docs/sources/reference/commandline/cli.md <ide> Import to docker via pipe and *stdin*. <ide> <ide> **Import from a local directory:** <ide> <del> $ sudo tar -c . | docker import - exampleimagedir <add> $ sudo tar -c . | sudo docker import - exampleimagedir <ide> <ide> Note the `sudo` in this example – you must preserve <ide> the ownership of the files (especially root ownership) during the
1
Text
Text
fix the changelog typo[ci skip]
36aaf463725f36f30f2e1c4a69b05299fe30f29f
<ide><path>actionview/CHANGELOG.md <ide> * Fix `current_page?` when the URL contains escaped characters and the <del> original URL is using the hexdecimal lowercased. <add> original URL is using the hexadecimal lowercased. <ide> <ide> *Rafael Mendonça França* <ide> <ide><path>activerecord/CHANGELOG.md <ide> <ide> * When using optimistic locking, `update` was not passing the column to `quote_value` <ide> to allow the connection adapter to properly determine how to quote the value. This was <del> affecting certain databases that use specific colmn types. <add> affecting certain databases that use specific column types. <ide> <ide> Fixes: #6763 <ide>
2
Python
Python
fix numpy.testing.assert_equal in release mode
b98e5984c2c74c61b5ee452ce7553640622b46e7
<ide><path>numpy/testing/nose_tools/utils.py <ide> def assert_equal(actual, desired, err_msg='', verbose=True): <ide> isdesnat = isnat(desired) <ide> isactnat = isnat(actual) <ide> dtypes_match = array(desired).dtype.type == array(actual).dtype.type <del> if isdesnat and isactnat and dtypes_match: <add> if isdesnat and isactnat: <ide> # If both are NaT (and have the same dtype -- datetime or <ide> # timedelta) they are considered equal. <del> return <add> if dtypes_match: <add> return <add> else: <add> raise AssertionError(msg) <add> <ide> except (TypeError, ValueError, NotImplementedError): <ide> pass <ide> <del> <ide> try: <ide> # Explicitly use __eq__ for comparison, gh-2552 <ide> if not (desired == actual):
1
Javascript
Javascript
fix position computation
46a73b9409a6b072c4c77106f760f094ac97a5e6
<ide><path>lib/readline.js <ide> Interface.prototype._getDisplayPos = function(str) { <ide> i++; <ide> } <ide> if (code === 0x0a) { // new line \n <add> // row must be incremented by 1 even if offset = 0 or col = +Infinity <add> row += Math.ceil(offset / col) || 1; <ide> offset = 0; <del> row += 1; <ide> continue; <ide> } <ide> const width = getStringWidth(code); <ide><path>test/parallel/test-readline-interface.js <ide> function isWarned(emitter) { <ide> rli.close(); <ide> } <ide> <del> // multi-line cursor position <add> // Multi-line input cursor position <ide> { <ide> const fi = new FakeInput(); <ide> const rli = new readline.Interface({ <ide> function isWarned(emitter) { <ide> rli.close(); <ide> } <ide> <add> // Multi-line prompt cursor position <add> { <add> const fi = new FakeInput(); <add> const rli = new readline.Interface({ <add> input: fi, <add> output: fi, <add> prompt: '\nfilledline\nwraping text\n> ', <add> terminal: terminal <add> }); <add> fi.columns = 10; <add> fi.emit('data', 't'); <add> const cursorPos = rli._getCursorPos(); <add> assert.strictEqual(cursorPos.rows, 4); <add> assert.strictEqual(cursorPos.cols, 3); <add> rli.close(); <add> } <add> <ide> // Clear the whole screen <ide> { <ide> const fi = new FakeInput();
2
Go
Go
move cobra customizations into cmd/dockerd
6a90113e689e92bc27ba2b26cdf7ce547b81b37e
<add><path>cmd/dockerd/cobra.go <del><path>cli/cobra.go <del>package cli // import "github.com/docker/docker/cli" <add>package main <ide> <ide> import ( <ide> "fmt" <ide><path>cmd/dockerd/docker.go <ide> import ( <ide> "fmt" <ide> "os" <ide> <del> "github.com/docker/docker/cli" <ide> "github.com/docker/docker/daemon/config" <ide> "github.com/docker/docker/dockerversion" <ide> "github.com/docker/docker/pkg/jsonmessage" <ide> func newDaemonCommand() (*cobra.Command, error) { <ide> Short: "A self-sufficient runtime for containers.", <ide> SilenceUsage: true, <ide> SilenceErrors: true, <del> Args: cli.NoArgs, <add> Args: NoArgs, <ide> RunE: func(cmd *cobra.Command, args []string) error { <ide> opts.flags = cmd.Flags() <ide> return runDaemon(opts) <ide> }, <ide> DisableFlagsInUseLine: true, <ide> Version: fmt.Sprintf("%s, build %s", dockerversion.Version, dockerversion.GitCommit), <ide> } <del> cli.SetupRootCommand(cmd) <add> SetupRootCommand(cmd) <ide> <ide> flags := cmd.Flags() <ide> flags.BoolP("version", "v", false, "Print version information and quit") <add><path>cmd/dockerd/error.go <del><path>cli/error.go <del>package cli // import "github.com/docker/docker/cli" <add>package main <ide> <ide> import ( <ide> "fmt" <add><path>cmd/dockerd/required.go <del><path>cli/required.go <del>package cli // import "github.com/docker/docker/cli" <add>package main <ide> <ide> import ( <ide> "strings"
4
Javascript
Javascript
delete its tokens and provider id
bedd03c420d278c6c02fdbc9a6a6aa9a8ab97fdd
<ide><path>controllers/user.js <ide> exports.postSignup = function(req, res) { <ide> }); <ide> }; <ide> <del>/** <del> * POST /account/link <del> * @param req <del> * @param res <del> */ <del>exports.postOauthLink = function(req, res) { <del> console.log('linking oauth2'); <del>}; <ide> <ide> /** <del> * POST /account/unlink <del> * @param req <del> * @param res <add> * GET /account/unlink/:provider <ide> */ <del>exports.postOauthUnlink = function(req, res) { <add>exports.getOauthUnlink = function(req, res) { <ide> console.log('unlinking oauth2'); <del> var provider = req.body.provider; <add> var provider = req.params.provider; <ide> User.findById(req.user.id, function(err, user) { <del> user.tokens = _.reject(x.tokens, function(tok) { return tok.kind === 'google'; }); <ide> delete user[provider]; <add> user.tokens = _.reject(x.tokens, function(tok) { return tok.kind === 'google'; }); <ide> user.save(function(err) { <ide> console.log('Successfully unlinked:', provider); <del> res.redirect('/account'); <add> res.redirect('/account#settings'); <ide> }); <ide> }); <ide> };
1
Mixed
Javascript
emit a warning when servername is an ip address
9b2ffff62cdbfe6ab538e87aafa5828bfbaaa196
<ide><path>doc/api/deprecations.md <ide> Type: Runtime <ide> Please use `Server.prototype.setSecureContext()` instead. <ide> <ide> <add><a id="DEP0123"></a> <add>### DEP0123: setting the TLS ServerName to an IP address <add><!-- YAML <add>changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/REPLACEME <add> description: Runtime deprecation. <add>--> <add> <add>Type: Runtime <add> <add>Setting the TLS ServerName to an IP address is not permitted by <add>[RFC 6066][]. This will be ignored in a future version. <add> <ide> [`--pending-deprecation`]: cli.html#cli_pending_deprecation <ide> [`Buffer.allocUnsafeSlow(size)`]: buffer.html#buffer_class_method_buffer_allocunsafeslow_size <ide> [`Buffer.from(array)`]: buffer.html#buffer_class_method_buffer_from_array <ide> Please use `Server.prototype.setSecureContext()` instead. <ide> [legacy `urlObject`]: url.html#url_legacy_urlobject <ide> [NIST SP 800-38D]: https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf <ide> [WHATWG URL API]: url.html#url_the_whatwg_url_api <add>[RFC 6066]: https://tools.ietf.org/html/rfc6066#section-3 <ide><path>lib/_tls_wrap.js <ide> const kSNICallback = Symbol('snicallback'); <ide> <ide> const noop = () => {}; <ide> <add>let ipServernameWarned = false; <add> <ide> function onhandshakestart(now) { <ide> debug('onhandshakestart'); <ide> <ide> exports.connect = function connect(...args) { <ide> if (options.session) <ide> socket.setSession(options.session); <ide> <del> if (options.servername) <add> if (options.servername) { <add> if (!ipServernameWarned && net.isIP(options.servername)) { <add> process.emitWarning( <add> 'Setting the TLS ServerName to an IP address is not permitted by ' + <add> 'RFC 6066. This will be ignored in a future version.', <add> 'DeprecationWarning', <add> 'DEP0123' <add> ); <add> ipServernameWarned = true; <add> } <ide> socket.setServername(options.servername); <add> } <ide> <ide> if (options.socket) <ide> socket._start(); <ide><path>test/parallel/test-tls-ip-servername-deprecation.js <add>'use strict'; <add> <add>const common = require('../common'); <add>const fixtures = require('../common/fixtures'); <add> <add>if (!common.hasCrypto) <add> common.skip('missing crypto'); <add> <add>const tls = require('tls'); <add> <add>// This test expects `tls.connect()` to emit a warning when <add>// `servername` of options is an IP address. <add>common.expectWarning( <add> 'DeprecationWarning', <add> 'Setting the TLS ServerName to an IP address is not permitted by ' + <add> 'RFC 6066. This will be ignored in a future version.', <add> 'DEP0123' <add>); <add> <add>{ <add> const options = { <add> key: fixtures.readKey('agent1-key.pem'), <add> cert: fixtures.readKey('agent1-cert.pem') <add> }; <add> <add> const server = tls.createServer(options, function(s) { <add> s.end('hello'); <add> }).listen(0, function() { <add> const client = tls.connect({ <add> port: this.address().port, <add> rejectUnauthorized: false, <add> servername: '127.0.0.1', <add> }, function() { <add> client.end(); <add> }); <add> }); <add> <add> server.on('connection', common.mustCall(function(socket) { <add> server.close(); <add> })); <add>}
3
Javascript
Javascript
add blocks and comments to fs-promises tests
3b7f9bc761091785fb74109487c2be01dbc37857
<ide><path>test/parallel/test-fs-promises.js <ide> async function getHandle(dest) { <ide> { <ide> async function doTest() { <ide> tmpdir.refresh(); <add> <ide> const dest = path.resolve(tmpDir, 'baz.js'); <del> await copyFile(fixtures.path('baz.js'), dest); <del> await access(dest, 'r'); <ide> <del> const handle = await open(dest, 'r+'); <del> assert.strictEqual(typeof handle, 'object'); <add> // handle is object <add> { <add> const handle = await getHandle(dest); <add> assert.strictEqual(typeof handle, 'object'); <add> } <ide> <del> let stats = await handle.stat(); <del> verifyStatObject(stats); <del> assert.strictEqual(stats.size, 35); <add> // file stats <add> { <add> const handle = await getHandle(dest); <add> let stats = await handle.stat(); <add> verifyStatObject(stats); <add> assert.strictEqual(stats.size, 35); <ide> <del> await handle.truncate(1); <add> await handle.truncate(1); <ide> <del> stats = await handle.stat(); <del> verifyStatObject(stats); <del> assert.strictEqual(stats.size, 1); <add> stats = await handle.stat(); <add> verifyStatObject(stats); <add> assert.strictEqual(stats.size, 1); <ide> <del> stats = await stat(dest); <del> verifyStatObject(stats); <add> stats = await stat(dest); <add> verifyStatObject(stats); <ide> <del> stats = await handle.stat(); <del> verifyStatObject(stats); <add> stats = await handle.stat(); <add> verifyStatObject(stats); <ide> <del> await handle.datasync(); <del> await handle.sync(); <add> await handle.datasync(); <add> await handle.sync(); <add> } <ide> <ide> // test fs.read promises when length to read is zero bytes <ide> { <ide> async function getHandle(dest) { <ide> await unlink(dest); <ide> } <ide> <del> const buf = Buffer.from('hello fsPromises'); <del> const bufLen = buf.length; <del> await handle.write(buf); <del> const ret = await handle.read(Buffer.alloc(bufLen), 0, bufLen, 0); <del> assert.strictEqual(ret.bytesRead, bufLen); <del> assert.deepStrictEqual(ret.buffer, buf); <del> <del> const buf2 = Buffer.from('hello FileHandle'); <del> const buf2Len = buf2.length; <del> await handle.write(buf2, 0, buf2Len, 0); <del> const ret2 = await handle.read(Buffer.alloc(buf2Len), 0, buf2Len, 0); <del> assert.strictEqual(ret2.bytesRead, buf2Len); <del> assert.deepStrictEqual(ret2.buffer, buf2); <del> await truncate(dest, 5); <del> assert.deepStrictEqual((await readFile(dest)).toString(), 'hello'); <del> <del> await chmod(dest, 0o666); <del> await handle.chmod(0o666); <del> <del> await chmod(dest, (0o10777)); <del> await handle.chmod(0o10777); <del> <del> if (!common.isWindows) { <del> await chown(dest, process.getuid(), process.getgid()); <del> await handle.chown(process.getuid(), process.getgid()); <add> // bytes written to file match buffer <add> { <add> const handle = await getHandle(dest); <add> const buf = Buffer.from('hello fsPromises'); <add> const bufLen = buf.length; <add> await handle.write(buf); <add> const ret = await handle.read(Buffer.alloc(bufLen), 0, bufLen, 0); <add> assert.strictEqual(ret.bytesRead, bufLen); <add> assert.deepStrictEqual(ret.buffer, buf); <ide> } <ide> <del> assert.rejects( <del> async () => { <del> await chown(dest, 1, -1); <del> }, <del> { <del> code: 'ERR_OUT_OF_RANGE', <del> name: 'RangeError [ERR_OUT_OF_RANGE]', <del> message: 'The value of "gid" is out of range. ' + <del> 'It must be >= 0 && < 4294967296. Received -1' <del> }); <add> // truncate file to specified length <add> { <add> const handle = await getHandle(dest); <add> const buf = Buffer.from('hello FileHandle'); <add> const bufLen = buf.length; <add> await handle.write(buf, 0, bufLen, 0); <add> const ret = await handle.read(Buffer.alloc(bufLen), 0, bufLen, 0); <add> assert.strictEqual(ret.bytesRead, bufLen); <add> assert.deepStrictEqual(ret.buffer, buf); <add> await truncate(dest, 5); <add> assert.deepStrictEqual((await readFile(dest)).toString(), 'hello'); <add> } <ide> <del> assert.rejects( <del> async () => { <del> await handle.chown(1, -1); <del> }, <del> { <del> code: 'ERR_OUT_OF_RANGE', <del> name: 'RangeError [ERR_OUT_OF_RANGE]', <del> message: 'The value of "gid" is out of range. ' + <del> 'It must be >= 0 && < 4294967296. Received -1' <del> }); <add> // invalid change of ownership <add> { <add> const handle = await getHandle(dest); <ide> <del> await utimes(dest, new Date(), new Date()); <del> <del> try { <del> await handle.utimes(new Date(), new Date()); <del> } catch (err) { <del> // Some systems do not have futimes. If there is an error, <del> // expect it to be ENOSYS <del> common.expectsError({ <del> code: 'ENOSYS', <del> type: Error <del> })(err); <add> await chmod(dest, 0o666); <add> await handle.chmod(0o666); <add> <add> await chmod(dest, (0o10777)); <add> await handle.chmod(0o10777); <add> <add> if (!common.isWindows) { <add> await chown(dest, process.getuid(), process.getgid()); <add> await handle.chown(process.getuid(), process.getgid()); <add> } <add> <add> assert.rejects( <add> async () => { <add> await chown(dest, 1, -1); <add> }, <add> { <add> code: 'ERR_OUT_OF_RANGE', <add> name: 'RangeError [ERR_OUT_OF_RANGE]', <add> message: 'The value of "gid" is out of range. ' + <add> 'It must be >= 0 && < 4294967296. Received -1' <add> }); <add> <add> assert.rejects( <add> async () => { <add> await handle.chown(1, -1); <add> }, <add> { <add> code: 'ERR_OUT_OF_RANGE', <add> name: 'RangeError [ERR_OUT_OF_RANGE]', <add> message: 'The value of "gid" is out of range. ' + <add> 'It must be >= 0 && < 4294967296. Received -1' <add> }); <ide> } <ide> <del> await handle.close(); <add> // set modification times <add> { <add> const handle = await getHandle(dest); <ide> <del> const newPath = path.resolve(tmpDir, 'baz2.js'); <del> await rename(dest, newPath); <del> stats = await stat(newPath); <del> verifyStatObject(stats); <add> await utimes(dest, new Date(), new Date()); <ide> <del> if (common.canCreateSymLink()) { <del> const newLink = path.resolve(tmpDir, 'baz3.js'); <del> await symlink(newPath, newLink); <del> if (!common.isWindows) { <del> await lchown(newLink, process.getuid(), process.getgid()); <add> try { <add> await handle.utimes(new Date(), new Date()); <add> } catch (err) { <add> // Some systems do not have futimes. If there is an error, <add> // expect it to be ENOSYS <add> common.expectsError({ <add> code: 'ENOSYS', <add> type: Error <add> })(err); <ide> } <del> stats = await lstat(newLink); <del> verifyStatObject(stats); <ide> <del> assert.strictEqual(newPath.toLowerCase(), <del> (await realpath(newLink)).toLowerCase()); <del> assert.strictEqual(newPath.toLowerCase(), <del> (await readlink(newLink)).toLowerCase()); <add> await handle.close(); <add> } <add> <add> // create symlink <add> { <add> const newPath = path.resolve(tmpDir, 'baz2.js'); <add> await rename(dest, newPath); <add> let stats = await stat(newPath); <add> verifyStatObject(stats); <ide> <del> const newMode = 0o666; <del> if (common.isOSX) { <del> // lchmod is only available on macOS <del> await lchmod(newLink, newMode); <add> if (common.canCreateSymLink()) { <add> const newLink = path.resolve(tmpDir, 'baz3.js'); <add> await symlink(newPath, newLink); <add> if (!common.isWindows) { <add> await lchown(newLink, process.getuid(), process.getgid()); <add> } <ide> stats = await lstat(newLink); <del> assert.strictEqual(stats.mode & 0o777, newMode); <del> } else { <del> await Promise.all([ <del> assert.rejects( <del> lchmod(newLink, newMode), <del> common.expectsError({ <del> code: 'ERR_METHOD_NOT_IMPLEMENTED', <del> type: Error, <del> message: 'The lchmod() method is not implemented' <del> }) <del> ) <del> ]); <add> verifyStatObject(stats); <add> <add> assert.strictEqual(newPath.toLowerCase(), <add> (await realpath(newLink)).toLowerCase()); <add> assert.strictEqual(newPath.toLowerCase(), <add> (await readlink(newLink)).toLowerCase()); <add> <add> const newMode = 0o666; <add> if (common.isOSX) { <add> // lchmod is only available on macOS <add> await lchmod(newLink, newMode); <add> stats = await lstat(newLink); <add> assert.strictEqual(stats.mode & 0o777, newMode); <add> } else { <add> await Promise.all([ <add> assert.rejects( <add> lchmod(newLink, newMode), <add> common.expectsError({ <add> code: 'ERR_METHOD_NOT_IMPLEMENTED', <add> type: Error, <add> message: 'The lchmod() method is not implemented' <add> }) <add> ) <add> ]); <add> } <add> <add> await unlink(newLink); <ide> } <del> <del> await unlink(newLink); <ide> } <ide> <del> const newLink2 = path.resolve(tmpDir, 'baz4.js'); <del> await link(newPath, newLink2); <add> // create hard link <add> { <add> const newPath = path.resolve(tmpDir, 'baz2.js'); <add> const newLink = path.resolve(tmpDir, 'baz4.js'); <add> await link(newPath, newLink); <ide> <del> await unlink(newLink2); <add> await unlink(newLink); <add> } <ide> <ide> // testing readdir lists both files and directories <ide> { <ide> async function getHandle(dest) { <ide> await mkdir(newDir); <ide> await writeFile(newFile, 'DAWGS WIN!', 'utf8'); <ide> <del> stats = await stat(newDir); <add> const stats = await stat(newDir); <ide> assert(stats.isDirectory()); <ide> const list = await readdir(tmpDir); <ide> assert.notStrictEqual(list.indexOf('dir'), -1); <ide> async function getHandle(dest) { <ide> { <ide> const dir = path.join(tmpDir, nextdir()); <ide> await mkdir(dir, 777); <del> stats = await stat(dir); <add> const stats = await stat(dir); <ide> assert(stats.isDirectory()); <ide> } <ide> <ide> // mkdir when options is string. <ide> { <ide> const dir = path.join(tmpDir, nextdir()); <ide> await mkdir(dir, '777'); <del> stats = await stat(dir); <add> const stats = await stat(dir); <ide> assert(stats.isDirectory()); <ide> } <ide> <ide> // mkdirp when folder does not yet exist. <ide> { <ide> const dir = path.join(tmpDir, nextdir(), nextdir()); <ide> await mkdir(dir, { recursive: true }); <del> stats = await stat(dir); <add> const stats = await stat(dir); <ide> assert(stats.isDirectory()); <ide> } <ide> <ide> async function getHandle(dest) { <ide> { <ide> const dir = path.resolve(tmpDir, `${nextdir()}/./${nextdir()}`); <ide> await mkdir(dir, { recursive: true }); <del> stats = await stat(dir); <add> const stats = await stat(dir); <ide> assert(stats.isDirectory()); <ide> } <ide> <ide> // mkdirp ../ <ide> { <ide> const dir = path.resolve(tmpDir, `${nextdir()}/../${nextdir()}`); <ide> await mkdir(dir, { recursive: true }); <del> stats = await stat(dir); <add> const stats = await stat(dir); <ide> assert(stats.isDirectory()); <ide> } <ide> <ide> async function getHandle(dest) { <ide> }); <ide> } <ide> <del> await mkdtemp(path.resolve(tmpDir, 'FOO')); <del> assert.rejects( <del> // mkdtemp() expects to get a string prefix. <del> async () => mkdtemp(1), <del> { <del> code: 'ERR_INVALID_ARG_TYPE', <del> name: 'TypeError [ERR_INVALID_ARG_TYPE]' <del> } <del> ); <add> // mkdtemp with invalid numeric prefix <add> { <add> await mkdtemp(path.resolve(tmpDir, 'FOO')); <add> assert.rejects( <add> // mkdtemp() expects to get a string prefix. <add> async () => mkdtemp(1), <add> { <add> code: 'ERR_INVALID_ARG_TYPE', <add> name: 'TypeError [ERR_INVALID_ARG_TYPE]' <add> } <add> ); <add> } <ide> <ide> } <ide>
1
Javascript
Javascript
forbid throwing of literals
6d2e29bbe7dd760235ae8f95e790d2de3cd99654
<ide><path>.eslintrc.js <ide> module.exports = { <ide> rules: { <ide> 'semi': 'error', <ide> 'no-unused-vars': 'error', <add> 'no-throw-literal': 'error', <ide> 'no-useless-escape': 'off', // TODO: bring this back <ide> 'prettier/prettier': 'error', <ide> }, <ide> module.exports = { <ide> <ide> 'semi': 'error', <ide> 'no-unused-vars': 'error', <add> 'no-throw-literal': 'error', <ide> 'comma-dangle': 'off', <ide> }, <ide> }, <ide> module.exports = { <ide> rules: Object.assign({}, require('eslint-plugin-node').configs.recommended.rules, { <ide> // add your custom rules and overrides for node files here <ide> 'no-process-exit': 'off', <add> 'no-throw-literal': 'error' <ide> }), <ide> }, <ide> { <ide><path>blueprints/component-test/index.js <ide> module.exports = useTestFrameworkDetector({ <ide> }, <ide> __testType__(options) { <ide> if (options.locals.testType === 'unit') { <del> throw "The --unit flag isn't supported within a module unification app"; <add> throw new Error("The --unit flag isn't supported within a module unification app"); <ide> } <ide> <ide> return ''; <ide> }, <ide> __path__(options) { <ide> if (options.pod) { <del> throw "Pods aren't supported within a module unification app"; <add> throw new Error("Pods aren't supported within a module unification app"); <ide> } <ide> return path.join('ui', 'components', options.dasherizedModuleName); <ide> }, <ide><path>blueprints/controller-test/index.js <ide> module.exports = useTestFrameworkDetector({ <ide> }, <ide> __root__(options) { <ide> if (options.pod) { <del> throw "Pods aren't supported within a module unification app"; <add> throw new Error("Pods aren't supported within a module unification app"); <ide> } <ide> return 'src'; <ide> }, <ide><path>blueprints/controller/index.js <ide> module.exports = { <ide> return { <ide> __root__(options) { <ide> if (options.pod) { <del> throw "Pods aren't supported within a module unification app"; <add> throw new Error("Pods aren't supported within a module unification app"); <ide> } <ide> if (options.inDummy) { <ide> return path.join('tests', 'dummy', 'src'); <ide><path>blueprints/initializer-test/index.js <ide> module.exports = useTestFrameworkDetector({ <ide> return { <ide> __root__(options) { <ide> if (options.pod) { <del> throw 'Pods arenʼt supported within a module unification app'; <add> throw new Error('Pods arenʼt supported within a module unification app'); <ide> } else if (options.inDummy) { <ide> return path.join('tests', 'dummy', 'src', 'init'); <ide> } <ide><path>blueprints/initializer/index.js <ide> module.exports = { <ide> return { <ide> __root__(options) { <ide> if (options.pod) { <del> throw 'Pods arenʼt supported within a module unification app'; <add> throw new Error('Pods arenʼt supported within a module unification app'); <ide> } else if (options.inDummy) { <ide> return path.join('tests', 'dummy', 'src/init'); <ide> } <ide><path>blueprints/mixin-test/index.js <ide> module.exports = useTestFrameworkDetector({ <ide> return { <ide> __root__(options) { <ide> if (options.pod) { <del> throw "Pods aren't supported within a module unification app"; <add> throw new Error("Pods aren't supported within a module unification app"); <ide> } <ide> <ide> return 'src'; <ide><path>blueprints/mixin/index.js <ide> module.exports = { <ide> return { <ide> __root__(options) { <ide> if (options.pod) { <del> throw "Pods aren't supported within a module unification app"; <add> throw new Error("Pods aren't supported within a module unification app"); <ide> } <ide> <ide> return 'src'; <ide><path>blueprints/route/index.js <ide> module.exports = { <ide> return { <ide> __root__(options) { <ide> if (options.pod) { <del> throw "Pods aren't supported within a module unification app"; <add> throw new Error("Pods aren't supported within a module unification app"); <ide> } <ide> if (options.inDummy) { <ide> return path.join('tests', 'dummy', 'src'); <ide><path>blueprints/service-test/index.js <ide> module.exports = useTestFrameworkDetector({ <ide> return { <ide> __root__(options) { <ide> if (options.pod) { <del> throw "Pods aren't supported within a module unification app"; <add> throw new Error("Pods aren't supported within a module unification app"); <ide> } <ide> <ide> return 'src'; <ide><path>blueprints/service/index.js <ide> module.exports = { <ide> return { <ide> __root__(options) { <ide> if (options.pod) { <del> throw "Pods aren't supported within a module unification app"; <add> throw new Error("Pods aren't supported within a module unification app"); <ide> } <ide> <ide> return 'src'; <ide><path>blueprints/template/index.js <ide> module.exports = { <ide> return { <ide> __root__(options) { <ide> if (options.pod) { <del> throw "Pods aren't supported within a module unification app"; <add> throw new Error("Pods aren't supported within a module unification app"); <ide> } else if (options.inDummy) { <ide> return 'tests/dummy/src/ui/routes'; <ide> } else { <ide><path>blueprints/util-test/index.js <ide> module.exports = useTestFrameworkDetector({ <ide> return { <ide> __root__(options) { <ide> if (options.pod) { <del> throw "Pods aren't supported within a module unification app"; <add> throw new Error("Pods aren't supported within a module unification app"); <ide> } <ide> <ide> return 'src'; <ide><path>blueprints/util/index.js <ide> module.exports = { <ide> return { <ide> __root__(options) { <ide> if (options.pod) { <del> throw "Pods aren't supported within a module unification app"; <add> throw new Error("Pods aren't supported within a module unification app"); <ide> } <ide> <ide> return 'src'; <ide><path>node-tests/blueprints/component-test-test.js <ide> describe('Blueprint: component-test', function() { <ide> it('component-test x-foo --unit', function() { <ide> return emberGenerate(['component-test', 'x-foo', '--unit']) <ide> .then(() => { <del> throw 'the command should raise an exception'; <add> throw new Error('the command should raise an exception'); <ide> }) <ide> .catch(error => { <ide> expect(error).to.equal("The --unit flag isn't supported within a module unification app"); <ide><path>node-tests/helpers/expect-error.js <ide> const expect = chai.expect; <ide> module.exports = function expectError(promise, expectedErrorText) { <ide> return promise <ide> .then(() => { <del> throw 'the command should raise an exception'; <add> throw new Error('the command should raise an exception'); <ide> }) <ide> .catch(error => { <ide> expect(error).to.equal(expectedErrorText); <ide><path>packages/ember/tests/routing/decoupled_basic_test.js <ide> moduleFor( <ide> 'route:special', <ide> Route.extend({ <ide> setup() { <del> throw 'Setup error'; <add> throw new Error('Setup error'); <ide> }, <ide> actions: { <ide> error(reason) { <ide> moduleFor( <ide> 'route:special', <ide> Route.extend({ <ide> setup() { <del> throw 'Setup error'; <add> throw new Error('Setup error'); <ide> }, <ide> }) <ide> );
17
Go
Go
remove unused fallbackerror
5e9829b75d4d57a49d1cbe17ccc6bf73b4a18fed
<ide><path>registry/auth.go <ide> func (scs staticCredentialStore) RefreshToken(*url.URL, string) string { <ide> func (scs staticCredentialStore) SetRefreshToken(*url.URL, string, string) { <ide> } <ide> <del>type fallbackError struct { <del> err error <del>} <del> <del>func (err fallbackError) Error() string { <del> return err.err.Error() <del>} <del> <ide> // loginV2 tries to login to the v2 registry server. The given registry <ide> // endpoint will be pinged to get authorization challenges. These challenges <ide> // will be used to authenticate against the registry to validate credentials. <ide><path>registry/service.go <ide> func (s *defaultService) Search(ctx context.Context, term string, limit int, aut <ide> modifiers := Headers(userAgent, nil) <ide> v2Client, err := v2AuthHTTPClient(endpoint.URL, endpoint.client.Transport, modifiers, creds, scopes) <ide> if err != nil { <del> if fErr, ok := err.(fallbackError); ok { <del> logrus.WithError(fErr.err).Error("cannot use identity token for search, v2 auth not supported") <del> } else { <del> return nil, err <del> } <del> } else { <del> // Copy non transport http client features <del> v2Client.Timeout = endpoint.client.Timeout <del> v2Client.CheckRedirect = endpoint.client.CheckRedirect <del> v2Client.Jar = endpoint.client.Jar <del> <del> logrus.Debugf("using v2 client for search to %s", endpoint.URL) <del> client = v2Client <add> return nil, err <ide> } <del> } <del> <del> if client == nil { <add> // Copy non transport http client features <add> v2Client.Timeout = endpoint.client.Timeout <add> v2Client.CheckRedirect = endpoint.client.CheckRedirect <add> v2Client.Jar = endpoint.client.Jar <add> <add> logrus.Debugf("using v2 client for search to %s", endpoint.URL) <add> client = v2Client <add> } else { <ide> client = endpoint.client <ide> if err := authorizeClient(client, authConfig, endpoint); err != nil { <ide> return nil, err
2
Javascript
Javascript
add test case for updating runtime modules
7eff4c300f8665164f177510e1e36fcfd155168e
<ide><path>test/hotCases/runtime/replace-runtime-module/a.js <add>export default "a"; <ide><path>test/hotCases/runtime/replace-runtime-module/b.js <add>export default "b"; <ide><path>test/hotCases/runtime/replace-runtime-module/index.js <add>import m from "./module"; <add> <add>it("should dispose a chunk which is removed from bundle", (done) => { <add> m.then(a => { <add> expect(a.default).toEqual("a"); <add> NEXT(require("../../update")(done, true, () => { <add> m.then(b => { <add> expect(b.default).toEqual("b"); <add> done(); <add> }).catch(done); <add> })); <add> }).catch(done); <add>}); <add> <add>if(module.hot) { <add> module.hot.accept("./module"); <add>} <ide><path>test/hotCases/runtime/replace-runtime-module/module.js <add>export default import(/* webpackChunkName: "a" */ "./a"); <add>--- <add>export default import(/* webpackChunkName: "b" */ "./b");
4
Javascript
Javascript
optimize the bundle size of next.js core
304225d9ea754323b19a17dc3d1e541e79f134e8
<ide><path>lib/app.js <ide> import React, { Component } from 'react' <ide> import PropTypes from 'prop-types' <del>import { AppContainer } from 'react-hot-loader' <ide> import shallowEquals from './shallow-equals' <ide> import { warn } from './utils' <ide> <del>const ErrorDebug = process.env.NODE_ENV === 'production' <del> ? null : require('./error-debug').default <del> <ide> export default class App extends Component { <ide> static childContextTypes = { <ide> headManager: PropTypes.object <ide> class Container extends Component { <ide> render () { <ide> const { Component, props, url } = this.props <ide> <del> // includes AppContainer which bypasses shouldComponentUpdate method <del> // https://github.com/gaearon/react-hot-loader/issues/442 <del> return <AppContainer errorReporter={ErrorDebug}> <del> <Component {...props} url={url} /> <del> </AppContainer> <add> if (process.env.NODE_ENV === 'production') { <add> return (<Component {...props} url={url} />) <add> } else { <add> const ErrorDebug = require('./error-debug').default <add> const { AppContainer } = require('react-hot-loader') <add> <add> // includes AppContainer which bypasses shouldComponentUpdate method <add> // https://github.com/gaearon/react-hot-loader/issues/442 <add> return ( <add> <AppContainer errorReporter={ErrorDebug}> <add> <Component {...props} url={url} /> <add> </AppContainer> <add> ) <add> } <ide> } <ide> } <ide> <ide><path>server/build/webpack.js <ide> export default async function createCompiler (dir, { dev = false, quiet = false, <ide> // used in all of the pages. Otherwise, move modules used in at-least <ide> // 1/2 of the total pages into commons. <ide> if (totalPages <= 2) { <del> return count === totalPages <add> return count >= totalPages <ide> } <ide> return count >= totalPages * 0.5 <ide> } <ide> export default async function createCompiler (dir, { dev = false, quiet = false, <ide> plugins.push(new FriendlyErrorsWebpackPlugin()) <ide> } <ide> } else { <add> plugins.push(new webpack.IgnorePlugin(/react-hot-loader/)) <ide> plugins.push( <ide> new CombineAssetsPlugin({ <ide> input: ['manifest.js', 'commons.js', 'main.js'], <ide> export default async function createCompiler (dir, { dev = false, quiet = false, <ide> performance: { hints: false } <ide> } <ide> <del> if (!dev) { <del> // We do this to use the minified version of React in production. <del> // This will significant file size redution when turned off uglifyjs. <del> webpackConfig.resolve.alias = { <del> 'react': require.resolve('react/dist/react.min.js'), <del> 'react-dom': require.resolve('react-dom/dist/react-dom.min.js') <del> } <del> } <del> <ide> if (config.webpack) { <ide> console.log(`> Using "webpack" config function defined in ${config.configOrigin}.`) <ide> webpackConfig = await config.webpack(webpackConfig, { dev })
2
PHP
PHP
fresh in databasemigrations
72de89c32d3b2ccca51008807d10e698e897d5db
<ide><path>src/Illuminate/Foundation/Testing/DatabaseMigrations.php <ide> trait DatabaseMigrations <ide> */ <ide> public function runDatabaseMigrations() <ide> { <del> $this->artisan('migrate'); <add> $this->artisan('migrate:fresh'); <ide> <ide> $this->app[Kernel::class]->setArtisan(null); <ide>
1
Javascript
Javascript
fix spacing issue
616777b520a52707816118f624c5b153ab51cd3c
<ide><path>lib/optimize/RemoveParentModulesPlugin.js <ide> function allHaveModule(someChunks, module, checkedChunks) { <ide> return chunks; <ide> } <ide> <del> <ide> class RemoveParentModulesPlugin { <ide> apply(compiler) { <ide> compiler.plugin("compilation", (compilation) => {
1
Ruby
Ruby
highlight new revision message
b878d9c1ca3a25429f4ad6501a4f4636978d4cc7
<ide><path>Library/Homebrew/cmd/update-report.rb <ide> def output_update_report <ide> Settings.write "latesttag", new_tag if new_tag != old_tag <ide> <ide> if new_tag == old_tag <del> puts "Updated Homebrew from #{shorten_revision(initial_revision)} to #{shorten_revision(current_revision)}." <add> ohai "Updated Homebrew from #{shorten_revision(initial_revision)} to #{shorten_revision(current_revision)}." <ide> elsif old_tag.blank? <ide> ohai "Updated Homebrew from #{shorten_revision(initial_revision)} " \ <ide> "to #{new_tag} (#{shorten_revision(current_revision)})."
1
Python
Python
add ipc_mode for dockeroperator
a504a8267dd5530923bbe2c8ec4d1b409f909d83
<ide><path>airflow/providers/docker/operators/docker.py <ide> class DockerOperator(BaseOperator): <ide> :param log_opts_max_file: The maximum number of log files that can be present. <ide> If rolling the logs creates excess files, the oldest file is removed. <ide> Only effective when max-size is also set. A positive integer. Defaults to 1. <add> :param ipc_mode: Set the IPC mode for the container. <ide> """ <ide> <ide> template_fields: Sequence[str] = ("image", "command", "environment", "env_file", "container_name") <ide> def __init__( <ide> device_requests: list[DeviceRequest] | None = None, <ide> log_opts_max_size: str | None = None, <ide> log_opts_max_file: str | None = None, <add> ipc_mode: str | None = None, <ide> **kwargs, <ide> ) -> None: <ide> super().__init__(**kwargs) <ide> def __init__( <ide> self.device_requests = device_requests <ide> self.log_opts_max_size = log_opts_max_size <ide> self.log_opts_max_file = log_opts_max_file <add> self.ipc_mode = ipc_mode <ide> <ide> def get_hook(self) -> DockerHook: <ide> """ <ide> def _run_image_with_mounts(self, target_mounts, add_tmp_variable: bool) -> list[ <ide> privileged=self.privileged, <ide> device_requests=self.device_requests, <ide> log_config=LogConfig(config=docker_log_config), <add> ipc_mode=self.ipc_mode, <ide> ), <ide> image=self.image, <ide> user=self.user, <ide><path>tests/providers/docker/operators/test_docker.py <ide> def test_execute(self): <ide> privileged=False, <ide> device_requests=[DeviceRequest(count=-1, capabilities=[["gpu"]])], <ide> log_config=LogConfig(config={"max-size": "10m", "max-file": "5"}), <add> ipc_mode=None, <ide> ) <ide> self.tempdir_mock.assert_called_once_with(dir="/host/airflow", prefix="airflowtmp") <ide> self.client_mock.images.assert_called_once_with(name="ubuntu:latest") <ide> def test_execute_no_temp_dir(self): <ide> privileged=False, <ide> device_requests=None, <ide> log_config=LogConfig(config={}), <add> ipc_mode=None, <ide> ) <ide> self.tempdir_mock.assert_not_called() <ide> self.client_mock.images.assert_called_once_with(name="ubuntu:latest") <ide> def test_execute_fallback_temp_dir(self): <ide> privileged=False, <ide> device_requests=None, <ide> log_config=LogConfig(config={}), <add> ipc_mode=None, <ide> ), <ide> call( <ide> mounts=[ <ide> def test_execute_fallback_temp_dir(self): <ide> privileged=False, <ide> device_requests=None, <ide> log_config=LogConfig(config={}), <add> ipc_mode=None, <ide> ), <ide> ] <ide> )
2
Javascript
Javascript
fix effectcomposer reference to renderer
8101efea28e683237efd01daedd6b4c9a2bcc611
<ide><path>examples/js/postprocessing/EffectComposer.js <ide> THREE.EffectComposer.prototype = { <ide> <ide> renderTarget = this.renderTarget1.clone(); <ide> <del> var pixelRatio = renderer.getPixelRatio(); <add> var pixelRatio = this.renderer.getPixelRatio(); <ide> <ide> renderTarget.width = Math.floor( this.renderer.context.canvas.width / pixelRatio ); <ide> renderTarget.height = Math.floor( this.renderer.context.canvas.height / pixelRatio );
1
Python
Python
add call to super call in apache providers
7e6372a681a2a543f4710b083219aeb53b074388
<ide><path>airflow/providers/apache/cassandra/hooks/cassandra.py <ide> class CassandraHook(BaseHook, LoggingMixin): <ide> For details of the Cluster config, see cassandra.cluster. <ide> """ <ide> def __init__(self, cassandra_conn_id: str = 'cassandra_default'): <add> super().__init__() <ide> conn = self.get_connection(cassandra_conn_id) <ide> <ide> conn_config = {} <ide><path>airflow/providers/apache/druid/hooks/druid.py <ide> def __init__( <ide> timeout=1, <ide> max_ingestion_time=None): <ide> <add> super().__init__() <ide> self.druid_ingest_conn_id = druid_ingest_conn_id <ide> self.timeout = timeout <ide> self.max_ingestion_time = max_ingestion_time <ide><path>airflow/providers/apache/hdfs/hooks/hdfs.py <ide> class HDFSHook(BaseHook): <ide> """ <ide> def __init__(self, hdfs_conn_id='hdfs_default', proxy_user=None, <ide> autoconfig=False): <add> super().__init__() <ide> if not snakebite_loaded: <ide> raise ImportError( <ide> 'This HDFSHook implementation requires snakebite, but ' <ide><path>airflow/providers/apache/hdfs/hooks/webhdfs.py <ide> class WebHDFSHook(BaseHook): <ide> """ <ide> <ide> def __init__(self, webhdfs_conn_id='webhdfs_default', proxy_user=None): <add> super().__init__() <ide> self.webhdfs_conn_id = webhdfs_conn_id <ide> self.proxy_user = proxy_user <ide> <ide><path>airflow/providers/apache/hive/hooks/hive.py <ide> def __init__( <ide> mapred_queue=None, <ide> mapred_queue_priority=None, <ide> mapred_job_name=None): <add> super().__init__() <ide> conn = self.get_connection(hive_cli_conn_id) <ide> self.hive_cli_params = conn.extra_dejson.get('hive_cli_params', '') <ide> self.use_beeline = conn.extra_dejson.get('use_beeline', False) <ide> class HiveMetastoreHook(BaseHook): <ide> MAX_PART_COUNT = 32767 <ide> <ide> def __init__(self, metastore_conn_id='metastore_default'): <add> super().__init__() <ide> self.conn_id = metastore_conn_id <ide> self.metastore = self.get_metastore_client() <ide> <ide> class HiveServer2Hook(BaseHook): <ide> ``extra`` of your connection in the UI <ide> """ <ide> def __init__(self, hiveserver2_conn_id='hiveserver2_default'): <add> super().__init__() <ide> self.hiveserver2_conn_id = hiveserver2_conn_id <ide> <ide> def get_conn(self, schema=None): <ide><path>airflow/providers/apache/pig/hooks/pig.py <ide> class PigCliHook(BaseHook): <ide> def __init__( <ide> self, <ide> pig_cli_conn_id="pig_cli_default"): <add> super().__init__() <ide> conn = self.get_connection(pig_cli_conn_id) <ide> self.pig_properties = conn.extra_dejson.get('pig_properties', '') <ide> self.conn = conn <ide><path>airflow/providers/apache/pinot/hooks/pinot.py <ide> def __init__(self, <ide> conn_id="pinot_admin_default", <ide> cmd_path="pinot-admin.sh", <ide> pinot_admin_system_exit=False): <add> super().__init__() <ide> conn = self.get_connection(conn_id) <ide> self.host = conn.host <ide> self.port = str(conn.port) <ide><path>airflow/providers/apache/spark/hooks/spark_sql.py <ide> def __init__(self, <ide> verbose=True, <ide> yarn_queue='default' <ide> ): <add> super().__init__() <ide> self._sql = sql <ide> self._conf = conf <ide> self._conn = self.get_connection(conn_id) <ide><path>airflow/providers/apache/spark/hooks/spark_submit.py <ide> def __init__(self, <ide> env_vars=None, <ide> verbose=False, <ide> spark_binary=None): <add> super().__init__() <ide> self._conf = conf or {} <ide> self._conn_id = conn_id <ide> self._files = files <ide><path>airflow/providers/apache/sqoop/hooks/sqoop.py <ide> def __init__(self, conn_id='sqoop_default', verbose=False, <ide> num_mappers=None, hcatalog_database=None, <ide> hcatalog_table=None, properties=None): <ide> # No mutable types in the default parameters <add> super().__init__() <ide> self.conn = self.get_connection(conn_id) <ide> connection_parameters = self.conn.extra_dejson <ide> self.job_tracker = connection_parameters.get('job_tracker', None)
10
Ruby
Ruby
fix handling of tap migrations to new cask names
45357ef0dd2bfc0bf8d957fd890e030fd9f7cf6a
<ide><path>Library/Homebrew/migrator.rb <ide> def fix_tabs <ide> end <ide> <ide> def from_same_taps? <add> new_tap = if old_tap <add> if migrate_tap = old_tap.tap_migrations[formula.oldname] <add> new_tap_user, new_tap_repo, = migrate_tap.split("/") <add> "#{new_tap_user}/#{new_tap_repo}" <add> end <add> end <add> <ide> if formula.tap == old_tap <ide> true <ide> # Homebrew didn't use to update tabs while performing tap-migrations, <ide> # so there can be INSTALL_RECEIPT's containing wrong information about tap, <ide> # so we check if there is an entry about oldname migrated to tap and if <ide> # newname's tap is the same as tap to which oldname migrated, then we <ide> # can perform migrations and the taps for oldname and newname are the same. <del> elsif formula.tap && old_tap && formula.tap == old_tap.tap_migrations[formula.oldname] <add> elsif formula.tap && old_tap && formula.tap == new_tap <ide> fix_tabs <ide> true <ide> else <ide><path>Library/Homebrew/missing_formula.rb <ide> def tap_migration_reason(name) <ide> message = nil <ide> <ide> Tap.each do |old_tap| <del> new_tap_name = old_tap.tap_migrations[name] <del> next unless new_tap_name <add> new_tap = old_tap.tap_migrations[name] <add> next unless new_tap <add> <add> new_tap_user, new_tap_repo, = new_tap.split("/") <add> new_tap_name = "#{new_tap_user}/#{new_tap_repo}" <add> <ide> message = <<-EOS.undent <del> It was migrated from #{old_tap} to #{new_tap_name}. <add> It was migrated from #{old_tap} to #{new_tap}. <ide> You can access it again by running: <ide> brew tap #{new_tap_name} <ide> EOS
2
Ruby
Ruby
remove unused --tap args for brew bottle
79018e4e242dbad09adce4c60e2f4f061df0a402
<ide><path>Library/Homebrew/cmd/test-bot.rb <ide> def formula(formula_name) <ide> bottle_step.output.gsub(/.*(\.\/\S+#{bottle_native_regex}).*/m, '\1') <ide> bottle_rb_filename = bottle_filename.gsub(/\.(\d+\.)?tar\.gz$/, ".rb") <ide> bottle_merge_args = ["--merge", "--write", "--no-commit", bottle_rb_filename] <del> bottle_merge_args << "--tap=#{@tap}" if @tap <ide> bottle_merge_args << "--keep-old" if ARGV.include? "--keep-old" <ide> test "brew", "bottle", *bottle_merge_args <ide> test "brew", "uninstall", "--force", canonical_formula_name <ide> def test_ci_upload(tap) <ide> end <ide> <ide> bottle_args = ["--merge", "--write", *Dir["*.bottle.rb"]] <del> bottle_args << "--tap=#{tap}" if tap <ide> bottle_args << "--keep-old" if ARGV.include? "--keep-old" <ide> system "brew", "bottle", *bottle_args <ide>
1
Ruby
Ruby
allow alpha.gnu.org urls
603bcb6cc80c3a725868766a8ee3a9a7b284d56d
<ide><path>Library/Homebrew/cmd/audit.rb <ide> def audit_urls <ide> urls = [(f.stable.url rescue nil), (f.devel.url rescue nil), (f.head.url rescue nil)].compact <ide> <ide> # Check GNU urls; doesn't apply to mirrors <del> if urls.any? { |p| p =~ %r[^(https?|ftp)://(.+)/gnu/] } <add> if urls.any? { |p| p =~ %r[^(https?|ftp)://(?!alpha).+/gnu/] } <ide> problem "\"ftpmirror.gnu.org\" is preferred for GNU software." <ide> end <ide>
1
Java
Java
use conscrypt as security provider if available
75af15ede44135110e40de75a649d5b15430c590
<ide><path>ReactAndroid/src/main/java/com/facebook/react/modules/network/OkHttpClientProvider.java <ide> import com.facebook.common.logging.FLog; <ide> <ide> import java.io.File; <add>import java.security.Provider; <add>import java.security.Security; <ide> import java.util.ArrayList; <ide> import java.util.List; <ide> import java.util.concurrent.TimeUnit; <ide> public static OkHttpClient.Builder createClientBuilder() { <ide> .writeTimeout(0, TimeUnit.MILLISECONDS) <ide> .cookieJar(new ReactCookieJarContainer()); <ide> <del> return enableTls12OnPreLollipop(client); <add> try { <add> Class ConscryptProvider = Class.forName("org.conscrypt.OpenSSLProvider"); <add> Security.insertProviderAt( <add> (Provider) ConscryptProvider.newInstance(), 1); <add> return client; <add> } catch (Exception e) { <add> return enableTls12OnPreLollipop(client); <add> } <ide> } <ide> <ide> public static OkHttpClient.Builder createClientBuilder(Context context) {
1
Go
Go
start the stack trap earlier for daemon
94d44066f3abb7c7eea7fcb81e8419ae7331d1fd
<ide><path>daemon/daemon.go <ide> func NewDaemon(config *config.Config, registryService registry.Service, containe <ide> } <ide> }() <ide> <add> // set up SIGUSR1 handler on Unix-like systems, or a Win32 global event <add> // on Windows to dump Go routine stacks <add> stackDumpDir := config.Root <add> if execRoot := config.GetExecRoot(); execRoot != "" { <add> stackDumpDir = execRoot <add> } <add> d.setupDumpStackTrap(stackDumpDir) <add> <ide> if err := d.setupSeccompProfile(); err != nil { <ide> return nil, err <ide> } <ide> func NewDaemon(config *config.Config, registryService registry.Service, containe <ide> engineCpus.Set(float64(info.NCPU)) <ide> engineMemory.Set(float64(info.MemTotal)) <ide> <del> // set up SIGUSR1 handler on Unix-like systems, or a Win32 global event <del> // on Windows to dump Go routine stacks <del> stackDumpDir := config.Root <del> if execRoot := config.GetExecRoot(); execRoot != "" { <del> stackDumpDir = execRoot <del> } <del> d.setupDumpStackTrap(stackDumpDir) <del> <ide> return d, nil <ide> } <ide>
1
Python
Python
fix invalid log order in elasticsearchtaskhandler
944dc32c2b4a758564259133a08f2ea8d28dcb6c
<ide><path>airflow/providers/elasticsearch/log/es_task_handler.py <ide> def es_read(self, log_id: str, offset: str, metadata: dict) -> list: <ide> <ide> return logs <ide> <add> def emit(self, record): <add> if self.handler: <add> record.offset = int(time() * (10 ** 9)) <add> self.handler.emit(record) <add> <ide> def set_context(self, ti: TaskInstance) -> None: <ide> """ <ide> Provide task_instance context to airflow task handler. <ide> def set_context(self, ti: TaskInstance) -> None: <ide> if self.json_format: <ide> self.formatter = JSONFormatter( <ide> fmt=self.formatter._fmt, <del> json_fields=self.json_fields, <add> json_fields=self.json_fields + [self.offset_field], <ide> extras={ <ide> 'dag_id': str(ti.dag_id), <ide> 'task_id': str(ti.task_id), <ide> 'execution_date': self._clean_execution_date(ti.execution_date), <ide> 'try_number': str(ti.try_number), <ide> 'log_id': self._render_log_id(ti, ti.try_number), <del> 'offset': int(time() * (10 ** 9)), <ide> }, <ide> ) <ide> <ide><path>tests/providers/elasticsearch/log/test_es_task_handler.py <ide> # KIND, either express or implied. See the License for the <ide> # specific language governing permissions and limitations <ide> # under the License. <del> <add>import io <add>import json <ide> import logging <ide> import os <ide> import shutil <ide> from urllib.parse import quote <ide> <ide> import elasticsearch <add>import freezegun <ide> import pendulum <ide> from parameterized import parameterized <ide> <ide> def test_get_external_log_url(self, json_format, es_frontend, expected_url): <ide> def test_supports_external_link(self, frontend, expected): <ide> self.es_task_handler.frontend = frontend <ide> assert self.es_task_handler.supports_external_link == expected <add> <add> @mock.patch('sys.__stdout__', new_callable=io.StringIO) <add> def test_dynamic_offset(self, stdout_mock): <add> # arrange <add> handler = ElasticsearchTaskHandler( <add> base_log_folder=self.local_log_location, <add> filename_template=self.filename_template, <add> log_id_template=self.log_id_template, <add> end_of_log_mark=self.end_of_log_mark, <add> write_stdout=True, <add> json_format=True, <add> json_fields=self.json_fields, <add> host_field=self.host_field, <add> offset_field=self.offset_field, <add> ) <add> handler.formatter = logging.Formatter() <add> <add> logger = logging.getLogger(__name__) <add> logger.handlers = [handler] <add> logger.propagate = False <add> <add> self.ti._log = logger <add> handler.set_context(self.ti) <add> <add> t1 = pendulum.naive(year=2017, month=1, day=1, hour=1, minute=1, second=15) <add> t2, t3 = t1 + pendulum.duration(seconds=5), t1 + pendulum.duration(seconds=10) <add> <add> # act <add> with freezegun.freeze_time(t1): <add> self.ti.log.info("Test") <add> with freezegun.freeze_time(t2): <add> self.ti.log.info("Test2") <add> with freezegun.freeze_time(t3): <add> self.ti.log.info("Test3") <add> <add> # assert <add> first_log, second_log, third_log = map(json.loads, stdout_mock.getvalue().strip().split("\n")) <add> assert first_log['offset'] < second_log['offset'] < third_log['offset'] <add> assert first_log['asctime'] == t1.format("YYYY-MM-DD HH:mm:ss,SSS") <add> assert second_log['asctime'] == t2.format("YYYY-MM-DD HH:mm:ss,SSS") <add> assert third_log['asctime'] == t3.format("YYYY-MM-DD HH:mm:ss,SSS")
2
Python
Python
fix a typo. python function name
52c7c53e3b13ed7524253a16ab02c9ec4d621a79
<ide><path>samples/outreach/blogs/blog_estimators_dataset.py <ide> URL_TEST = "http://download.tensorflow.org/data/iris_test.csv" <ide> <ide> <del>def downloadDataset(url, file): <add>def download_dataset(url, file): <ide> if not os.path.exists(PATH_DATASET): <ide> os.makedirs(PATH_DATASET) <ide> if not os.path.exists(file): <ide> data = request.urlopen(url).read() <ide> with open(file, "wb") as f: <ide> f.write(data) <ide> f.close() <del>downloadDataset(URL_TRAIN, FILE_TRAIN) <del>downloadDataset(URL_TEST, FILE_TEST) <add>download_dataset(URL_TRAIN, FILE_TRAIN) <add>download_dataset(URL_TEST, FILE_TEST) <ide> <ide> tf.logging.set_verbosity(tf.logging.INFO) <ide> <ide> def decode_csv(line): <ide> n_classes=3, <ide> model_dir=PATH) # Path to where checkpoints etc are stored <ide> <del># Train our model, use the previously function my_input_fn <add># Train our model, use the previously defined function my_input_fn <ide> # Input to training is a file with training example <ide> # Stop training after 8 iterations of train data (epochs) <ide> classifier.train( <ide> def decode_csv(line): <ide> [6.9, 3.1, 5.4, 2.1], # -> 2, Iris Virginica <ide> [5.1, 3.3, 1.7, 0.5]] # -> 0, Iris Sentosa <ide> <add> <ide> def new_input_fn(): <ide> def decode(x): <ide> x = tf.split(x, 4) # Need to split into our 4 features
1
Javascript
Javascript
improve grammar and clarity
2c00476baeecc55fbfb4df167858c9ac3b0ed314
<ide><path>src/ng/rootScope.js <ide> * @description <ide> * <ide> * Every application has a single root {@link ng.$rootScope.Scope scope}. <del> * All other scopes are child scopes of the root scope. Scopes provide mechanism for watching the model and provide <del> * event processing life cycle. See {@link guide/scope developer guide on scopes}. <add> * All other scopes are descendant scopes of the root scope. Scopes provide separation <add> * between the model and the view, via a mechanism for watching the model for changes. <add> * They also provide an event emission/broadcast and subscription facility. See the <add> * {@link guide/scope developer guide on scopes}. <ide> */ <ide> function $RootScopeProvider(){ <ide> var TTL = 10;
1
Javascript
Javascript
use object destructuring for contextifyscript
ed2a110f916b35a516dda6093b308e21027a92eb
<ide><path>lib/internal/bootstrap/loaders.js <ide> }; <ide> } <ide> <del> const ContextifyScript = process.binding('contextify').ContextifyScript; <add> const { ContextifyScript } = process.binding('contextify'); <ide> <ide> // Set up NativeModule <ide> function NativeModule(id) {
1
Javascript
Javascript
update logarithmic algorithm
f51d7753bd3dea42e51487831c3b0f6f732460c1
<ide><path>src/scales/scale.logarithmic.js <ide> <ide> // label settings <ide> ticks: { <del> callback: function(value) { <add> callback: function(value, index, arr) { <ide> var remain = value / (Math.pow(10, Math.floor(Chart.helpers.log10(value)))); <ide> <del> if (remain === 1 || remain === 2 || remain === 5) { <add> if (remain === 1 || remain === 2 || remain === 5 || index === 0 || index === arr.length - 1) { <ide> return value.toExponential(); <ide> } else { <ide> return ''; <ide> }, this); <ide> } <ide> <del> if (this.options.ticks.max) { <del> this.max = this.options.ticks.max; <del> } <del> <del> if (this.options.ticks.min) { <del> this.min = this.options.ticks.min; <del> } <add> this.min = this.options.ticks.min !== undefined ? this.options.ticks.min : this.min; <add> this.max = this.options.ticks.max !== undefined ? this.options.ticks.max : this.max; <ide> <ide> if (this.min === this.max) { <ide> if (this.min !== 0 && this.min !== null) { <ide> // We also limit the maximum number of ticks to 11 which gives a nice 10 squares on <ide> // the graph <ide> <del> var minExponent = Math.floor(helpers.log10(this.min)); <del> var maxExponent = Math.ceil(helpers.log10(this.max)); <add> var tickVal = this.options.ticks.min !== undefined ? this.options.ticks.min : Math.pow(10, Math.floor(helpers.log10(this.min))); <ide> <del> for (var exponent = minExponent; exponent < maxExponent; ++exponent) { <del> for (var i = 1; i < 10; ++i) { <del> this.tickValues.push(i * Math.pow(10, exponent)); <add> while (tickVal < this.max) { <add> this.tickValues.push(tickVal); <add> <add> var exp = Math.floor(helpers.log10(tickVal)); <add> var significand = Math.floor(tickVal / Math.pow(10, exp)) + 1; <add> <add> if (significand === 10) { <add> significand = 1; <add> ++exp; <ide> } <add> <add> tickVal = significand * Math.pow(10, exp); <ide> } <ide> <del> this.tickValues.push(1.0 * Math.pow(10, maxExponent)); <add> /*var minExponent = Math.floor(helpers.log10(this.min)); <add> var maxExponent = Math.ceil(helpers.log10(this.max)); <ide> <del> if (this.options.ticks.min) { <del> this.tickValues[0] = this.min; <del> } <add> for (var exponent = minExponent; exponent < maxExponent; ++exponent) { <add> for (var i = 1; i < 10; ++i) { <add> if (this.options.ticks.min) { <ide> <del> if (this.options.ticks.max) { <del> this.tickValues[this.tickValues.length - 1] = this.max; <del> } <add> } else { <add> this.tickValues.push(i * Math.pow(10, exponent)); <add> } <add> } <add> }*/ <add> <add> var lastTick = this.options.ticks.max !== undefined ? this.options.ticks.max : tickVal; <add> this.tickValues.push(lastTick); <ide> <ide> if (this.options.position == "left" || this.options.position == "right") { <ide> // We are in a vertical orientation. The top value is the highest. So reverse the array <ide> this.max = helpers.max(this.tickValues); <ide> this.min = helpers.min(this.tickValues); <ide> <del> if (this.options.ticks.min) { <del> this.min = this.options.ticks.min; <del> } <del> <del> if (this.options.ticks.max) { <del> this.max = this.options.ticks.max; <del> } <del> <ide> if (this.options.ticks.reverse) { <ide> this.tickValues.reverse(); <ide>
1
Javascript
Javascript
update github in use error message copy
6233f6641163ffe504a012be360fd988d16dfea3
<ide><path>server/boot/a-extendUserIdent.js <ide> export default function({ models }) { <ide> return Observable.throw( <ide> new Error( <ide> dedent` <del> It looks like you already have an account associated with that sign in method. <del> Here's what you can do: 1) Sign out of this account. 2) Use that sign in <del> method to sign into your other account. 3) Delete that account. <del> 4) Then sign back into this account and you'll be able to link it here. <del> If you need help, send us an email at team@freecodecamp.com. <add> Your GitHub is already associated with another account. You may have accidentally created a duplicate account. <add> No worries, though. We can fix this real quick. Please email us with your GitHub username: team@freecodecamp.com. <ide> `.split('/n').join(' ') <ide> ) <ide> );
1
Javascript
Javascript
remove obsolete file
e1473e2d4a155ae1695b2ca8baa6f7a6f23864b8
<ide><path>src/externs.js <del>// JavaScript built-ins. <del>var console, <del> JSON; <del> <del>// d3 <del>var d3;
1
PHP
PHP
make note of method removal
4f179b01bdc702d86181de23004b70015afe944f
<ide><path>lib/Cake/Controller/Controller.php <ide> public function flash($message, $url, $pause = 1, $layout = 'flash') { <ide> * @param boolean $exclusive If true, and $op is an array, fields not included in $op will not be <ide> * included in the returned conditions <ide> * @return array An array of model conditions <del> * @deprecated <add> * @deprecated Will be removed in 3.0 <ide> */ <ide> public function postConditions($data = array(), $op = null, $bool = 'AND', $exclusive = false) { <ide> if (!is_array($data) || empty($data)) {
1
Text
Text
remove extra line breaks in the faq
e269c36e1ff5cdd2fd0f7cd0c9b911940cc69cea
<ide><path>docs/FAQ.md <ide> We typically do not assign issues to anyone other than long-time contributors. I <ide> <ide> ### I am interested in being a moderator at freeCodeCamp. Where should I start? <ide> <del>Our community moderators are our heroes. Their voluntary contributions make <del>freeCodeCamp a safe and welcoming community. <add>Our community moderators are our heroes. Their voluntary contributions make freeCodeCamp a safe and welcoming community. <ide> <del>First and foremost, we would need you to be an active participant in the <del>community, and live by our [code of conduct](https://www.freecodecamp.org/news/code-of-conduct/) <del>(not just enforce it). <add>First and foremost, we would need you to be an active participant in the community, and live by our [code of conduct](https://www.freecodecamp.org/news/code-of-conduct/) (not just enforce it). <ide> <ide> Here are some recommended paths for some of our platforms: <ide> <del>- To be a **Discord/Chat** moderator, have an active presence in our chat and <del> have positive engagements with others, while also learning and practicing how <del> to deal with potential conflicts that may arise. <del>- To be a **Forum** moderator, similar to a chat moderator, have an active <del> presence and engage with other forum posters, supporting others in their <del> learning journey, and even giving feedback when asked. Take a look at <del> [The Subforum Leader Handbook](https://forum.freecodecamp.org/t/the-subforum-leader-handbook/326326) <del> for more information. <del>- To be a **GitHub** moderator, help process GitHub issues that are brought up <del> to see if they are valid and (ideally) try to propose solutions for these <del> issues to be picked up by others (or yourself). <del> <del>Altogether, be respectful to others. We are humans from all around the world. With <del>that in mind, please also consider using encouraging or supportive language and <del>be mindful of cross-cultural communication. <del> <del>If you practice the above **consistently for a while** and our fellow moderator <del>members recommend you, a staff member will reach out and onboard you to the <del>moderators' team. Open source work is voluntary work and our time is limited. <del>We acknowledge that this is probably true in your case as well. So we emphasize <del>being **consistent** rather than engaging in the community 24/7. <del> <del>Take a look at our [Moderator Handbook](moderator-handbook.md) <del>for a more exhaustive list of other responsibilities and expectations we have <del>of our moderators. <add>- To be a **Discord/Chat** moderator, have an active presence in our chat and have positive engagements with others, while also learning and practicing how to deal with potential conflicts that may arise. <add>- To be a **Forum** moderator, similar to a chat moderator, have an active presence and engage with other forum posters, supporting others in their learning journey, and even giving feedback when asked. Take a look at [The Subforum Leader Handbook](https://forum.freecodecamp.org/t/the-subforum-leader-handbook/326326) for more information. <add>- To be a **GitHub** moderator, help process GitHub issues that are brought up to see if they are valid and (ideally) try to propose solutions for these issues to be picked up by others (or yourself). <add> <add>Altogether, be respectful to others. We are humans from all around the world. With that in mind, please also consider using encouraging or supportive language and be mindful of cross-cultural communication. <add> <add>If you practice the above **consistently for a while** and our fellow moderator members recommend you, a staff member will reach out and onboard you to the moderators' team. Open source work is voluntary work and our time is limited. We acknowledge that this is probably true in your case as well. So we emphasize being **consistent** rather than engaging in the community 24/7. <add> <add>Take a look at our [Moderator Handbook](moderator-handbook.md) for a more exhaustive list of other responsibilities and expectations we have of our moderators. <ide> <ide> ### I am stuck on something that is not included in this documentation. <ide>
1
Go
Go
return exec.controller instead of nil
3a9be929272d089d57745350b8888760a18b2526
<ide><path>api/types/swarm/task.go <ide> type TaskSpec struct { <ide> // parameters have been changed. <ide> ForceUpdate uint64 <ide> <del> Runtime RuntimeType `json:",omitempty"` <del> RuntimeData []byte `json:",omitempty"` <add> Runtime RuntimeType `json:",omitempty"` <add> // TODO (ehazlett): this should be removed and instead <add> // use struct tags (proto) for the runtimes <add> RuntimeData []byte `json:",omitempty"` <ide> } <ide> <ide> // Resources represents resources (CPU/Memory). <ide><path>daemon/cluster/convert/service.go <ide> func serviceSpecFromGRPC(spec *swarmapi.ServiceSpec) (*types.ServiceSpec, error) <ide> <ide> taskTemplate := taskSpecFromGRPC(spec.Task) <ide> <del> switch t := spec.Task.Runtime.(type) { <add> switch t := spec.Task.GetRuntime().(type) { <ide> case *swarmapi.TaskSpec_Container: <ide> containerConfig := t.Container <ide> taskTemplate.ContainerSpec = containerSpecFromGRPC(containerConfig) <ide><path>daemon/cluster/executor/container/executor.go <ide> func (e *executor) Controller(t *api.Task) (exec.Controller, error) { <ide> case *api.TaskSpec_Container: <ide> c, err := newController(e.backend, t, secrets.Restrict(e.secrets, t)) <ide> if err != nil { <del> return nil, err <add> return ctlr, err <ide> } <ide> ctlr = c <ide> default: <del> return nil, fmt.Errorf("unsupported runtime: %q", r) <add> return ctlr, fmt.Errorf("unsupported runtime: %q", r) <ide> } <ide> <ide> return ctlr, nil
3
Ruby
Ruby
activate env extensions for postinstall
19c118d0026482d9e0a59833570cc9985092cb4d
<ide><path>Library/Homebrew/formula.rb <ide> def run_post_install <ide> <ide> with_env(new_env) do <ide> ENV.clear_sensitive_environment! <add> ENV.activate_extensions! <ide> <ide> etc_var_dirs = [bottle_prefix/"etc", bottle_prefix/"var"] <ide> T.unsafe(Find).find(*etc_var_dirs.select(&:directory?)) do |path|
1
Ruby
Ruby
add collection_check_boxes helper
7af0ec75d0d933d75f9a63a63bbbde554f206721
<ide><path>actionpack/lib/action_view/helpers/form_options_helper.rb <ide> def collection_radio_buttons(object, method, collection, value_method, text_meth <ide> Tags::CollectionRadioButtons.new(object, method, self, collection, value_method, text_method, options, html_options).render(&block) <ide> end <ide> <add> def collection_check_boxes(object, method, collection, value_method, text_method, options = {}, html_options = {}, &block) <add> Tags::CollectionCheckBoxes.new(object, method, self, collection, value_method, text_method, options, html_options).render(&block) <add> end <add> <ide> # Returns <tt><select></tt>, <tt><optgroup></tt> and <tt><option></tt> tags for the collection of existing return values of <ide> # +method+ for +object+'s class. The value returned from calling +method+ on the instance +object+ will <ide> # be selected. If calling +method+ returns +nil+, no selection is made without including <tt>:prompt</tt> <ide><path>actionpack/lib/action_view/helpers/tags.rb <ide> module Tags #:nodoc: <ide> <ide> autoload :Base <ide> autoload :CheckBox <add> autoload :CollectionCheckBoxes <ide> autoload :CollectionRadioButtons <ide> autoload :CollectionSelect <ide> autoload :DateSelect <ide><path>actionpack/lib/action_view/helpers/tags/collection_check_boxes.rb <add>module ActionView <add> module Helpers <add> module Tags <add> class CollectionCheckBoxes < CollectionRadioButtons <add> delegate :check_box, :label, :to => :@template_object <add> <add> def render <add> rendered_collection = render_collection( <add> @method_name, @collection, @value_method, @text_method, @options, @html_options <add> ) do |value, text, default_html_options| <add> default_html_options[:multiple] = true <add> <add> if block_given? <add> yield sanitize_attribute_name(@method_name, value), text, value, default_html_options <add> else <add> check_box(@object_name, @method_name, default_html_options, value, nil) + <add> label(@object_name, sanitize_attribute_name(@method_name, value), text, :class => "collection_check_boxes") <add> end <add> end <add> <add> # Prepend a hidden field to make sure something will be sent back to the <add> # server if all checkboxes are unchecked. <add> hidden = @template_object.hidden_field_tag("#{@object_name}[#{@method_name}][]", "", :id => nil) <add> <add> wrap_rendered_collection(rendered_collection + hidden, @options) <add> end <add> end <add> end <add> end <add>end <ide><path>actionpack/test/template/form_collections_helper_test.rb <ide> require 'abstract_unit' <ide> <add>class Tag < Struct.new(:id, :name) <add>end <add> <ide> class FormCollectionsHelperTest < ActionView::TestCase <ide> def assert_no_select(selector, value = nil) <ide> assert_select(selector, :text => value, :count => 0) <ide> def with_collection_radio_buttons(*args, &block) <ide> concat collection_radio_buttons(*args, &block) <ide> end <ide> <del> # COLLECTION RADIO <add> def with_collection_check_boxes(*args, &block) <add> concat collection_check_boxes(*args, &block) <add> end <add> <add> # COLLECTION RADIO BUTTONS <ide> test 'collection radio accepts a collection and generate inputs from value method' do <ide> with_collection_radio_buttons :user, :active, [true, false], :to_s, :to_s <ide> <ide> def with_collection_radio_buttons(*args, &block) <ide> assert_select 'label[for=user_active_true] > input#user_active_true[type=radio]' <ide> assert_select 'label[for=user_active_false] > input#user_active_false[type=radio]' <ide> end <add> <add> # COLLECTION CHECK BOXES <add> test 'collection check boxes accepts a collection and generate a serie of checkboxes for value method' do <add> collection = [Tag.new(1, 'Tag 1'), Tag.new(2, 'Tag 2')] <add> with_collection_check_boxes :user, :tag_ids, collection, :id, :name <add> <add> assert_select 'input#user_tag_ids_1[type=checkbox][value=1]' <add> assert_select 'input#user_tag_ids_2[type=checkbox][value=2]' <add> end <add> <add> test 'collection check boxes generates only one hidden field for the entire collection, to ensure something will be sent back to the server when posting an empty collection' do <add> collection = [Tag.new(1, 'Tag 1'), Tag.new(2, 'Tag 2')] <add> with_collection_check_boxes :user, :tag_ids, collection, :id, :name <add> <add> assert_select "input[type=hidden][name='user[tag_ids][]'][value=]", :count => 1 <add> end <add> <add> test 'collection check boxes accepts a collection and generate a serie of checkboxes with labels for label method' do <add> collection = [Tag.new(1, 'Tag 1'), Tag.new(2, 'Tag 2')] <add> with_collection_check_boxes :user, :tag_ids, collection, :id, :name <add> <add> assert_select 'label.collection_check_boxes[for=user_tag_ids_1]', 'Tag 1' <add> assert_select 'label.collection_check_boxes[for=user_tag_ids_2]', 'Tag 2' <add> end <add> <add> test 'collection check boxes handles camelized collection values for labels correctly' do <add> with_collection_check_boxes :user, :active, ['Yes', 'No'], :to_s, :to_s <add> <add> assert_select 'label.collection_check_boxes[for=user_active_yes]', 'Yes' <add> assert_select 'label.collection_check_boxes[for=user_active_no]', 'No' <add> end <add> <add> test 'colection check box should sanitize collection values for labels correctly' do <add> with_collection_check_boxes :user, :name, ['$0.99', '$1.99'], :to_s, :to_s <add> assert_select 'label.collection_check_boxes[for=user_name_099]', '$0.99' <add> assert_select 'label.collection_check_boxes[for=user_name_199]', '$1.99' <add> end <add> <add> test 'collection check boxes accepts selected values as :checked option' do <add> collection = (1..3).map{|i| [i, "Tag #{i}"] } <add> with_collection_check_boxes :user, :tag_ids, collection, :first, :last, :checked => [1, 3] <add> <add> assert_select 'input[type=checkbox][value=1][checked=checked]' <add> assert_select 'input[type=checkbox][value=3][checked=checked]' <add> assert_no_select 'input[type=checkbox][value=2][checked=checked]' <add> end <add> <add> test 'collection check boxes accepts a single checked value' do <add> collection = (1..3).map{|i| [i, "Tag #{i}"] } <add> with_collection_check_boxes :user, :tag_ids, collection, :first, :last, :checked => 3 <add> <add> assert_select 'input[type=checkbox][value=3][checked=checked]' <add> assert_no_select 'input[type=checkbox][value=1][checked=checked]' <add> assert_no_select 'input[type=checkbox][value=2][checked=checked]' <add> end <add> <add> test 'collection check boxes accepts selected values as :checked option and override the model values' do <add> skip "check with fields for" <add> collection = (1..3).map{|i| [i, "Tag #{i}"] } <add> :user.tag_ids = [2] <add> with_collection_check_boxes :user, :tag_ids, collection, :first, :last, :checked => [1, 3] <add> <add> assert_select 'input[type=checkbox][value=1][checked=checked]' <add> assert_select 'input[type=checkbox][value=3][checked=checked]' <add> assert_no_select 'input[type=checkbox][value=2][checked=checked]' <add> end <add> <add> test 'collection check boxes accepts multiple disabled items' do <add> collection = (1..3).map{|i| [i, "Tag #{i}"] } <add> with_collection_check_boxes :user, :tag_ids, collection, :first, :last, :disabled => [1, 3] <add> <add> assert_select 'input[type=checkbox][value=1][disabled=disabled]' <add> assert_select 'input[type=checkbox][value=3][disabled=disabled]' <add> assert_no_select 'input[type=checkbox][value=2][disabled=disabled]' <add> end <add> <add> test 'collection check boxes accepts single disable item' do <add> collection = (1..3).map{|i| [i, "Tag #{i}"] } <add> with_collection_check_boxes :user, :tag_ids, collection, :first, :last, :disabled => 1 <add> <add> assert_select 'input[type=checkbox][value=1][disabled=disabled]' <add> assert_no_select 'input[type=checkbox][value=3][disabled=disabled]' <add> assert_no_select 'input[type=checkbox][value=2][disabled=disabled]' <add> end <add> <add> test 'collection check boxes accepts a proc to disabled items' do <add> collection = (1..3).map{|i| [i, "Tag #{i}"] } <add> with_collection_check_boxes :user, :tag_ids, collection, :first, :last, :disabled => proc { |i| i.first == 1 } <add> <add> assert_select 'input[type=checkbox][value=1][disabled=disabled]' <add> assert_no_select 'input[type=checkbox][value=3][disabled=disabled]' <add> assert_no_select 'input[type=checkbox][value=2][disabled=disabled]' <add> end <add> <add> test 'collection check boxes accepts html options' do <add> collection = [[1, 'Tag 1'], [2, 'Tag 2']] <add> with_collection_check_boxes :user, :tag_ids, collection, :first, :last, {}, :class => 'check' <add> <add> assert_select 'input.check[type=checkbox][value=1]' <add> assert_select 'input.check[type=checkbox][value=2]' <add> end <add> <add> test 'collection check boxes with fields for' do <add> skip "test collection check boxes with fields for (and radio buttons as well)" <add> collection = [Tag.new(1, 'Tag 1'), Tag.new(2, 'Tag 2')] <add> concat(form_for(:user) do |f| <add> f.fields_for(:post) do |p| <add> p.collection_check_boxes :tag_ids, collection, :id, :name <add> end <add> end) <add> <add> assert_select 'input#user_post_tag_ids_1[type=checkbox][value=1]' <add> assert_select 'input#user_post_tag_ids_2[type=checkbox][value=2]' <add> <add> assert_select 'label.collection_check_boxes[for=user_post_tag_ids_1]', 'Tag 1' <add> assert_select 'label.collection_check_boxes[for=user_post_tag_ids_2]', 'Tag 2' <add> end <add> <add> test 'collection check boxeses wraps the collection in the given collection wrapper tag' do <add> with_collection_check_boxes :user, :active, [true, false], :to_s, :to_s, :collection_wrapper_tag => :ul <add> <add> assert_select 'ul input[type=checkbox]', :count => 2 <add> end <add> <add> test 'collection check boxeses does not render any wrapper tag by default' do <add> with_collection_check_boxes :user, :active, [true, false], :to_s, :to_s <add> <add> assert_select 'input[type=checkbox]', :count => 2 <add> assert_no_select 'ul' <add> end <add> <add> test 'collection check boxeses does not wrap the collection when given falsy values' do <add> with_collection_check_boxes :user, :active, [true, false], :to_s, :to_s, :collection_wrapper_tag => false <add> <add> assert_select 'input[type=checkbox]', :count => 2 <add> assert_no_select 'ul' <add> end <add> <add> test 'collection check boxeses uses the given class for collection wrapper tag' do <add> with_collection_check_boxes :user, :active, [true, false], :to_s, :to_s, <add> :collection_wrapper_tag => :ul, :collection_wrapper_class => "items-list" <add> <add> assert_select 'ul.items-list input[type=checkbox]', :count => 2 <add> end <add> <add> test 'collection check boxeses uses no class for collection wrapper tag when no wrapper tag is given' do <add> with_collection_check_boxes :user, :active, [true, false], :to_s, :to_s, <add> :collection_wrapper_class => "items-list" <add> <add> assert_select 'input[type=checkbox]', :count => 2 <add> assert_no_select 'ul' <add> assert_no_select '.items-list' <add> end <add> <add> test 'collection check boxeses uses no class for collection wrapper tag by default' do <add> with_collection_check_boxes :user, :active, [true, false], :to_s, :to_s, :collection_wrapper_tag => :ul <add> <add> assert_select 'ul' <add> assert_no_select 'ul[class]' <add> end <add> <add> test 'collection check boxeses wrap items in a span tag by default' do <add> with_collection_check_boxes :user, :active, [true, false], :to_s, :to_s <add> <add> assert_select 'span input[type=checkbox]', :count => 2 <add> end <add> <add> test 'collection check boxeses wraps each item in the given item wrapper tag' do <add> with_collection_check_boxes :user, :active, [true, false], :to_s, :to_s, :item_wrapper_tag => :li <add> <add> assert_select 'li input[type=checkbox]', :count => 2 <add> end <add> <add> test 'collection check boxeses does not wrap each item when given explicitly falsy value' do <add> with_collection_check_boxes :user, :active, [true, false], :to_s, :to_s, :item_wrapper_tag => false <add> <add> assert_select 'input[type=checkbox]' <add> assert_no_select 'span input[type=checkbox]' <add> end <add> <add> test 'collection check boxeses uses the given class for item wrapper tag' do <add> with_collection_check_boxes :user, :active, [true, false], :to_s, :to_s, <add> :item_wrapper_tag => :li, :item_wrapper_class => "inline" <add> <add> assert_select "li.inline input[type=checkbox]", :count => 2 <add> end <add> <add> test 'collection check boxeses uses no class for item wrapper tag when no wrapper tag is given' do <add> with_collection_check_boxes :user, :active, [true, false], :to_s, :to_s, <add> :item_wrapper_tag => nil, :item_wrapper_class => "inline" <add> <add> assert_select 'input[type=checkbox]', :count => 2 <add> assert_no_select 'li' <add> assert_no_select '.inline' <add> end <add> <add> test 'collection check boxeses uses no class for item wrapper tag by default' do <add> with_collection_check_boxes :user, :active, [true, false], :to_s, :to_s, <add> :item_wrapper_tag => :li <add> <add> assert_select "li", :count => 2 <add> assert_no_select "li[class]" <add> end <add> <add> test 'collection check boxes does not wrap input inside the label' do <add> with_collection_check_boxes :user, :active, [true, false], :to_s, :to_s <add> <add> assert_select 'input[type=checkbox] + label' <add> assert_no_select 'label input' <add> end <add> <add> test 'collection check boxes accepts a block to render the radio and label as required' do <add> with_collection_check_boxes :user, :active, [true, false], :to_s, :to_s do |label_for, text, value, html_options| <add> label(:user, label_for, text) { check_box(:user, :active, html_options, value) } <add> end <add> <add> assert_select 'label[for=user_active_true] > input#user_active_true[type=checkbox]' <add> assert_select 'label[for=user_active_false] > input#user_active_false[type=checkbox]' <add> end <ide> end
4
Javascript
Javascript
add bigint64array and biguint64array to globals
11ae1791e78367e5d24b402b808807479bd65364
<ide><path>.eslintrc.js <ide> module.exports = { <ide> }, <ide> globals: { <ide> BigInt: false, <add> BigInt64Array: false, <add> BigUint64Array: false, <ide> COUNTER_HTTP_CLIENT_REQUEST: false, <ide> COUNTER_HTTP_CLIENT_RESPONSE: false, <ide> COUNTER_HTTP_SERVER_REQUEST: false,
1
Text
Text
put value into quotes
7ce8c587099fc4d8c8f555c6ecef9febefa0c3b7
<ide><path>curriculum/challenges/english/02-javascript-algorithms-and-data-structures/es6/use-arrow-functions-to-write-concise-anonymous-functions.md <ide> When there is no function body, and only a return value, arrow function syntax a <ide> const myFunc = () => "value"; <ide> ``` <ide> <del>This code will still return <code>value</code> by default. <add>This code will still return the string <code>value</code> by default. <ide> </section> <ide> <ide> ## Instructions
1
Python
Python
fix failing docs on main
4fdfef909e3b9a22461c95e4ee123a84c47186fd
<ide><path>tests/system/providers/google/cloud/cloud_build/example_cloud_build_trigger.py <ide> <ide> ENV_ID = os.environ.get("SYSTEM_TESTS_ENV_ID") <ide> PROJECT_ID = os.environ.get("SYSTEM_TESTS_GCP_PROJECT") <del>TRIGGER_NAME = f"cloud-build-trigger-{ENV_ID}" <ide> <ide> DAG_ID = "example_gcp_cloud_build_trigger" <ide>
1
Python
Python
use math mode
24d653f11a55f76b125a91d7d4523052ef14b9b9
<ide><path>numpy/core/numeric.py <ide> def correlate(a, v, mode='valid'): <ide> This function computes the correlation as generally defined in signal <ide> processing texts:: <ide> <del> c_{av}[k] = sum_n a[n+k] * conj(v[n]) <add> .. math:: c_k = \sum_n a_{n+k} * \overline{v_n} <ide> <del> with a and v sequences being zero-padded where necessary and conj being <del> the conjugate. <add> with a and v sequences being zero-padded where necessary and <add> :math:`\overline x` denoting complex conjugation. <ide> <ide> Parameters <ide> ---------- <ide> def correlate(a, v, mode='valid'): <ide> The definition of correlation above is not unique and sometimes correlation <ide> may be defined differently. Another common definition is:: <ide> <del> c'_{av}[k] = sum_n a[n] conj(v[n+k]) <add> .. math:: c'_k = \sum_n a_{n} * \overline{v_{n+k} <ide> <del> which is related to ``c_{av}[k]`` by ``c'_{av}[k] = c_{av}[-k]``. <add> which is related to :math:`c_k` by :math:`c'_k = c_{-k}`. <ide> <ide> `numpy.correlate` may perform slowly in large arrays (i.e. n = 1e5) because it does <ide> not use the FFT to compute the convolution; in that case, `scipy.signal.correlate` might
1
Go
Go
add /proc/acpi to masked paths
569b9702a59804617e1cd3611fbbe953e4247b3e
<ide><path>oci/defaults.go <ide> func DefaultLinuxSpec() specs.Spec { <ide> <ide> s.Linux = &specs.Linux{ <ide> MaskedPaths: []string{ <add> "/proc/acpi", <ide> "/proc/kcore", <ide> "/proc/keys", <ide> "/proc/latency_stats",
1
Javascript
Javascript
use boolean naming conventions
5cf25f10c905b4f7db98589c72cc63f82a411da9
<ide><path>packages/ember-metal/lib/computed_macros.js <ide> function registerComputedWithProperties(name, macro) { <ide> <ide> ```javascript <ide> var ToDoList = Ember.Object.extend({ <del> done: Ember.computed.empty('todos') <add> isDone: Ember.computed.empty('todos') <ide> }); <ide> <ide> var todoList = ToDoList.create({ <ide> todos: ['Unit Test', 'Documentation', 'Release'] <ide> }); <ide> <del> todoList.get('done'); // false <add> todoList.get('isDone'); // false <ide> todoList.get('todos').clear(); <del> todoList.get('done'); // true <add> todoList.get('isDone'); // true <ide> ``` <ide> <ide> @since 1.6.0
1
Python
Python
add mapping of type for choicefield.
bc4d52558bbf3d8a1311c23194123ea7517b2697
<ide><path>rest_framework/schemas/openapi.py <ide> import warnings <add>from collections import OrderedDict <add>from decimal import Decimal <ide> from operator import attrgetter <ide> from urllib.parse import urljoin <ide> <ide> def _get_pagination_parameters(self, path, method): <ide> <ide> return paginator.get_schema_operation_parameters(view) <ide> <add> def _map_choicefield(self, field): <add> choices = list(OrderedDict.fromkeys(field.choices)) # preserve order and remove duplicates <add> if all(isinstance(choice, bool) for choice in choices): <add> type = 'boolean' <add> elif all(isinstance(choice, int) for choice in choices): <add> type = 'integer' <add> elif all(isinstance(choice, (int, float, Decimal)) for choice in choices): # `number` includes `integer` <add> # Ref: https://tools.ietf.org/html/draft-wright-json-schema-validation-00#section-5.21 <add> type = 'number' <add> elif all(isinstance(choice, str) for choice in choices): <add> type = 'string' <add> else: <add> type = None <add> <add> mapping = { <add> # The value of `enum` keyword MUST be an array and SHOULD be unique. <add> # Ref: https://tools.ietf.org/html/draft-wright-json-schema-validation-00#section-5.20 <add> 'enum': choices <add> } <add> <add> # If We figured out `type` then and only then we should set it. It must be a string. <add> # Ref: https://swagger.io/docs/specification/data-models/data-types/#mixed-type <add> # It is optional but it can not be null. <add> # Ref: https://tools.ietf.org/html/draft-wright-json-schema-validation-00#section-5.21 <add> if type: <add> mapping['type'] = type <add> return mapping <add> <ide> def _map_field(self, field): <ide> <ide> # Nested Serializers, `many` or not. <ide> def _map_field(self, field): <ide> if isinstance(field, serializers.MultipleChoiceField): <ide> return { <ide> 'type': 'array', <del> 'items': { <del> 'enum': list(field.choices) <del> }, <add> 'items': self._map_choicefield(field) <ide> } <ide> <ide> if isinstance(field, serializers.ChoiceField): <del> return { <del> 'enum': list(field.choices), <del> } <add> return self._map_choicefield(field) <ide> <ide> # ListField. <ide> if isinstance(field, serializers.ListField): <ide><path>tests/schemas/test_openapi.py <add>import uuid <add> <ide> import pytest <ide> from django.conf.urls import url <ide> from django.test import RequestFactory, TestCase, override_settings <ide> def test_pagination(self): <ide> <ide> class TestFieldMapping(TestCase): <ide> def test_list_field_mapping(self): <add> uuid1 = uuid.uuid4() <add> uuid2 = uuid.uuid4() <ide> inspector = AutoSchema() <ide> cases = [ <ide> (serializers.ListField(), {'items': {}, 'type': 'array'}), <ide> def test_list_field_mapping(self): <ide> (serializers.ListField(child=serializers.IntegerField(max_value=4294967295)), <ide> {'items': {'type': 'integer', 'maximum': 4294967295, 'format': 'int64'}, 'type': 'array'}), <ide> (serializers.ListField(child=serializers.ChoiceField(choices=[('a', 'Choice A'), ('b', 'Choice B')])), <del> {'items': {'enum': ['a', 'b']}, 'type': 'array'}), <add> {'items': {'enum': ['a', 'b'], 'type': 'string'}, 'type': 'array'}), <add> (serializers.ListField(child=serializers.ChoiceField(choices=[(1, 'One'), (2, 'Two')])), <add> {'items': {'enum': [1, 2], 'type': 'integer'}, 'type': 'array'}), <add> (serializers.ListField(child=serializers.ChoiceField(choices=[(1.1, 'First'), (2.2, 'Second')])), <add> {'items': {'enum': [1.1, 2.2], 'type': 'number'}, 'type': 'array'}), <add> (serializers.ListField(child=serializers.ChoiceField(choices=[(True, 'true'), (False, 'false')])), <add> {'items': {'enum': [True, False], 'type': 'boolean'}, 'type': 'array'}), <add> (serializers.ListField(child=serializers.ChoiceField(choices=[(uuid1, 'uuid1'), (uuid2, 'uuid2')])), <add> {'items': {'enum': [uuid1, uuid2]}, 'type': 'array'}), <add> (serializers.ListField(child=serializers.ChoiceField(choices=[(1, 'One'), ('a', 'Choice A')])), <add> {'items': {'enum': [1, 'a']}, 'type': 'array'}), <add> (serializers.ListField(child=serializers.ChoiceField(choices=[ <add> (1, 'One'), ('a', 'Choice A'), (1.1, 'First'), (1.1, 'First'), (1, 'One'), ('a', 'Choice A'), (1, 'One') <add> ])), <add> {'items': {'enum': [1, 'a', 1.1]}, 'type': 'array'}), <add> (serializers.ListField(child=serializers.ChoiceField(choices=[ <add> (1, 'One'), (2, 'Two'), (3, 'Three'), (2, 'Two'), (3, 'Three'), (1, 'One'), <add> ])), <add> {'items': {'enum': [1, 2, 3], 'type': 'integer'}, 'type': 'array'}), <ide> (serializers.IntegerField(min_value=2147483648), <ide> {'type': 'integer', 'minimum': 2147483648, 'format': 'int64'}), <ide> ]
2
Python
Python
move it into the setup() method
aeccd1850a36b33c6c28927290e98be37bb92aee
<ide><path>libcloud/test/compute/test_openstack.py <ide> def get_endpoint(*args, **kwargs): <ide> return "https://servers.api.rackspacecloud.com/v1.0/slug" <ide> <ide> OpenStack_1_1_NodeDriver.connectionCls.get_endpoint = get_endpoint <del> <del> def test_ex_force_auth_version_all_possible_values(self): <del> """ <del> Test case which verifies that the driver can be correctly instantiated using all the <del> supported API versions. <del> """ <ide> OpenStack_1_1_NodeDriver.connectionCls.conn_class = ( <ide> OpenStack_AllAuthVersions_MockHttp <ide> ) <ide> OpenStackMockHttp.type = None <ide> OpenStack_1_1_MockHttp.type = None <ide> OpenStack_2_0_MockHttp.type = None <ide> <add> def test_ex_force_auth_version_all_possible_values(self): <add> """ <add> Test case which verifies that the driver can be correctly instantiated using all the <add> supported API versions. <add> """ <ide> cls = get_driver(Provider.OPENSTACK) <ide> <ide> for auth_version in AUTH_VERSIONS_WITH_EXPIRES:
1
Ruby
Ruby
make revert of `disable_extension` to work
68eb6ca63119c35a6b42c7a90ca3557517b1bcda
<ide><path>activerecord/lib/active_record/migration/command_recorder.rb <ide> class CommandRecorder <ide> ReversibleAndIrreversibleMethods = [:create_table, :create_join_table, :rename_table, :add_column, :remove_column, <ide> :rename_index, :rename_column, :add_index, :remove_index, :add_timestamps, :remove_timestamps, <ide> :change_column_default, :add_reference, :remove_reference, :transaction, <del> :drop_join_table, :drop_table, :execute_block, :enable_extension, <add> :drop_join_table, :drop_table, :execute_block, :enable_extension, :disable_extension, <ide> :change_column, :execute, :remove_columns, :change_column_null, <ide> :add_foreign_key, :remove_foreign_key <ide> ] <ide><path>activerecord/test/cases/invertible_migration_test.rb <ide> def change <ide> end <ide> end <ide> <add> class DisableExtension1 < SilentMigration <add> def change <add> enable_extension "hstore" <add> end <add> end <add> <add> class DisableExtension2 < SilentMigration <add> def change <add> disable_extension "hstore" <add> end <add> end <add> <ide> class LegacyMigration < ActiveRecord::Migration <ide> def self.up <ide> create_table("horses") do |t| <ide> def test_migrate_revert_change_column_default <ide> assert_equal "Sekitoba", Horse.new.name <ide> end <ide> <add> if current_adapter?(:PostgreSQLAdapter) <add> def test_migrate_enable_and_disable_extension <add> migration1 = InvertibleMigration.new <add> migration2 = DisableExtension1.new <add> migration3 = DisableExtension2.new <add> <add> migration1.migrate(:up) <add> migration2.migrate(:up) <add> assert_equal true, Horse.connection.extension_enabled?('hstore') <add> <add> migration3.migrate(:up) <add> assert_equal false, Horse.connection.extension_enabled?('hstore') <add> <add> migration3.migrate(:down) <add> assert_equal true, Horse.connection.extension_enabled?('hstore') <add> <add> migration2.migrate(:down) <add> assert_equal false, Horse.connection.extension_enabled?('hstore') <add> end <add> end <add> <ide> def test_revert_order <ide> block = Proc.new{|t| t.string :name } <ide> recorder = ActiveRecord::Migration::CommandRecorder.new(ActiveRecord::Base.connection)
2
Mixed
Javascript
move dep0026 to end of life
2d578ad996de13acbe1227a8565c89dcd95d8bc8
<ide><path>doc/api/deprecations.md <ide> The `sys` module is deprecated. Please use the [`util`][] module instead. <ide> ### DEP0026: util.print() <ide> <!-- YAML <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/xxxxx <add> description: End-of-Life. <ide> - version: <ide> - v4.8.6 <ide> - v6.12.0 <ide> changes: <ide> description: Runtime deprecation. <ide> --> <ide> <del>Type: Runtime <add>Type: End-of-Life <ide> <del>The [`util.print()`][] API is deprecated. Please use [`console.log()`][] <del>instead. <add>`util.print()` has been removed. Please use [`console.log()`][] instead. <ide> <ide> <a id="DEP0027"></a> <ide> ### DEP0027: util.puts() <ide> Setting the TLS ServerName to an IP address is not permitted by <ide> [`util.isSymbol()`]: util.html#util_util_issymbol_object <ide> [`util.isUndefined()`]: util.html#util_util_isundefined_object <ide> [`util.log()`]: util.html#util_util_log_string <del>[`util.print()`]: util.html#util_util_print_strings <ide> [`util.puts()`]: util.html#util_util_puts_strings <ide> [`util.types`]: util.html#util_util_types <ide> [`util`]: util.html <ide><path>doc/api/util.md <ide> const util = require('util'); <ide> util.log('Timestamped message.'); <ide> ``` <ide> <del>### util.print([...strings]) <del><!-- YAML <del>added: v0.3.0 <del>deprecated: v0.11.3 <del>--> <del> <del>> Stability: 0 - Deprecated: Use [`console.log()`][] instead. <del> <del>Deprecated predecessor of `console.log`. <del> <ide> ### util.puts([...strings]) <ide> <!-- YAML <ide> added: v0.3.0 <ide><path>lib/util.js <ide> function _extend(target, source) { <ide> <ide> // Deprecated old stuff. <ide> <del>function print(...args) { <del> for (var i = 0, len = args.length; i < len; ++i) { <del> process.stdout.write(String(args[i])); <del> } <del>} <del> <ide> function puts(...args) { <ide> for (var i = 0, len = args.length; i < len; ++i) { <ide> process.stdout.write(`${args[i]}\n`); <ide> module.exports = exports = { <ide> error: deprecate(error, <ide> 'util.error is deprecated. Use console.error instead.', <ide> 'DEP0029'), <del> print: deprecate(print, <del> 'util.print is deprecated. Use console.log instead.', <del> 'DEP0026'), <ide> puts: deprecate(puts, <ide> 'util.puts is deprecated. Use console.log instead.', <ide> 'DEP0027') <ide><path>test/fixtures/test-init-index/index.js <ide> // USE OR OTHER DEALINGS IN THE SOFTWARE. <ide> <ide> (function() { <del> require('util').print('Loaded successfully!'); <add> process.stdout.write('Loaded successfully!'); <ide> })(); <ide> <ide><path>test/fixtures/test-init-native/fs.js <ide> (function() { <ide> const fs = require('fs'); <ide> if (fs.readFile) { <del> require('util').print('fs loaded successfully'); <add> process.stdout.write('fs loaded successfully'); <ide> } <ide> })(); <ide> <ide><path>test/parallel/test-util.js <ide> assert.strictEqual(util.isFunction(), false); <ide> assert.strictEqual(util.isFunction('string'), false); <ide> <ide> common.expectWarning('DeprecationWarning', [ <del> ['util.print is deprecated. Use console.log instead.', 'DEP0026'], <ide> ['util.puts is deprecated. Use console.log instead.', 'DEP0027'], <ide> ['util.debug is deprecated. Use console.error instead.', 'DEP0028'], <ide> ['util.error is deprecated. Use console.error instead.', 'DEP0029'] <ide> ]); <ide> <del>util.print('test'); <ide> util.puts('test'); <ide> util.debug('test'); <ide> util.error('test');
6
Python
Python
add tests for ticket #205
05cdc869ae8a7f44097dd186fe6688500a99e30f
<ide><path>numpy/core/tests/test_regression.py <ide> def check_mem_array_creation_invalid_specification(self,level=rlevel): <ide> # Correct way <ide> N.array([(1,'object')],dt) <ide> <add> def check_zero_sized_array_indexing(self,level=rlevel): <add> """Ticket #205""" <add> tmp = N.array([]) <add> def index_tmp(): tmp[N.array(10)] <add> self.failUnlessRaises(IndexError, index_tmp) <add> <add> def check_unique_zero_sized(self,level=rlevel): <add> """Ticket #205""" <add> assert_array_equal([], N.unique(N.array([]))) <add> <ide> if __name__ == "__main__": <ide> NumpyTest().run()
1
Javascript
Javascript
multiget breaking test and fix
52755fdde278404540a17117098151db5f2a86e3
<ide><path>IntegrationTests/AsyncStorageTest.js <ide> function testMerge() { <ide> expectAsyncNoError('testMerge/setItem', err3); <ide> expectEqual(JSON.parse(result), VAL_MERGE_EXPECT, 'testMerge'); <ide> updateMessage('objects deeply merged\nDone!'); <add> runTestCase('multi set and get', testOptimizedMultiGet); <add> }); <add> }); <add> }); <add>} <add> <add>function testOptimizedMultiGet() { <add> let batch = [[KEY_1, VAL_1], [KEY_2, VAL_2]]; <add> let keys = batch.map(([key, value]) => key); <add> AsyncStorage.multiSet(batch, (err1) => { <add> // yes, twice on purpose <add> ;[1, 2].forEach((i) => { <add> expectAsyncNoError(`${i} testOptimizedMultiGet/multiSet`, err1); <add> AsyncStorage.multiGet(keys, (err2, result) => { <add> expectAsyncNoError(`${i} testOptimizedMultiGet/multiGet`, err2); <add> expectEqual(result, batch, `${i} testOptimizedMultiGet multiGet`); <add> updateMessage('multiGet([key_1, key_2]) correctly returned ' + JSON.stringify(result)); <ide> done(); <ide> }); <ide> }); <ide> }); <ide> } <ide> <add> <ide> var AsyncStorageTest = React.createClass({ <ide> getInitialState() { <ide> return { <ide><path>Libraries/Storage/AsyncStorage.js <ide> var AsyncStorage = { <ide> // Even though the runtime complexity of this is theoretically worse vs if we used a map, <ide> // it's much, much faster in practice for the data sets we deal with (we avoid <ide> // allocating result pair arrays). This was heavily benchmarked. <add> // <add> // Is there a way to avoid using the map but fix the bug in this breaking test? <add> // https://github.com/facebook/react-native/commit/8dd8ad76579d7feef34c014d387bf02065692264 <add> let map = {}; <add> result.forEach(([key, value]) => map[key] = value); <ide> const reqLength = getRequests.length; <ide> for (let i = 0; i < reqLength; i++) { <ide> const request = getRequests[i]; <ide> const requestKeys = request.keys; <del> var requestResult = result.filter(function(resultPair) { <del> return requestKeys.indexOf(resultPair[0]) !== -1; <del> }); <del> <add> let requestResult = requestKeys.map(key => [key, map[key]]); <ide> request.callback && request.callback(null, requestResult); <ide> request.resolve && request.resolve(requestResult); <ide> } <ide> var AsyncStorage = { <ide> var getRequest = { <ide> keys: keys, <ide> callback: callback, <add> // do we need this? <ide> keyIndex: this._getKeys.length, <ide> resolve: null, <ide> reject: null, <ide> var AsyncStorage = { <ide> }); <ide> <ide> this._getRequests.push(getRequest); <del> this._getKeys.push.apply(this._getKeys, keys); <add> // avoid fetching duplicates <add> keys.forEach(key => { <add> if (this._getKeys.indexOf(key) === -1) { <add> this._getKeys.push(key); <add> } <add> }); <ide> <ide> return promiseResult; <ide> },
2
Ruby
Ruby
check requirement before dependency
666b48e39127e650681f4e24068787c309de5ee4
<ide><path>Library/Homebrew/dependency_collector.rb <ide> def parse_spec spec, tag <ide> parse_string_spec(spec, tag) <ide> when Symbol <ide> parse_symbol_spec(spec, tag) <del> when Dependency, Requirement <add> when Requirement, Dependency <ide> spec <ide> when Class <ide> parse_class_spec(spec, tag)
1
PHP
PHP
remove key when key exists
6b95535b4358967c603807804bf8116a36a0c8a8
<ide><path>src/Illuminate/Support/Arr.php <ide> public static function forget(&$array, $keys) <ide> } <ide> <ide> foreach ($keys as $key) { <add> if (static::exists($array, $key)) { <add> unset($array[$key]); <add> continue; <add> } <add> <ide> $parts = explode('.', $key); <ide> <ide> // clean up before each pass
1
Text
Text
add missing semicolon
24c6a1ec09c34a6ecfea4aee18ebd805961bdc4a
<ide><path>STYLEGUIDE.md <ide> var [ <ide> var person = { <ide> firstName: 'Stefan', <ide> lastName: 'Penner' <del>} <add>}; <ide> <ide> var { <ide> firstName, <ide> lastName <ide> } = person; <ide> ``` <ide> <del> <ide> ## Comments <ide> <ide> + Use [YUIDoc](http://yui.github.io/yuidoc/syntax/index.html) comments for
1
Text
Text
add apache airflow code_of_conduct.md
d8205676495319f51bfe6b45a3f99e59e5dbe504
<ide><path>CODE_OF_CONDUCT.md <add><!-- <add> Licensed to the Apache Software Foundation (ASF) under one <add> or more contributor license agreements. See the NOTICE file <add> distributed with this work for additional information <add> regarding copyright ownership. The ASF licenses this file <add> to you under the Apache License, Version 2.0 (the <add> "License"); you may not use this file except in compliance <add> with the License. You may obtain a copy of the License at <add> <add> http://www.apache.org/licenses/LICENSE-2.0 <add> <add> Unless required by applicable law or agreed to in writing, <add> software distributed under the License is distributed on an <add> "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY <add> KIND, either express or implied. See the License for the <add> specific language governing permissions and limitations <add> under the License. <add>--> <add> <add># Contributor Covenant Code of Conduct <add> <add>The Apache Airflow project follows the [Apache Software Foundation code of conduct](https://www.apache.org/foundation/policies/conduct.html). <add> <add>If you observe behavior that violates those rules please follow the [ASF reporting guidelines](https://www.apache.org/foundation/policies/conduct#reporting-guidelines).
1
PHP
PHP
improve performance of snake case
9f162064acd421275de87f5a4dfe04915323c7d4
<ide><path>src/Illuminate/Support/Str.php <ide> public static function slug($title, $separator = '-') <ide> */ <ide> public static function snake($value, $delimiter = '_') <ide> { <del> return trim(preg_replace_callback('/[A-Z]/', function($match) use ($delimiter) <del> { <del> return $delimiter.strtolower($match[0]); <add> $replace = '$1'.$delimiter.'$2'; <ide> <del> }, $value), $delimiter); <add> return ctype_lower($value) ? $value : strtolower(preg_replace('/(.)([A-Z])/', $replace, $value)); <ide> } <ide> <ide> /**
1
Java
Java
add request handling infrastructure
773d0444bf0834345a085616b8808a7e6c1925b1
<ide><path>spring-web-reactive/src/main/java/org/springframework/reactive/web/DispatcherHttpHandler.java <add>/* <add> * Copyright 2002-2015 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add>package org.springframework.reactive.web; <add> <add>import java.util.ArrayList; <add>import java.util.List; <add> <add>import org.reactivestreams.Publisher; <add>import org.reactivestreams.Subscriber; <add>import org.reactivestreams.Subscription; <add> <add>import org.springframework.beans.factory.BeanFactoryUtils; <add>import org.springframework.context.ApplicationContext; <add>import org.springframework.http.HttpStatus; <add> <add>/** <add> * @author Rossen Stoyanchev <add> */ <add>public class DispatcherHttpHandler implements HttpHandler { <add> <add> private List<HandlerMapping> handlerMappings; <add> <add> private List<HandlerAdapter> handlerAdapters; <add> <add> private List<HandlerResultHandler> resultHandlers; <add> <add> <add> protected void initStrategies(ApplicationContext context) { <add> <add> this.handlerMappings = new ArrayList<>(BeanFactoryUtils.beansOfTypeIncludingAncestors( <add> context, HandlerMapping.class, true, false).values()); <add> <add> this.handlerAdapters = new ArrayList<>(BeanFactoryUtils.beansOfTypeIncludingAncestors( <add> context, HandlerAdapter.class, true, false).values()); <add> <add> this.resultHandlers = new ArrayList<>(BeanFactoryUtils.beansOfTypeIncludingAncestors( <add> context, HandlerResultHandler.class, true, false).values()); <add> } <add> <add> <add> @Override <add> public Publisher<Void> handle(ServerHttpRequest request, ServerHttpResponse response) { <add> <add> Object handler = getHandler(request); <add> if (handler == null) { <add> // No exception handling mechanism yet <add> response.setStatusCode(HttpStatus.NOT_FOUND); <add> return Publishers.complete(); <add> } <add> <add> HandlerAdapter handlerAdapter = getHandlerAdapter(handler); <add> final Publisher<HandlerResult> resultPublisher = handlerAdapter.handle(request, response, handler); <add> <add> return new Publisher<Void>() { <add> <add> @Override <add> public void subscribe(final Subscriber<? super Void> subscriber) { <add> <add> resultPublisher.subscribe(new Subscriber<HandlerResult>() { <add> <add> @Override <add> public void onSubscribe(Subscription subscription) { <add> subscription.request(Long.MAX_VALUE); <add> } <add> <add> @Override <add> public void onNext(HandlerResult result) { <add> for (HandlerResultHandler resultHandler : resultHandlers) { <add> if (resultHandler.supports(result)) { <add> Publisher<Void> publisher = resultHandler.handleResult(request, response, result); <add> publisher.subscribe(new Subscriber<Void>() { <add> @Override <add> public void onSubscribe(Subscription subscription) { <add> subscription.request(Long.MAX_VALUE); <add> } <add> <add> @Override <add> public void onNext(Void aVoid) { <add> // no op <add> } <add> <add> @Override <add> public void onError(Throwable error) { <add> // Result handling error (no exception handling mechanism yet) <add> subscriber.onError(error); <add> } <add> <add> @Override <add> public void onComplete() { <add> subscriber.onComplete(); <add> } <add> }); <add> } <add> } <add> } <add> <add> @Override <add> public void onError(Throwable error) { <add> // Application handler error (no exception handling mechanism yet) <add> subscriber.onError(error); <add> } <add> <add> @Override <add> public void onComplete() { <add> // do nothing <add> } <add> }); <add> } <add> }; <add> } <add> <add> protected Object getHandler(ServerHttpRequest request) { <add> Object handler = null; <add> for (HandlerMapping handlerMapping : this.handlerMappings) { <add> handler = handlerMapping.getHandler(request); <add> if (handler != null) { <add> break; <add> } <add> } <add> return handler; <add> } <add> <add> protected HandlerAdapter getHandlerAdapter(Object handler) { <add> for (HandlerAdapter handlerAdapter : this.handlerAdapters) { <add> if (handlerAdapter.supports(handler)) { <add> return handlerAdapter; <add> } <add> } <add> // more specific exception <add> throw new IllegalStateException("No HandlerAdapter for " + handler); <add> } <add> <add> <add> private static class Publishers { <add> <add> <add> public static Publisher<Void> complete() { <add> return subscriber -> { <add> subscriber.onSubscribe(new NoopSubscription()); <add> subscriber.onComplete(); <add> }; <add> } <add> } <add> <add> private static class NoopSubscription implements Subscription { <add> <add> @Override <add> public void request(long n) { <add> } <add> <add> @Override <add> public void cancel() { <add> } <add> } <add> <add>} <ide><path>spring-web-reactive/src/main/java/org/springframework/reactive/web/HandlerAdapter.java <add>/* <add> * Copyright 2002-2015 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add>package org.springframework.reactive.web; <add> <add>import org.reactivestreams.Publisher; <add> <add>/** <add> * @author Rossen Stoyanchev <add> */ <add>public interface HandlerAdapter { <add> <add> boolean supports(Object handler); <add> <add> Publisher<HandlerResult> handle(ServerHttpRequest request, ServerHttpResponse response, Object handler); <add> <add>} <ide><path>spring-web-reactive/src/main/java/org/springframework/reactive/web/HandlerMapping.java <add>/* <add> * Copyright 2002-2015 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add>package org.springframework.reactive.web; <add> <add>/** <add> * @author Rossen Stoyanchev <add> */ <add>public interface HandlerMapping { <add> <add> Object getHandler(ServerHttpRequest request); <add> <add>} <ide><path>spring-web-reactive/src/main/java/org/springframework/reactive/web/HandlerResult.java <add>/* <add> * Copyright 2002-2015 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add>package org.springframework.reactive.web; <add> <add>/** <add> * @author Rossen Stoyanchev <add> */ <add>public class HandlerResult { <add> <add> private final Object returnValue; <add> <add> <add> public HandlerResult(Object returnValue) { <add> this.returnValue = returnValue; <add> } <add> <add> <add> public Object getReturnValue() { <add> return this.returnValue; <add> } <add> <add>} <ide><path>spring-web-reactive/src/main/java/org/springframework/reactive/web/HandlerResultHandler.java <add>/* <add> * Copyright 2002-2015 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add>package org.springframework.reactive.web; <add> <add>import org.reactivestreams.Publisher; <add> <add>/** <add> * @author Rossen Stoyanchev <add> */ <add>public interface HandlerResultHandler { <add> <add> boolean supports(HandlerResult result); <add> <add> Publisher<Void> handleResult(ServerHttpRequest request, ServerHttpResponse response, HandlerResult result); <add> <add>} <ide>\ No newline at end of file <ide><path>spring-web-reactive/src/test/java/org/springframework/reactive/web/DispatcherApp.java <add>/* <add> * Copyright 2002-2015 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add>package org.springframework.reactive.web; <add> <add>import java.nio.charset.Charset; <add>import java.util.HashMap; <add>import java.util.Map; <add> <add>import io.netty.buffer.ByteBuf; <add>import io.reactivex.netty.protocol.http.server.HttpServer; <add>import org.reactivestreams.Publisher; <add>import org.reactivestreams.Subscriber; <add>import org.reactivestreams.Subscription; <add> <add>import org.springframework.http.MediaType; <add>import org.springframework.reactive.web.rxnetty.RequestHandlerAdapter; <add>import org.springframework.web.context.support.StaticWebApplicationContext; <add> <add>/** <add> * @author Rossen Stoyanchev <add> */ <add>public class DispatcherApp { <add> <add> public static void main(String[] args) { <add> <add> StaticWebApplicationContext wac = new StaticWebApplicationContext(); <add> wac.registerSingleton("handlerMapping", SimpleUrlHandlerMapping.class); <add> wac.registerSingleton("handlerAdapter", PlainTextHandlerAdapter.class); <add> wac.registerSingleton("resultHandler", PlainTextResultHandler.class); <add> wac.refresh(); <add> <add> SimpleUrlHandlerMapping handlerMapping = wac.getBean(SimpleUrlHandlerMapping.class); <add> handlerMapping.addHandler("/text", new HelloWorldTextHandler()); <add> <add> DispatcherHttpHandler dispatcherHandler = new DispatcherHttpHandler(); <add> dispatcherHandler.initStrategies(wac); <add> <add> RequestHandlerAdapter requestHandler = new RequestHandlerAdapter(dispatcherHandler); <add> HttpServer<ByteBuf, ByteBuf> server = HttpServer.newServer(8080); <add> server.start(requestHandler::handle); <add> server.awaitShutdown(); <add> } <add> <add> <add> private static class SimpleUrlHandlerMapping implements HandlerMapping { <add> <add> private final Map<String, Object> handlerMap = new HashMap<>(); <add> <add> <add> public void addHandler(String path, Object handler) { <add> this.handlerMap.put(path, handler); <add> } <add> <add> @Override <add> public Object getHandler(ServerHttpRequest request) { <add> return this.handlerMap.get(request.getURI().getPath()); <add> } <add> } <add> <add> private interface PlainTextHandler { <add> <add> Publisher<String> handle(ServerHttpRequest request, ServerHttpResponse response); <add> <add> } <add> <add> private static class HelloWorldTextHandler implements PlainTextHandler { <add> <add> @Override <add> public Publisher<String> handle(ServerHttpRequest request, ServerHttpResponse response) { <add> <add> return new Publisher<String>() { <add> <add> @Override <add> public void subscribe(Subscriber<? super String> subscriber) { <add> subscriber.onSubscribe(new AbstractSubscription<String>(subscriber) { <add> <add> @Override <add> protected void requestInternal(long n) { <add> invokeOnNext("Hello world."); <add> invokeOnComplete(); <add> } <add> }); <add> } <add> }; <add> } <add> <add> } <add> <add> private static class PlainTextHandlerAdapter implements HandlerAdapter { <add> <add> @Override <add> public boolean supports(Object handler) { <add> return PlainTextHandler.class.isAssignableFrom(handler.getClass()); <add> } <add> <add> @Override <add> public Publisher<HandlerResult> handle(ServerHttpRequest request, ServerHttpResponse response, <add> Object handler) { <add> <add> PlainTextHandler textHandler = (PlainTextHandler) handler; <add> final Publisher<String> resultPublisher = textHandler.handle(request, response); <add> <add> return new Publisher<HandlerResult>() { <add> <add> @Override <add> public void subscribe(Subscriber<? super HandlerResult> handlerResultSubscriber) { <add> handlerResultSubscriber.onSubscribe(new AbstractSubscription<HandlerResult>(handlerResultSubscriber) { <add> <add> @Override <add> protected void requestInternal(long n) { <add> resultPublisher.subscribe(new Subscriber<Object>() { <add> <add> @Override <add> public void onSubscribe(Subscription subscription) { <add> subscription.request(Long.MAX_VALUE); <add> } <add> <add> @Override <add> public void onNext(Object result) { <add> invokeOnNext(new HandlerResult(result)); <add> } <add> <add> @Override <add> public void onError(Throwable error) { <add> invokeOnError(error); <add> } <add> <add> @Override <add> public void onComplete() { <add> invokeOnComplete(); <add> } <add> }); <add> } <add> }); <add> } <add> }; <add> } <add> } <add> <add> private static class PlainTextResultHandler implements HandlerResultHandler { <add> <add> @Override <add> public boolean supports(HandlerResult result) { <add> Object value = result.getReturnValue(); <add> return (value != null && String.class.equals(value.getClass())); <add> } <add> <add> @Override <add> public Publisher<Void> handleResult(ServerHttpRequest request, ServerHttpResponse response, <add> HandlerResult result) { <add> <add> response.getHeaders().setContentType(MediaType.TEXT_PLAIN); <add> <add> return response.writeWith(new Publisher<byte[]>() { <add> <add> @Override <add> public void subscribe(Subscriber<? super byte[]> writeSubscriber) { <add> writeSubscriber.onSubscribe(new AbstractSubscription<byte[]>(writeSubscriber) { <add> <add> @Override <add> protected void requestInternal(long n) { <add> Charset charset = Charset.forName("UTF-8"); <add> invokeOnNext(((String) result.getReturnValue()).getBytes(charset)); <add> invokeOnComplete(); <add> } <add> }); <add> } <add> }); <add> } <add> } <add> <add> <add> private static abstract class AbstractSubscription<T> implements Subscription { <add> <add> private final Subscriber<? super T> subscriber; <add> <add> private volatile boolean terminated; <add> <add> <add> public AbstractSubscription(Subscriber<? super T> subscriber) { <add> this.subscriber = subscriber; <add> } <add> <add> protected boolean isTerminated() { <add> return this.terminated; <add> } <add> <add> @Override <add> public void request(long n) { <add> if (isTerminated()) { <add> return; <add> } <add> if (n > 0) { <add> requestInternal(n); <add> } <add> } <add> <add> protected abstract void requestInternal(long n); <add> <add> @Override <add> public void cancel() { <add> this.terminated = true; <add> } <add> <add> protected void invokeOnNext(T data) { <add> this.subscriber.onNext(data); <add> } <add> <add> protected void invokeOnError(Throwable error) { <add> this.terminated = true; <add> this.subscriber.onError(error); <add> } <add> <add> protected void invokeOnComplete() { <add> this.terminated = true; <add> this.subscriber.onComplete(); <add> } <add> } <add> <add>}
6
Javascript
Javascript
expose test modules for requirement
009c0b92002fa1aeae985c1a5c8707119a945647
<ide><path>grunt/config/browserify.js <ide> var jasmine = { <ide> var test = { <ide> entries: [ <ide> "./build/modules/test/all.js", <del> "./build/modules/**/__tests__/*-test.js" <add> ], <add> requires: [ <add> "**/__tests__/*-test.js" <ide> ], <ide> outfile: './build/react-test.js', <ide> debug: false, <ide><path>grunt/tasks/browserify.js <ide> module.exports = function() { <ide> // More/better assertions <ide> // grunt.config.requires('outfile'); <ide> // grunt.config.requires('entries'); <del> config.requires = config.requires || {}; <ide> config.transforms = config.transforms || []; <ide> config.after = config.after || []; <ide> if (typeof config.after === 'function') { <ide> module.exports = function() { <ide> var bundle = browserify(entries); <ide> <ide> // Make sure the things that need to be exposed are. <del> // TODO: support a blob pattern maybe? <del> for (var name in config.requires) { <del> bundle.require(config.requires[name], { expose: name }); <add> var requires = config.requires || {}; <add> if (requires instanceof Array) { <add> grunt.file.expand({ <add> nonull: true, // Keep IDs that don't expand to anything. <add> cwd: "src" <add> }, requires).forEach(function(name) { <add> bundle.require("./build/modules/" + name, { <add> expose: name.replace(/\.js$/i, "") <add> }); <add> }); <add> } else if (typeof requires === "object") { <add> Object.keys(requires).forEach(function(name) { <add> bundle.require(requires[name], { expose: name }); <add> }); <ide> } <ide> <ide> // Extract other options
2
Java
Java
fix originalnode memory leak
8102e35271ab68e0525a9c60d86a855bbeef9c1a
<ide><path>ReactAndroid/src/main/java/com/facebook/react/fabric/FabricReconciler.java <ide> private void manageChildren( <ide> } <ide> enqueueUpdateProperties(newNode); <ide> manageChildren(prevNode, prevNode.getChildrenList(), newNode.getChildrenList()); <del> prevNode.setOriginalReactShadowNode(newNode); <add> newNode.setOriginalReactShadowNode(null); <ide> } <ide> int firstRemovedOrAddedViewIndex = sameReactTagIndex; <ide> <ide> private void manageChildren( <ide> viewsToAdd.add(new ViewAtIndex(newNode.getReactTag(), k)); <ide> List previousChildrenList = newNode.getOriginalReactShadowNode() == null ? null : newNode.getOriginalReactShadowNode().getChildrenList(); <ide> manageChildren(newNode, previousChildrenList, newNode.getChildrenList()); <del> newNode.setOriginalReactShadowNode(newNode); <add> newNode.setOriginalReactShadowNode(null); <ide> addedTags.add(newNode.getReactTag()); <ide> } <ide> <ide><path>ReactAndroid/src/main/java/com/facebook/react/fabric/FabricUIManager.java <ide> import com.facebook.react.bridge.ReadableMap; <ide> import com.facebook.react.bridge.ReadableNativeMap; <ide> import com.facebook.react.bridge.UIManager; <add>import com.facebook.react.common.annotations.VisibleForTesting; <ide> import com.facebook.react.modules.i18nmanager.I18nUtil; <ide> import com.facebook.react.uimanager.DisplayMetricsHolder; <ide> import com.facebook.react.uimanager.NativeViewHierarchyManager; <ide> public ReactShadowNode createNode( <ide> } <ide> } <ide> <del> private ReactShadowNode getRootNode(int rootTag) { <add> @VisibleForTesting <add> ReactShadowNode getRootNode(int rootTag) { <ide> return mRootShadowNodeRegistry.getNode(rootTag); <ide> } <ide> <ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactShadowNodeImpl.java <ide> import android.util.Log; <ide> import com.facebook.infer.annotation.Assertions; <ide> import com.facebook.react.uimanager.annotations.ReactPropertyHolder; <del>import com.facebook.yoga.YogaNodeCloneFunction; <ide> import com.facebook.yoga.YogaAlign; <ide> import com.facebook.yoga.YogaBaselineFunction; <ide> import com.facebook.yoga.YogaConfig; <ide> import com.facebook.yoga.YogaJustify; <ide> import com.facebook.yoga.YogaMeasureFunction; <ide> import com.facebook.yoga.YogaNode; <add>import com.facebook.yoga.YogaNodeCloneFunction; <ide> import com.facebook.yoga.YogaOverflow; <ide> import com.facebook.yoga.YogaPositionType; <ide> import com.facebook.yoga.YogaValue;
3
Ruby
Ruby
fix frozen pathname usage
9f616b6fe977b6e6709c17b7df26cdfb4cbfd5f4
<ide><path>Library/Homebrew/cmd/tap-info.rb <ide> def print_tap_info(taps) <ide> info += ", #{private_count} private" <ide> info += ", #{formula_count} #{"formula".pluralize(formula_count)}" <ide> info += ", #{command_count} #{"command".pluralize(command_count)}" <del> info += ", #{Tap::TAP_DIRECTORY.abv}" if Tap::TAP_DIRECTORY.directory? <add> info += ", #{Tap::TAP_DIRECTORY.dup.abv}" if Tap::TAP_DIRECTORY.directory? <ide> puts info <ide> else <ide> taps.each_with_index do |tap, i|
1
Text
Text
add arm64 info to cask-cookbook.md
ab8d3722723137889969d57028adacc7e2038ce5
<ide><path>docs/Cask-Cookbook.md <ide> The available symbols for hardware are: <ide> | ---------- | -------------- | <ide> | `:x86_64` | 64-bit Intel | <ide> | `:intel` | 64-bit Intel | <add>| `:arm64` | Apple M1 | <ide> <ide> The following are all valid expressions: <ide> <ide> ```ruby <ide> depends_on arch: :intel <ide> depends_on arch: :x86_64 # same meaning as above <ide> depends_on arch: [:x86_64] # same meaning as above <add>depends_on arch: :arm64 <ide> ``` <ide> <del>Since as of now all the macOS versions we support only run on 64-bit Intel, `depends_on arch:` is never necessary. <del> <ide> #### All depends_on Keys <ide> <ide> | key | description | <ide> strategy :header_match do |headers| <ide> v = headers["content-disposition"][/MyApp-(\d+(?:\.\d+)*)\.zip/i, 1] <ide> id = headers["location"][%r{/(\d+)/download$}i, 1] <ide> next if v.blank? || id.blank? <del> <add> <ide> "#{v},#{id}" <ide> end <ide> ``` <ide> Similarly, the `:page_match` strategy can also be used for more complex versions <ide> strategy :page_match do |page| <ide> match = page.match(%r{href=.*?/(\d+)/MyApp-(\d+(?:\.\d+)*)\.zip}i) <ide> next if match.blank? <del> <add> <ide> "#{match[2]},#{match[1]}" <ide> end <ide> ```
1
Javascript
Javascript
add tests for add/remove header after sent
a5994f75dc5735968d02f1a914c4035adc9f28af
<ide><path>test/parallel/test-http-response-add-header-after-sent.js <add>'use strict'; <add>require('../common'); <add>const assert = require('assert'); <add>const http = require('http'); <add> <add>const server = http.createServer((req, res) => { <add> assert.doesNotThrow(() => { <add> res.setHeader('header1', 1); <add> }); <add> res.write('abc'); <add> assert.throws(() => { <add> res.setHeader('header2', 2); <add> }, /Can't set headers after they are sent\./); <add> res.end(); <add>}); <add> <add>server.listen(0, () => { <add> http.get({port: server.address().port}, () => { <add> server.close(); <add> }); <add>}); <ide><path>test/parallel/test-http-response-remove-header-after-sent.js <add>'use strict'; <add>require('../common'); <add>const assert = require('assert'); <add>const http = require('http'); <add> <add>const server = http.createServer((req, res) => { <add> assert.doesNotThrow(() => { <add> res.removeHeader('header1', 1); <add> }); <add> res.write('abc'); <add> assert.throws(() => { <add> res.removeHeader('header2', 2); <add> }, /Can't remove headers after they are sent/); <add> res.end(); <add>}); <add> <add>server.listen(0, () => { <add> http.get({port: server.address().port}, () => { <add> server.close(); <add> }); <add>});
2
Javascript
Javascript
add error handling
7cb835aac44e34058f3909e5f5f06eb1f0b5c503
<ide><path>client/index.js <ide> app$({ history, location: appLocation }) <ide> .doOnNext(title => document.title = title) <ide> .subscribe(() => {}); <ide> <add> appStore$ <add> .pluck('err') <add> .filter(err => !!err) <add> .distinctUntilChanged() <add> .subscribe(err => console.error(err)); <add> <ide> synchroniseHistory( <ide> history, <ide> updateLocation, <ide><path>common/app/routes/Hikes/flux/Actions.js <ide> export default Actions({ <ide> } <ide> }; <ide> }) <del> .catch(err => { <del> console.error(err); <del> }); <add> .catch(err => Observable.just({ <add> transform(state) { return { ...state, err }; } <add> })); <ide> }, <ide> <ide> toggleQuestions() { <ide> export default Actions({ <ide> }) <ide> .delay(300) <ide> .startWith(correctAnswer) <del> .catch(err => { <del> console.error(err); <del> return Observable.just({ <del> set: { <del> error: err <del> } <del> }); <del> }); <add> .catch(err => Observable.just({ <add> transform(state) { return { ...state, err }; } <add> })); <ide> } <ide> }); <ide><path>common/app/routes/Jobs/flux/Actions.js <ide> import { Actions } from 'thundercats'; <ide> import store from 'store'; <add>import { Observable } from 'rx'; <add> <ide> import { nameSpacedTransformer } from '../../../../utils'; <ide> <ide> const assign = Object.assign; <ide> export default Actions({ <ide> }; <ide> } <ide> })) <del> .catch(err => ({ <add> .catch(err => Observable.just({ <ide> transform(state) { <ide> return { ...state, err }; <ide> } <ide> export default Actions({ <ide> return { ...state, currentJob: job }; <ide> }) <ide> })) <del> .catch(err => ({ <add> .catch(err => Observable.just({ <ide> transform(state) { <ide> return { ...state, err }; <ide> } <ide> export default Actions({ <ide> return { ...state, jobs }; <ide> }) <ide> })) <del> .catch(err => ({ <add> .catch(err => Observable.just({ <ide> transform(state) { <del> return { state, err }; <add> return { ...state, err }; <ide> } <ide> })); <ide> }, <ide> export default Actions({ <ide> })) <ide> }; <ide> }) <del> .catch(err => ({ <add> .catch(err => Observable.just({ <ide> transform(state) { <ide> return { ...state, err }; <ide> }
3
Python
Python
resolve merge issue
b6b5230dcd5ec934afa9c45dec29a79bd812c372
<ide><path>glances/plugins/glances_load.py <ide> def update_views(self): <ide> # Call the father's method <ide> GlancesPlugin.update_views(self) <ide> <del> if self.views != {}: <del> # Add specifics informations <add> # Add specifics informations <add> try: <ide> # Alert and log <ide> self.views['min15']['decoration'] = self.get_alert_log(self.stats['min15'], max=100 * self.stats['cpucore']) <ide> # Alert only <ide> self.views['min5']['decoration'] = self.get_alert(self.stats['min5'], max=100 * self.stats['cpucore']) <add> except KeyError: <add> # try/except mandatory for Windows compatibility (no load stats) <add> pass <ide> <ide> def msg_curse(self, args=None): <ide> """Return the dict to display in the curse interface."""
1
Python
Python
fix tuple error message
ea8e2edf17fed647037109f712672a44f5a66ac9
<ide><path>keras/utils/generic_utils.py <ide> def deserialize_keras_object(identifier, module_objects=None, <ide> else: <ide> fn = module_objects.get(function_name) <ide> if fn is None: <del> raise ValueError('Unknown ' + printable_module_name, <add> raise ValueError('Unknown ' + printable_module_name + <ide> ':' + function_name) <ide> return fn <ide> else:
1
Mixed
Text
add changelog for
86433b8d5f1a7d28e0bb6ceeaf824e67acf4b759
<ide><path>actionpack/CHANGELOG.md <add>* Allows ActionDispatch::Request::LOCALHOST to match any IPv4 127.0.0.0/8 <add> loopback address. <add> <add> *Earl St Sauver*, *Sven Riedel* <add> <ide> * Preserve original path in `ShowExceptions` middleware by stashing it as <ide> `env["action_dispatch.original_path"]` <ide> <ide><path>actionpack/test/dispatch/request_test.rb <ide> class RequestCGI < BaseRequestTest <ide> class LocalhostTest < BaseRequestTest <ide> test "IPs that match localhost" do <ide> request = stub_request("REMOTE_IP" => "127.1.1.1", "REMOTE_ADDR" => "127.1.1.1") <del> assert_equal !!request.local?, true <add> assert request.local? <ide> end <ide> end <ide>
2
Python
Python
fix typo in test
525f7988416f9d944f5993a793f999f91e8685f8
<ide><path>spacy/tests/pipeline/test_pipe_methods.py <ide> def test_disable_pipes_context_restore(nlp, name): <ide> """Test that a disabled component stays disabled after running the context manager.""" <ide> nlp.add_pipe("new_pipe", name=name) <ide> assert nlp.has_pipe(name) <del> nlp.disable_pipes(name) <add> nlp.disable_pipe(name) <ide> assert not nlp.has_pipe(name) <ide> with nlp.select_pipes(disable=name): <ide> assert not nlp.has_pipe(name)
1
Ruby
Ruby
install tap if needed
61b48d8557042519889860a0f57a66fb233e1d23
<ide><path>Library/Homebrew/formulary.rb <ide> def get_formula(spec, alias_path: nil) <ide> end <ide> <ide> def load_file <add> tap.install unless tap.installed? <add> <ide> super <ide> rescue MethodDeprecatedError => e <ide> e.issues_url = tap.issues_url || tap.to_s <ide><path>Library/Homebrew/test/formulary_spec.rb <ide> class Wrong#{described_class.class_s(formula_name)} < Formula <ide> end <ide> end <ide> <del> it "raises an error if the Formula is not available" do <add> it "raises an error if the Formula is not available after tapping" do <add> expect_any_instance_of(Tap).to receive(:install) <ide> expect { <ide> described_class.to_rack("a/b/#{formula_name}") <ide> }.to raise_error(TapFormulaUnavailableError)
2
Text
Text
correct cli --volumes-from description
4d0b88c52f896fe159fe2b1dfd7bdb8116c31da3
<ide><path>docs/sources/reference/commandline/cli.md <ide> schema. <ide> <ide> > **Note:** `docker build` will return a `no such file or directory` error <ide> > if the file or directory does not exist in the uploaded context. This may <del>> happen if there is no context, or if you specify a file that is elsewhere <add>> happen if there is no context, or if you specify a file that is elsewhere <ide> > on the Host system. The context is limited to the current directory (and its <ide> > children) for security reasons, and to ensure repeatable builds on remote <ide> > Docker hosts. This is also the reason why `ADD ../file` will not work. <ide> Current filters: <ide> <ide> $ sudo docker ps -a --filter 'exited=0' <ide> CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES <del> ea09c3c82f6e registry:latest /srv/run.sh 2 weeks ago Exited (0) 2 weeks ago 127.0.0.1:5000->5000/tcp desperate_leakey <del> 106ea823fe4e fedora:latest /bin/sh -c 'bash -l' 2 weeks ago Exited (0) 2 weeks ago determined_albattani <add> ea09c3c82f6e registry:latest /srv/run.sh 2 weeks ago Exited (0) 2 weeks ago 127.0.0.1:5000->5000/tcp desperate_leakey <add> 106ea823fe4e fedora:latest /bin/sh -c 'bash -l' 2 weeks ago Exited (0) 2 weeks ago determined_albattani <ide> 48ee228c9464 fedora:20 bash 2 weeks ago Exited (0) 2 weeks ago tender_torvalds <ide> <ide> This shows all the containers that have exited with status of '0' <ide> network and environment of the `redis` container via environment variables. <ide> The `--name` flag will assign the name `console` to the newly created <ide> container. <ide> <del> $ sudo docker run --volumes-from 777f7dc92da7,ba8c0c54f0f2:ro -i -t ubuntu pwd <add> $ sudo docker run --volumes-from 777f7dc92da7 --volumes-from ba8c0c54f0f2:ro -i -t ubuntu pwd <ide> <ide> The `--volumes-from` flag mounts all the defined volumes from the referenced <del>containers. Containers can be specified by a comma separated list or by <del>repetitions of the `--volumes-from` argument. The container ID may be <del>optionally suffixed with `:ro` or `:rw` to mount the volumes in read-only <del>or read-write mode, respectively. By default, the volumes are mounted in <del>the same mode (read write or read only) as the reference container. <add>containers. Containers can be specified by repetitions of the `--volumes-from` <add>argument. The container ID may be optionally suffixed with `:ro` or `:rw` to <add>mount the volumes in read-only or read-write mode, respectively. By default, <add>the volumes are mounted in the same mode (read write or read only) as <add>the reference container. <ide> <ide> The `-a` flag tells `docker run` to bind to the container's `STDIN`, `STDOUT` or <ide> `STDERR`. This makes it possible to manipulate the output and input as needed. <ide> application change: <ide> <ide> #### Restart Policies <ide> <del>Using the `--restart` flag on Docker run you can specify a restart policy for <add>Using the `--restart` flag on Docker run you can specify a restart policy for <ide> how a container should or should not be restarted on exit. <ide> <ide> ** no ** - Do not restart the container when it exits. <ide> how a container should or should not be restarted on exit. <ide> <ide> ** always ** - Always restart the container reguardless of the exit status. <ide> <del>You can also specify the maximum amount of times Docker will try to restart the <add>You can also specify the maximum amount of times Docker will try to restart the <ide> container when using the ** on-failure ** policy. The default is that Docker will try forever to restart the container. <ide> <ide> $ sudo docker run --restart=always redis <ide> <del>This will run the `redis` container with a restart policy of ** always ** so that if <add>This will run the `redis` container with a restart policy of ** always ** so that if <ide> the container exits, Docker will restart it. <ide> <ide> $ sudo docker run --restart=on-failure:10 redis <ide> <del>This will run the `redis` container with a restart policy of ** on-failure ** and a <del>maximum restart count of 10. If the `redis` container exits with a non-zero exit <add>This will run the `redis` container with a restart policy of ** on-failure ** and a <add>maximum restart count of 10. If the `redis` container exits with a non-zero exit <ide> status more than 10 times in a row Docker will abort trying to restart the container. <ide> <ide> ## save <ide> more details on finding shared images from the command line. <ide> -a, --attach=false Attach container's STDOUT and STDERR and forward all signals to the process <ide> -i, --interactive=false Attach container's STDIN <ide> <del>When run on a container that has already been started, <add>When run on a container that has already been started, <ide> takes no action and succeeds unconditionally. <ide> <ide> ## stop
1
Text
Text
add v3.19.0 to changelog
4d3eaaeef4659f22d6dc3bf5678c4b78aa16dd27
<ide><path>CHANGELOG.md <ide> # Ember Changelog <ide> <del>### v3.19.0-beta.4 (May 12, 2020) <add>### v3.19.0 (May 26, 2020) <ide> <add>- [#18982](https://github.com/emberjs/ember.js/pull/18982) / [#18913](https://github.com/emberjs/ember.js/pull/18913) [BUGFIX] Update rendering engine to latest version. <add> - Add a compile time error when passing arguments to regular HTML elements (e.g. `<a @foo=`) <add> - Fix: Rerender an `{{#each`s block only when the specific item has changed <ide> - [#18958](https://github.com/emberjs/ember.js/pull/18958) [BUGFIX] Ensure AST transforms using `in-element` work properly. <ide> - [#18960](https://github.com/emberjs/ember.js/pull/18960) [BUGFIX] More assertions for Application lifecycle methods <del> <del>### v3.19-0.beta.3 (May 4, 2020) <del> <del>- [#18941](https://github.com/emberjs/ember.js/pull/18941) [BUGFIX] Update rendering engine to latest version. <del> - Reduce template size growth to near 3.16 levels (still ~ 3% higher than 3.16) <del> - Ensures destroyable items added to an `{{#each` after initial render are invoked properly <del> - Fixes an issue with key collisions in `{{#each` <del> <del>### v3.19.0-beta.2 (April 27, 2020) <del> <del>- [#18913](https://github.com/emberjs/ember.js/pull/18913) [BUGFIX] Update to glimmer-vm 0.51.0. <ide> - [#18919](https://github.com/emberjs/ember.js/pull/18919) [BUGFIX] Add error for modifier manager without capabilities. <del> <del>### v3.19.0-beta.1 (April 14, 2020) <del> <ide> - [#18828](https://github.com/emberjs/ember.js/pull/18828) [BUGFIX] Prepend 'TODO: ' to 'Replace this with your real tests' comments in generated tests <ide> - [#18353](https://github.com/emberjs/ember.js/pull/18353) [BUGFIX] Improve `fn` & `on` undefined callback message <ide> - [#18824](https://github.com/emberjs/ember.js/pull/18824) [CLEANUP] Remove deprecated private `window.ENV`
1
Javascript
Javascript
use stackedsetmap for better performance
2ff9b53754305989b26735d3a57582a92e1b4586
<ide><path>lib/optimize/ModuleConcatenationPlugin.js <ide> const ModuleHotAcceptDependency = require("../dependencies/ModuleHotAcceptDepend <ide> const ModuleHotDeclineDependency = require("../dependencies/ModuleHotDeclineDependency"); <ide> const ConcatenatedModule = require("./ConcatenatedModule"); <ide> const HarmonyCompatibilityDependency = require("../dependencies/HarmonyCompatibilityDependency"); <add>const StackedSetMap = require("../util/StackedSetMap"); <ide> <ide> const formatBailoutReason = msg => { <ide> return "ModuleConcatenation bailout: " + msg; <ide> class ModuleConcatenationPlugin { <ide> } <ide> if(!currentConfiguration.isEmpty()) { <ide> concatConfigurations.push(currentConfiguration); <del> for(const module of currentConfiguration.modules) { <add> for(const module of currentConfiguration.getModules()) { <ide> if(module !== currentConfiguration.rootModule) <ide> usedAsInner.add(module); <ide> } <ide> class ModuleConcatenationPlugin { <ide> for(const concatConfiguration of concatConfigurations) { <ide> if(usedModules.has(concatConfiguration.rootModule)) <ide> continue; <del> const newModule = new ConcatenatedModule(concatConfiguration.rootModule, Array.from(concatConfiguration.modules)); <del> concatConfiguration.sortWarnings(); <del> for(const warning of concatConfiguration.warnings) { <add> const modules = concatConfiguration.getModules(); <add> const newModule = new ConcatenatedModule(concatConfiguration.rootModule, modules); <add> for(const warning of concatConfiguration.getWarningsSorted()) { <ide> newModule.optimizationBailout.push((requestShortener) => { <ide> const reason = getBailoutReason(warning[0], requestShortener); <ide> const reasonWithPrefix = reason ? ` (<- ${reason})` : ""; <ide> class ModuleConcatenationPlugin { <ide> }); <ide> } <ide> const chunks = concatConfiguration.rootModule.getChunks(); <del> for(const m of concatConfiguration.modules) { <add> for(const m of modules) { <ide> usedModules.add(m); <ide> chunks.forEach(chunk => chunk.removeModule(m)); <ide> } <ide> class ModuleConcatenationPlugin { <ide> } <ide> <ide> class ConcatConfiguration { <del> constructor(rootModule) { <add> constructor(rootModule, cloneFrom) { <ide> this.rootModule = rootModule; <del> this.modules = new Set([rootModule]); <del> this.warnings = new Map(); <add> if(cloneFrom) { <add> this.modules = cloneFrom.modules.createChild(5); <add> this.warnings = cloneFrom.warnings.createChild(5); <add> } else { <add> this.modules = new StackedSetMap(); <add> this.modules.add(rootModule); <add> this.warnings = new StackedSetMap(); <add> } <ide> } <ide> <ide> add(module) { <ide> class ConcatConfiguration { <ide> this.warnings.set(module, problem); <ide> } <ide> <del> sortWarnings() { <del> this.warnings = new Map(Array.from(this.warnings).sort((a, b) => { <add> getWarningsSorted() { <add> return new Map(this.warnings.asPairArray().sort((a, b) => { <ide> const ai = a[0].identifier(); <ide> const bi = b[0].identifier(); <ide> if(ai < bi) return -1; <ide> class ConcatConfiguration { <ide> })); <ide> } <ide> <add> getModules() { <add> return this.modules.asArray(); <add> } <add> <ide> clone() { <del> const clone = new ConcatConfiguration(this.rootModule); <del> for(const module of this.modules) <del> clone.add(module); <del> for(const pair of this.warnings) <del> clone.addWarning(pair[0], pair[1]); <del> return clone; <add> return new ConcatConfiguration(this.rootModule, this); <ide> } <ide> <ide> set(config) { <ide> this.rootModule = config.rootModule; <del> this.modules = new Set(config.modules); <del> this.warnings = new Map(config.warnings); <add> this.modules = config.modules; <add> this.warnings = config.warnings; <ide> } <ide> } <ide> <ide><path>lib/util/StackedSetMap.js <ide> class StackedSetMap { <ide> return new Set(Array.from(this.map.entries()).map(pair => pair[0])); <ide> } <ide> <add> asArray() { <add> this._compress(); <add> return Array.from(this.map.entries()).map(pair => pair[0]); <add> } <add> <ide> asMap() { <ide> this._compress(); <ide> return new Map(this.map.entries()); <ide> } <ide> <add> asPairArray() { <add> this._compress(); <add> return Array.from(this.map.entries()); <add> } <add> <ide> createChild() { <ide> return new StackedSetMap(this.stack); <ide> }
2
Text
Text
update spanish translation of "about vim"
265d1df54038b77812461d27ff3d1ed47fce7732
<ide><path>guide/spanish/vim/basic-usage/index.md <ide> localeTitle: Uso básico <ide> <ide> ## Acerca de Vim <ide> <del>Vim es el editor de texto que se usa básicamente en el modo CLI. Pero ahora el editor también está disponible en varias versiones. Allí tienen También GVIM que es la versión gráfica de VIM. vi fue el editor principal, luego se mejoró y lo llamó VI mejorado Vim. <add>Vim es un editor de texto que se usa básicamente en el modo CLI. Pero ahora el editor también está disponible en varias versiones. También existe la versión gráfica de VIM, llamada GVIM, que tiene todas las funcionalidades principales pero permite a los usuarios a añadir menús y barras de herramientas adicionales. vi fue el editor principal, luego se mejoró y lo llamó VI mejorado Vim.
1