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
add link to hub pr docs in model cards
284fc6c0bbf8176ab86e94d41ae1b78080ce7f58
<ide><path>model_cards/README.md <ide> You can either: <ide> <ide> **What if you want to create or update a model card for a model you don't have write access to?** <ide> <del>In that case, given that we don't have a Pull request system yet on huggingface.co (🤯), <del>you can open an issue here, post the card's content, and tag the model author(s) and/or the Hugging Face team. <del> <del>We might implement a more seamless process at some point, so your early feedback is precious! <del>Please let us know of any suggestion. <add>In that case, you can open a [Hub pull request](https://github.com/huggingface/hub-docs/blob/4befd62fb1f7502c9143ab228da538abb2de10e4/docs/hub/repositories-pull-requests-discussions.md)! Check out the [announcement](https://huggingface.co/blog/community-update) of this feature for more details 🤗. <ide> <ide> ### What happened to the model cards here? <ide>
1
Ruby
Ruby
add qlplugins check to guess_cask_version
778d5df6d4bf44b832a4d15ade004227cac1b328
<ide><path>Library/Homebrew/unversioned_cask_checker.rb <ide> def all_versions <ide> <ide> sig { returns(T.nilable(String)) } <ide> def guess_cask_version <del> if apps.empty? && pkgs.empty? <del> opoo "Cask #{cask} does not contain any apps or PKG installers." <add> if apps.empty? && pkgs.empty? && qlplugins.empty? <add> opoo "Cask #{cask} does not contain any apps, qlplugins or PKG installers." <ide> return <ide> end <ide>
1
Python
Python
limit k of top_k to the size of the dynamic input
fcb152bf5207f0e2218fcf1e4bf0460aae3eda80
<ide><path>research/object_detection/meta_architectures/center_net_meta_arch.py <ide> def top_k_feature_map_locations(feature_map, max_pool_kernel_size=3, k=100, <ide> feature_map_peaks_flat, axis=1, output_type=tf.dtypes.int32), axis=-1) <ide> else: <ide> feature_map_peaks_flat = tf.reshape(feature_map_peaks, [batch_size, -1]) <del> scores, peak_flat_indices = tf.math.top_k(feature_map_peaks_flat, k=k) <add> safe_k = tf.minimum(k, tf.shape(feature_map_peaks_flat)[1]) <add> scores, peak_flat_indices = tf.math.top_k(feature_map_peaks_flat, <add> k=safe_k) <ide> <ide> # Get x, y and channel indices corresponding to the top indices in the flat <ide> # array. <ide><path>research/object_detection/meta_architectures/center_net_meta_arch_tf2_test.py <ide> def graph_fn(): <ide> np.testing.assert_array_equal([1, 0, 2], x_inds[1]) <ide> np.testing.assert_array_equal([1, 0, 0], channel_inds[1]) <ide> <add> def test_top_k_feature_map_locations_very_large(self): <add> feature_map_np = np.zeros((2, 3, 3, 2), dtype=np.float32) <add> feature_map_np[0, 2, 0, 1] = 1.0 <add> <add> def graph_fn(): <add> feature_map = tf.constant(feature_map_np) <add> feature_map.set_shape(tf.TensorShape([2, 3, None, 2])) <add> scores, y_inds, x_inds, channel_inds = ( <add> cnma.top_k_feature_map_locations( <add> feature_map, max_pool_kernel_size=1, k=3000)) <add> return scores, y_inds, x_inds, channel_inds <add> # graph execution will fail if large k's are not handled. <add> scores, y_inds, x_inds, channel_inds = self.execute(graph_fn, []) <add> self.assertEqual(scores.shape, (2, 18)) <add> self.assertEqual(y_inds.shape, (2, 18)) <add> self.assertEqual(x_inds.shape, (2, 18)) <add> self.assertEqual(channel_inds.shape, (2, 18)) <add> <ide> def test_top_k_feature_map_locations_per_channel(self): <ide> feature_map_np = np.zeros((2, 3, 3, 2), dtype=np.float32) <ide> feature_map_np[0, 2, 0, 0] = 1.0 # Selected.
2
Go
Go
add tests for autoacceptoption
c544649874bfecf2e6b8a00a0b25db309d81cf94
<ide><path>api/client/swarm/init.go <ide> func newInitCommand(dockerCli *client.DockerCli) *cobra.Command { <ide> }, <ide> } <ide> <del> flags := cmd.Flags() <add> flags = cmd.Flags() <ide> flags.Var(&opts.listenAddr, flagListenAddr, "Listen address") <ide> flags.Var(&opts.autoAccept, flagAutoAccept, "Auto acceptance policy (worker, manager, or none)") <ide> flags.StringVar(&opts.secret, flagSecret, "", "Set secret value needed to accept nodes into cluster") <ide><path>api/client/swarm/opts.go <ide> type AutoAcceptOption struct { <ide> // String prints a string representation of this option <ide> func (o *AutoAcceptOption) String() string { <ide> keys := []string{} <del> for key := range o.values { <del> keys = append(keys, key) <add> for key, value := range o.values { <add> keys = append(keys, fmt.Sprintf("%s=%v", strings.ToLower(key), value)) <ide> } <del> return strings.Join(keys, " ") <add> return strings.Join(keys, ", ") <ide> } <ide> <ide> // Set sets a new value on this option <ide><path>api/client/swarm/opts_test.go <ide> import ( <ide> "testing" <ide> <ide> "github.com/docker/docker/pkg/testutil/assert" <add> "github.com/docker/engine-api/types/swarm" <ide> ) <ide> <ide> func TestNodeAddrOptionSetHostAndPort(t *testing.T) { <ide> func TestNodeAddrOptionSetInvalidFormat(t *testing.T) { <ide> opt := NewListenAddrOption() <ide> assert.Error(t, opt.Set("http://localhost:4545"), "Invalid url") <ide> } <add> <add>func TestAutoAcceptOptionSetWorker(t *testing.T) { <add> opt := NewAutoAcceptOption() <add> assert.NilError(t, opt.Set("worker")) <add> assert.Equal(t, opt.values[WORKER], true) <add>} <add> <add>func TestAutoAcceptOptionSetManager(t *testing.T) { <add> opt := NewAutoAcceptOption() <add> assert.NilError(t, opt.Set("manager")) <add> assert.Equal(t, opt.values[MANAGER], true) <add>} <add> <add>func TestAutoAcceptOptionSetInvalid(t *testing.T) { <add> opt := NewAutoAcceptOption() <add> assert.Error(t, opt.Set("bogus"), "must be one of") <add>} <add> <add>func TestAutoAcceptOptionSetNone(t *testing.T) { <add> opt := NewAutoAcceptOption() <add> assert.NilError(t, opt.Set("none")) <add> assert.Equal(t, opt.values[MANAGER], false) <add> assert.Equal(t, opt.values[WORKER], false) <add>} <add> <add>func TestAutoAcceptOptionSetConflict(t *testing.T) { <add> opt := NewAutoAcceptOption() <add> assert.NilError(t, opt.Set("manager")) <add> assert.Error(t, opt.Set("none"), "value NONE is incompatible with MANAGER") <add> <add> opt = NewAutoAcceptOption() <add> assert.NilError(t, opt.Set("none")) <add> assert.Error(t, opt.Set("worker"), "value NONE is incompatible with WORKER") <add>} <add> <add>func TestAutoAcceptOptionPoliciesDefault(t *testing.T) { <add> opt := NewAutoAcceptOption() <add> secret := "thesecret" <add> <add> policies := opt.Policies(&secret) <add> assert.Equal(t, len(policies), 2) <add> assert.Equal(t, policies[0], swarm.Policy{ <add> Role: WORKER, <add> Autoaccept: true, <add> Secret: &secret, <add> }) <add> assert.Equal(t, policies[1], swarm.Policy{ <add> Role: MANAGER, <add> Autoaccept: false, <add> Secret: &secret, <add> }) <add>} <add> <add>func TestAutoAcceptOptionPoliciesWithManager(t *testing.T) { <add> opt := NewAutoAcceptOption() <add> secret := "thesecret" <add> <add> assert.NilError(t, opt.Set("manager")) <add> <add> policies := opt.Policies(&secret) <add> assert.Equal(t, len(policies), 2) <add> assert.Equal(t, policies[0], swarm.Policy{ <add> Role: WORKER, <add> Autoaccept: false, <add> Secret: &secret, <add> }) <add> assert.Equal(t, policies[1], swarm.Policy{ <add> Role: MANAGER, <add> Autoaccept: true, <add> Secret: &secret, <add> }) <add>} <add> <add>func TestAutoAcceptOptionString(t *testing.T) { <add> opt := NewAutoAcceptOption() <add> assert.NilError(t, opt.Set("manager")) <add> assert.NilError(t, opt.Set("worker")) <add> <add> repr := opt.String() <add> assert.Contains(t, repr, "worker=true") <add> assert.Contains(t, repr, "manager=true") <add>}
3
Ruby
Ruby
make git audit only --new-formula only
4efc1276b3d6594338b34bc53701f74b9d4214b7
<ide><path>Library/Homebrew/dev-cmd/audit.rb <ide> def audit_deps <ide> problem "Dependency #{dep} does not define option #{opt.name.inspect}" <ide> end <ide> <del> problem "Don't use git as a dependency (it's always available)" if dep.name == "git" <add> problem "Don't use git as a dependency (it's always available)" if @new_formula && dep.name == "git" <ide> <ide> problem "Dependency '#{dep.name}' is marked as :run. Remove :run; it is a no-op." if dep.tags.include?(:run) <ide>
1
Go
Go
allow reattempt of overlay network sbox join
4f8c645173d461012d470c56727b20ab0739e878
<ide><path>libnetwork/drivers/overlay/overlay.go <ide> func Init(dc driverapi.DriverCallback, config map[string]interface{}) error { <ide> } <ide> } <ide> <del> d.restoreEndpoints() <add> if err := d.restoreEndpoints(); err != nil { <add> logrus.Warnf("Failure during overlay endpoints restore: %v", err) <add> } <add> <add> // If an error happened when the network join the sandbox during the endpoints restore <add> // we should reset it now along with the once variable, so that subsequent endpoint joins <add> // outside of the restore path can potentially fix the network join and succeed. <add> for nid, n := range d.networks { <add> if n.initErr != nil { <add> logrus.Infof("resetting init error and once variable for network %s after unsuccesful endpoint restore: %v", nid, n.initErr) <add> n.initErr = nil <add> n.once = &sync.Once{} <add> } <add> } <ide> <ide> return dc.RegisterDriver(networkType, d, c) <ide> }
1
Mixed
Javascript
add returnonexit option
6aff62fcb326bd3d51dbbcf91e63f6d2150488b3
<ide><path>doc/api/wasi.md <ide> added: v13.3.0 <ide> sandbox directory structure. The string keys of `preopens` are treated as <ide> directories within the sandbox. The corresponding values in `preopens` are <ide> the real paths to those directories on the host machine. <add> * `returnOnExit` {boolean} By default, WASI applications terminate the Node.js <add> process via the `__wasi_proc_exit()` function. Setting this option to `true` <add> causes `wasi.start()` to return the exit code rather than terminate the <add> process. **Default:** `false`. <ide> <ide> ### `wasi.start(instance)` <ide> <!-- YAML <ide><path>lib/wasi.js <ide> const { <ide> } = require('internal/errors').codes; <ide> const { emitExperimentalWarning } = require('internal/util'); <ide> const { WASI: _WASI } = internalBinding('wasi'); <add>const kExitCode = Symbol('exitCode'); <ide> const kSetMemory = Symbol('setMemory'); <ide> const kStarted = Symbol('started'); <ide> <ide> class WASI { <ide> if (options === null || typeof options !== 'object') <ide> throw new ERR_INVALID_ARG_TYPE('options', 'object', options); <ide> <del> const { env, preopens } = options; <add> const { env, preopens, returnOnExit = false } = options; <ide> let { args = [] } = options; <ide> <ide> if (ArrayIsArray(args)) <ide> class WASI { <ide> throw new ERR_INVALID_ARG_TYPE('options.preopens', 'Object', preopens); <ide> } <ide> <add> if (typeof returnOnExit !== 'boolean') { <add> throw new ERR_INVALID_ARG_TYPE( <add> 'options.returnOnExit', 'boolean', returnOnExit); <add> } <add> <ide> const wrap = new _WASI(args, envPairs, preopenArray); <ide> <ide> for (const prop in wrap) { <ide> wrap[prop] = FunctionPrototypeBind(wrap[prop], wrap); <ide> } <ide> <add> if (returnOnExit) { <add> wrap.proc_exit = FunctionPrototypeBind(wasiReturnOnProcExit, this); <add> } <add> <ide> this[kSetMemory] = wrap._setMemory; <ide> delete wrap._setMemory; <ide> this.wasiImport = wrap; <ide> this[kStarted] = false; <add> this[kExitCode] = 0; <ide> } <ide> <ide> start(instance) { <ide> class WASI { <ide> this[kStarted] = true; <ide> this[kSetMemory](memory); <ide> <del> if (exports._start) <del> exports._start(); <del> else if (exports.__wasi_unstable_reactor_start) <del> exports.__wasi_unstable_reactor_start(); <add> try { <add> if (exports._start) <add> exports._start(); <add> else if (exports.__wasi_unstable_reactor_start) <add> exports.__wasi_unstable_reactor_start(); <add> } catch (err) { <add> if (err !== kExitCode) { <add> throw err; <add> } <add> } <add> <add> return this[kExitCode]; <ide> } <ide> } <ide> <ide> <ide> module.exports = { WASI }; <add> <add> <add>function wasiReturnOnProcExit(rval) { <add> // If __wasi_proc_exit() does not terminate the process, an assertion is <add> // triggered in the wasm runtime. Node can sidestep the assertion and return <add> // an exit code by recording the exit code, and throwing a JavaScript <add> // exception that WebAssembly cannot catch. <add> this[kExitCode] = rval; <add> throw kExitCode; <add>} <ide><path>test/wasi/test-return-on-exit.js <add>// Flags: --experimental-wasi-unstable-preview1 --experimental-wasm-bigint <add>'use strict'; <add>const common = require('../common'); <add>const assert = require('assert'); <add>const fs = require('fs'); <add>const path = require('path'); <add>const { WASI } = require('wasi'); <add>const wasi = new WASI({ returnOnExit: true }); <add>const importObject = { wasi_snapshot_preview1: wasi.wasiImport }; <add>const wasmDir = path.join(__dirname, 'wasm'); <add>const modulePath = path.join(wasmDir, 'exitcode.wasm'); <add>const buffer = fs.readFileSync(modulePath); <add> <add>(async () => { <add> const { instance } = await WebAssembly.instantiate(buffer, importObject); <add> <add> assert.strictEqual(wasi.start(instance), 120); <add>})().then(common.mustCall()); <ide><path>test/wasi/test-wasi-options-validation.js <ide> assert.throws(() => { new WASI({ env: 'fhqwhgads' }); }, <ide> assert.throws(() => { new WASI({ preopens: 'fhqwhgads' }); }, <ide> { code: 'ERR_INVALID_ARG_TYPE', message: /\bpreopens\b/ }); <ide> <add>// If returnOnExit is not a boolean and not undefined, it should throw. <add>assert.throws(() => { new WASI({ returnOnExit: 'fhqwhgads' }); }, <add> { code: 'ERR_INVALID_ARG_TYPE', message: /\breturnOnExit\b/ }); <add> <ide> // If options is provided, but not an object, the constructor should throw. <ide> [null, 'foo', '', 0, NaN, Symbol(), true, false, () => {}].forEach((value) => { <ide> assert.throws(() => { new WASI(value); },
4
PHP
PHP
fix return comment
50a0be8ad3de589bc7be08eae71d31945dacda0f
<ide><path>src/Illuminate/Foundation/Console/PolicyMakeCommand.php <ide> protected function buildClass($name) <ide> * Replace the user model for the given stub. <ide> * <ide> * @param string $stub <del> * @return string mixed <add> * @return string <ide> */ <ide> protected function replaceUserModelNamespace($stub) <ide> {
1
PHP
PHP
return $this from setter
6be9b8374e8a2af6fc2fef34de541329c2fa3ed6
<ide><path>src/Controller/ComponentRegistry.php <ide> public function getController(): Controller <ide> * Set the controller associated with the collection. <ide> * <ide> * @param \Cake\Controller\Controller $controller Controller instance. <del> * @return void <add> * @return $this <ide> */ <del> public function setController(Controller $controller): void <add> public function setController(Controller $controller) <ide> { <ide> $this->_Controller = $controller; <ide> $this->setEventManager($controller->getEventManager()); <add> <add> return $this; <ide> } <ide> <ide> /**
1
PHP
PHP
pluck
e3bc23b952466ceca259d028af2e3c8c0695b21c
<ide><path>src/Illuminate/Support/Collection.php <ide> public function last(callable $callback = null, $default = null) <ide> } <ide> <ide> /** <del> * Get an array with the values of a given key. <add> * Get the values of a given key. <ide> * <ide> * @param string $value <ide> * @param string $key
1
Text
Text
remove duplicated period in link
3a23203255e75cdfca608f19be93b08bb260692e
<ide><path>README.md <ide> Contributing to Docker <ide> [![Jenkins Build Status](https://jenkins.dockerproject.org/job/Docker%20Master/badge/icon)](https://jenkins.dockerproject.org/job/Docker%20Master/) <ide> <ide> Want to hack on Docker? Awesome! We have [instructions to help you get <del>started contributing code or documentation.](https://docs.docker.com/project/who-written-for/). <add>started contributing code or documentation](https://docs.docker.com/project/who-written-for/). <ide> <ide> These instructions are probably not perfect, please let us know if anything <ide> feels wrong or incomplete. Better yet, submit a PR and improve them yourself.
1
Java
Java
harmonize use of generate
97986b368a42f858a8f6ee84e2ca4a79f17e7410
<ide><path>spring-beans/src/main/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessor.java <ide> public void applyTo(CodeContribution contribution) { <ide> boolean isRequired = isRequired(element); <ide> Member member = element.getMember(); <ide> analyzeMember(contribution, member); <del> contribution.statements().addStatement(this.generator.writeInjection(member, isRequired)); <add> contribution.statements().addStatement(this.generator.generateInjection(member, isRequired)); <ide> }); <ide> } <ide> <ide><path>spring-beans/src/main/java/org/springframework/beans/factory/generator/BeanParameterGenerator.java <ide> import org.springframework.util.ObjectUtils; <ide> <ide> /** <del> * Support for writing parameters. <add> * Support for generating parameters. <ide> * <ide> * @author Stephane Nicoll <ide> * @since 6.0 <ide> public final class BeanParameterGenerator { <ide> <ide> private final ResolvableTypeGenerator typeGenerator = new ResolvableTypeGenerator(); <ide> <del> private final BiConsumer<BeanDefinition, Builder> innerBeanDefinitionWriter; <add> private final BiConsumer<BeanDefinition, Builder> innerBeanDefinitionGenerator; <ide> <ide> <ide> /** <del> * Create an instance with the callback to use to write an inner bean <add> * Create an instance with the callback to use to generate an inner bean <ide> * definition. <del> * @param innerBeanDefinitionWriter the inner bean definition writer <add> * @param innerBeanDefinitionGenerator the inner bean definition generator <ide> */ <del> public BeanParameterGenerator(BiConsumer<BeanDefinition, Builder> innerBeanDefinitionWriter) { <del> this.innerBeanDefinitionWriter = innerBeanDefinitionWriter; <add> public BeanParameterGenerator(BiConsumer<BeanDefinition, Builder> innerBeanDefinitionGenerator) { <add> this.innerBeanDefinitionGenerator = innerBeanDefinitionGenerator; <ide> } <ide> <ide> /** <ide> public BeanParameterGenerator() { <ide> <ide> <ide> /** <del> * Write the specified parameter {@code value}. <add> * Generate the specified parameter {@code value}. <ide> * @param value the value of the parameter <ide> * @return the value of the parameter <ide> */ <del> public CodeBlock writeParameterValue(@Nullable Object value) { <del> return writeParameterValue(value, () -> ResolvableType.forInstance(value)); <add> public CodeBlock generateParameterValue(@Nullable Object value) { <add> return generateParameterValue(value, () -> ResolvableType.forInstance(value)); <ide> } <ide> <ide> /** <del> * Write the specified parameter {@code value}. <add> * Generate the specified parameter {@code value}. <ide> * @param value the value of the parameter <ide> * @param parameterType the type of the parameter <ide> * @return the value of the parameter <ide> */ <del> public CodeBlock writeParameterValue(@Nullable Object value, Supplier<ResolvableType> parameterType) { <add> public CodeBlock generateParameterValue(@Nullable Object value, Supplier<ResolvableType> parameterType) { <ide> Builder code = CodeBlock.builder(); <del> writeParameterValue(code, value, parameterType); <add> generateParameterValue(code, value, parameterType); <ide> return code.build(); <ide> } <ide> <ide> /** <del> * Write the parameter types of the specified {@link Executable}. <add> * Generate the parameter types of the specified {@link Executable}. <ide> * @param executable the executable <ide> * @return the parameter types of the executable as a comma separated list <ide> */ <del> public CodeBlock writeExecutableParameterTypes(Executable executable) { <add> public CodeBlock generateExecutableParameterTypes(Executable executable) { <ide> Class<?>[] parameterTypes = Arrays.stream(executable.getParameters()) <ide> .map(Parameter::getType).toArray(Class<?>[]::new); <ide> return CodeBlock.of(Arrays.stream(parameterTypes).map(d -> "$T.class") <ide> .collect(Collectors.joining(", ")), (Object[]) parameterTypes); <ide> } <ide> <del> private void writeParameterValue(Builder code, @Nullable Object value, Supplier<ResolvableType> parameterTypeSupplier) { <add> private void generateParameterValue(Builder code, @Nullable Object value, Supplier<ResolvableType> parameterTypeSupplier) { <ide> if (value == null) { <ide> code.add("null"); <ide> return; <ide> } <ide> ResolvableType parameterType = parameterTypeSupplier.get(); <ide> if (parameterType.isArray()) { <ide> code.add("new $T { ", parameterType.toClass()); <del> code.add(writeAll(Arrays.asList(ObjectUtils.toObjectArray(value)), <add> code.add(generateAll(Arrays.asList(ObjectUtils.toObjectArray(value)), <ide> item -> parameterType.getComponentType())); <ide> code.add(" }"); <ide> } <ide> else if (value instanceof List<?> list) { <ide> Class<?> listType = (value instanceof ManagedList ? ManagedList.class : List.class); <ide> code.add("$T.of(", listType); <ide> ResolvableType collectionType = parameterType.as(List.class).getGenerics()[0]; <del> code.add(writeAll(list, item -> collectionType)); <add> code.add(generateAll(list, item -> collectionType)); <ide> code.add(")"); <ide> } <ide> } <ide> else if (value instanceof Set<?> set) { <ide> Class<?> setType = (value instanceof ManagedSet ? ManagedSet.class : Set.class); <ide> code.add("$T.of(", setType); <ide> ResolvableType collectionType = parameterType.as(Set.class).getGenerics()[0]; <del> code.add(writeAll(set, item -> collectionType)); <add> code.add(generateAll(set, item -> collectionType)); <ide> code.add(")"); <ide> } <ide> } <ide> else if (value instanceof Map<?, ?> map) { <ide> parameters.add(mapKey); <ide> parameters.add(mapValue); <ide> }); <del> code.add(writeAll(parameters, ResolvableType::forInstance)); <add> code.add(generateAll(parameters, ResolvableType::forInstance)); <ide> code.add(")"); <ide> } <ide> } <ide> else if (value instanceof ResolvableType) { <ide> code.add(this.typeGenerator.generateTypeFor((ResolvableType) value)); <ide> } <ide> else if (value instanceof BeanDefinition) { <del> this.innerBeanDefinitionWriter.accept((BeanDefinition) value, code); <add> this.innerBeanDefinitionGenerator.accept((BeanDefinition) value, code); <ide> } <ide> else if (value instanceof BeanReference) { <ide> code.add("new $T($S)", RuntimeBeanReference.class, ((BeanReference) value).getBeanName()); <ide> else if (value instanceof BeanReference) { <ide> } <ide> } <ide> <del> private <T> CodeBlock writeAll(Iterable<T> items, Function<T, ResolvableType> elementType) { <add> private <T> CodeBlock generateAll(Iterable<T> items, Function<T, ResolvableType> elementType) { <ide> MultiCodeBlock multi = new MultiCodeBlock(); <ide> items.forEach(item -> multi.add(code -> <del> writeParameterValue(code, item, () -> elementType.apply(item)))); <add> generateParameterValue(code, item, () -> elementType.apply(item)))); <ide> return multi.join(", "); <ide> } <ide> <ide><path>spring-beans/src/main/java/org/springframework/beans/factory/generator/DefaultBeanInstantiationGenerator.java <ide> import org.springframework.util.ClassUtils; <ide> <ide> /** <del> * Write the necessary statements to instantiate a bean. <add> * Generate the necessary statements to instantiate a bean. <ide> * <ide> * @author Stephane Nicoll <ide> * @see BeanInstantiationContribution <ide> class DefaultBeanInstantiationGenerator { <ide> * @return a code contribution that provides an initialized bean instance <ide> */ <ide> public CodeContribution generateBeanInstantiation(RuntimeHints runtimeHints) { <del> DefaultCodeContribution contribution = new DefaultCodeContribution(runtimeHints); <del> contribution.protectedAccess().analyze(this.instanceCreator, this.beanInstanceOptions); <add> DefaultCodeContribution codeContribution = new DefaultCodeContribution(runtimeHints); <add> codeContribution.protectedAccess().analyze(this.instanceCreator, this.beanInstanceOptions); <ide> if (this.instanceCreator instanceof Constructor<?> constructor) { <del> writeBeanInstantiation(contribution, constructor); <add> generateBeanInstantiation(codeContribution, constructor); <ide> } <ide> else if (this.instanceCreator instanceof Method method) { <del> writeBeanInstantiation(contribution, method); <add> generateBeanInstantiation(codeContribution, method); <ide> } <del> return contribution; <add> return codeContribution; <ide> } <ide> <del> private void writeBeanInstantiation(CodeContribution contribution, Constructor<?> constructor) { <add> private void generateBeanInstantiation(CodeContribution codeContribution, Constructor<?> constructor) { <ide> Class<?> declaringType = ClassUtils.getUserClass(constructor.getDeclaringClass()); <ide> boolean innerClass = isInnerClass(declaringType); <ide> boolean multiStatements = !this.contributions.isEmpty(); <ide> private void writeBeanInstantiation(CodeContribution contribution, Constructor<? <ide> code.add("$T::new", declaringType); <ide> } <ide> } <del> contribution.statements().addStatement(code.build()); <add> codeContribution.statements().addStatement(code.build()); <ide> return; <ide> } <del> contribution.runtimeHints().reflection().registerConstructor(constructor, <add> codeContribution.runtimeHints().reflection().registerConstructor(constructor, <ide> hint -> hint.withMode(ExecutableMode.INTROSPECT)); <ide> code.add("(instanceContext) ->"); <ide> branch(multiStatements, () -> code.beginControlFlow(""), () -> code.add(" ")); <ide> if (multiStatements) { <ide> code.add("$T bean = ", declaringType); <ide> } <del> code.add(this.injectionGenerator.writeInstantiation(constructor)); <del> contribution.statements().addStatement(code.build()); <add> code.add(this.injectionGenerator.generateInstantiation(constructor)); <add> codeContribution.statements().addStatement(code.build()); <ide> <ide> if (multiStatements) { <del> for (BeanInstantiationContribution contributor : this.contributions) { <del> contributor.applyTo(contribution); <add> for (BeanInstantiationContribution contribution : this.contributions) { <add> contribution.applyTo(codeContribution); <ide> } <del> contribution.statements().addStatement("return bean") <add> codeContribution.statements().addStatement("return bean") <ide> .add(codeBlock -> codeBlock.unindent().add("}")); <ide> } <ide> } <ide> private static boolean isInnerClass(Class<?> type) { <ide> return type.isMemberClass() && !Modifier.isStatic(type.getModifiers()); <ide> } <ide> <del> private void writeBeanInstantiation(CodeContribution contribution, Method method) { <add> private void generateBeanInstantiation(CodeContribution codeContribution, Method method) { <ide> // Factory method can be introspected <del> contribution.runtimeHints().reflection().registerMethod(method, <add> codeContribution.runtimeHints().reflection().registerMethod(method, <ide> hint -> hint.withMode(ExecutableMode.INTROSPECT)); <ide> List<Class<?>> parameterTypes = new ArrayList<>(Arrays.asList(method.getParameterTypes())); <ide> boolean multiStatements = !this.contributions.isEmpty(); <ide> private void writeBeanInstantiation(CodeContribution contribution, Method method <ide> () -> code.add("$T", declaringType), <ide> () -> code.add("beanFactory.getBean($T.class)", declaringType)); <ide> code.add(".$L()", method.getName()); <del> contribution.statements().addStatement(code.build()); <add> codeContribution.statements().addStatement(code.build()); <ide> return; <ide> } <ide> code.add("(instanceContext) ->"); <ide> branch(multiStatements, () -> code.beginControlFlow(""), () -> code.add(" ")); <ide> if (multiStatements) { <ide> code.add("$T bean = ", method.getReturnType()); <ide> } <del> code.add(this.injectionGenerator.writeInstantiation(method)); <del> contribution.statements().addStatement(code.build()); <add> code.add(this.injectionGenerator.generateInstantiation(method)); <add> codeContribution.statements().addStatement(code.build()); <ide> if (multiStatements) { <del> for (BeanInstantiationContribution contributor : this.contributions) { <del> contributor.applyTo(contribution); <add> for (BeanInstantiationContribution contribution : this.contributions) { <add> contribution.applyTo(codeContribution); <ide> } <del> contribution.statements().addStatement("return bean") <add> codeContribution.statements().addStatement("return bean") <ide> .add(codeBlock -> codeBlock.unindent().add("}")); <ide> } <ide> } <ide><path>spring-beans/src/main/java/org/springframework/beans/factory/generator/InjectionGenerator.java <ide> import org.springframework.util.ReflectionUtils; <ide> <ide> /** <del> * Generate the necessary code to {@link #writeInstantiation(Executable) <del> * create a bean instance} or {@link #writeInjection(Member, boolean) <add> * Generate the necessary code to {@link #generateInstantiation(Executable) <add> * create a bean instance} or {@link #generateInjection(Member, boolean) <ide> * inject dependencies}. <ide> * <p/> <ide> * The generator assumes a number of variables to be accessible: <ide> public class InjectionGenerator { <ide> <ide> <ide> /** <del> * Write the necessary code to instantiate an object using the specified <add> * Generate the necessary code to instantiate an object using the specified <ide> * {@link Executable}. The code is suitable to be assigned to a variable <ide> * or used as a {@literal return} statement. <ide> * @param creator the executable to invoke to create an instance of the <ide> * requested object <ide> * @return the code to instantiate an object using the specified executable <ide> */ <del> public CodeBlock writeInstantiation(Executable creator) { <add> public CodeBlock generateInstantiation(Executable creator) { <ide> if (creator instanceof Constructor<?> constructor) { <del> return write(constructor); <add> return generateConstructorInstantiation(constructor); <ide> } <ide> if (creator instanceof Method method) { <del> return writeMethodInstantiation(method); <add> return generateMethodInstantiation(method); <ide> } <ide> throw new IllegalArgumentException("Could not handle creator " + creator); <ide> } <ide> <ide> /** <del> * Write the code to inject a value resolved by {@link BeanInstanceContext} <add> * Generate the code to inject a value resolved by {@link BeanInstanceContext} <ide> * in the specified {@link Member}. <ide> * @param member the field or method to inject <ide> * @param required whether the value is required <ide> * @return a statement that injects a value to the specified member <ide> * @see #getProtectedAccessInjectionOptions(Member) <ide> */ <del> public CodeBlock writeInjection(Member member, boolean required) { <add> public CodeBlock generateInjection(Member member, boolean required) { <ide> if (member instanceof Method method) { <del> return writeMethodInjection(method, required); <add> return generateMethodInjection(method, required); <ide> } <ide> if (member instanceof Field field) { <del> return writeFieldInjection(field, required); <add> return generateFieldInjection(field, required); <ide> } <ide> throw new IllegalArgumentException("Could not handle member " + member); <ide> } <ide> public Options getProtectedAccessInjectionOptions(Member member) { <ide> throw new IllegalArgumentException("Could not handle member " + member); <ide> } <ide> <del> private CodeBlock write(Constructor<?> creator) { <add> private CodeBlock generateConstructorInstantiation(Constructor<?> creator) { <ide> Builder code = CodeBlock.builder(); <ide> Class<?> declaringType = ClassUtils.getUserClass(creator.getDeclaringClass()); <ide> boolean innerClass = isInnerClass(declaringType); <ide> private static boolean isInnerClass(Class<?> type) { <ide> return type.isMemberClass() && !Modifier.isStatic(type.getModifiers()); <ide> } <ide> <del> private CodeBlock writeMethodInstantiation(Method injectionPoint) { <add> private CodeBlock generateMethodInstantiation(Method injectionPoint) { <ide> if (injectionPoint.getParameterCount() == 0) { <ide> Builder code = CodeBlock.builder(); <ide> Class<?> declaringType = injectionPoint.getDeclaringClass(); <ide> private CodeBlock writeMethodInstantiation(Method injectionPoint) { <ide> code.add(".$L()", injectionPoint.getName()); <ide> return code.build(); <ide> } <del> return write(injectionPoint, code -> code.add(".create(beanFactory, (attributes) ->"), true); <add> return generateMethodInvocation(injectionPoint, code -> code.add(".create(beanFactory, (attributes) ->"), true); <ide> } <ide> <del> private CodeBlock writeMethodInjection(Method injectionPoint, boolean required) { <add> private CodeBlock generateMethodInjection(Method injectionPoint, boolean required) { <ide> Consumer<Builder> attributesResolver = code -> { <ide> if (required) { <ide> code.add(".invoke(beanFactory, (attributes) ->"); <ide> private CodeBlock writeMethodInjection(Method injectionPoint, boolean required) <ide> code.add(".resolve(beanFactory, false).ifResolved((attributes) ->"); <ide> } <ide> }; <del> return write(injectionPoint, attributesResolver, false); <add> return generateMethodInvocation(injectionPoint, attributesResolver, false); <ide> } <ide> <del> private CodeBlock write(Method injectionPoint, Consumer<Builder> attributesResolver, boolean instantiation) { <add> private CodeBlock generateMethodInvocation(Method injectionPoint, Consumer<Builder> attributesResolver, boolean instantiation) { <ide> Builder code = CodeBlock.builder(); <ide> code.add("instanceContext"); <ide> if (!instantiation) { <ide> code.add(".method($S, ", injectionPoint.getName()); <del> code.add(this.parameterGenerator.writeExecutableParameterTypes(injectionPoint)); <add> code.add(this.parameterGenerator.generateExecutableParameterTypes(injectionPoint)); <ide> code.add(")\n").indent().indent(); <ide> } <ide> attributesResolver.accept(code); <ide> private CodeBlock write(Method injectionPoint, Consumer<Builder> attributesResol <ide> return code.build(); <ide> } <ide> <del> CodeBlock writeFieldInjection(Field injectionPoint, boolean required) { <add> CodeBlock generateFieldInjection(Field injectionPoint, boolean required) { <ide> Builder code = CodeBlock.builder(); <ide> code.add("instanceContext.field($S, $T.class", injectionPoint.getName(), injectionPoint.getType()); <ide> code.add(")\n").indent().indent(); <ide><path>spring-beans/src/test/java/org/springframework/beans/factory/generator/BeanParameterGeneratorTests.java <ide> import org.springframework.core.ResolvableType; <ide> import org.springframework.core.io.ResourceLoader; <ide> import org.springframework.javapoet.support.CodeSnippet; <add>import org.springframework.lang.Nullable; <ide> import org.springframework.util.ReflectionUtils; <ide> <ide> import static org.assertj.core.api.Assertions.assertThat; <ide> class BeanParameterGeneratorTests { <ide> private final BeanParameterGenerator generator = new BeanParameterGenerator(); <ide> <ide> @Test <del> void writeCharArray() { <add> void generateCharArray() { <ide> char[] value = new char[] { 'v', 'a', 'l', 'u', 'e' }; <del> assertThat(write(value, ResolvableType.forArrayComponent(ResolvableType.forClass(char.class)))) <add> assertThat(generate(value, ResolvableType.forArrayComponent(ResolvableType.forClass(char.class)))) <ide> .isEqualTo("new char[] { 'v', 'a', 'l', 'u', 'e' }"); <ide> } <ide> <ide> @Test <del> void writeStringArray() { <add> void generateStringArray() { <ide> String[] value = new String[] { "a", "test" }; <del> assertThat(write(value, ResolvableType.forArrayComponent(ResolvableType.forClass(String.class)))) <add> assertThat(generate(value, ResolvableType.forArrayComponent(ResolvableType.forClass(String.class)))) <ide> .isEqualTo("new String[] { \"a\", \"test\" }"); <ide> } <ide> <ide> @Test <del> void writeStringList() { <add> void generateStringList() { <ide> List<String> value = List.of("a", "test"); <ide> CodeSnippet code = codeSnippet(value, ResolvableType.forClassWithGenerics(List.class, String.class)); <ide> assertThat(code.getSnippet()).isEqualTo( <ide> void writeStringList() { <ide> } <ide> <ide> @Test <del> void writeStringManagedList() { <add> void generateStringManagedList() { <ide> ManagedList<String> value = ManagedList.of("a", "test"); <ide> CodeSnippet code = codeSnippet(value, ResolvableType.forClassWithGenerics(List.class, String.class)); <ide> assertThat(code.getSnippet()).isEqualTo( <ide> void writeStringManagedList() { <ide> } <ide> <ide> @Test <del> void writeEmptyList() { <add> void generateEmptyList() { <ide> List<String> value = List.of(); <ide> CodeSnippet code = codeSnippet(value, ResolvableType.forClassWithGenerics(List.class, String.class)); <ide> assertThat(code.getSnippet()).isEqualTo("Collections.emptyList()"); <ide> assertThat(code.hasImport(Collections.class)).isTrue(); <ide> } <ide> <ide> @Test <del> void writeStringSet() { <add> void generateStringSet() { <ide> Set<String> value = Set.of("a", "test"); <ide> CodeSnippet code = codeSnippet(value, ResolvableType.forClassWithGenerics(Set.class, String.class)); <ide> assertThat(code.getSnippet()).startsWith("Set.of(").contains("a").contains("test"); <ide> assertThat(code.hasImport(Set.class)).isTrue(); <ide> } <ide> <ide> @Test <del> void writeStringManagedSet() { <add> void generateStringManagedSet() { <ide> Set<String> value = ManagedSet.of("a", "test"); <ide> CodeSnippet code = codeSnippet(value, ResolvableType.forClassWithGenerics(Set.class, String.class)); <ide> assertThat(code.getSnippet()).isEqualTo( <ide> void writeStringManagedSet() { <ide> } <ide> <ide> @Test <del> void writeEmptySet() { <add> void generateEmptySet() { <ide> Set<String> value = Set.of(); <ide> CodeSnippet code = codeSnippet(value, ResolvableType.forClassWithGenerics(Set.class, String.class)); <ide> assertThat(code.getSnippet()).isEqualTo("Collections.emptySet()"); <ide> assertThat(code.hasImport(Collections.class)).isTrue(); <ide> } <ide> <ide> @Test <del> void writeMap() { <add> void generateMap() { <ide> Map<String, Object> value = new LinkedHashMap<>(); <ide> value.put("name", "Hello"); <ide> value.put("counter", 42); <del> assertThat(write(value)).isEqualTo("Map.of(\"name\", \"Hello\", \"counter\", 42)"); <add> assertThat(generate(value)).isEqualTo("Map.of(\"name\", \"Hello\", \"counter\", 42)"); <ide> } <ide> <ide> @Test <del> void writeMapWithEnum() { <add> void generateMapWithEnum() { <ide> Map<String, Object> value = new HashMap<>(); <ide> value.put("unit", ChronoUnit.DAYS); <del> assertThat(write(value)).isEqualTo("Map.of(\"unit\", ChronoUnit.DAYS)"); <add> assertThat(generate(value)).isEqualTo("Map.of(\"unit\", ChronoUnit.DAYS)"); <ide> } <ide> <ide> @Test <del> void writeEmptyMap() { <del> assertThat(write(Map.of())).isEqualTo("Map.of()"); <add> void generateEmptyMap() { <add> assertThat(generate(Map.of())).isEqualTo("Map.of()"); <ide> } <ide> <ide> @Test <del> void writeString() { <del> assertThat(write("test", ResolvableType.forClass(String.class))).isEqualTo("\"test\""); <add> void generateString() { <add> assertThat(generate("test", ResolvableType.forClass(String.class))).isEqualTo("\"test\""); <ide> } <ide> <ide> @Test <del> void writeCharEscapeBackslash() { <del> assertThat(write('\\', ResolvableType.forType(char.class))).isEqualTo("'\\\\'"); <add> void generateCharEscapeBackslash() { <add> assertThat(generate('\\', ResolvableType.forType(char.class))).isEqualTo("'\\\\'"); <ide> } <ide> <ide> @ParameterizedTest <ide> @MethodSource("primitiveValues") <del> void writePrimitiveValue(Object value, String parameter) { <del> assertThat(write(value, ResolvableType.forClass(value.getClass()))).isEqualTo(parameter); <add> void generatePrimitiveValue(Object value, String parameter) { <add> assertThat(generate(value, ResolvableType.forClass(value.getClass()))).isEqualTo(parameter); <ide> } <ide> <ide> private static Stream<Arguments> primitiveValues() { <ide> private static Stream<Arguments> primitiveValues() { <ide> } <ide> <ide> @Test <del> void writeEnum() { <del> assertThat(write(ChronoUnit.DAYS, ResolvableType.forClass(ChronoUnit.class))) <add> void generateEnum() { <add> assertThat(generate(ChronoUnit.DAYS, ResolvableType.forClass(ChronoUnit.class))) <ide> .isEqualTo("ChronoUnit.DAYS"); <ide> } <ide> <ide> @Test <del> void writeClass() { <del> assertThat(write(Integer.class, ResolvableType.forClass(Class.class))) <add> void generateClass() { <add> assertThat(generate(Integer.class, ResolvableType.forClass(Class.class))) <ide> .isEqualTo("Integer.class"); <ide> } <ide> <ide> @Test <del> void writeResolvableType() { <add> void generateResolvableType() { <ide> ResolvableType type = ResolvableType.forClassWithGenerics(Consumer.class, Integer.class); <del> assertThat(write(type, type)) <add> assertThat(generate(type, type)) <ide> .isEqualTo("ResolvableType.forClassWithGenerics(Consumer.class, Integer.class)"); <ide> } <ide> <ide> @Test <del> void writeExecutableParameterTypesWithConstructor() { <add> void generateExecutableParameterTypesWithConstructor() { <ide> Constructor<?> constructor = TestSample.class.getDeclaredConstructors()[0]; <del> assertThat(CodeSnippet.process(this.generator.writeExecutableParameterTypes(constructor))) <add> assertThat(CodeSnippet.process(this.generator.generateExecutableParameterTypes(constructor))) <ide> .isEqualTo("String.class, ResourceLoader.class"); <ide> } <ide> <ide> @Test <del> void writeExecutableParameterTypesWithNoArgConstructor() { <add> void generateExecutableParameterTypesWithNoArgConstructor() { <ide> Constructor<?> constructor = BeanParameterGeneratorTests.class.getDeclaredConstructors()[0]; <del> assertThat(CodeSnippet.process(this.generator.writeExecutableParameterTypes(constructor))) <add> assertThat(CodeSnippet.process(this.generator.generateExecutableParameterTypes(constructor))) <ide> .isEmpty(); <ide> } <ide> <ide> @Test <del> void writeExecutableParameterTypesWithMethod() { <add> void generateExecutableParameterTypesWithMethod() { <ide> Method method = ReflectionUtils.findMethod(TestSample.class, "createBean", String.class, Integer.class); <del> assertThat(CodeSnippet.process(this.generator.writeExecutableParameterTypes(method))) <add> assertThat(CodeSnippet.process(this.generator.generateExecutableParameterTypes(method))) <ide> .isEqualTo("String.class, Integer.class"); <ide> } <ide> <ide> @Test <del> void writeNull() { <del> assertThat(write(null)).isEqualTo("null"); <add> void generateNull() { <add> assertThat(generate(null)).isEqualTo("null"); <ide> } <ide> <ide> @Test <del> void writeBeanReference() { <add> void generateBeanReference() { <ide> BeanReference beanReference = mock(BeanReference.class); <ide> given(beanReference.getBeanName()).willReturn("testBean"); <del> assertThat(write(beanReference)).isEqualTo("new RuntimeBeanReference(\"testBean\")"); <add> assertThat(generate(beanReference)).isEqualTo("new RuntimeBeanReference(\"testBean\")"); <ide> } <ide> <ide> @Test <del> void writeBeanDefinitionCallsConsumer() { <add> void generateBeanDefinitionCallsConsumer() { <ide> BeanParameterGenerator customGenerator = new BeanParameterGenerator( <ide> ((beanDefinition, builder) -> builder.add("test"))); <del> assertThat(CodeSnippet.process(customGenerator.writeParameterValue(new RootBeanDefinition()))).isEqualTo("test"); <add> assertThat(CodeSnippet.process(customGenerator.generateParameterValue( <add> new RootBeanDefinition()))).isEqualTo("test"); <ide> } <ide> <ide> @Test <del> void writeBeanDefinitionWithoutConsumerFails() { <add> void generateBeanDefinitionWithoutConsumerFails() { <ide> BeanParameterGenerator customGenerator = new BeanParameterGenerator(); <ide> assertThatIllegalStateException().isThrownBy(() -> customGenerator <del> .writeParameterValue(new RootBeanDefinition())); <add> .generateParameterValue(new RootBeanDefinition())); <ide> } <ide> <ide> @Test <del> void writeUnsupportedParameter() { <del> assertThatIllegalArgumentException().isThrownBy(() -> write(new StringWriter())) <add> void generateUnsupportedParameter() { <add> assertThatIllegalArgumentException().isThrownBy(() -> generate(new StringWriter())) <ide> .withMessageContaining(StringWriter.class.getName()); <ide> } <ide> <del> private String write(Object value) { <del> return CodeSnippet.process(this.generator.writeParameterValue(value)); <add> private String generate(@Nullable Object value) { <add> return CodeSnippet.process(this.generator.generateParameterValue(value)); <ide> } <ide> <del> private String write(Object value, ResolvableType resolvableType) { <add> private String generate(Object value, ResolvableType resolvableType) { <ide> return codeSnippet(value, resolvableType).getSnippet(); <ide> } <ide> <ide> private CodeSnippet codeSnippet(Object value, ResolvableType resolvableType) { <del> return CodeSnippet.of(this.generator.writeParameterValue(value, () -> resolvableType)); <add> return CodeSnippet.of(this.generator.generateParameterValue(value, () -> resolvableType)); <ide> } <ide> <ide> <ide><path>spring-beans/src/test/java/org/springframework/beans/factory/generator/InjectionGeneratorTests.java <ide> class InjectionGeneratorTests { <ide> private final ProtectedAccess protectedAccess = new ProtectedAccess(); <ide> <ide> @Test <del> void writeInstantiationForConstructorWithNoArgUseShortcut() { <add> void generateInstantiationForConstructorWithNoArgUseShortcut() { <ide> Constructor<?> constructor = SimpleBean.class.getDeclaredConstructors()[0]; <del> assertThat(writeInstantiation(constructor).lines()) <add> assertThat(generateInstantiation(constructor).lines()) <ide> .containsExactly("new InjectionGeneratorTests.SimpleBean()"); <ide> } <ide> <ide> @Test <del> void writeInstantiationForConstructorWithNonGenericParameter() { <add> void generateInstantiationForConstructorWithNonGenericParameter() { <ide> Constructor<?> constructor = SimpleConstructorBean.class.getDeclaredConstructors()[0]; <del> assertThat(writeInstantiation(constructor).lines()).containsExactly( <add> assertThat(generateInstantiation(constructor).lines()).containsExactly( <ide> "instanceContext.create(beanFactory, (attributes) -> new InjectionGeneratorTests.SimpleConstructorBean(attributes.get(0), attributes.get(1)))"); <ide> } <ide> <ide> @Test <del> void writeInstantiationForConstructorWithGenericParameter() { <add> void generateInstantiationForConstructorWithGenericParameter() { <ide> Constructor<?> constructor = GenericConstructorBean.class.getDeclaredConstructors()[0]; <del> assertThat(writeInstantiation(constructor).lines()).containsExactly( <add> assertThat(generateInstantiation(constructor).lines()).containsExactly( <ide> "instanceContext.create(beanFactory, (attributes) -> new InjectionGeneratorTests.GenericConstructorBean(attributes.get(0)))"); <ide> } <ide> <ide> @Test <del> void writeInstantiationForAmbiguousConstructor() throws Exception { <add> void generateInstantiationForAmbiguousConstructor() throws Exception { <ide> Constructor<?> constructor = AmbiguousConstructorBean.class.getDeclaredConstructor(String.class, Number.class); <del> assertThat(writeInstantiation(constructor).lines()).containsExactly( <add> assertThat(generateInstantiation(constructor).lines()).containsExactly( <ide> "instanceContext.create(beanFactory, (attributes) -> new InjectionGeneratorTests.AmbiguousConstructorBean(attributes.get(0, String.class), attributes.get(1, Number.class)))"); <ide> } <ide> <ide> @Test <del> void writeInstantiationForConstructorInInnerClass() { <add> void generateInstantiationForConstructorInInnerClass() { <ide> Constructor<?> constructor = InnerClass.class.getDeclaredConstructors()[0]; <del> assertThat(writeInstantiation(constructor).lines()).containsExactly( <add> assertThat(generateInstantiation(constructor).lines()).containsExactly( <ide> "beanFactory.getBean(InjectionGeneratorTests.SimpleConstructorBean.class).new InnerClass()"); <ide> } <ide> <ide> @Test <del> void writeInstantiationForMethodWithNoArgUseShortcut() { <del> assertThat(writeInstantiation(method(SimpleBean.class, "name")).lines()).containsExactly( <add> void generateInstantiationForMethodWithNoArgUseShortcut() { <add> assertThat(generateInstantiation(method(SimpleBean.class, "name")).lines()).containsExactly( <ide> "beanFactory.getBean(InjectionGeneratorTests.SimpleBean.class).name()"); <ide> } <ide> <ide> @Test <del> void writeInstantiationForStaticMethodWithNoArgUseShortcut() { <del> assertThat(writeInstantiation(method(SimpleBean.class, "number")).lines()).containsExactly( <add> void generateInstantiationForStaticMethodWithNoArgUseShortcut() { <add> assertThat(generateInstantiation(method(SimpleBean.class, "number")).lines()).containsExactly( <ide> "InjectionGeneratorTests.SimpleBean.number()"); <ide> } <ide> <ide> @Test <del> void writeInstantiationForMethodWithNonGenericParameter() { <del> assertThat(writeInstantiation(method(SampleBean.class, "source", Integer.class)).lines()).containsExactly( <add> void generateInstantiationForMethodWithNonGenericParameter() { <add> assertThat(generateInstantiation(method(SampleBean.class, "source", Integer.class)).lines()).containsExactly( <ide> "instanceContext.create(beanFactory, (attributes) -> beanFactory.getBean(InjectionGeneratorTests.SampleBean.class).source(attributes.get(0)))"); <ide> } <ide> <ide> @Test <del> void writeInstantiationForStaticMethodWithNonGenericParameter() { <del> assertThat(writeInstantiation(method(SampleBean.class, "staticSource", Integer.class)).lines()).containsExactly( <add> void generateInstantiationForStaticMethodWithNonGenericParameter() { <add> assertThat(generateInstantiation(method(SampleBean.class, "staticSource", Integer.class)).lines()).containsExactly( <ide> "instanceContext.create(beanFactory, (attributes) -> InjectionGeneratorTests.SampleBean.staticSource(attributes.get(0)))"); <ide> } <ide> <ide> @Test <del> void writeInstantiationForMethodWithGenericParameters() { <del> assertThat(writeInstantiation(method(SampleBean.class, "source", ObjectProvider.class)).lines()).containsExactly( <add> void generateInstantiationForMethodWithGenericParameters() { <add> assertThat(generateInstantiation(method(SampleBean.class, "source", ObjectProvider.class)).lines()).containsExactly( <ide> "instanceContext.create(beanFactory, (attributes) -> beanFactory.getBean(InjectionGeneratorTests.SampleBean.class).source(attributes.get(0)))"); <ide> } <ide> <ide> @Test <del> void writeInjectionForUnsupportedMember() { <del> assertThatIllegalArgumentException().isThrownBy(() -> writeInjection(mock(Member.class), false)); <add> void generateInjectionForUnsupportedMember() { <add> assertThatIllegalArgumentException().isThrownBy(() -> generateInjection(mock(Member.class), false)); <ide> } <ide> <ide> @Test <del> void writeInjectionForNonRequiredMethodWithNonGenericParameters() { <add> void generateInjectionForNonRequiredMethodWithNonGenericParameters() { <ide> Method method = method(SampleBean.class, "sourceAndCounter", String.class, Integer.class); <del> assertThat(writeInjection(method, false)).isEqualTo(""" <add> assertThat(generateInjection(method, false)).isEqualTo(""" <ide> instanceContext.method("sourceAndCounter", String.class, Integer.class) <ide> .resolve(beanFactory, false).ifResolved((attributes) -> bean.sourceAndCounter(attributes.get(0), attributes.get(1)))"""); <ide> } <ide> <ide> @Test <del> void writeInjectionForRequiredMethodWithGenericParameter() { <add> void generateInjectionForRequiredMethodWithGenericParameter() { <ide> Method method = method(SampleBean.class, "nameAndCounter", String.class, ObjectProvider.class); <del> assertThat(writeInjection(method, true)).isEqualTo(""" <add> assertThat(generateInjection(method, true)).isEqualTo(""" <ide> instanceContext.method("nameAndCounter", String.class, ObjectProvider.class) <ide> .invoke(beanFactory, (attributes) -> bean.nameAndCounter(attributes.get(0), attributes.get(1)))"""); <ide> } <ide> <ide> @Test <del> void writeInjectionForNonRequiredMethodWithGenericParameter() { <add> void generateInjectionForNonRequiredMethodWithGenericParameter() { <ide> Method method = method(SampleBean.class, "nameAndCounter", String.class, ObjectProvider.class); <del> assertThat(writeInjection(method, false)).isEqualTo(""" <add> assertThat(generateInjection(method, false)).isEqualTo(""" <ide> instanceContext.method("nameAndCounter", String.class, ObjectProvider.class) <ide> .resolve(beanFactory, false).ifResolved((attributes) -> bean.nameAndCounter(attributes.get(0), attributes.get(1)))"""); <ide> } <ide> <ide> @Test <del> void writeInjectionForRequiredField() { <add> void generateInjectionForRequiredField() { <ide> Field field = field(SampleBean.class, "counter"); <del> assertThat(writeInjection(field, true)).isEqualTo(""" <add> assertThat(generateInjection(field, true)).isEqualTo(""" <ide> instanceContext.field("counter", Integer.class) <ide> .invoke(beanFactory, (attributes) -> bean.counter = attributes.get(0))"""); <ide> } <ide> <ide> @Test <del> void writeInjectionForNonRequiredField() { <add> void generateInjectionForNonRequiredField() { <ide> Field field = field(SampleBean.class, "counter"); <del> assertThat(writeInjection(field, false)).isEqualTo(""" <add> assertThat(generateInjection(field, false)).isEqualTo(""" <ide> instanceContext.field("counter", Integer.class) <ide> .resolve(beanFactory, false).ifResolved((attributes) -> bean.counter = attributes.get(0))"""); <ide> } <ide> <ide> @Test <del> void writeInjectionForRequiredPrivateField() { <add> void generateInjectionForRequiredPrivateField() { <ide> Field field = field(SampleBean.class, "source"); <del> assertThat(writeInjection(field, true)).isEqualTo(""" <add> assertThat(generateInjection(field, true)).isEqualTo(""" <ide> instanceContext.field("source", String.class) <ide> .invoke(beanFactory, (attributes) -> { <ide> Field sourceField = ReflectionUtils.findField(InjectionGeneratorTests.SampleBean.class, "source", String.class); <ide> private Field field(Class<?> type, String name) { <ide> return field; <ide> } <ide> <del> private String writeInstantiation(Executable creator) { <del> return CodeSnippet.process(code -> code.add(new InjectionGenerator().writeInstantiation(creator))); <add> private String generateInstantiation(Executable creator) { <add> return CodeSnippet.process(code -> code.add(new InjectionGenerator().generateInstantiation(creator))); <ide> } <ide> <del> private String writeInjection(Member member, boolean required) { <del> return CodeSnippet.process(code -> code.add(new InjectionGenerator().writeInjection(member, required))); <add> private String generateInjection(Member member, boolean required) { <add> return CodeSnippet.process(code -> code.add(new InjectionGenerator().generateInjection(member, required))); <ide> } <ide> <ide> private void analyzeProtectedAccess(Member member) {
6
PHP
PHP
unskip some tests
71b41ed91cef204283ed3dca105d35baf55fbc03
<ide><path>lib/Cake/Test/Case/View/Helper/HtmlHelperTest.php <ide> public function testImageWithTimestampping() { <ide> * @return void <ide> */ <ide> public function testImageTagWithTheme() { <del> $this->skipIf(!is_writable(WWW_ROOT . 'theme'), 'Cannot write to webroot/theme.'); <add> $this->skipIf(!is_writable(WWW_ROOT), 'Cannot write to webroot.'); <add> $themeExists = is_dir(WWW_ROOT . 'theme'); <ide> <ide> App::uses('File', 'Utility'); <ide> <ide> public function testImageTagWithTheme() { <ide> <ide> $dir = new Folder(WWW_ROOT . 'theme' . DS . 'test_theme'); <ide> $dir->delete(); <add> if (!$themeExists) { <add> $dir = new Folder(WWW_ROOT . 'theme'); <add> $dir->delete(); <add> } <ide> } <ide> <ide> /** <ide> function testScriptAssetFilter() { <ide> * @return void <ide> */ <ide> public function testScriptInTheme() { <del> $this->skipIf(!is_writable(WWW_ROOT . 'theme'), 'Cannot write to webroot/theme.'); <add> $this->skipIf(!is_writable(WWW_ROOT), 'Cannot write to webroot.'); <add> $themeExists = is_dir(WWW_ROOT . 'theme'); <ide> <ide> App::uses('File', 'Utility'); <ide> <ide> public function testScriptInTheme() { <ide> <ide> $Folder = new Folder(WWW_ROOT . 'theme' . DS . 'test_theme'); <ide> $Folder->delete(); <del> App::build(); <add> <add> if (!$themeExists) { <add> $dir = new Folder(WWW_ROOT . 'theme'); <add> $dir->delete(); <add> } <ide> } <ide> <ide> /** <ide><path>lib/Cake/Test/Case/View/Helper/RssHelperTest.php <ide> public function testItemCdata() { <ide> * @return void <ide> */ <ide> public function testItemEnclosureLength() { <del> $tmpFile = $this->_getWwwTmpFile(); <del> <del> if (file_exists($tmpFile)) { <del> unlink($tmpFile); <add> if (!is_writable(WWW_ROOT)) { <add> $this->markTestSkipped(__d('cake_dev', 'Webroot is not writable.')); <ide> } <add> $testExists = is_dir(WWW_ROOT . 'tests'); <add> <add> $tmpFile = WWW_ROOT . 'tests' . DS . 'cakephp.file.test.tmp'; <add> $File = new File($tmpFile, true); <ide> <del> $File = new File($tmpFile, true, '0777'); <ide> $this->assertTrue($File->write('123'), 'Could not write to ' . $tmpFile); <ide> clearstatcache(true, $tmpFile); <ide> <ide> public function testItemEnclosureLength() { <ide> ); <ide> $this->assertTags($result, $expected); <ide> <del> unlink($tmpFile); <del> } <add> $File->delete(); <ide> <del>/** <del> * testTime method <del> * <del> * @return void <del> */ <del> public function testTime() { <add> if (!$testExists) { <add> $Folder = new Folder(WWW_ROOT . 'tests'); <add> $Folder->delete(); <add> } <ide> } <ide> <ide> /** <ide> public function testElementAttrNotInParent() { <ide> $this->assertTags($result, $expected); <ide> } <ide> <del>/** <del> * getWwwTmpFile method <del> * <del> * @param bool $paintSkip <del> * @return void <del> */ <del> function _getWwwTmpFile() { <del> $path = WWW_ROOT . 'tests' . DS; <del> $tmpFile = $path. 'cakephp.file.test.tmp'; <del> if (is_writable(dirname($tmpFile)) && (!file_exists($tmpFile) || is_writable($tmpFile))) { <del> return $tmpFile; <del> }; <del> <del> $message = __d('cake_dev', '%s is not writeable', $path ); <del> $this->markTestSkipped($message); <del> return false; <del> } <ide> }
2
Java
Java
update integration tests for reactor-netty
ba47d06cbb6a07bdc57042da9dd59daafe5c5aae
<ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestMappingMessageConversionIntegrationTests.java <ide> import org.springframework.http.ResponseEntity; <ide> import org.springframework.http.codec.json.Jackson2JsonEncoder; <ide> import org.springframework.http.server.reactive.ZeroCopyIntegrationTests; <del>import org.springframework.http.server.reactive.bootstrap.ReactorHttpServer; <ide> import org.springframework.web.bind.annotation.GetMapping; <ide> import org.springframework.web.bind.annotation.PostMapping; <ide> import org.springframework.web.bind.annotation.RequestBody; <ide> import static java.util.Arrays.asList; <ide> import static org.junit.Assert.assertEquals; <ide> import static org.junit.Assert.assertTrue; <del>import static org.junit.Assume.assumeFalse; <ide> import static org.springframework.http.MediaType.APPLICATION_XML; <ide> <ide> /** <ide><path>spring-web/src/test/java/org/springframework/http/server/reactive/FlushingIntegrationTests.java <ide> public void writeAndAutoFlushOnComplete() { <ide> StepVerifier.create(result) <ide> .consumeNextWith(value -> Assert.isTrue(value.length() == 200000)) <ide> .expectComplete() <del> .verify(); <add> .verify(Duration.ofSeconds(5L)); <ide> } <ide> <ide> @Override <ide><path>spring-web/src/test/java/org/springframework/http/server/reactive/ZeroCopyIntegrationTests.java <ide> import java.io.File; <ide> import java.net.URI; <ide> <del>import org.junit.Assume; <ide> import org.junit.Test; <ide> import reactor.core.publisher.Mono; <ide> <ide> <ide> import static org.junit.Assert.assertEquals; <ide> import static org.junit.Assert.assertTrue; <del>import static org.junit.Assume.assumeFalse; <ide> import static org.junit.Assume.assumeTrue; <ide> <ide> /** <ide> protected HttpHandler createHttpHandler() { <ide> @Test <ide> public void zeroCopy() throws Exception { <ide> <del> // SPR-14975 <del> assumeFalse(server instanceof ReactorHttpServer); <del> <ide> // Zero-copy only does not support servlet <ide> assumeTrue(server instanceof ReactorHttpServer || server instanceof UndertowHttpServer); <ide> <ide><path>spring-web/src/test/java/org/springframework/web/client/reactive/WebClientIntegrationTests.java <ide> public void headers() throws Exception { <ide> assertEquals(13L, httpHeaders.getContentLength()); <ide> }) <ide> .expectComplete() <del> .verify(); <add> .verify(Duration.ofSeconds(3)); <ide> <ide> RecordedRequest recordedRequest = server.takeRequest(); <ide> assertEquals(1, server.getRequestCount()); <ide> public void plainText() throws Exception { <ide> StepVerifier.create(result) <ide> .expectNext("Hello Spring!") <ide> .expectComplete() <del> .verify(); <add> .verify(Duration.ofSeconds(3)); <ide> <ide> RecordedRequest recordedRequest = server.takeRequest(); <ide> assertEquals(1, server.getRequestCount()); <ide> public void jsonString() throws Exception { <ide> StepVerifier.create(result) <ide> .expectNext(content) <ide> .expectComplete() <del> .verify(); <add> .verify(Duration.ofSeconds(3)); <ide> <ide> RecordedRequest recordedRequest = server.takeRequest(); <ide> assertEquals(1, server.getRequestCount()); <ide> public void jsonPojoMono() throws Exception { <ide> StepVerifier.create(result) <ide> .consumeNextWith(p -> assertEquals("barbar", p.getBar())) <ide> .expectComplete() <del> .verify(); <add> .verify(Duration.ofSeconds(3)); <ide> <ide> RecordedRequest recordedRequest = server.takeRequest(); <ide> assertEquals(1, server.getRequestCount()); <ide> public void jsonPojoFlux() throws Exception { <ide> .consumeNextWith(p -> assertThat(p.getBar(), Matchers.is("bar1"))) <ide> .consumeNextWith(p -> assertThat(p.getBar(), Matchers.is("bar2"))) <ide> .expectComplete() <del> .verify(); <add> .verify(Duration.ofSeconds(3)); <ide> <ide> RecordedRequest recordedRequest = server.takeRequest(); <ide> assertEquals(1, server.getRequestCount()); <ide> public void postJsonPojo() throws Exception { <ide> StepVerifier.create(result) <ide> .consumeNextWith(p -> assertEquals("BARBAR", p.getBar())) <ide> .expectComplete() <del> .verify(); <add> .verify(Duration.ofSeconds(3)); <ide> <ide> RecordedRequest recordedRequest = server.takeRequest(); <ide> assertEquals(1, server.getRequestCount()); <ide> public void cookies() throws Exception { <ide> StepVerifier.create(result) <ide> .expectNext("test") <ide> .expectComplete() <del> .verify(); <add> .verify(Duration.ofSeconds(3)); <ide> <ide> RecordedRequest recordedRequest = server.takeRequest(); <ide> assertEquals(1, server.getRequestCount()); <ide> public void buildFilter() throws Exception { <ide> StepVerifier.create(result) <ide> .expectNext("Hello Spring!") <ide> .expectComplete() <del> .verify(); <add> .verify(Duration.ofSeconds(3)); <ide> <ide> RecordedRequest recordedRequest = server.takeRequest(); <ide> assertEquals(1, server.getRequestCount()); <ide> public void filter() throws Exception { <ide> StepVerifier.create(result) <ide> .expectNext("Hello Spring!") <ide> .expectComplete() <del> .verify(); <add> .verify(Duration.ofSeconds(3)); <ide> <ide> RecordedRequest recordedRequest = server.takeRequest(); <ide> assertEquals(1, server.getRequestCount());
4
Java
Java
add storage module to fb
6a7567e742f27e8118a84432192bd473f82a49b6
<ide><path>ReactAndroid/src/main/java/com/facebook/react/modules/storage/AsyncStorageModule.java <ide> <ide> public AsyncStorageModule(ReactApplicationContext reactContext) { <ide> super(reactContext); <del> mReactDatabaseSupplier = new ReactDatabaseSupplier(reactContext); <add> mReactDatabaseSupplier = ReactDatabaseSupplier.getInstance(reactContext); <ide> } <ide> <ide> @Override <ide> public void clearSensitiveData() { <ide> // Clear local storage. If fails, crash, since the app is potentially in a bad state and could <ide> // cause a privacy violation. We're still not recovering from this well, but at least the error <ide> // will be reported to the server. <del> clear( <del> new Callback() { <del> @Override <del> public void invoke(Object... args) { <del> if (args.length == 0) { <del> FLog.d(ReactConstants.TAG, "Cleaned AsyncLocalStorage."); <del> return; <del> } <del> // Clearing the database has failed, delete it instead. <del> if (mReactDatabaseSupplier.deleteDatabase()) { <del> FLog.d(ReactConstants.TAG, "Deleted Local Database AsyncLocalStorage."); <del> return; <del> } <del> // Everything failed, crash the app <del> throw new RuntimeException("Clearing and deleting database failed: " + args[0]); <del> } <del> }); <add> mReactDatabaseSupplier.clearAndCloseDatabase(); <ide> } <ide> <ide> /** <ide> protected void doInBackgroundGuarded(Void... params) { <ide> return; <ide> } <ide> try { <del> mReactDatabaseSupplier.get().delete(TABLE_CATALYST, null, null); <add> mReactDatabaseSupplier.clear(); <ide> callback.invoke(); <ide> } catch (Exception e) { <ide> FLog.w(ReactConstants.TAG, e.getMessage(), e); <ide><path>ReactAndroid/src/main/java/com/facebook/react/modules/storage/ReactDatabaseSupplier.java <ide> import android.database.sqlite.SQLiteException; <ide> import android.database.sqlite.SQLiteOpenHelper; <ide> <del>// VisibleForTesting <add>import com.facebook.common.logging.FLog; <add>import com.facebook.react.common.ReactConstants; <add> <add>/** <add> * Database supplier of the database used by react native. This creates, opens and deletes the <add> * database as necessary. <add> */ <ide> public class ReactDatabaseSupplier extends SQLiteOpenHelper { <ide> <ide> // VisibleForTesting <ide> public class ReactDatabaseSupplier extends SQLiteOpenHelper { <ide> <ide> private Context mContext; <ide> private @Nullable SQLiteDatabase mDb; <add> private static @Nullable ReactDatabaseSupplier mReactDatabaseSupplierInstance; <ide> <del> public ReactDatabaseSupplier(Context context) { <add> private ReactDatabaseSupplier(Context context) { <ide> super(context, DATABASE_NAME, null, DATABASE_VERSION); <ide> mContext = context; <ide> } <ide> <add> public static ReactDatabaseSupplier getInstance(Context context) { <add> if (mReactDatabaseSupplierInstance == null) { <add> mReactDatabaseSupplierInstance = new ReactDatabaseSupplier(context); <add> } <add> return mReactDatabaseSupplierInstance; <add> } <add> <ide> @Override <ide> public void onCreate(SQLiteDatabase db) { <ide> db.execSQL(VERSION_TABLE_CREATE); <ide> public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { <ide> return mDb; <ide> } <ide> <del> /* package */ synchronized boolean deleteDatabase() { <add> public synchronized void clearAndCloseDatabase() throws RuntimeException { <add> try { <add> clear(); <add> closeDatabase(); <add> FLog.d(ReactConstants.TAG, "Cleaned " + DATABASE_NAME); <add> } catch (Exception e) { <add> // Clearing the database has failed, delete it instead. <add> if (deleteDatabase()) { <add> FLog.d(ReactConstants.TAG, "Deleted Local Database " + DATABASE_NAME); <add> return; <add> } <add> // Everything failed, throw <add> throw new RuntimeException("Clearing and deleting database " + DATABASE_NAME + " failed"); <add> } <add> } <add> <add> /* package */ synchronized void clear() { <add> get().delete(TABLE_CATALYST, null, null); <add> } <add> <add> private synchronized boolean deleteDatabase() { <add> closeDatabase(); <add> return mContext.deleteDatabase(DATABASE_NAME); <add> } <add> <add> private synchronized void closeDatabase() { <ide> if (mDb != null && mDb.isOpen()) { <ide> mDb.close(); <ide> mDb = null; <ide> } <del> return mContext.deleteDatabase(DATABASE_NAME); <add> } <add> <add> // For testing purposes only! <add> public static void deleteInstance() { <add> mReactDatabaseSupplierInstance = null; <ide> } <ide> }
2
Python
Python
update affected code
9b82f0a47b6a72fe2ba960f1895d5dbb9215599e
<ide><path>libcloud/compute/drivers/ec2.py <ide> class BaseEC2NodeDriver(NodeDriver): <ide> connectionCls = EC2Connection <ide> features = {'create_node': ['ssh_key']} <ide> path = '/' <add> signature_version = DEFAULT_SIGNATURE_VERSION <ide> <ide> NODE_STATE_MAP = { <ide> 'pending': NodeState.PENDING, <ide> class EucNodeDriver(BaseEC2NodeDriver): <ide> api_name = 'ec2_us_east' <ide> region_name = 'us-east-1' <ide> connectionCls = EucConnection <add> signature_version = '2' <ide> <ide> def __init__(self, key, secret=None, secure=True, host=None, <ide> path=None, port=None, api_version=DEFAULT_EUCA_API_VERSION): <ide> class NimbusNodeDriver(BaseEC2NodeDriver): <ide> region_name = 'nimbus' <ide> friendly_name = 'Nimbus Private Cloud' <ide> connectionCls = NimbusConnection <add> signature_version = '2' <ide> <ide> def ex_describe_addresses(self, nodes): <ide> """ <ide> class OutscaleNodeDriver(BaseEC2NodeDriver): <ide> name = 'Outscale' <ide> website = 'http://www.outscale.com' <ide> path = '/' <add> signature_version = '2' <ide> <ide> NODE_STATE_MAP = { <ide> 'pending': NodeState.PENDING,
1
Javascript
Javascript
add theme server validations
ae3ccdd672d03410de390e1cd84f24b885ba981d
<ide><path>client/epics/index.js <ide> import analyticsEpic from './analytics-epic.js'; <ide> import errEpic from './err-epic.js'; <ide> import hardGoToEpic from './hard-go-to-epic.js'; <ide> import mouseTrapEpic from './mouse-trap-epic.js'; <del>import nightModeEpic from './night-mode-epic.js'; <ide> import titleEpic from './title-epic.js'; <ide> <ide> export default [ <ide> analyticsEpic, <ide> errEpic, <ide> hardGoToEpic, <ide> mouseTrapEpic, <del> nightModeEpic, <ide> titleEpic <ide> ]; <ide><path>common/app/redux/index.js <ide> import { createSelector } from 'reselect'; <ide> import fetchUserEpic from './fetch-user-epic.js'; <ide> import updateMyCurrentChallengeEpic from './update-my-challenge-epic.js'; <ide> import fetchChallengesEpic from './fetch-challenges-epic.js'; <add>import nightModeEpic from './night-mode-epic.js'; <ide> <ide> import { createFilesMetaCreator } from '../files'; <ide> import { updateThemeMetacreator, entitiesSelector } from '../entities'; <add>import { utils } from '../Flash/redux'; <ide> import { types as challenges } from '../routes/Challenges/redux'; <ide> import { challengeToFiles } from '../routes/Challenges/utils'; <ide> <ide> import ns from '../ns.json'; <ide> import { themes, invertTheme } from '../../utils/themes.js'; <ide> <ide> export const epics = [ <del> fetchUserEpic, <ide> fetchChallengesEpic, <add> fetchUserEpic, <add> nightModeEpic, <ide> updateMyCurrentChallengeEpic <ide> ]; <ide> <ide> export const types = createTypes([ <ide> <ide> // night mode <ide> 'toggleNightMode', <del> 'postThemeComplete' <add> createAsyncTypes('postTheme') <ide> ], ns); <ide> <ide> const throwIfUndefined = () => { <ide> export const createErrorObservable = error => Observable.just({ <ide> type: types.handleError, <ide> error <ide> }); <add>// use sparingly <ide> // doActionOnError( <ide> // actionCreator: (() => Action|Null) <ide> // ) => (error: Error) => Observable[Action] <ide> export const toggleNightMode = createAction( <ide> (username, theme) => updateThemeMetacreator(username, invertTheme(theme)) <ide> ); <ide> export const postThemeComplete = createAction( <del> types.postThemeComplete, <add> types.postTheme.complete, <add> null, <add> utils.createFlashMetaAction <add>); <add> <add>export const postThemeError = createAction( <add> types.postTheme.error, <ide> null, <del> updateThemeMetacreator <add> (username, theme, err) => ({ <add> ...updateThemeMetacreator(username, invertTheme(theme)), <add> ...utils.createFlashMetaAction(err) <add> }) <ide> ); <ide> <ide> const defaultState = { <ide><path>common/app/redux/night-mode-epic.js <ide> import store from 'store'; <ide> import { themes } from '../../utils/themes.js'; <ide> import { postJSON$ } from '../../utils/ajax-stream.js'; <ide> import { <del> types, <del> <add> csrfSelector, <ide> postThemeComplete, <del> createErrorObservable, <del> <add> postThemeError, <ide> themeSelector, <del> usernameSelector, <del> csrfSelector <add> types, <add> usernameSelector <ide> } from './index.js'; <ide> <ide> function persistTheme(theme) { <ide> export default function nightModeEpic( <ide> ::ofType( <ide> types.fetchUser.complete, <ide> types.toggleNightMode, <del> types.postThemeComplete <add> types.postTheme.complete, <add> types.postTheme.error <ide> ) <ide> .map(_.flow(getState, themeSelector)) <ide> // catch existing night mode users <ide> export default function nightModeEpic( <ide> const theme = themeSelector(getState()); <ide> const username = usernameSelector(getState()); <ide> return postJSON$('/update-my-theme', { _csrf, theme }) <del> .pluck('updatedTo') <del> .map(theme => postThemeComplete(username, theme)) <del> .catch(createErrorObservable); <add> .map(postThemeComplete) <add> .catch(err => { <add> return Observable.of(postThemeError(username, theme, err)); <add> }); <ide> }); <ide> <ide> return Observable.merge(toggleBodyClass, postThemeEpic); <ide><path>common/models/user.js <ide> module.exports = function(User) { <ide> ); <ide> return Promise.reject(err); <ide> } <del> return this.update$({ theme }) <del> .map({ updatedTo: theme }) <del> .toPromise(); <add> return this.update$({ theme }).toPromise(); <ide> }; <ide> <ide> // deprecated. remove once live <ide><path>server/boot/settings.js <ide> import { <ide> createValidatorErrorHandler <ide> } from '../utils/middleware'; <ide> import supportedLanguages from '../../common/utils/supported-languages.js'; <add>import { themes } from '../../common/utils/themes.js'; <ide> <ide> export default function settingsController(app) { <ide> const api = app.loopback.Router(); <ide> export default function settingsController(app) { <ide> updateMyCurrentChallenge <ide> ); <ide> <add> const updateMyThemeValidators = [ <add> check('theme') <add> .isIn(Object.keys(themes)) <add> .withMessage('Theme is invalid.') <add> ]; <ide> function updateMyTheme(req, res, next) { <del> req.checkBody('theme', 'Theme is invalid.').isLength({ min: 4 }); <ide> const { body: { theme } } = req; <del> const errors = req.validationErrors(true); <del> if (errors) { <del> return res.status(403).json({ errors }); <del> } <ide> if (req.user.theme === theme) { <del> return res.json({ msg: 'Theme already set' }); <add> return res.sendFlash('info', 'Theme already set'); <ide> } <del> return req.user.updateTheme('' + theme) <add> return req.user.updateTheme(theme) <ide> .then( <del> data => res.json(data), <add> () => res.sendFlash('info', 'Your theme has been updated'), <ide> next <ide> ); <ide> } <add> api.post( <add> '/update-my-theme', <add> ifNoUser401, <add> updateMyThemeValidators, <add> createValidatorErrorHandler('errors'), <add> updateMyTheme <add> ); <ide> <ide> api.post( <ide> '/toggle-available-for-hire', <ide> export default function settingsController(app) { <ide> ifNoUser401, <ide> updateMyLang <ide> ); <del> api.post( <del> '/update-my-theme', <del> ifNoUser401, <del> updateMyTheme <del> ); <ide> <ide> app.use(api); <ide> } <ide><path>server/utils/create-handled-error.js <ide> export function wrapHandledError(err, { <ide> } <ide> <ide> // for use with express-validator error formatter <del>export const createValidatorErrorFormatter = (type, redirectTo, status) => <add>export const createValidatorErrorFormatter = (type, redirectTo) => <ide> ({ msg }) => wrapHandledError( <ide> new Error(msg), <ide> { <ide> type, <ide> message: msg, <ide> redirectTo, <del> status <add> // we default to 400 as these are malformed requests <add> status: 400 <ide> } <ide> );
6
Java
Java
fix a crash in image when passed an invalid uri
798acac18e9daab543d7b2e947bc2ed760703d99
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/image/ReactImageView.java <ide> private static int getResourceDrawableId(Context context, @Nullable String name) <ide> return resId > 0 ? context.getResources().getDrawable(resId) : null; <ide> } <ide> <del> private static @Nullable Uri getResourceDrawableUri(Context context, @Nullable String name) { <add> private static Uri getResourceDrawableUri(Context context, @Nullable String name) { <ide> int resId = getResourceDrawableId(context, name); <ide> return resId > 0 ? new Uri.Builder() <ide> .scheme(UriUtil.LOCAL_RESOURCE_SCHEME) <ide> .path(String.valueOf(resId)) <del> .build() : null; <add> .build() : Uri.EMPTY; <ide> } <ide> }
1
Javascript
Javascript
prevent proxying canvasgradient in node platform
c8b885dd3e35632df407df4bd463d9a5cc90280b
<ide><path>src/helpers/helpers.config.js <ide> export function _descriptors(proxy, defaults = {scriptable: true, indexable: tru <ide> } <ide> <ide> const readKey = (prefix, name) => prefix ? prefix + _capitalize(name) : name; <del>const needsSubResolver = (prop, value) => isObject(value) && prop !== 'adapters'; <add>const needsSubResolver = (prop, value) => isObject(value) && prop !== 'adapters' && <add> (Object.getPrototypeOf(value) === null || value.constructor === Object); <ide> <ide> function _cached(target, prop, resolve) { <ide> if (Object.prototype.hasOwnProperty.call(target, prop)) { <ide> function _resolveScriptable(prop, value, target, receiver) { <ide> _stack.add(prop); <ide> value = value(_context, _subProxy || receiver); <ide> _stack.delete(prop); <del> if (isObject(value)) { <add> if (needsSubResolver(prop, value)) { <ide> // When scriptable option returns an object, create a resolver on that. <ide> value = createSubResolver(_proxy._scopes, _proxy, prop, value); <ide> } <ide><path>test/specs/helpers.config.tests.js <ide> describe('Chart.helpers.config', function() { <ide> expect(fn()).toEqual('ok'); <ide> }); <ide> <add> it('should not create proxy for objects with custom constructor', function() { <add> class MyClass { <add> constructor() { <add> this.string = 'test string'; <add> } <add> method(arg) { <add> return arg === undefined ? 'ok' : 'fail'; <add> } <add> } <add> <add> const defaults = { <add> test: new MyClass() <add> }; <add> <add> const resolver = _createResolver([{}, defaults]); <add> const opts = _attachContext(resolver, {index: 1}); <add> const fn = opts.test.method; <add> expect(typeof fn).toBe('function'); <add> expect(fn()).toEqual('ok'); <add> expect(opts.test.string).toEqual('test string'); <add> expect(opts.test.constructor).toEqual(MyClass); <add> }); <add> <ide> it('should properly set value to object in array of objects', function() { <ide> const defaults = {}; <ide> const options = {
2
Javascript
Javascript
avoid argumentsadaptortrampoline frame
038b636562444574d5256bf4ac198ed808e65537
<ide><path>lib/module.js <ide> Module.prototype.load = function(filename) { <ide> Module.prototype.require = function(path) { <ide> assert(path, 'missing path'); <ide> assert(typeof path === 'string', 'path must be a string'); <del> return Module._load(path, this); <add> return Module._load(path, this, /* isMain */ false); <ide> }; <ide> <ide>
1
Mixed
Javascript
add drawerlockmode prop to drawerlayoutandroid
ec173b1a1767aa52cf85fe652044d19264def699
<ide><path>Libraries/Components/DrawerAndroid/DrawerLayoutAndroid.android.js <ide> var INNERVIEW_REF = 'innerView'; <ide> var DrawerLayoutValidAttributes = { <ide> drawerWidth: true, <ide> drawerPosition: true, <add> drawerLockMode: true <ide> }; <ide> <ide> var DRAWER_STATES = [ <ide> var DrawerLayoutAndroid = React.createClass({ <ide> * from the edge of the window. <ide> */ <ide> drawerWidth: ReactPropTypes.number, <add> /** <add> * Specifies the lock mode of the drawer. The drawer can be locked in 3 states: <add> * - unlocked (default), meaning that the drawer will respond (open/close) to touch gestures. <add> * - locked closed, meaning that the drawer will stay closed and not respond to gestures. <add> * - locked open, meaning that the drawer will stay opened and not respond to gestures. <add> * The drawer may still be opened and closed programmatically (`openDrawer`/`closeDrawer`). <add> */ <add> drawerLockMode: ReactPropTypes.oneOf([ <add> 'unlocked', <add> 'locked-closed', <add> 'locked-open' <add> ]), <ide> /** <ide> * Function called whenever there is an interaction with the navigation view. <ide> */ <ide> var DrawerLayoutAndroid = React.createClass({ <ide> ref={RK_DRAWER_REF} <ide> drawerWidth={this.props.drawerWidth} <ide> drawerPosition={this.props.drawerPosition} <add> drawerLockMode={this.props.drawerLockMode} <ide> style={styles.base} <ide> onDrawerSlide={this._onDrawerSlide} <ide> onDrawerOpen={this._onDrawerOpen} <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/drawer/ReactDrawerLayoutManager.java <ide> public void getDrawerWidth(ReactDrawerLayout view, float width) { <ide> view.setDrawerWidth(widthInPx); <ide> } <ide> <add> @ReactProp(name = "drawerLockMode") <add> public void setDrawerLockMode(ReactDrawerLayout view, @Nullable String drawerLockMode) { <add> if (drawerLockMode == null || "unlocked".equals(drawerLockMode)) { <add> view.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED); <add> } else if ("locked-closed".equals(drawerLockMode)) { <add> view.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED); <add> } else if ("locked-open".equals(drawerLockMode)) { <add> view.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_OPEN); <add> } else { <add> throw new JSApplicationIllegalArgumentException("Unknown drawerLockMode " + drawerLockMode); <add> } <add> } <add> <ide> @Override <ide> public boolean needsCustomLayoutForChildren() { <ide> // Return true, since DrawerLayout will lay out it's own children.
2
PHP
PHP
fix missing blank line
0c6892b244b8a282fbdae2080f578ce2a0a114f2
<ide><path>tests/TestCase/Utility/TextTest.php <ide> public function testWrapIndent() <ide> TEXT; <ide> $this->assertTextEquals($expected, $result); <ide> } <add> <ide> /** <ide> * test wrapBlock() indentical to wrap() <ide> * <ide> public function testWrapBlockIndenticalToWrap() <ide> $expected = Text::wrap($text, ['width' => 33, 'indentAt' => 0]); <ide> $this->assertTextEquals($expected, $result); <ide> } <add> <ide> /** <ide> * test wrapBlock() indenting from first line <ide> * <ide> public function testWrapBlockWithIndentAt0() <ide> TEXT; <ide> $this->assertTextEquals($expected, $result); <ide> } <add> <ide> /** <ide> * test wrapBlock() indenting from second line <ide> *
1
Text
Text
remove references to python 2 from the docs
8687f6135fc374c8d7977939ff3d8b2514c00e51
<ide><path>CONTRIBUTING.md <ide> It's also useful to remember that if you have an outstanding pull request then p <ide> <ide> GitHub's documentation for working on pull requests is [available here][pull-requests]. <ide> <del>Always run the tests before submitting pull requests, and ideally run `tox` in order to check that your modifications are compatible with both Python 2 and Python 3, and that they run properly on all supported versions of Django. <add>Always run the tests before submitting pull requests, and ideally run `tox` in order to check that your modifications are compatible on all supported versions of Python and Django. <ide> <ide> Once you've made a pull request take a look at the Travis build status in the GitHub interface and make sure the tests are running as you'd expect. <ide> <ide><path>docs/community/contributing.md <ide> It's also useful to remember that if you have an outstanding pull request then p <ide> <ide> GitHub's documentation for working on pull requests is [available here][pull-requests]. <ide> <del>Always run the tests before submitting pull requests, and ideally run `tox` in order to check that your modifications are compatible with both Python 2 and Python 3, and that they run properly on all supported versions of Django. <add>Always run the tests before submitting pull requests, and ideally run `tox` in order to check that your modifications are compatible on all supported versions of Python and Django. <ide> <ide> Once you've made a pull request take a look at the Travis build status in the GitHub interface and make sure the tests are running as you'd expect. <ide> <ide><path>docs/index.md <ide> continued development by **[signing up for a paid plan][funding]**. <ide> <ide> REST framework requires the following: <ide> <del>* Python (2.7, 3.4, 3.5, 3.6, 3.7) <add>* Python (3.4, 3.5, 3.6, 3.7) <ide> * Django (1.11, 2.0, 2.1, 2.2) <ide> <ide> We **highly recommend** and only officially support the latest patch release of
3
Javascript
Javascript
remove keymirror in topleveltypes
2f9a9dc4c56c1caee250626c54c587c5f233fcab
<ide><path>src/renderers/dom/client/ReactBrowserEventEmitter.js <ide> <ide> 'use strict'; <ide> <del>var EventConstants = require('EventConstants'); <ide> var EventPluginRegistry = require('EventPluginRegistry'); <ide> var ReactEventEmitterMixin = require('ReactEventEmitterMixin'); <ide> var ViewportMetrics = require('ViewportMetrics'); <ide> var ReactBrowserEventEmitter = Object.assign({}, ReactEventEmitterMixin, { <ide> var dependencies = <ide> EventPluginRegistry.registrationNameDependencies[registrationName]; <ide> <del> var topLevelTypes = EventConstants.topLevelTypes; <ide> for (var i = 0; i < dependencies.length; i++) { <ide> var dependency = dependencies[i]; <ide> if (!( <ide> isListening.hasOwnProperty(dependency) && <ide> isListening[dependency] <ide> )) { <del> if (dependency === topLevelTypes.topWheel) { <add> if (dependency === 'topWheel') { <ide> if (isEventSupported('wheel')) { <ide> ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent( <del> topLevelTypes.topWheel, <add> 'topWheel', <ide> 'wheel', <ide> mountAt <ide> ); <ide> } else if (isEventSupported('mousewheel')) { <ide> ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent( <del> topLevelTypes.topWheel, <add> 'topWheel', <ide> 'mousewheel', <ide> mountAt <ide> ); <ide> } else { <ide> // Firefox needs to capture a different mouse scroll event. <ide> // @see http://www.quirksmode.org/dom/events/tests/scroll.html <ide> ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent( <del> topLevelTypes.topWheel, <add> 'topWheel', <ide> 'DOMMouseScroll', <ide> mountAt <ide> ); <ide> } <del> } else if (dependency === topLevelTypes.topScroll) { <add> } else if (dependency === 'topScroll') { <ide> <ide> if (isEventSupported('scroll', true)) { <ide> ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent( <del> topLevelTypes.topScroll, <add> 'topScroll', <ide> 'scroll', <ide> mountAt <ide> ); <ide> } else { <ide> ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent( <del> topLevelTypes.topScroll, <add> 'topScroll', <ide> 'scroll', <ide> ReactBrowserEventEmitter.ReactEventListener.WINDOW_HANDLE <ide> ); <ide> } <del> } else if (dependency === topLevelTypes.topFocus || <del> dependency === topLevelTypes.topBlur) { <add> } else if (dependency === 'topFocus' || <add> dependency === 'topBlur') { <ide> <ide> if (isEventSupported('focus', true)) { <ide> ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent( <del> topLevelTypes.topFocus, <add> 'topFocus', <ide> 'focus', <ide> mountAt <ide> ); <ide> ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent( <del> topLevelTypes.topBlur, <add> 'topBlur', <ide> 'blur', <ide> mountAt <ide> ); <ide> } else if (isEventSupported('focusin')) { <ide> // IE has `focusin` and `focusout` events which bubble. <ide> // @see http://www.quirksmode.org/blog/archives/2008/04/delegating_the.html <ide> ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent( <del> topLevelTypes.topFocus, <add> 'topFocus', <ide> 'focusin', <ide> mountAt <ide> ); <ide> ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent( <del> topLevelTypes.topBlur, <add> 'topBlur', <ide> 'focusout', <ide> mountAt <ide> ); <ide> } <ide> <ide> // to make sure blur and focus event listeners are only attached once <del> isListening[topLevelTypes.topBlur] = true; <del> isListening[topLevelTypes.topFocus] = true; <add> isListening.topBlur = true; <add> isListening.topFocus = true; <ide> } else if (topEventMapping.hasOwnProperty(dependency)) { <ide> ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent( <ide> dependency, <ide><path>src/renderers/dom/client/eventPlugins/BeforeInputEventPlugin.js <ide> <ide> 'use strict'; <ide> <del>var EventConstants = require('EventConstants'); <ide> var EventPropagators = require('EventPropagators'); <ide> var ExecutionEnvironment = require('ExecutionEnvironment'); <ide> var FallbackCompositionState = require('FallbackCompositionState'); <ide> var SyntheticInputEvent = require('SyntheticInputEvent'); <ide> <ide> var keyOf = require('keyOf'); <ide> <add>import type { TopLevelTypes } from 'EventConstants'; <add> <ide> var END_KEYCODES = [9, 13, 27, 32]; // Tab, Return, Esc, Space <ide> var START_KEYCODE = 229; <ide> <ide> function isPresto() { <ide> var SPACEBAR_CODE = 32; <ide> var SPACEBAR_CHAR = String.fromCharCode(SPACEBAR_CODE); <ide> <del>var topLevelTypes = EventConstants.topLevelTypes; <del> <ide> // Events and their corresponding property names. <ide> var eventTypes = { <ide> beforeInput: { <ide> var eventTypes = { <ide> captured: keyOf({onBeforeInputCapture: null}), <ide> }, <ide> dependencies: [ <del> topLevelTypes.topCompositionEnd, <del> topLevelTypes.topKeyPress, <del> topLevelTypes.topTextInput, <del> topLevelTypes.topPaste, <add> 'topCompositionEnd', <add> 'topKeyPress', <add> 'topTextInput', <add> 'topPaste', <ide> ], <ide> }, <ide> compositionEnd: { <ide> var eventTypes = { <ide> captured: keyOf({onCompositionEndCapture: null}), <ide> }, <ide> dependencies: [ <del> topLevelTypes.topBlur, <del> topLevelTypes.topCompositionEnd, <del> topLevelTypes.topKeyDown, <del> topLevelTypes.topKeyPress, <del> topLevelTypes.topKeyUp, <del> topLevelTypes.topMouseDown, <add> 'topBlur', <add> 'topCompositionEnd', <add> 'topKeyDown', <add> 'topKeyPress', <add> 'topKeyUp', <add> 'topMouseDown', <ide> ], <ide> }, <ide> compositionStart: { <ide> var eventTypes = { <ide> captured: keyOf({onCompositionStartCapture: null}), <ide> }, <ide> dependencies: [ <del> topLevelTypes.topBlur, <del> topLevelTypes.topCompositionStart, <del> topLevelTypes.topKeyDown, <del> topLevelTypes.topKeyPress, <del> topLevelTypes.topKeyUp, <del> topLevelTypes.topMouseDown, <add> 'topBlur', <add> 'topCompositionStart', <add> 'topKeyDown', <add> 'topKeyPress', <add> 'topKeyUp', <add> 'topMouseDown', <ide> ], <ide> }, <ide> compositionUpdate: { <ide> var eventTypes = { <ide> captured: keyOf({onCompositionUpdateCapture: null}), <ide> }, <ide> dependencies: [ <del> topLevelTypes.topBlur, <del> topLevelTypes.topCompositionUpdate, <del> topLevelTypes.topKeyDown, <del> topLevelTypes.topKeyPress, <del> topLevelTypes.topKeyUp, <del> topLevelTypes.topMouseDown, <add> 'topBlur', <add> 'topCompositionUpdate', <add> 'topKeyDown', <add> 'topKeyPress', <add> 'topKeyUp', <add> 'topMouseDown', <ide> ], <ide> }, <ide> }; <ide> function isKeypressCommand(nativeEvent) { <ide> */ <ide> function getCompositionEventType(topLevelType) { <ide> switch (topLevelType) { <del> case topLevelTypes.topCompositionStart: <add> case 'topCompositionStart': <ide> return eventTypes.compositionStart; <del> case topLevelTypes.topCompositionEnd: <add> case 'topCompositionEnd': <ide> return eventTypes.compositionEnd; <del> case topLevelTypes.topCompositionUpdate: <add> case 'topCompositionUpdate': <ide> return eventTypes.compositionUpdate; <ide> } <ide> } <ide> function getCompositionEventType(topLevelType) { <ide> */ <ide> function isFallbackCompositionStart(topLevelType, nativeEvent) { <ide> return ( <del> topLevelType === topLevelTypes.topKeyDown && <add> topLevelType === 'topKeyDown' && <ide> nativeEvent.keyCode === START_KEYCODE <ide> ); <ide> } <ide> function isFallbackCompositionStart(topLevelType, nativeEvent) { <ide> */ <ide> function isFallbackCompositionEnd(topLevelType, nativeEvent) { <ide> switch (topLevelType) { <del> case topLevelTypes.topKeyUp: <add> case 'topKeyUp': <ide> // Command keys insert or clear IME input. <ide> return (END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1); <del> case topLevelTypes.topKeyDown: <add> case 'topKeyDown': <ide> // Expect IME keyCode on each keydown. If we get any other <ide> // code we must have exited earlier. <ide> return (nativeEvent.keyCode !== START_KEYCODE); <del> case topLevelTypes.topKeyPress: <del> case topLevelTypes.topMouseDown: <del> case topLevelTypes.topBlur: <add> case 'topKeyPress': <add> case 'topMouseDown': <add> case 'topBlur': <ide> // Events are not possible without cancelling IME. <ide> return true; <ide> default: <ide> function extractCompositionEvent( <ide> * @param {object} nativeEvent Native browser event. <ide> * @return {?string} The string corresponding to this `beforeInput` event. <ide> */ <del>function getNativeBeforeInputChars(topLevelType, nativeEvent) { <add>function getNativeBeforeInputChars(topLevelType: TopLevelTypes, nativeEvent) { <ide> switch (topLevelType) { <del> case topLevelTypes.topCompositionEnd: <add> case 'topCompositionEnd': <ide> return getDataFromCustomEvent(nativeEvent); <del> case topLevelTypes.topKeyPress: <add> case 'topKeyPress': <ide> /** <ide> * If native `textInput` events are available, our goal is to make <ide> * use of them. However, there is a special case: the spacebar key. <ide> function getNativeBeforeInputChars(topLevelType, nativeEvent) { <ide> hasSpaceKeypress = true; <ide> return SPACEBAR_CHAR; <ide> <del> case topLevelTypes.topTextInput: <add> case 'topTextInput': <ide> // Record the characters to be added to the DOM. <ide> var chars = nativeEvent.data; <ide> <ide> function getNativeBeforeInputChars(topLevelType, nativeEvent) { <ide> * @param {object} nativeEvent Native browser event. <ide> * @return {?string} The fallback string for this `beforeInput` event. <ide> */ <del>function getFallbackBeforeInputChars(topLevelType, nativeEvent) { <add>function getFallbackBeforeInputChars(topLevelType: TopLevelTypes, nativeEvent) { <ide> // If we are currently composing (IME) and using a fallback to do so, <ide> // try to extract the composed characters from the fallback object. <ide> if (currentComposition) { <ide> if ( <del> topLevelType === topLevelTypes.topCompositionEnd || <add> topLevelType === 'topCompositionEnd' || <ide> isFallbackCompositionEnd(topLevelType, nativeEvent) <ide> ) { <ide> var chars = currentComposition.getData(); <ide> function getFallbackBeforeInputChars(topLevelType, nativeEvent) { <ide> } <ide> <ide> switch (topLevelType) { <del> case topLevelTypes.topPaste: <add> case 'topPaste': <ide> // If a paste event occurs after a keypress, throw out the input <ide> // chars. Paste events should not lead to BeforeInput events. <ide> return null; <del> case topLevelTypes.topKeyPress: <add> case 'topKeyPress': <ide> /** <ide> * As of v27, Firefox may fire keypress events even when no character <ide> * will be inserted. A few possibilities: <ide> function getFallbackBeforeInputChars(topLevelType, nativeEvent) { <ide> return String.fromCharCode(nativeEvent.which); <ide> } <ide> return null; <del> case topLevelTypes.topCompositionEnd: <add> case 'topCompositionEnd': <ide> return useFallbackCompositionData ? null : nativeEvent.data; <ide> default: <ide> return null; <ide><path>src/renderers/dom/client/eventPlugins/ChangeEventPlugin.js <ide> <ide> 'use strict'; <ide> <del>var EventConstants = require('EventConstants'); <ide> var EventPluginHub = require('EventPluginHub'); <ide> var EventPropagators = require('EventPropagators'); <ide> var ExecutionEnvironment = require('ExecutionEnvironment'); <ide> var isEventSupported = require('isEventSupported'); <ide> var isTextInputElement = require('isTextInputElement'); <ide> var keyOf = require('keyOf'); <ide> <del>var topLevelTypes = EventConstants.topLevelTypes; <del> <ide> <ide> var eventTypes = { <ide> change: { <ide> var eventTypes = { <ide> captured: keyOf({onChangeCapture: null}), <ide> }, <ide> dependencies: [ <del> topLevelTypes.topBlur, <del> topLevelTypes.topChange, <del> topLevelTypes.topClick, <del> topLevelTypes.topFocus, <del> topLevelTypes.topInput, <del> topLevelTypes.topKeyDown, <del> topLevelTypes.topKeyUp, <del> topLevelTypes.topSelectionChange, <add> 'topBlur', <add> 'topChange', <add> 'topClick', <add> 'topFocus', <add> 'topInput', <add> 'topKeyDown', <add> 'topKeyUp', <add> 'topSelectionChange', <ide> ], <ide> }, <ide> }; <ide> function getTargetInstForChangeEvent( <ide> topLevelType, <ide> targetInst <ide> ) { <del> if (topLevelType === topLevelTypes.topChange) { <add> if (topLevelType === 'topChange') { <ide> return targetInst; <ide> } <ide> } <ide> function handleEventsForChangeEventIE8( <ide> target, <ide> targetInst <ide> ) { <del> if (topLevelType === topLevelTypes.topFocus) { <add> if (topLevelType === 'topFocus') { <ide> // stopWatching() should be a noop here but we call it just in case we <ide> // missed a blur event somehow. <ide> stopWatchingForChangeEventIE8(); <ide> startWatchingForChangeEventIE8(target, targetInst); <del> } else if (topLevelType === topLevelTypes.topBlur) { <add> } else if (topLevelType === 'topBlur') { <ide> stopWatchingForChangeEventIE8(); <ide> } <ide> } <ide> function handleEventsForInputEventPolyfill( <ide> target, <ide> targetInst <ide> ) { <del> if (topLevelType === topLevelTypes.topFocus) { <add> if (topLevelType === 'topFocus') { <ide> // In IE8, we can capture almost all .value changes by adding a <ide> // propertychange handler and looking for events with propertyName <ide> // equal to 'value' <ide> function handleEventsForInputEventPolyfill( <ide> // missed a blur event somehow. <ide> stopWatchingForValueChange(); <ide> startWatchingForValueChange(target, targetInst); <del> } else if (topLevelType === topLevelTypes.topBlur) { <add> } else if (topLevelType === 'topBlur') { <ide> stopWatchingForValueChange(); <ide> } <ide> } <ide> function getTargetInstForInputEventPolyfill( <ide> topLevelType, <ide> targetInst <ide> ) { <del> if (topLevelType === topLevelTypes.topSelectionChange || <del> topLevelType === topLevelTypes.topKeyUp || <del> topLevelType === topLevelTypes.topKeyDown) { <add> if (topLevelType === 'topSelectionChange' || <add> topLevelType === 'topKeyUp' || <add> topLevelType === 'topKeyDown') { <ide> // On the selectionchange event, the target is just document which isn't <ide> // helpful for us so just check activeElement instead. <ide> // <ide> function getTargetInstForClickEvent( <ide> topLevelType, <ide> targetInst <ide> ) { <del> if (topLevelType === topLevelTypes.topClick) { <add> if (topLevelType === 'topClick') { <ide> return getInstIfValueChanged(targetInst); <ide> } <ide> } <ide> function getTargetInstForInputOrChangeEvent( <ide> targetInst <ide> ) { <ide> if ( <del> topLevelType === topLevelTypes.topInput || <del> topLevelType === topLevelTypes.topChange <add> topLevelType === 'topInput' || <add> topLevelType === 'topChange' <ide> ) { <ide> return getInstIfValueChanged(targetInst); <ide> } <ide><path>src/renderers/dom/client/eventPlugins/EnterLeaveEventPlugin.js <ide> <ide> 'use strict'; <ide> <del>var EventConstants = require('EventConstants'); <ide> var EventPropagators = require('EventPropagators'); <ide> var ReactDOMComponentTree = require('ReactDOMComponentTree'); <ide> var SyntheticMouseEvent = require('SyntheticMouseEvent'); <ide> <ide> var keyOf = require('keyOf'); <ide> <del>var topLevelTypes = EventConstants.topLevelTypes; <del> <ide> var eventTypes = { <ide> mouseEnter: { <ide> registrationName: keyOf({onMouseEnter: null}), <ide> dependencies: [ <del> topLevelTypes.topMouseOut, <del> topLevelTypes.topMouseOver, <add> 'topMouseOut', <add> 'topMouseOver', <ide> ], <ide> }, <ide> mouseLeave: { <ide> registrationName: keyOf({onMouseLeave: null}), <ide> dependencies: [ <del> topLevelTypes.topMouseOut, <del> topLevelTypes.topMouseOver, <add> 'topMouseOut', <add> 'topMouseOver', <ide> ], <ide> }, <ide> }; <ide> var EnterLeaveEventPlugin = { <ide> nativeEvent, <ide> nativeEventTarget <ide> ) { <del> if (topLevelType === topLevelTypes.topMouseOver && <add> if (topLevelType === 'topMouseOver' && <ide> (nativeEvent.relatedTarget || nativeEvent.fromElement)) { <ide> return null; <ide> } <del> if (topLevelType !== topLevelTypes.topMouseOut && <del> topLevelType !== topLevelTypes.topMouseOver) { <add> if (topLevelType !== 'topMouseOut' && <add> topLevelType !== 'topMouseOver') { <ide> // Must not be a mouse in or mouse out - ignoring. <ide> return null; <ide> } <ide> var EnterLeaveEventPlugin = { <ide> <ide> var from; <ide> var to; <del> if (topLevelType === topLevelTypes.topMouseOut) { <add> if (topLevelType === 'topMouseOut') { <ide> from = targetInst; <ide> var related = nativeEvent.relatedTarget || nativeEvent.toElement; <ide> to = related ? <ide><path>src/renderers/dom/client/eventPlugins/SelectEventPlugin.js <ide> <ide> 'use strict'; <ide> <del>var EventConstants = require('EventConstants'); <ide> var EventPropagators = require('EventPropagators'); <ide> var ExecutionEnvironment = require('ExecutionEnvironment'); <ide> var ReactDOMComponentTree = require('ReactDOMComponentTree'); <ide> var isTextInputElement = require('isTextInputElement'); <ide> var keyOf = require('keyOf'); <ide> var shallowEqual = require('shallowEqual'); <ide> <del>var topLevelTypes = EventConstants.topLevelTypes; <del> <ide> var skipSelectionChangeEvent = ( <ide> ExecutionEnvironment.canUseDOM && <ide> 'documentMode' in document && <ide> var eventTypes = { <ide> captured: keyOf({onSelectCapture: null}), <ide> }, <ide> dependencies: [ <del> topLevelTypes.topBlur, <del> topLevelTypes.topContextMenu, <del> topLevelTypes.topFocus, <del> topLevelTypes.topKeyDown, <del> topLevelTypes.topKeyUp, <del> topLevelTypes.topMouseDown, <del> topLevelTypes.topMouseUp, <del> topLevelTypes.topSelectionChange, <add> 'topBlur', <add> 'topContextMenu', <add> 'topFocus', <add> 'topKeyDown', <add> 'topKeyUp', <add> 'topMouseDown', <add> 'topMouseUp', <add> 'topSelectionChange', <ide> ], <ide> }, <ide> }; <ide> var SelectEventPlugin = { <ide> <ide> switch (topLevelType) { <ide> // Track the input node that has focus. <del> case topLevelTypes.topFocus: <add> case 'topFocus': <ide> if (isTextInputElement(targetNode) || <ide> targetNode.contentEditable === 'true') { <ide> activeElement = targetNode; <ide> activeElementInst = targetInst; <ide> lastSelection = null; <ide> } <ide> break; <del> case topLevelTypes.topBlur: <add> case 'topBlur': <ide> activeElement = null; <ide> activeElementInst = null; <ide> lastSelection = null; <ide> break; <ide> <ide> // Don't fire the event while the user is dragging. This matches the <ide> // semantics of the native select event. <del> case topLevelTypes.topMouseDown: <add> case 'topMouseDown': <ide> mouseDown = true; <ide> break; <del> case topLevelTypes.topContextMenu: <del> case topLevelTypes.topMouseUp: <add> case 'topContextMenu': <add> case 'topMouseUp': <ide> mouseDown = false; <ide> return constructSelectEvent(nativeEvent, nativeEventTarget); <ide> <ide> var SelectEventPlugin = { <ide> // keyup, but we check on keydown as well in the case of holding down a <ide> // key, when multiple keydown events are fired but only one keyup is. <ide> // This is also our approach for IE handling, for the reason above. <del> case topLevelTypes.topSelectionChange: <add> case 'topSelectionChange': <ide> if (skipSelectionChangeEvent) { <ide> break; <ide> } <ide> // falls through <del> case topLevelTypes.topKeyDown: <del> case topLevelTypes.topKeyUp: <add> case 'topKeyDown': <add> case 'topKeyUp': <ide> return constructSelectEvent(nativeEvent, nativeEventTarget); <ide> } <ide> <ide><path>src/renderers/dom/client/eventPlugins/SimpleEventPlugin.js <ide> <ide> 'use strict'; <ide> <del>var EventConstants = require('EventConstants'); <ide> var EventListener = require('EventListener'); <ide> var EventPropagators = require('EventPropagators'); <ide> var ReactDOMComponentTree = require('ReactDOMComponentTree'); <ide> var getEventCharCode = require('getEventCharCode'); <ide> var invariant = require('invariant'); <ide> var keyOf = require('keyOf'); <ide> <del>var topLevelTypes = EventConstants.topLevelTypes; <del> <ide> var eventTypes = { <ide> abort: { <ide> phasedRegistrationNames: { <ide> var SimpleEventPlugin = { <ide> } <ide> var EventConstructor; <ide> switch (topLevelType) { <del> case topLevelTypes.topAbort: <del> case topLevelTypes.topCanPlay: <del> case topLevelTypes.topCanPlayThrough: <del> case topLevelTypes.topDurationChange: <del> case topLevelTypes.topEmptied: <del> case topLevelTypes.topEncrypted: <del> case topLevelTypes.topEnded: <del> case topLevelTypes.topError: <del> case topLevelTypes.topInput: <del> case topLevelTypes.topInvalid: <del> case topLevelTypes.topLoad: <del> case topLevelTypes.topLoadedData: <del> case topLevelTypes.topLoadedMetadata: <del> case topLevelTypes.topLoadStart: <del> case topLevelTypes.topPause: <del> case topLevelTypes.topPlay: <del> case topLevelTypes.topPlaying: <del> case topLevelTypes.topProgress: <del> case topLevelTypes.topRateChange: <del> case topLevelTypes.topReset: <del> case topLevelTypes.topSeeked: <del> case topLevelTypes.topSeeking: <del> case topLevelTypes.topStalled: <del> case topLevelTypes.topSubmit: <del> case topLevelTypes.topSuspend: <del> case topLevelTypes.topTimeUpdate: <del> case topLevelTypes.topVolumeChange: <del> case topLevelTypes.topWaiting: <add> case 'topAbort': <add> case 'topCanPlay': <add> case 'topCanPlayThrough': <add> case 'topDurationChange': <add> case 'topEmptied': <add> case 'topEncrypted': <add> case 'topEnded': <add> case 'topError': <add> case 'topInput': <add> case 'topInvalid': <add> case 'topLoad': <add> case 'topLoadedData': <add> case 'topLoadedMetadata': <add> case 'topLoadStart': <add> case 'topPause': <add> case 'topPlay': <add> case 'topPlaying': <add> case 'topProgress': <add> case 'topRateChange': <add> case 'topReset': <add> case 'topSeeked': <add> case 'topSeeking': <add> case 'topStalled': <add> case 'topSubmit': <add> case 'topSuspend': <add> case 'topTimeUpdate': <add> case 'topVolumeChange': <add> case 'topWaiting': <ide> // HTML Events <ide> // @see http://www.w3.org/TR/html5/index.html#events-0 <ide> EventConstructor = SyntheticEvent; <ide> break; <del> case topLevelTypes.topKeyPress: <add> case 'topKeyPress': <ide> // Firefox creates a keypress event for function keys too. This removes <ide> // the unwanted keypress events. Enter is however both printable and <ide> // non-printable. One would expect Tab to be as well (but it isn't). <ide> if (getEventCharCode(nativeEvent) === 0) { <ide> return null; <ide> } <ide> /* falls through */ <del> case topLevelTypes.topKeyDown: <del> case topLevelTypes.topKeyUp: <add> case 'topKeyDown': <add> case 'topKeyUp': <ide> EventConstructor = SyntheticKeyboardEvent; <ide> break; <del> case topLevelTypes.topBlur: <del> case topLevelTypes.topFocus: <add> case 'topBlur': <add> case 'topFocus': <ide> EventConstructor = SyntheticFocusEvent; <ide> break; <del> case topLevelTypes.topClick: <add> case 'topClick': <ide> // Firefox creates a click event on right mouse clicks. This removes the <ide> // unwanted click events. <ide> if (nativeEvent.button === 2) { <ide> return null; <ide> } <ide> /* falls through */ <del> case topLevelTypes.topContextMenu: <del> case topLevelTypes.topDoubleClick: <del> case topLevelTypes.topMouseDown: <del> case topLevelTypes.topMouseMove: <del> case topLevelTypes.topMouseOut: <del> case topLevelTypes.topMouseOver: <del> case topLevelTypes.topMouseUp: <add> case 'topContextMenu': <add> case 'topDoubleClick': <add> case 'topMouseDown': <add> case 'topMouseMove': <add> case 'topMouseOut': <add> case 'topMouseOver': <add> case 'topMouseUp': <ide> EventConstructor = SyntheticMouseEvent; <ide> break; <del> case topLevelTypes.topDrag: <del> case topLevelTypes.topDragEnd: <del> case topLevelTypes.topDragEnter: <del> case topLevelTypes.topDragExit: <del> case topLevelTypes.topDragLeave: <del> case topLevelTypes.topDragOver: <del> case topLevelTypes.topDragStart: <del> case topLevelTypes.topDrop: <add> case 'topDrag': <add> case 'topDragEnd': <add> case 'topDragEnter': <add> case 'topDragExit': <add> case 'topDragLeave': <add> case 'topDragOver': <add> case 'topDragStart': <add> case 'topDrop': <ide> EventConstructor = SyntheticDragEvent; <ide> break; <del> case topLevelTypes.topTouchCancel: <del> case topLevelTypes.topTouchEnd: <del> case topLevelTypes.topTouchMove: <del> case topLevelTypes.topTouchStart: <add> case 'topTouchCancel': <add> case 'topTouchEnd': <add> case 'topTouchMove': <add> case 'topTouchStart': <ide> EventConstructor = SyntheticTouchEvent; <ide> break; <del> case topLevelTypes.topAnimationEnd: <del> case topLevelTypes.topAnimationIteration: <del> case topLevelTypes.topAnimationStart: <add> case 'topAnimationEnd': <add> case 'topAnimationIteration': <add> case 'topAnimationStart': <ide> EventConstructor = SyntheticAnimationEvent; <ide> break; <del> case topLevelTypes.topTransitionEnd: <add> case 'topTransitionEnd': <ide> EventConstructor = SyntheticTransitionEvent; <ide> break; <del> case topLevelTypes.topScroll: <add> case 'topScroll': <ide> EventConstructor = SyntheticUIEvent; <ide> break; <del> case topLevelTypes.topWheel: <add> case 'topWheel': <ide> EventConstructor = SyntheticWheelEvent; <ide> break; <del> case topLevelTypes.topCopy: <del> case topLevelTypes.topCut: <del> case topLevelTypes.topPaste: <add> case 'topCopy': <add> case 'topCut': <add> case 'topPaste': <ide> EventConstructor = SyntheticClipboardEvent; <ide> break; <ide> } <ide><path>src/renderers/dom/client/eventPlugins/TapEventPlugin.js <ide> <ide> 'use strict'; <ide> <del>var EventConstants = require('EventConstants'); <ide> var EventPluginUtils = require('EventPluginUtils'); <ide> var EventPropagators = require('EventPropagators'); <ide> var SyntheticUIEvent = require('SyntheticUIEvent'); <ide> var TouchEventUtils = require('TouchEventUtils'); <ide> var ViewportMetrics = require('ViewportMetrics'); <ide> <ide> var keyOf = require('keyOf'); <del>var topLevelTypes = EventConstants.topLevelTypes; <ide> <ide> var isStartish = EventPluginUtils.isStartish; <ide> var isEndish = EventPluginUtils.isEndish; <ide> function getDistance(coords, nativeEvent) { <ide> } <ide> <ide> var touchEvents = [ <del> topLevelTypes.topTouchStart, <del> topLevelTypes.topTouchCancel, <del> topLevelTypes.topTouchEnd, <del> topLevelTypes.topTouchMove, <add> 'topTouchStart', <add> 'topTouchCancel', <add> 'topTouchEnd', <add> 'topTouchMove', <ide> ]; <ide> <ide> var dependencies = [ <del> topLevelTypes.topMouseDown, <del> topLevelTypes.topMouseMove, <del> topLevelTypes.topMouseUp, <add> 'topMouseDown', <add> 'topMouseMove', <add> 'topMouseUp', <ide> ].concat(touchEvents); <ide> <ide> var eventTypes = { <ide><path>src/renderers/dom/client/eventPlugins/__tests__/EnterLeaveEventPlugin-test.js <ide> 'use strict'; <ide> <ide> var EnterLeaveEventPlugin; <del>var EventConstants; <ide> var React; <ide> var ReactDOM; <ide> var ReactDOMComponentTree; <ide> <del>var topLevelTypes; <del> <ide> describe('EnterLeaveEventPlugin', function() { <ide> beforeEach(function() { <ide> jest.resetModuleRegistry(); <ide> <ide> EnterLeaveEventPlugin = require('EnterLeaveEventPlugin'); <del> EventConstants = require('EventConstants'); <ide> React = require('React'); <ide> ReactDOM = require('ReactDOM'); <ide> ReactDOMComponentTree = require('ReactDOMComponentTree'); <del> <del> topLevelTypes = EventConstants.topLevelTypes; <ide> }); <ide> <ide> it('should set relatedTarget properly in iframe', function() { <ide> describe('EnterLeaveEventPlugin', function() { <ide> var div = ReactDOM.findDOMNode(component); <ide> <ide> var extracted = EnterLeaveEventPlugin.extractEvents( <del> topLevelTypes.topMouseOver, <add> 'topMouseOver', <ide> ReactDOMComponentTree.getInstanceFromNode(div), <ide> {target: div}, <ide> div <ide><path>src/renderers/dom/client/eventPlugins/__tests__/SelectEventPlugin-test.js <ide> <ide> 'use strict'; <ide> <del>var EventConstants; <ide> var React; <ide> var ReactDOM; <ide> var ReactDOMComponentTree; <ide> var ReactTestUtils; <ide> var SelectEventPlugin; <ide> <del>var topLevelTypes; <del> <ide> describe('SelectEventPlugin', function() { <ide> function extract(node, topLevelEvent) { <ide> return SelectEventPlugin.extractEvents( <ide> describe('SelectEventPlugin', function() { <ide> } <ide> <ide> beforeEach(function() { <del> EventConstants = require('EventConstants'); <ide> React = require('React'); <ide> ReactDOM = require('ReactDOM'); <ide> ReactDOMComponentTree = require('ReactDOMComponentTree'); <ide> ReactTestUtils = require('ReactTestUtils'); <ide> SelectEventPlugin = require('SelectEventPlugin'); <del> <del> topLevelTypes = EventConstants.topLevelTypes; <ide> }); <ide> <ide> it('should skip extraction if no listeners are present', function() { <ide> describe('SelectEventPlugin', function() { <ide> var node = ReactDOM.findDOMNode(rendered); <ide> node.focus(); <ide> <del> var mousedown = extract(node, topLevelTypes.topMouseDown); <add> var mousedown = extract(node, 'topMouseDown'); <ide> expect(mousedown).toBe(null); <ide> <del> var mouseup = extract(node, topLevelTypes.topMouseUp); <add> var mouseup = extract(node, 'topMouseUp'); <ide> expect(mouseup).toBe(null); <ide> }); <ide> <ide> describe('SelectEventPlugin', function() { <ide> node.selectionEnd = 0; <ide> node.focus(); <ide> <del> var focus = extract(node, topLevelTypes.topFocus); <add> var focus = extract(node, 'topFocus'); <ide> expect(focus).toBe(null); <ide> <del> var mousedown = extract(node, topLevelTypes.topMouseDown); <add> var mousedown = extract(node, 'topMouseDown'); <ide> expect(mousedown).toBe(null); <ide> <del> var mouseup = extract(node, topLevelTypes.topMouseUp); <add> var mouseup = extract(node, 'topMouseUp'); <ide> expect(mouseup).not.toBe(null); <ide> expect(typeof mouseup).toBe('object'); <ide> expect(mouseup.type).toBe('select'); <ide><path>src/renderers/dom/client/wrappers/__tests__/ReactDOMInput-test.js <ide> var emptyFunction = require('emptyFunction'); <ide> <ide> describe('ReactDOMInput', function() { <del> var EventConstants; <ide> var React; <ide> var ReactDOM; <ide> var ReactDOMServer; <ide> describe('ReactDOMInput', function() { <ide> <ide> beforeEach(function() { <ide> jest.resetModuleRegistry(); <del> EventConstants = require('EventConstants'); <ide> React = require('React'); <ide> ReactDOM = require('ReactDOM'); <ide> ReactDOMServer = require('ReactDOMServer'); <ide> describe('ReactDOMInput', function() { <ide> fakeNativeEvent.target = node; <ide> fakeNativeEvent.path = [node, container]; <ide> ReactTestUtils.simulateNativeEventOnNode( <del> EventConstants.topLevelTypes.topInput, <add> 'topInput', <ide> node, <ide> fakeNativeEvent <ide> ); <ide><path>src/renderers/dom/shared/ReactDOMComponent.js <ide> var DOMLazyTree = require('DOMLazyTree'); <ide> var DOMNamespaces = require('DOMNamespaces'); <ide> var DOMProperty = require('DOMProperty'); <ide> var DOMPropertyOperations = require('DOMPropertyOperations'); <del>var EventConstants = require('EventConstants'); <ide> var EventPluginHub = require('EventPluginHub'); <ide> var EventPluginRegistry = require('EventPluginRegistry'); <ide> var ReactBrowserEventEmitter = require('ReactBrowserEventEmitter'); <ide> function trapBubbledEventsLocal() { <ide> case 'object': <ide> inst._wrapperState.listeners = [ <ide> ReactBrowserEventEmitter.trapBubbledEvent( <del> EventConstants.topLevelTypes.topLoad, <add> 'topLoad', <ide> 'load', <ide> node <ide> ), <ide> function trapBubbledEventsLocal() { <ide> if (mediaEvents.hasOwnProperty(event)) { <ide> inst._wrapperState.listeners.push( <ide> ReactBrowserEventEmitter.trapBubbledEvent( <del> EventConstants.topLevelTypes[event], <add> event, <ide> mediaEvents[event], <ide> node <ide> ) <ide> function trapBubbledEventsLocal() { <ide> case 'source': <ide> inst._wrapperState.listeners = [ <ide> ReactBrowserEventEmitter.trapBubbledEvent( <del> EventConstants.topLevelTypes.topError, <add> 'topError', <ide> 'error', <ide> node <ide> ), <ide> function trapBubbledEventsLocal() { <ide> case 'img': <ide> inst._wrapperState.listeners = [ <ide> ReactBrowserEventEmitter.trapBubbledEvent( <del> EventConstants.topLevelTypes.topError, <add> 'topError', <ide> 'error', <ide> node <ide> ), <ide> ReactBrowserEventEmitter.trapBubbledEvent( <del> EventConstants.topLevelTypes.topLoad, <add> 'topLoad', <ide> 'load', <ide> node <ide> ), <ide> function trapBubbledEventsLocal() { <ide> case 'form': <ide> inst._wrapperState.listeners = [ <ide> ReactBrowserEventEmitter.trapBubbledEvent( <del> EventConstants.topLevelTypes.topReset, <add> 'topReset', <ide> 'reset', <ide> node <ide> ), <ide> ReactBrowserEventEmitter.trapBubbledEvent( <del> EventConstants.topLevelTypes.topSubmit, <add> 'topSubmit', <ide> 'submit', <ide> node <ide> ), <ide> function trapBubbledEventsLocal() { <ide> case 'textarea': <ide> inst._wrapperState.listeners = [ <ide> ReactBrowserEventEmitter.trapBubbledEvent( <del> EventConstants.topLevelTypes.topInvalid, <add> 'topInvalid', <ide> 'invalid', <ide> node <ide> ), <ide><path>src/renderers/native/ReactNativeEventEmitter.js <ide> */ <ide> 'use strict'; <ide> <del>var EventConstants = require('EventConstants'); <ide> var EventPluginHub = require('EventPluginHub'); <ide> var EventPluginRegistry = require('EventPluginRegistry'); <ide> var ReactEventEmitterMixin = require('ReactEventEmitterMixin'); <ide> var ReactUpdates = require('ReactUpdates'); <ide> <ide> var warning = require('warning'); <ide> <del>var topLevelTypes = EventConstants.topLevelTypes; <del> <ide> /** <ide> * Version of `ReactBrowserEventEmitter` that works on the receiving side of a <ide> * serialized worker boundary. <ide> var ReactNativeEventEmitter = { <ide> changedIndices: Array<number> <ide> ) { <ide> var changedTouches = <del> eventTopLevelType === topLevelTypes.topTouchEnd || <del> eventTopLevelType === topLevelTypes.topTouchCancel ? <add> eventTopLevelType === 'topTouchEnd' || <add> eventTopLevelType === 'topTouchCancel' ? <ide> removeTouchesAtIndices(touches, changedIndices) : <ide> touchSubsequence(touches, changedIndices); <ide> <ide><path>src/renderers/shared/stack/event/EventConstants.js <ide> <ide> 'use strict'; <ide> <del>var keyMirror = require('keyMirror'); <del> <ide> export type PropagationPhases = 'bubbled' | 'captured'; <ide> <ide> /** <ide> * Types of raw signals from the browser caught at the top level. <ide> */ <del>var topLevelTypes = keyMirror({ <add>var topLevelTypes = { <ide> topAbort: null, <ide> topAnimationEnd: null, <ide> topAnimationIteration: null, <ide> var topLevelTypes = keyMirror({ <ide> topVolumeChange: null, <ide> topWaiting: null, <ide> topWheel: null, <del>}); <add>}; <add> <add>export type TopLevelTypes = $Enum<typeof topLevelTypes>; <ide> <ide> var EventConstants = { <del> topLevelTypes: topLevelTypes, <add> topLevelTypes, <ide> }; <ide> <ide> module.exports = EventConstants; <ide><path>src/renderers/shared/stack/event/EventPluginUtils.js <ide> <ide> 'use strict'; <ide> <del>var EventConstants = require('EventConstants'); <ide> var ReactErrorUtils = require('ReactErrorUtils'); <ide> <ide> var invariant = require('invariant'); <ide> var injection = { <ide> }, <ide> }; <ide> <del>var topLevelTypes = EventConstants.topLevelTypes; <del> <ide> function isEndish(topLevelType) { <del> return topLevelType === topLevelTypes.topMouseUp || <del> topLevelType === topLevelTypes.topTouchEnd || <del> topLevelType === topLevelTypes.topTouchCancel; <add> return topLevelType === 'topMouseUp' || <add> topLevelType === 'topTouchEnd' || <add> topLevelType === 'topTouchCancel'; <ide> } <ide> <ide> function isMoveish(topLevelType) { <del> return topLevelType === topLevelTypes.topMouseMove || <del> topLevelType === topLevelTypes.topTouchMove; <add> return topLevelType === 'topMouseMove' || <add> topLevelType === 'topTouchMove'; <ide> } <ide> function isStartish(topLevelType) { <del> return topLevelType === topLevelTypes.topMouseDown || <del> topLevelType === topLevelTypes.topTouchStart; <add> return topLevelType === 'topMouseDown' || <add> topLevelType === 'topTouchStart'; <ide> } <ide> <ide> <ide><path>src/renderers/shared/stack/event/eventPlugins/ResponderEventPlugin.js <ide> <ide> 'use strict'; <ide> <del>var EventConstants = require('EventConstants'); <ide> var EventPluginUtils = require('EventPluginUtils'); <ide> var EventPropagators = require('EventPropagators'); <ide> var ResponderSyntheticEvent = require('ResponderSyntheticEvent'); <ide> function setResponderAndExtractTransfer( <ide> var shouldSetEventType = <ide> isStartish(topLevelType) ? eventTypes.startShouldSetResponder : <ide> isMoveish(topLevelType) ? eventTypes.moveShouldSetResponder : <del> topLevelType === EventConstants.topLevelTypes.topSelectionChange ? <add> topLevelType === 'topSelectionChange' ? <ide> eventTypes.selectionChangeShouldSetResponder : <ide> eventTypes.scrollShouldSetResponder; <ide> <ide> function canTriggerTransfer(topLevelType, topLevelInst, nativeEvent) { <ide> // responderIgnoreScroll: We are trying to migrate away from specifically <ide> // tracking native scroll events here and responderIgnoreScroll indicates we <ide> // will send topTouchCancel to handle canceling touch events instead <del> (topLevelType === EventConstants.topLevelTypes.topScroll && <add> (topLevelType === 'topScroll' && <ide> !nativeEvent.responderIgnoreScroll) || <ide> (trackedTouchCount > 0 && <del> topLevelType === EventConstants.topLevelTypes.topSelectionChange) || <add> topLevelType === 'topSelectionChange') || <ide> isStartish(topLevelType) || <ide> isMoveish(topLevelType) <ide> ); <ide> var ResponderEventPlugin = { <ide> <ide> var isResponderTerminate = <ide> responderInst && <del> topLevelType === EventConstants.topLevelTypes.topTouchCancel; <add> topLevelType === 'topTouchCancel'; <ide> var isResponderRelease = <ide> responderInst && <ide> !isResponderTerminate && <ide><path>src/renderers/shared/stack/event/eventPlugins/__tests__/ResponderEventPlugin-test.js <ide> 'use strict'; <ide> <ide> var EventPluginHub; <del>var EventConstants; <ide> var ReactInstanceHandles; <ide> var ResponderEventPlugin; <ide> var EventPluginUtils; <ide> <del>var topLevelTypes; <del> <ide> var touch = function(nodeHandle, i) { <ide> return {target: nodeHandle, identifier: i}; <ide> }; <ide> var _touchConfig = function( <ide> */ <ide> var startConfig = function(nodeHandle, allTouchHandles, changedIndices) { <ide> return _touchConfig( <del> topLevelTypes.topTouchStart, <add> 'topTouchStart', <ide> nodeHandle, <ide> allTouchHandles, <ide> changedIndices, <ide> var startConfig = function(nodeHandle, allTouchHandles, changedIndices) { <ide> */ <ide> var moveConfig = function(nodeHandle, allTouchHandles, changedIndices) { <ide> return _touchConfig( <del> topLevelTypes.topTouchMove, <add> 'topTouchMove', <ide> nodeHandle, <ide> allTouchHandles, <ide> changedIndices, <ide> var moveConfig = function(nodeHandle, allTouchHandles, changedIndices) { <ide> */ <ide> var endConfig = function(nodeHandle, allTouchHandles, changedIndices) { <ide> return _touchConfig( <del> topLevelTypes.topTouchEnd, <add> 'topTouchEnd', <ide> nodeHandle, <ide> allTouchHandles, <ide> changedIndices, <ide> describe('ResponderEventPlugin', function() { <ide> beforeEach(function() { <ide> jest.resetModuleRegistry(); <ide> <del> EventConstants = require('EventConstants'); <ide> EventPluginHub = require('EventPluginHub'); <ide> EventPluginUtils = require('EventPluginUtils'); <ide> ReactInstanceHandles = require('ReactInstanceHandles'); <ide> describe('ResponderEventPlugin', function() { <ide> ); <ide> }, <ide> }); <del> <del> topLevelTypes = EventConstants.topLevelTypes; <ide> }); <ide> <ide> it('should do nothing when no one wants to respond', function() { <ide> describe('ResponderEventPlugin', function() { <ide> config.responderReject.parent = {order: 5}; <ide> <ide> run(config, three, { <del> topLevelType: topLevelTypes.topScroll, <add> topLevelType: 'topScroll', <ide> targetInst: idToInstance[three.parent], <ide> nativeEvent: {}, <ide> }); <ide> describe('ResponderEventPlugin', function() { <ide> config.responderTerminate.child = {order: 5}; <ide> <ide> run(config, three, { <del> topLevelType: topLevelTypes.topScroll, <add> topLevelType: 'topScroll', <ide> targetInst: idToInstance[three.parent], <ide> nativeEvent: {}, <ide> }); <ide> describe('ResponderEventPlugin', function() { <ide> config.responderTerminate.child = {order: 1}; <ide> <ide> var nativeEvent = _touchConfig( <del> topLevelTypes.topTouchCancel, <add> 'topTouchCancel', <ide> three.child, <ide> [three.child], <ide> [0]
16
Python
Python
fix typos in arrayprint docstrings
74dbda5345ee426d91472f91975993f760c224ec
<ide><path>numpy/core/arrayprint.py <ide> def set_printoptions(precision=None, threshold=None, edgeitems=None, <ide> - 'longfloat' : 128-bit floats <ide> - 'complexfloat' <ide> - 'longcomplexfloat' : composed of two 128-bit floats <del> - 'numpy_str' : types `numpy.string_` and `numpy.unicode_` <add> - 'numpystr' : types `numpy.string_` and `numpy.unicode_` <ide> - 'str' : all other strings <ide> <ide> Other keys that can be used to set a group of types at once are:: <ide> def array2string(a, max_line_width=None, precision=None, <ide> - 'longfloat' : 128-bit floats <ide> - 'complexfloat' <ide> - 'longcomplexfloat' : composed of two 128-bit floats <del> - 'numpy_str' : types `numpy.string_` and `numpy.unicode_` <add> - 'numpystr' : types `numpy.string_` and `numpy.unicode_` <ide> - 'str' : all other strings <ide> <ide> Other keys that can be used to set a group of types at once are::
1
PHP
PHP
apply fixes from styleci
ffa3ef355ad015ecd87399a21214e1a7efbd9fb0
<ide><path>src/Illuminate/Filesystem/FilesystemManager.php <ide> protected function adapt(FilesystemInterface $filesystem) <ide> public function set($name, $disk) <ide> { <ide> $this->disks[$name] = $disk; <del> <add> <ide> return $this; <ide> } <ide>
1
Javascript
Javascript
remove the `requestanimationframe` polyfill
d5174cd826bdf2f1a11aed8123ebeabe97ae7626
<ide><path>src/shared/compatibility.js <ide> PDFJS.compatibilityChecked = true; <ide> } <ide> })(); <ide> <del>// Support: IE<10, Android<4.0, iOS <del>(function checkRequestAnimationFrame() { <del> function installFakeAnimationFrameFunctions() { <del> window.requestAnimationFrame = function (callback) { <del> return window.setTimeout(callback, 20); <del> }; <del> window.cancelAnimationFrame = function (timeoutID) { <del> window.clearTimeout(timeoutID); <del> }; <del> } <del> <del> if (!hasDOM) { <del> return; <del> } <del> if (isIOS) { <del> // requestAnimationFrame on iOS is broken, replacing with fake one. <del> installFakeAnimationFrameFunctions(); <del> return; <del> } <del> if ('requestAnimationFrame' in window) { <del> return; <del> } <del> window.requestAnimationFrame = window.mozRequestAnimationFrame || <del> window.webkitRequestAnimationFrame; <del> if (window.requestAnimationFrame) { <del> return; <del> } <del> installFakeAnimationFrameFunctions(); <del>})(); <del> <ide> // Support: Android, iOS <ide> (function checkCanvasSizeLimitation() { <ide> if (isIOS || isAndroid) {
1
Text
Text
add circleci, clarify travis over macos
1200bfe6a1706ba927dec777ed5125fe14a0e0f7
<ide><path>docs/build-instructions/build-status.md <del># Atom build status <add># Atom build statusgg <ide> <del>| System | macOS | Windows | Dependencies | <del>|--------|------|---------|--------------| <del>| [Atom](https://github.com/atom/atom) | [![macOS Build Status](https://travis-ci.org/atom/atom.svg?branch=master)](https://travis-ci.org/atom/atom) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/1tkktwh654w07eim?svg=true)](https://ci.appveyor.com/project/Atom/atom) | [![Dependency Status](https://david-dm.org/atom/atom.svg)](https://david-dm.org/atom/atom) | <del>| [APM](https://github.com/atom/apm) | [![macOS Build Status](https://travis-ci.org/atom/apm.svg?branch=master)](https://travis-ci.org/atom/apm) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/j6ixw374a397ugkb/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/apm/branch/master) | [![Dependency Status](https://david-dm.org/atom/apm.svg)](https://david-dm.org/atom/apm) | <del>| [Electron](https://github.com/electron/electron) | [![macOS Build Status](https://travis-ci.org/electron/electron.svg?branch=master)](https://travis-ci.org/electron/electron) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/kvxe4byi7jcxbe26/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/electron) | [![Dependency Status](https://david-dm.org/electron/electron/dev-status.svg)](https://david-dm.org/electron/electron) <add>| System | Travis | AppVeyor/Win | Circle/Mac | Dependencies | <add>|--------|--------|--------------|------------|--------------| <add>| [Atom](https://github.com/atom/atom) | [![Travis Build Status](https://travis-ci.org/atom/atom.svg?branch=master)](https://travis-ci.org/atom/atom) | [![AppVeyor/Wi Build Status](https://ci.appveyor.com/api/projects/status/1tkktwh654w07eim?svg=true)](https://ci.appveyor.com/project/Atom/atom) | [![Circle/Mac Build Status](https://circleci.com/gh/atom/atom.svg?style=svg)](https://circleci.com/gh/atom/atom) | [![Dependency Status](https://david-dm.org/atom/atom.svg)](https://david-dm.org/atom/atom) | <add>| [APM](https://github.com/atom/apm) | [![Travis Build Status](https://travis-ci.org/atom/apm.svg?branch=master)](https://travis-ci.org/atom/apm) | [![AppVeyor/Wi Build Status](https://ci.appveyor.com/api/projects/status/j6ixw374a397ugkb/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/apm/branch/master) | | [![Dependency Status](https://david-dm.org/atom/apm.svg)](https://david-dm.org/atom/apm) | <add>| [Electron](https://github.com/electron/electron) | [![Travis Build Status](https://travis-ci.org/electron/electron.svg?branch=master)](https://travis-ci.org/electron/electron) | [![AppVeyor/Wi Build Status](https://ci.appveyor.com/api/projects/status/kvxe4byi7jcxbe26/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/electron) | | [![Dependency Status](https://david-dm.org/electron/electron/dev-status.svg)](https://david-dm.org/electron/electron) <ide> <ide> ## Packages <ide> <del>| Package | macOS | Windows | Dependencies | <del>|---------|------|---------|--------------| <add>| Package | Travis | AppVeyor/Win | Dependencies | <add>|---------|--------|--------------|--------------| <ide> | [About](https://github.com/atom/about) | [![macOS Build Status](https://travis-ci.org/atom/about.svg?branch=master)](https://travis-ci.org/atom/about) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/msprea3vq47l8oce/branch/master?svg=true)](https://ci.appveyor.com/project/atom/about/branch/master) | [![Dependency Status](https://david-dm.org/atom/about.svg)](https://david-dm.org/atom/about) | <ide> | [Archive View](https://github.com/atom/archive-view) | [![macOS Build Status](https://travis-ci.org/atom/archive-view.svg?branch=master)](https://travis-ci.org/atom/archive-view) | [![Windows Build status](https://ci.appveyor.com/api/projects/status/u3qfgaod4lhriqlj/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/archive-view/branch/master) | [![Dependency Status](https://david-dm.org/atom/archive-view.svg)](https://david-dm.org/atom/archive-view) | <ide> | [AutoComplete Atom API](https://github.com/atom/autocomplete-atom-api) | [![macOS Build Status](https://travis-ci.org/atom/autocomplete-atom-api.svg?branch=master)](https://travis-ci.org/atom/autocomplete-atom-api) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/1x3uqd9ddchpe555/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/autocomplete-atom-api/branch/master) | [![Dependency Status](https://david-dm.org/atom/autocomplete-atom-api.svg)](https://david-dm.org/atom/autocomplete-atom-api) | <ide> <ide> ## Libraries <ide> <del>| Library | macOS | Windows | Dependencies | <del>|---------|------|---------|--------------| <add>| Library | Travis | AppVeyor/Win | Dependencies | <add>|---------|--------|--------------|--------------| <ide> | [Clear Cut](https://github.com/atom/clear-cut) | [![macOS Build Status](https://travis-ci.org/atom/clear-cut.svg?branch=master)](https://travis-ci.org/atom/clear-cut) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/civ54x89l06286m9/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/clear-cut/branch/master) | [![Dependency Status](https://david-dm.org/atom/clear-cut.svg)](https://david-dm.org/atom/clear-cut) | <ide> | [Event Kit](https://github.com/atom/event-kit) | [![macOS Build Status](https://travis-ci.org/atom/event-kit.svg?branch=master)](https://travis-ci.org/atom/event-kit) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/lb32q70204lpmlxo/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/event-kit/branch/master) | [![Dependency Status](https://david-dm.org/atom/event-kit.svg)](https://david-dm.org/atom/event-kit) | <ide> | [First Mate](https://github.com/atom/first-mate) | [![macOS Build Status](https://travis-ci.org/atom/first-mate.svg?branch=master)](https://travis-ci.org/atom/first-mate) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/p5im21uq22cwgb6d/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/first-mate) | [![Dependency Status](https://david-dm.org/atom/first-mate/status.svg)](https://david-dm.org/atom/first-mate) | <ide> | [Underscore-Plus](https://github.com/atom/underscore-plus) | [![macOS Build Status](https://travis-ci.org/atom/underscore-plus.svg?branch=master)](https://travis-ci.org/atom/underscore-plus) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/c7l8009vgpaojxcd/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/underscore-plus/branch/master) | [![Dependency Status](https://david-dm.org/atom/underscore-plus.svg)](https://david-dm.org/atom/underscore-plus) | <ide> <ide> ## Tools <del>| Language | macOS | Windows | Dependencies | <del>|----------|------|---------|--------------| <add>| Language | Travis | AppVeyor/Win | Dependencies | <add>|----------|--------|--------------|--------------| <ide> | [AtomDoc](https://github.com/atom/atomdoc) | [![macOS Build Status](https://travis-ci.org/atom/atomdoc.svg?branch=master)](https://travis-ci.org/atom/atomdoc) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/chi2bmaafr3puyq2/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/atomdoc/branch/master) | [![Dependency Status](https://david-dm.org/atom/atomdoc.svg)](https://david-dm.org/atom/atomdoc) <ide> <ide> ## Languages <ide> <del>| Language | macOS | Windows | <del>|----------|------|---------| <add>| Language | Travis | AppVeyor/Win | <add>|----------|--------|--------------| <ide> | [C/C++](https://github.com/atom/language-c) | [![macOS Build Status](https://travis-ci.org/atom/language-c.svg?branch=master)](https://travis-ci.org/atom/language-c) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/8oy1hmp4yrij7c32/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-c/branch/master) | <ide> | [C#](https://github.com/atom/language-csharp) | [![macOS Build Status](https://travis-ci.org/atom/language-csharp.svg?branch=master)](https://travis-ci.org/atom/language-csharp) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/j1as3753y5t90obn/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-csharp/branch/master) | <ide> | [Clojure](https://github.com/atom/language-clojure) | [![macOS Build Status](https://travis-ci.org/atom/language-clojure.svg?branch=master)](https://travis-ci.org/atom/language-clojure) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/6kd5fs48y5hixde6/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/language-clojure/branch/master) |
1
Python
Python
add a flag for find_unused_parameters
c7b7bd9963945ee3b10de1c2d2243d23cb621a98
<ide><path>src/transformers/trainer.py <ide> def train(self, model_path: Optional[str] = None, trial: Union["optuna.Trial", D <ide> elif is_sagemaker_distributed_available(): <ide> model = DDP(model, device_ids=[dist.get_local_rank()], broadcast_buffers=False) <ide> elif self.args.local_rank != -1: <add> if self.args.ddp_find_unused_parameters is not None: <add> find_unused_parameters = self.args.ddp_find_unused_parameters <add> elif isinstance(model, PreTrainedModel): <add> # find_unused_parameters breaks checkpointing as per <add> # https://github.com/huggingface/transformers/pull/4659#issuecomment-643356021 <add> find_unused_parameters = not getattr(model.config, "gradient_checkpointing", False) <add> else: <add> find_unused_parameters = True <ide> model = torch.nn.parallel.DistributedDataParallel( <ide> model, <ide> device_ids=[self.args.local_rank], <ide> output_device=self.args.local_rank, <del> find_unused_parameters=( <del> not getattr(model.config, "gradient_checkpointing", False) <del> if isinstance(model, PreTrainedModel) <del> else True <del> ), <add> find_unused_parameters=find_unused_parameters, <ide> ) <del> # find_unused_parameters breaks checkpointing as per <del> # https://github.com/huggingface/transformers/pull/4659#issuecomment-643356021 <ide> <ide> # for the rest of this function `model` is the outside model, whether it was wrapped or not <ide> if model is not self.model: <ide><path>src/transformers/training_args.py <ide> class TrainingArguments: <ide> report_to (:obj:`List[str]`, `optional`, defaults to the list of integrations platforms installed): <ide> The list of integrations to report the results and logs to. Supported platforms are :obj:`"azure_ml"`, <ide> :obj:`"comet_ml"`, :obj:`"mlflow"`, :obj:`"tensorboard"` and :obj:`"wandb"`. <add> ddp_find_unused_parameters (:obj:`bool`, `optional`): <add> When using distributed training, the value of the flag :obj:`find_unused_parameters` passed to <add> :obj:`DistributedDataParallel`. Will defaut to :obj:`False` if gradient checkpointing is used, :obj:`True` <add> otherwise. <ide> """ <ide> <ide> output_dir: str = field( <ide> class TrainingArguments: <ide> report_to: Optional[List[str]] = field( <ide> default=None, metadata={"help": "The list of integrations to report the results and logs to."} <ide> ) <add> ddp_find_unused_parameters: Optional[bool] = field( <add> default=None, <add> metadata={ <add> "help": "When using distributed training, the value of the flag `find_unused_parameters` passed to " <add> "`DistributedDataParallel`." <add> }, <add> ) <ide> _n_gpu: int = field(init=False, repr=False, default=-1) <ide> <ide> def __post_init__(self):
2
Go
Go
check propagation properties of source mount point
d4b4ce2588d02acd3602d42b788c6b36ab9b01e5
<ide><path>daemon/execdriver/native/create.go <ide> func checkResetVolumePropagation(container *configs.Config) { <ide> } <ide> } <ide> <add>func getMountInfo(mountinfo []*mount.Info, dir string) *mount.Info { <add> for _, m := range mountinfo { <add> if m.Mountpoint == dir { <add> return m <add> } <add> } <add> return nil <add>} <add> <add>// Get the source mount point of directory passed in as argument. Also return <add>// optional fields. <add>func getSourceMount(source string) (string, string, error) { <add> // Ensure any symlinks are resolved. <add> sourcePath, err := filepath.EvalSymlinks(source) <add> if err != nil { <add> return "", "", err <add> } <add> <add> mountinfos, err := mount.GetMounts() <add> if err != nil { <add> return "", "", err <add> } <add> <add> mountinfo := getMountInfo(mountinfos, sourcePath) <add> if mountinfo != nil { <add> return sourcePath, mountinfo.Optional, nil <add> } <add> <add> path := sourcePath <add> for { <add> path = filepath.Dir(path) <add> <add> mountinfo = getMountInfo(mountinfos, path) <add> if mountinfo != nil { <add> return path, mountinfo.Optional, nil <add> } <add> <add> if path == "/" { <add> break <add> } <add> } <add> <add> // If we are here, we did not find parent mount. Something is wrong. <add> return "", "", fmt.Errorf("Could not find source mount of %s", source) <add>} <add> <add>// Ensure mount point on which path is mouted, is shared. <add>func ensureShared(path string) error { <add> sharedMount := false <add> <add> sourceMount, optionalOpts, err := getSourceMount(path) <add> if err != nil { <add> return err <add> } <add> // Make sure source mount point is shared. <add> optsSplit := strings.Split(optionalOpts, " ") <add> for _, opt := range optsSplit { <add> if strings.HasPrefix(opt, "shared:") { <add> sharedMount = true <add> break <add> } <add> } <add> <add> if !sharedMount { <add> return fmt.Errorf("Path %s is mounted on %s but it is not a shared mount.", path, sourceMount) <add> } <add> return nil <add>} <add> <add>// Ensure mount point on which path is mounted, is either shared or slave. <add>func ensureSharedOrSlave(path string) error { <add> sharedMount := false <add> slaveMount := false <add> <add> sourceMount, optionalOpts, err := getSourceMount(path) <add> if err != nil { <add> return err <add> } <add> // Make sure source mount point is shared. <add> optsSplit := strings.Split(optionalOpts, " ") <add> for _, opt := range optsSplit { <add> if strings.HasPrefix(opt, "shared:") { <add> sharedMount = true <add> break <add> } else if strings.HasPrefix(opt, "master:") { <add> slaveMount = true <add> break <add> } <add> } <add> <add> if !sharedMount && !slaveMount { <add> return fmt.Errorf("Path %s is mounted on %s but it is not a shared or slave mount.", path, sourceMount) <add> } <add> return nil <add>} <add> <ide> func (d *Driver) setupMounts(container *configs.Config, c *execdriver.Command) error { <ide> userMounts := make(map[string]struct{}) <ide> for _, m := range c.Mounts { <ide> func (d *Driver) setupMounts(container *configs.Config, c *execdriver.Command) e <ide> <ide> pFlag = mountPropagationMap[m.Propagation] <ide> if pFlag == mount.SHARED || pFlag == mount.RSHARED { <add> if err := ensureShared(m.Source); err != nil { <add> return err <add> } <ide> rootpg := container.RootPropagation <ide> if rootpg != mount.SHARED && rootpg != mount.RSHARED { <ide> execdriver.SetRootPropagation(container, mount.SHARED) <ide> } <ide> } else if pFlag == mount.SLAVE || pFlag == mount.RSLAVE { <add> if err := ensureSharedOrSlave(m.Source); err != nil { <add> return err <add> } <ide> rootpg := container.RootPropagation <ide> if rootpg != mount.SHARED && rootpg != mount.RSHARED && rootpg != mount.SLAVE && rootpg != mount.RSLAVE { <ide> execdriver.SetRootPropagation(container, mount.RSLAVE)
1
Java
Java
introduce localecontextresolver in webflux
e0e6736bc58101af13a352d4aa2a6c2dc0994d72
<ide><path>spring-context/src/main/java/org/springframework/context/i18n/SimpleTimeZoneAwareLocaleContext.java <ide> public SimpleTimeZoneAwareLocaleContext(@Nullable Locale locale, @Nullable TimeZ <ide> } <ide> <ide> <add> @Override <ide> public TimeZone getTimeZone() { <ide> return this.timeZone; <ide> } <ide><path>spring-test/src/main/java/org/springframework/mock/http/server/reactive/MockServerWebExchange.java <ide> import org.springframework.http.codec.ServerCodecConfigurer; <ide> import org.springframework.web.server.ServerWebExchangeDecorator; <ide> import org.springframework.web.server.adapter.DefaultServerWebExchange; <add>import org.springframework.web.server.i18n.AcceptHeaderLocaleContextResolver; <ide> import org.springframework.web.server.session.DefaultWebSessionManager; <ide> <ide> /** <ide> public class MockServerWebExchange extends ServerWebExchangeDecorator { <ide> public MockServerWebExchange(MockServerHttpRequest request) { <ide> super(new DefaultServerWebExchange( <ide> request, new MockServerHttpResponse(), new DefaultWebSessionManager(), <del> ServerCodecConfigurer.create())); <add> ServerCodecConfigurer.create(), new AcceptHeaderLocaleContextResolver())); <ide> } <ide> <ide> <ide><path>spring-web/src/main/java/org/springframework/web/server/ServerWebExchange.java <ide> <ide> import reactor.core.publisher.Mono; <ide> <add>import org.springframework.context.i18n.LocaleContext; <ide> import org.springframework.http.codec.multipart.Part; <ide> import org.springframework.http.server.reactive.ServerHttpRequest; <ide> import org.springframework.http.server.reactive.ServerHttpResponse; <ide> import org.springframework.lang.Nullable; <ide> import org.springframework.util.MultiValueMap; <add>import org.springframework.web.server.i18n.LocaleContextResolver; <ide> <ide> /** <ide> * Contract for an HTTP request-response interaction. Provides access to the HTTP <ide> public interface ServerWebExchange { <ide> */ <ide> Mono<MultiValueMap<String, Part>> getMultipartData(); <ide> <add> /** <add> * Return the {@link LocaleContext} using the configured {@link LocaleContextResolver}. <add> */ <add> LocaleContext getLocaleContext(); <add> <ide> /** <ide> * Returns {@code true} if the one of the {@code checkNotModified} methods <ide> * in this contract were used and they returned true. <ide><path>spring-web/src/main/java/org/springframework/web/server/ServerWebExchangeDecorator.java <ide> <ide> import reactor.core.publisher.Mono; <ide> <add>import org.springframework.context.i18n.LocaleContext; <ide> import org.springframework.http.codec.multipart.Part; <ide> import org.springframework.http.server.reactive.ServerHttpRequest; <ide> import org.springframework.http.server.reactive.ServerHttpResponse; <ide> public <T extends Principal> Mono<T> getPrincipal() { <ide> return getDelegate().getPrincipal(); <ide> } <ide> <add> @Override <add> public LocaleContext getLocaleContext() { <add> return getDelegate().getLocaleContext(); <add> } <add> <ide> @Override <ide> public Mono<MultiValueMap<String, String>> getFormData() { <ide> return getDelegate().getFormData(); <ide><path>spring-web/src/main/java/org/springframework/web/server/adapter/DefaultServerWebExchange.java <ide> <ide> import reactor.core.publisher.Mono; <ide> <add>import org.springframework.context.i18n.LocaleContext; <ide> import org.springframework.core.ResolvableType; <ide> import org.springframework.http.HttpHeaders; <ide> import org.springframework.http.HttpMethod; <ide> import org.springframework.util.LinkedMultiValueMap; <ide> import org.springframework.util.MultiValueMap; <ide> import org.springframework.util.StringUtils; <add>import org.springframework.web.server.i18n.LocaleContextResolver; <ide> import org.springframework.web.server.ServerWebExchange; <ide> import org.springframework.web.server.WebSession; <ide> import org.springframework.web.server.session.WebSessionManager; <ide> public class DefaultServerWebExchange implements ServerWebExchange { <ide> <ide> private final Mono<WebSession> sessionMono; <ide> <add> private final LocaleContextResolver localeContextResolver; <add> <ide> private final Mono<MultiValueMap<String, String>> formDataMono; <ide> <ide> private final Mono<MultiValueMap<String, Part>> multipartDataMono; <ide> <ide> private volatile boolean notModified; <ide> <ide> <del> /** <del> * Alternate constructor with a WebSessionManager parameter. <del> */ <ide> public DefaultServerWebExchange(ServerHttpRequest request, ServerHttpResponse response, <del> WebSessionManager sessionManager, ServerCodecConfigurer codecConfigurer) { <add> WebSessionManager sessionManager, ServerCodecConfigurer codecConfigurer, LocaleContextResolver localeContextResolver) { <ide> <ide> Assert.notNull(request, "'request' is required"); <ide> Assert.notNull(response, "'response' is required"); <ide> Assert.notNull(sessionManager, "'sessionManager' is required"); <ide> Assert.notNull(codecConfigurer, "'codecConfigurer' is required"); <add> Assert.notNull(localeContextResolver, "'localeContextResolver' is required"); <ide> <ide> this.request = request; <ide> this.response = response; <ide> this.sessionMono = sessionManager.getSession(this).cache(); <add> this.localeContextResolver = localeContextResolver; <ide> this.formDataMono = initFormData(request, codecConfigurer); <ide> this.multipartDataMono = initMultipartData(request, codecConfigurer); <ide> } <ide> public <T extends Principal> Mono<T> getPrincipal() { <ide> return Mono.empty(); <ide> } <ide> <add> @Override <add> public LocaleContext getLocaleContext() { <add> return this.localeContextResolver.resolveLocaleContext(this); <add> } <add> <ide> @Override <ide> public Mono<MultiValueMap<String, String>> getFormData() { <ide> return this.formDataMono; <ide><path>spring-web/src/main/java/org/springframework/web/server/adapter/HttpWebHandlerAdapter.java <ide> import org.springframework.http.server.reactive.ServerHttpRequest; <ide> import org.springframework.http.server.reactive.ServerHttpResponse; <ide> import org.springframework.util.Assert; <add>import org.springframework.web.server.i18n.LocaleContextResolver; <ide> import org.springframework.web.server.ServerWebExchange; <ide> import org.springframework.web.server.WebHandler; <ide> import org.springframework.web.server.handler.WebHandlerDecorator; <add>import org.springframework.web.server.i18n.AcceptHeaderLocaleContextResolver; <ide> import org.springframework.web.server.session.DefaultWebSessionManager; <ide> import org.springframework.web.server.session.WebSessionManager; <ide> <ide> public class HttpWebHandlerAdapter extends WebHandlerDecorator implements HttpHa <ide> <ide> private ServerCodecConfigurer codecConfigurer; <ide> <add> private LocaleContextResolver localeContextResolver; <add> <ide> <ide> public HttpWebHandlerAdapter(WebHandler delegate) { <ide> super(delegate); <ide> public void setCodecConfigurer(ServerCodecConfigurer codecConfigurer) { <ide> this.codecConfigurer = codecConfigurer; <ide> } <ide> <add> /** <add> * Configure a custom {@link LocaleContextResolver}. The provided instance is set on <add> * each created {@link DefaultServerWebExchange}. <add> * <p>By default this is set to {@link org.springframework.web.server.i18n.AcceptHeaderLocaleContextResolver}. <add> * @param localeContextResolver the locale context resolver to use <add> */ <add> public void setLocaleContextResolver(LocaleContextResolver localeContextResolver) { <add> this.localeContextResolver = localeContextResolver; <add> } <add> <ide> /** <ide> * Return the configured {@link ServerCodecConfigurer}. <ide> */ <ide> public ServerCodecConfigurer getCodecConfigurer() { <ide> return (this.codecConfigurer != null ? this.codecConfigurer : ServerCodecConfigurer.create()); <ide> } <ide> <add> /** <add> * Return the configured {@link LocaleContextResolver}. <add> */ <add> public LocaleContextResolver getLocaleContextResolver() { <add> return (this.localeContextResolver != null ? this.localeContextResolver : new AcceptHeaderLocaleContextResolver()); <add> } <add> <ide> <ide> @Override <ide> public Mono<Void> handle(ServerHttpRequest request, ServerHttpResponse response) { <ide> public Mono<Void> handle(ServerHttpRequest request, ServerHttpResponse response) <ide> } <ide> <ide> protected ServerWebExchange createExchange(ServerHttpRequest request, ServerHttpResponse response) { <del> return new DefaultServerWebExchange(request, response, this.sessionManager, getCodecConfigurer()); <add> return new DefaultServerWebExchange(request, response, this.sessionManager, getCodecConfigurer(), getLocaleContextResolver()); <ide> } <ide> <ide> private void logHandleFailure(Throwable ex) { <ide><path>spring-web/src/main/java/org/springframework/web/server/adapter/WebHttpHandlerBuilder.java <ide> import org.springframework.http.server.reactive.HttpHandler; <ide> import org.springframework.util.Assert; <ide> import org.springframework.util.ObjectUtils; <add>import org.springframework.web.server.i18n.LocaleContextResolver; <ide> import org.springframework.web.server.ServerWebExchange; <ide> import org.springframework.web.server.WebExceptionHandler; <ide> import org.springframework.web.server.WebFilter; <ide> public class WebHttpHandlerBuilder { <ide> /** Well-known name for the ServerCodecConfigurer in the bean factory. */ <ide> public static final String SERVER_CODEC_CONFIGURER_BEAN_NAME = "serverCodecConfigurer"; <ide> <add> /** Well-known name for the LocaleContextResolver in the bean factory. */ <add> public static final String LOCALE_CONTEXT_RESOLVER_BEAN_NAME = "localeContextResolver"; <add> <ide> <ide> private final WebHandler webHandler; <ide> <ide> public class WebHttpHandlerBuilder { <ide> <ide> private ServerCodecConfigurer codecConfigurer; <ide> <add> private LocaleContextResolver localeContextResolver; <add> <ide> <ide> /** <ide> * Private constructor. <ide> public static WebHttpHandlerBuilder webHandler(WebHandler webHandler) { <ide> * {@link #WEB_SESSION_MANAGER_BEAN_NAME}. <ide> * <li>{@link ServerCodecConfigurer} [0..1] -- looked up by the name <ide> * {@link #SERVER_CODEC_CONFIGURER_BEAN_NAME}. <add> *<li>{@link LocaleContextResolver} [0..1] -- looked up by the name <add> * {@link #LOCALE_CONTEXT_RESOLVER_BEAN_NAME}. <ide> * </ul> <ide> * @param context the application context to use for the lookup <ide> * @return the prepared builder <ide> public static WebHttpHandlerBuilder applicationContext(ApplicationContext contex <ide> // Fall back on default <ide> } <ide> <add> try { <add> builder.localeContextResolver( <add> context.getBean(LOCALE_CONTEXT_RESOLVER_BEAN_NAME, LocaleContextResolver.class)); <add> } <add> catch (NoSuchBeanDefinitionException ex) { <add> // Fall back on default <add> } <add> <ide> return builder; <ide> } <ide> <ide> public WebHttpHandlerBuilder codecConfigurer(ServerCodecConfigurer codecConfigur <ide> return this; <ide> } <ide> <add> /** <add> * Configure the {@link LocaleContextResolver} to set on the <add> * {@link ServerWebExchange WebServerExchange}. <add> * @param localeContextResolver the locale context resolver <add> */ <add> public WebHttpHandlerBuilder localeContextResolver(LocaleContextResolver localeContextResolver) { <add> this.localeContextResolver = localeContextResolver; <add> return this; <add> } <add> <ide> <ide> /** <ide> * Build the {@link HttpHandler}. <ide> public HttpHandler build() { <ide> if (this.codecConfigurer != null) { <ide> adapted.setCodecConfigurer(this.codecConfigurer); <ide> } <add> if (this.localeContextResolver != null) { <add> adapted.setLocaleContextResolver(this.localeContextResolver); <add> } <ide> <ide> return adapted; <ide> } <ide><path>spring-web/src/main/java/org/springframework/web/server/i18n/AcceptHeaderLocaleContextResolver.java <add>/* <add> * Copyright 2002-2017 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> <add>package org.springframework.web.server.i18n; <add> <add>import java.util.ArrayList; <add>import java.util.List; <add>import java.util.Locale; <add> <add>import org.springframework.context.i18n.LocaleContext; <add>import org.springframework.context.i18n.SimpleLocaleContext; <add>import org.springframework.http.HttpHeaders; <add>import org.springframework.http.server.reactive.ServerHttpRequest; <add>import org.springframework.lang.Nullable; <add>import org.springframework.web.server.ServerWebExchange; <add> <add>/** <add> * {@link LocaleContextResolver} implementation that simply uses the primary locale <add> * specified in the "Accept-Language" header of the HTTP request (that is, <add> * the locale sent by the client browser, normally that of the client's OS). <add> * <add> * <p>Note: Does not support {@code setLocale}, since the accept header <add> * can only be changed through changing the client's locale settings. <add> * <add> * @author Sebastien Deleuze <add> * @since 5.0 <add> */ <add>public class AcceptHeaderLocaleContextResolver implements LocaleContextResolver { <add> <add> private final List<Locale> supportedLocales = new ArrayList<>(4); <add> <add> private Locale defaultLocale; <add> <add> <add> /** <add> * Configure supported locales to check against the requested locales <add> * determined via {@link HttpHeaders#getAcceptLanguageAsLocales()}. <add> * @param locales the supported locales <add> */ <add> public void setSupportedLocales(List<Locale> locales) { <add> this.supportedLocales.clear(); <add> if (locales != null) { <add> this.supportedLocales.addAll(locales); <add> } <add> } <add> <add> /** <add> * Return the configured list of supported locales. <add> */ <add> public List<Locale> getSupportedLocales() { <add> return this.supportedLocales; <add> } <add> <add> /** <add> * Configure a fixed default locale to fall back on if the request does not <add> * have an "Accept-Language" header (not set by default). <add> * @param defaultLocale the default locale to use <add> */ <add> public void setDefaultLocale(Locale defaultLocale) { <add> this.defaultLocale = defaultLocale; <add> } <add> <add> /** <add> * The configured default locale, if any. <add> */ <add> @Nullable <add> public Locale getDefaultLocale() { <add> return this.defaultLocale; <add> } <add> <add> @Override <add> public LocaleContext resolveLocaleContext(ServerWebExchange exchange) { <add> ServerHttpRequest request = exchange.getRequest(); <add> List<Locale> acceptableLocales = request.getHeaders().getAcceptLanguageAsLocales(); <add> if (this.defaultLocale != null && acceptableLocales.isEmpty()) { <add> return new SimpleLocaleContext(this.defaultLocale); <add> } <add> Locale requestLocale = acceptableLocales.isEmpty() ? null : acceptableLocales.get(0); <add> if (isSupportedLocale(requestLocale)) { <add> return new SimpleLocaleContext(requestLocale); <add> } <add> Locale supportedLocale = findSupportedLocale(request); <add> if (supportedLocale != null) { <add> return new SimpleLocaleContext(supportedLocale); <add> } <add> return (defaultLocale != null ? new SimpleLocaleContext(defaultLocale) : new SimpleLocaleContext(requestLocale)); <add> } <add> <add> private boolean isSupportedLocale(@Nullable Locale locale) { <add> if (locale == null) { <add> return false; <add> } <add> List<Locale> supportedLocales = getSupportedLocales(); <add> return (supportedLocales.isEmpty() || supportedLocales.contains(locale)); <add> } <add> <add> @Nullable <add> private Locale findSupportedLocale(ServerHttpRequest request) { <add> List<Locale> requestLocales = request.getHeaders().getAcceptLanguageAsLocales(); <add> for (Locale locale : requestLocales) { <add> if (getSupportedLocales().contains(locale)) { <add> return locale; <add> } <add> } <add> return null; <add> } <add> <add> @Override <add> public void setLocaleContext(ServerWebExchange exchange, @Nullable LocaleContext locale) { <add> throw new UnsupportedOperationException( <add> "Cannot change HTTP accept header - use a different locale context resolution strategy"); <add> } <add> <add>} <ide><path>spring-web/src/main/java/org/springframework/web/server/i18n/FixedLocaleContextResolver.java <add>/* <add> * Copyright 2002-2013 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> <add>package org.springframework.web.server.i18n; <add> <add>import java.util.Locale; <add>import java.util.TimeZone; <add> <add>import org.springframework.context.i18n.LocaleContext; <add>import org.springframework.context.i18n.TimeZoneAwareLocaleContext; <add>import org.springframework.lang.Nullable; <add>import org.springframework.util.Assert; <add>import org.springframework.web.server.ServerWebExchange; <add> <add>/** <add> * {@link LocaleContextResolver} implementation <add> * that always returns a fixed default locale and optionally time zone. <add> * Default is the current JVM's default locale. <add> * <add> * <p>Note: Does not support {@code setLocale(Context)}, as the fixed <add> * locale and time zone cannot be changed. <add> * <add> * @author Sebastien Deleuze <add> * @since 5.0 <add> */ <add>public class FixedLocaleContextResolver implements LocaleContextResolver { <add> <add> private final Locale locale; <add> <add> private final TimeZone timeZone; <add> <add> <add> /** <add> * Create a default FixedLocaleResolver, exposing a configured default <add> * locale (or the JVM's default locale as fallback). <add> */ <add> public FixedLocaleContextResolver() { <add> this(Locale.getDefault()); <add> } <add> <add> /** <add> * Create a FixedLocaleResolver that exposes the given locale. <add> * @param locale the locale to expose <add> */ <add> public FixedLocaleContextResolver(Locale locale) { <add> this(locale, null); <add> } <add> <add> /** <add> * Create a FixedLocaleResolver that exposes the given locale and time zone. <add> * @param locale the locale to expose <add> * @param timeZone the time zone to expose <add> */ <add> public FixedLocaleContextResolver(Locale locale, @Nullable TimeZone timeZone) { <add> Assert.notNull(locale, "Locale must not be null"); <add> this.locale = locale; <add> this.timeZone = timeZone; <add> } <add> <add> @Override <add> public LocaleContext resolveLocaleContext(ServerWebExchange exchange) { <add> return new TimeZoneAwareLocaleContext() { <add> @Override <add> public Locale getLocale() { <add> return locale; <add> } <add> @Override <add> public TimeZone getTimeZone() { <add> return timeZone; <add> } <add> }; <add> } <add> <add> @Override <add> public void setLocaleContext(ServerWebExchange exchange, @Nullable LocaleContext localeContext) { <add> throw new UnsupportedOperationException("Cannot change fixed locale - use a different locale context resolution strategy"); <add> } <add> <add>} <ide><path>spring-web/src/main/java/org/springframework/web/server/i18n/LocaleContextResolver.java <add>/* <add> * Copyright 2002-2013 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> <add>package org.springframework.web.server.i18n; <add> <add>import org.springframework.context.i18n.LocaleContext; <add>import org.springframework.lang.Nullable; <add>import org.springframework.web.server.ServerWebExchange; <add> <add>/** <add> * Interface for web-based locale context resolution strategies that allows <add> * for both locale context resolution via the request and locale context modification <add> * via the HTTP exchange. <add> * <add> * <p>The {@link org.springframework.context.i18n.LocaleContext} object can potentially <add> * includes associated time zone and other locale related information. <add> * <add> * @author Sebastien Deleuze <add> * @since 5.0 <add> * @see LocaleContext <add> */ <add>public interface LocaleContextResolver { <add> <add> /** <add> * Resolve the current locale context via the given exchange. <add> * <add> * <p>The returned context may be a <add> * {@link org.springframework.context.i18n.TimeZoneAwareLocaleContext}, <add> * containing a locale with associated time zone information. <add> * Simply apply an {@code instanceof} check and downcast accordingly. <add> * <p>Custom resolver implementations may also return extra settings in <add> * the returned context, which again can be accessed through downcasting. <add> * @param exchange current server exchange <add> * @return the current locale context (never {@code null} <add> */ <add> LocaleContext resolveLocaleContext(ServerWebExchange exchange); <add> <add> /** <add> * Set the current locale context to the given one, <add> * potentially including a locale with associated time zone information. <add> * @param exchange current server exchange <add> * @param localeContext the new locale context, or {@code null} to clear the locale <add> * @throws UnsupportedOperationException if the LocaleResolver implementation <add> * does not support dynamic changing of the locale or time zone <add> * @see org.springframework.context.i18n.SimpleLocaleContext <add> * @see org.springframework.context.i18n.SimpleTimeZoneAwareLocaleContext <add> */ <add> void setLocaleContext(ServerWebExchange exchange, @Nullable LocaleContext localeContext); <add> <add>} <ide><path>spring-web/src/main/java/org/springframework/web/server/i18n/package-info.java <add>/** <add> * Locale related support classes. <add> * Provides standard LocaleContextResolver implementations. <add> */ <add>@NonNullApi <add>package org.springframework.web.server.i18n; <add> <add>import org.springframework.lang.NonNullApi; <ide><path>spring-web/src/test/java/org/springframework/mock/http/server/reactive/test/MockServerHttpRequest.java <ide> import java.util.Arrays; <ide> import java.util.Collection; <ide> import java.util.List; <add>import java.util.Locale; <ide> import java.util.Optional; <ide> <ide> import org.reactivestreams.Publisher; <ide> public static BaseBuilder<?> options(String urlTemplate, Object... uriVars) { <ide> */ <ide> B acceptCharset(Charset... acceptableCharsets); <ide> <add> /** <add> * Set the list of acceptable {@linkplain Locale locales}, as specified <add> * by the {@code Accept-Languages} header. <add> * @param acceptableLocales the acceptable locales <add> */ <add> B acceptLanguageAsLocales(Locale... acceptableLocales); <add> <ide> /** <ide> * Set the value of the {@code If-Modified-Since} header. <ide> * <p>The date should be specified as the number of milliseconds since <ide> public BodyBuilder acceptCharset(Charset... acceptableCharsets) { <ide> return this; <ide> } <ide> <add> @Override <add> public BodyBuilder acceptLanguageAsLocales(Locale... acceptableLocales) { <add> this.headers.setAcceptLanguageAsLocales(Arrays.asList(acceptableLocales)); <add> return this; <add> } <add> <ide> @Override <ide> public BodyBuilder contentLength(long contentLength) { <ide> this.headers.setContentLength(contentLength); <ide><path>spring-web/src/test/java/org/springframework/mock/http/server/reactive/test/MockServerWebExchange.java <ide> import org.springframework.http.codec.ServerCodecConfigurer; <ide> import org.springframework.web.server.ServerWebExchangeDecorator; <ide> import org.springframework.web.server.adapter.DefaultServerWebExchange; <add>import org.springframework.web.server.i18n.AcceptHeaderLocaleContextResolver; <ide> import org.springframework.web.server.session.DefaultWebSessionManager; <ide> <ide> /** <ide> public class MockServerWebExchange extends ServerWebExchangeDecorator { <ide> <ide> public MockServerWebExchange(MockServerHttpRequest request) { <ide> super(new DefaultServerWebExchange( <del> request, new MockServerHttpResponse(), new DefaultWebSessionManager(), ServerCodecConfigurer.create())); <add> request, new MockServerHttpResponse(), new DefaultWebSessionManager(), <add> ServerCodecConfigurer.create(), new AcceptHeaderLocaleContextResolver())); <ide> } <ide> <ide> <ide><path>spring-web/src/test/java/org/springframework/web/server/i18n/AcceptHeaderLocaleContextResolverTests.java <add>/* <add> * Copyright 2002-2017 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> <add>package org.springframework.web.server.i18n; <add> <add>import java.util.Arrays; <add>import java.util.Collections; <add>import java.util.Locale; <add> <add>import org.junit.Test; <add> <add>import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest; <add>import org.springframework.mock.http.server.reactive.test.MockServerWebExchange; <add>import org.springframework.web.server.ServerWebExchange; <add> <add>import static java.util.Locale.*; <add>import static org.junit.Assert.assertEquals; <add> <add>/** <add> * Unit tests for {@link AcceptHeaderLocaleContextResolver}. <add> * <add> * @author Sebastien Deleuze <add> */ <add>public class AcceptHeaderLocaleContextResolverTests { <add> <add> private AcceptHeaderLocaleContextResolver resolver = new AcceptHeaderLocaleContextResolver(); <add> <add> <add> @Test <add> public void resolve() throws Exception { <add> assertEquals(CANADA, this.resolver.resolveLocaleContext(exchange(CANADA)).getLocale()); <add> assertEquals(US, this.resolver.resolveLocaleContext(exchange(US, CANADA)).getLocale()); <add> } <add> <add> @Test <add> public void resolvePreferredSupported() throws Exception { <add> this.resolver.setSupportedLocales(Collections.singletonList(CANADA)); <add> assertEquals(CANADA, this.resolver.resolveLocaleContext(exchange(US, CANADA)).getLocale()); <add> } <add> <add> @Test <add> public void resolvePreferredNotSupported() throws Exception { <add> this.resolver.setSupportedLocales(Collections.singletonList(CANADA)); <add> assertEquals(US, this.resolver.resolveLocaleContext(exchange(US, UK)).getLocale()); <add> } <add> <add> @Test <add> public void resolvePreferredNotSupportedWithDefault() { <add> this.resolver.setSupportedLocales(Arrays.asList(US, JAPAN)); <add> this.resolver.setDefaultLocale(JAPAN); <add> <add> MockServerWebExchange exchange = new MockServerWebExchange(MockServerHttpRequest <add> .get("/") <add> .acceptLanguageAsLocales(KOREA) <add> .build()); <add> assertEquals(JAPAN, this.resolver.resolveLocaleContext(exchange).getLocale()); <add> } <add> <add> @Test <add> public void defaultLocale() throws Exception { <add> this.resolver.setDefaultLocale(JAPANESE); <add> MockServerWebExchange exchange = new MockServerWebExchange(MockServerHttpRequest <add> .get("/") <add> .build()); <add> assertEquals(JAPANESE, this.resolver.resolveLocaleContext(exchange).getLocale()); <add> <add> exchange = new MockServerWebExchange(MockServerHttpRequest <add> .get("/") <add> .acceptLanguageAsLocales(US) <add> .build()); <add> assertEquals(US, this.resolver.resolveLocaleContext(exchange).getLocale()); <add> } <add> <add> <add> private ServerWebExchange exchange(Locale... locales) { <add> return new MockServerWebExchange(MockServerHttpRequest <add> .get("") <add> .acceptLanguageAsLocales(locales) <add> .build()); <add> } <add> <add>} <ide><path>spring-web/src/test/java/org/springframework/web/server/i18n/FixedLocaleContextResolverTests.java <add>package org.springframework.web.server.i18n; <add> <add>import java.time.ZoneId; <add>import java.util.Locale; <add>import java.util.TimeZone; <add> <add>import org.junit.Before; <add>import org.junit.Test; <add> <add>import org.springframework.context.i18n.TimeZoneAwareLocaleContext; <add>import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest; <add>import org.springframework.mock.http.server.reactive.test.MockServerWebExchange; <add>import org.springframework.web.server.ServerWebExchange; <add> <add>import static java.util.Locale.CANADA; <add>import static java.util.Locale.FRANCE; <add>import static java.util.Locale.US; <add>import static org.junit.Assert.assertEquals; <add> <add>/** <add> * Unit tests for {@link FixedLocaleContextResolver}. <add> * <add> * @author Sebastien Deleuze <add> */ <add>public class FixedLocaleContextResolverTests { <add> <add> private FixedLocaleContextResolver resolver; <add> <add> @Before <add> public void setup() { <add> Locale.setDefault(US); <add> } <add> <add> @Test <add> public void resolveDefaultLocale() { <add> this.resolver = new FixedLocaleContextResolver(); <add> assertEquals(US, this.resolver.resolveLocaleContext(exchange()).getLocale()); <add> assertEquals(US, this.resolver.resolveLocaleContext(exchange(CANADA)).getLocale()); <add> } <add> <add> @Test <add> public void resolveCustomizedLocale() { <add> this.resolver = new FixedLocaleContextResolver(FRANCE); <add> assertEquals(FRANCE, this.resolver.resolveLocaleContext(exchange()).getLocale()); <add> assertEquals(FRANCE, this.resolver.resolveLocaleContext(exchange(CANADA)).getLocale()); <add> } <add> <add> @Test <add> public void resolveCustomizedAndTimeZoneLocale() { <add> TimeZone timeZone = TimeZone.getTimeZone(ZoneId.of("UTC")); <add> this.resolver = new FixedLocaleContextResolver(FRANCE, timeZone); <add> TimeZoneAwareLocaleContext context = (TimeZoneAwareLocaleContext)this.resolver.resolveLocaleContext(exchange()); <add> assertEquals(FRANCE, context.getLocale()); <add> assertEquals(timeZone, context.getTimeZone()); <add> } <add> <add> private ServerWebExchange exchange(Locale... locales) { <add> return new MockServerWebExchange(MockServerHttpRequest <add> .get("") <add> .acceptLanguageAsLocales(locales) <add> .build()); <add> } <add> <add>} <ide><path>spring-web/src/test/java/org/springframework/web/server/session/DefaultWebSessionManagerTests.java <ide> import org.springframework.web.server.ServerWebExchange; <ide> import org.springframework.web.server.WebSession; <ide> import org.springframework.web.server.adapter.DefaultServerWebExchange; <add>import org.springframework.web.server.i18n.AcceptHeaderLocaleContextResolver; <ide> <ide> import static org.junit.Assert.assertEquals; <ide> import static org.junit.Assert.assertFalse; <ide> public void setUp() throws Exception { <ide> <ide> MockServerHttpRequest request = MockServerHttpRequest.get("/path").build(); <ide> MockServerHttpResponse response = new MockServerHttpResponse(); <del> this.exchange = new DefaultServerWebExchange(request, response, this.manager, ServerCodecConfigurer.create()); <add> this.exchange = new DefaultServerWebExchange(request, response, this.manager, <add> ServerCodecConfigurer.create(), new AcceptHeaderLocaleContextResolver()); <ide> } <ide> <ide> <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/config/WebFluxConfigurationSupport.java <ide> import org.springframework.web.reactive.result.method.annotation.ResponseEntityResultHandler; <ide> import org.springframework.web.reactive.result.view.ViewResolutionResultHandler; <ide> import org.springframework.web.reactive.result.view.ViewResolver; <add>import org.springframework.web.server.i18n.LocaleContextResolver; <ide> import org.springframework.web.server.ServerWebExchange; <ide> import org.springframework.web.server.WebExceptionHandler; <ide> import org.springframework.web.server.handler.ResponseStatusExceptionHandler; <add>import org.springframework.web.server.i18n.AcceptHeaderLocaleContextResolver; <ide> <ide> /** <ide> * The main class for Spring WebFlux configuration. <ide> public ServerCodecConfigurer serverCodecConfigurer() { <ide> return serverCodecConfigurer; <ide> } <ide> <add> /** <add> * Override to plug a sub-class of {@link LocaleContextResolver}. <add> */ <add> protected LocaleContextResolver createLocaleContextResolver() { <add> return new AcceptHeaderLocaleContextResolver(); <add> } <add> <add> @Bean <add> public LocaleContextResolver localeContextResolver() { <add> return createLocaleContextResolver(); <add> } <add> <ide> /** <ide> * Override to configure the HTTP message readers and writers to use. <ide> */ <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/server/DefaultHandlerStrategiesBuilder.java <ide> import org.springframework.http.codec.ServerCodecConfigurer; <ide> import org.springframework.util.Assert; <ide> import org.springframework.web.reactive.result.view.ViewResolver; <add>import org.springframework.web.server.i18n.LocaleContextResolver; <ide> import org.springframework.web.server.WebExceptionHandler; <ide> import org.springframework.web.server.WebFilter; <ide> import org.springframework.web.server.handler.ResponseStatusExceptionHandler; <add>import org.springframework.web.server.i18n.AcceptHeaderLocaleContextResolver; <ide> <ide> /** <ide> * Default implementation of {@link HandlerStrategies.Builder}. <ide> class DefaultHandlerStrategiesBuilder implements HandlerStrategies.Builder { <ide> <ide> private final List<WebExceptionHandler> exceptionHandlers = new ArrayList<>(); <ide> <add> private LocaleContextResolver localeContextResolver; <add> <ide> <ide> public DefaultHandlerStrategiesBuilder() { <ide> this.codecConfigurer.registerDefaults(false); <ide> public DefaultHandlerStrategiesBuilder() { <ide> public void defaultConfiguration() { <ide> this.codecConfigurer.registerDefaults(true); <ide> exceptionHandler(new ResponseStatusExceptionHandler()); <add> localeContextResolver(new AcceptHeaderLocaleContextResolver()); <ide> } <ide> <ide> @Override <ide> public HandlerStrategies.Builder exceptionHandler(WebExceptionHandler exceptionH <ide> return this; <ide> } <ide> <add> @Override <add> public HandlerStrategies.Builder localeContextResolver(LocaleContextResolver localeContextResolver) { <add> Assert.notNull(localeContextResolver, "'localeContextResolver' must not be null"); <add> this.localeContextResolver = localeContextResolver; <add> return this; <add> } <add> <ide> @Override <ide> public HandlerStrategies build() { <ide> return new DefaultHandlerStrategies(this.codecConfigurer.getReaders(), <ide> this.codecConfigurer.getWriters(), this.viewResolvers, this.webFilters, <del> this.exceptionHandlers); <add> this.exceptionHandlers, this.localeContextResolver); <ide> } <ide> <ide> <ide> private static class DefaultHandlerStrategies implements HandlerStrategies { <ide> <ide> private final List<WebExceptionHandler> exceptionHandlers; <ide> <add> private final LocaleContextResolver localeContextResolver; <add> <add> <ide> public DefaultHandlerStrategies( <ide> List<HttpMessageReader<?>> messageReaders, <ide> List<HttpMessageWriter<?>> messageWriters, <ide> List<ViewResolver> viewResolvers, <ide> List<WebFilter> webFilters, <del> List<WebExceptionHandler> exceptionHandlers) { <add> List<WebExceptionHandler> exceptionHandlers, <add> LocaleContextResolver localeContextResolver) { <ide> <ide> this.messageReaders = unmodifiableCopy(messageReaders); <ide> this.messageWriters = unmodifiableCopy(messageWriters); <ide> this.viewResolvers = unmodifiableCopy(viewResolvers); <ide> this.webFilters = unmodifiableCopy(webFilters); <ide> this.exceptionHandlers = unmodifiableCopy(exceptionHandlers); <add> this.localeContextResolver = localeContextResolver; <ide> } <ide> <ide> private static <T> List<T> unmodifiableCopy(List<? extends T> list) { <ide> public List<WebFilter> webFilters() { <ide> public List<WebExceptionHandler> exceptionHandlers() { <ide> return this.exceptionHandlers; <ide> } <add> <add> @Override <add> public LocaleContextResolver localeContextResolver() { <add> return this.localeContextResolver; <add> } <ide> } <ide> <ide> } <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/server/DefaultRenderingResponseBuilder.java <ide> import java.util.Collection; <ide> import java.util.Collections; <ide> import java.util.LinkedHashMap; <del>import java.util.List; <ide> import java.util.Locale; <ide> import java.util.Map; <ide> import java.util.stream.Stream; <ide> public Mono<Void> writeTo(ServerWebExchange exchange, Context context) { <ide> ServerHttpResponse response = exchange.getResponse(); <ide> writeStatusAndHeaders(response); <ide> MediaType contentType = exchange.getResponse().getHeaders().getContentType(); <del> Locale locale = resolveLocale(exchange); <add> Locale locale = exchange.getLocaleContext().getLocale(); <ide> Stream<ViewResolver> viewResolverStream = context.viewResolvers().stream(); <ide> <ide> return Flux.fromStream(viewResolverStream) <ide> public Mono<Void> writeTo(ServerWebExchange exchange, Context context) { <ide> .flatMap(view -> view.render(model(), contentType, exchange)); <ide> } <ide> <del> private Locale resolveLocale(ServerWebExchange exchange) { <del> List<Locale> locales = exchange.getRequest().getHeaders().getAcceptLanguageAsLocales(); <del> return locales.isEmpty() ? Locale.getDefault() : locales.get(0); <del> <del> } <ide> } <ide> <ide> } <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/server/HandlerStrategies.java <ide> import org.springframework.http.codec.HttpMessageWriter; <ide> import org.springframework.http.codec.ServerCodecConfigurer; <ide> import org.springframework.web.reactive.result.view.ViewResolver; <add>import org.springframework.web.server.i18n.LocaleContextResolver; <ide> import org.springframework.web.server.WebExceptionHandler; <ide> import org.springframework.web.server.WebFilter; <ide> <ide> * <ide> * @author Arjen Poutsma <ide> * @author Juergen Hoeller <add> * @author Sebastien Deleuze <ide> * @since 5.0 <ide> * @see RouterFunctions#toHttpHandler(RouterFunction, HandlerStrategies) <ide> */ <ide> public interface HandlerStrategies { <ide> */ <ide> List<WebExceptionHandler> exceptionHandlers(); <ide> <add> /** <add> * Return the {@link LocaleContextResolver} to be used for resolving locale context. <add> * @return the locale context resolver <add> */ <add> LocaleContextResolver localeContextResolver(); <add> <ide> <ide> // Static methods <ide> <ide> interface Builder { <ide> */ <ide> Builder exceptionHandler(WebExceptionHandler exceptionHandler); <ide> <add> /** <add> * Add the given locale context resolver to this builder. <add> * @param localeContextResolver the locale context resolver to add <add> * @return this builder <add> */ <add> Builder localeContextResolver(LocaleContextResolver localeContextResolver); <add> <ide> /** <ide> * Builds the {@link HandlerStrategies}. <ide> * @return the built strategies <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/server/RouterFunctions.java <ide> public static HttpHandler toHttpHandler(RouterFunction<?> routerFunction, Handle <ide> return WebHttpHandlerBuilder.webHandler(webHandler) <ide> .filters(strategies.webFilters()) <ide> .exceptionHandlers(strategies.exceptionHandlers()) <add> .localeContextResolver(strategies.localeContextResolver()) <ide> .build(); <ide> } <ide> <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/view/RequestContext.java <ide> import org.springframework.context.MessageSource; <ide> import org.springframework.context.MessageSourceResolvable; <ide> import org.springframework.context.NoSuchMessageException; <add>import org.springframework.context.i18n.LocaleContext; <add>import org.springframework.context.i18n.TimeZoneAwareLocaleContext; <ide> import org.springframework.http.server.reactive.ServerHttpRequest; <ide> import org.springframework.lang.Nullable; <ide> import org.springframework.util.Assert; <ide> public RequestContext(ServerWebExchange exchange, Map<String, Object> model, Mes <ide> this.model = model; <ide> this.messageSource = messageSource; <ide> <del> List<Locale> locales = exchange.getRequest().getHeaders().getAcceptLanguageAsLocales(); <del> this.locale = locales.isEmpty() ? Locale.getDefault() : locales.get(0); <del> this.timeZone = TimeZone.getDefault(); // TODO <add> LocaleContext localeContext = exchange.getLocaleContext(); <add> this.locale = localeContext.getLocale(); <add> this.timeZone = (localeContext instanceof TimeZoneAwareLocaleContext ? <add> ((TimeZoneAwareLocaleContext)localeContext).getTimeZone() : TimeZone.getDefault()); <ide> <ide> this.defaultHtmlEscape = null; // TODO <ide> this.dataValueProcessor = dataValueProcessor; <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/view/ViewResolutionResultHandler.java <ide> public Mono<Void> handleResult(ServerWebExchange exchange, HandlerResult result) <ide> Model model = result.getModel(); <ide> MethodParameter parameter = result.getReturnTypeSource(); <ide> <del> List<Locale> locales = exchange.getRequest().getHeaders().getAcceptLanguageAsLocales(); <del> Locale locale = locales.isEmpty() ? Locale.getDefault() : locales.get(0); <add> Locale locale = exchange.getLocaleContext().getLocale(); <ide> <ide> Class<?> clazz = valueType.getRawClass(); <ide> if (clazz == null) { <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/view/freemarker/FreeMarkerView.java <ide> import java.io.OutputStreamWriter; <ide> import java.io.Writer; <ide> import java.nio.charset.Charset; <del>import java.util.List; <ide> import java.util.Locale; <ide> import java.util.Map; <ide> import java.util.Optional; <ide> protected Mono<Void> renderInternal(Map<String, Object> renderAttributes, <ide> logger.debug("Rendering FreeMarker template [" + getUrl() + "]."); <ide> } <ide> <del> List<Locale> locales = exchange.getRequest().getHeaders().getAcceptLanguageAsLocales(); <del> Locale locale = locales.isEmpty() ? Locale.getDefault() : locales.get(0); <add> Locale locale = exchange.getLocaleContext().getLocale(); <ide> <ide> DataBuffer dataBuffer = exchange.getResponse().bufferFactory().allocateBuffer(); <ide> try { <ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/function/server/LocaleContextResolverIntegrationTests.java <add>/* <add> * Copyright 2002-2017 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> <add>package org.springframework.web.reactive.function.server; <add> <add>import java.util.Collections; <add>import java.util.List; <add>import java.util.Locale; <add>import java.util.Map; <add> <add>import org.junit.Test; <add>import reactor.core.publisher.Mono; <add>import reactor.test.StepVerifier; <add> <add>import org.springframework.http.HttpStatus; <add>import org.springframework.http.MediaType; <add>import org.springframework.lang.Nullable; <add>import org.springframework.web.reactive.function.client.ClientResponse; <add>import org.springframework.web.reactive.function.client.WebClient; <add>import org.springframework.web.reactive.result.view.View; <add>import org.springframework.web.reactive.result.view.ViewResolver; <add>import org.springframework.web.server.ServerWebExchange; <add>import org.springframework.web.server.i18n.FixedLocaleContextResolver; <add> <add>import static org.junit.Assert.assertEquals; <add> <add>/** <add> * @author Sebastien Deleuze <add> */ <add>public class LocaleContextResolverIntegrationTests extends AbstractRouterFunctionIntegrationTests { <add> <add> private final WebClient webClient = WebClient.create(); <add> <add> @Test <add> public void fixedLocale() { <add> Mono<ClientResponse> result = webClient <add> .get() <add> .uri("http://localhost:" + this.port + "/") <add> .exchange(); <add> <add> StepVerifier <add> .create(result) <add> .consumeNextWith(response -> { <add> assertEquals(HttpStatus.OK, response.statusCode()); <add> assertEquals(Locale.GERMANY, response.headers().asHttpHeaders().getContentLanguage()); <add> }) <add> .verifyComplete(); <add> } <add> <add> @Override <add> protected RouterFunction<?> routerFunction() { <add> return RouterFunctions.route(RequestPredicates.path("/"), this::render); <add> } <add> <add> public Mono<RenderingResponse> render(ServerRequest request) { <add> return RenderingResponse.create("foo").build(); <add> } <add> <add> @Override <add> protected HandlerStrategies handlerStrategies() { <add> return HandlerStrategies.builder() <add> .viewResolver(new DummyViewResolver()) <add> .localeContextResolver(new FixedLocaleContextResolver(Locale.GERMANY)) <add> .build(); <add> } <add> <add> private static class DummyViewResolver implements ViewResolver { <add> <add> @Override <add> public Mono<View> resolveViewName(String viewName, Locale locale) { <add> return Mono.just(new DummyView(locale)); <add> } <add> } <add> <add> private static class DummyView implements View { <add> <add> private final Locale locale; <add> <add> public DummyView(Locale locale) { <add> this.locale = locale; <add> } <add> <add> @Override <add> public List<MediaType> getSupportedMediaTypes() { <add> return Collections.singletonList(MediaType.TEXT_HTML); <add> } <add> <add> @Override <add> public Mono<Void> render(@Nullable Map<String, ?> model, @Nullable MediaType contentType, <add> ServerWebExchange exchange) { <add> exchange.getResponse().getHeaders().setContentLanguage(locale); <add> return Mono.empty(); <add> } <add> } <add>} <ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/SessionAttributeMethodArgumentResolverTests.java <ide> import org.springframework.web.server.ServerWebInputException; <ide> import org.springframework.web.server.WebSession; <ide> import org.springframework.web.server.adapter.DefaultServerWebExchange; <add>import org.springframework.web.server.i18n.AcceptHeaderLocaleContextResolver; <ide> import org.springframework.web.server.session.MockWebSessionManager; <ide> import org.springframework.web.server.session.WebSessionManager; <ide> <ide> public void setup() throws Exception { <ide> WebSessionManager sessionManager = new MockWebSessionManager(this.session); <ide> <ide> ServerHttpRequest request = MockServerHttpRequest.get("/").build(); <del> this.exchange = new DefaultServerWebExchange(request, new MockServerHttpResponse(), sessionManager, ServerCodecConfigurer.create()); <add> this.exchange = new DefaultServerWebExchange(request, new MockServerHttpResponse(), <add> sessionManager, ServerCodecConfigurer.create(), new AcceptHeaderLocaleContextResolver()); <ide> <ide> this.handleMethod = ReflectionUtils.findMethod(getClass(), "handleWithSessionAttribute", (Class<?>[]) null); <ide> } <ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/WebSessionArgumentResolverTests.java <ide> import org.springframework.web.server.ServerWebExchange; <ide> import org.springframework.web.server.WebSession; <ide> import org.springframework.web.server.adapter.DefaultServerWebExchange; <add>import org.springframework.web.server.i18n.AcceptHeaderLocaleContextResolver; <ide> import org.springframework.web.server.session.DefaultWebSession; <ide> import org.springframework.web.server.session.WebSessionManager; <ide> <ide> public void resolverArgument() throws Exception { <ide> WebSessionManager manager = exchange -> Mono.just(session); <ide> MockServerHttpRequest request = MockServerHttpRequest.get("/").build(); <ide> ServerWebExchange exchange = new DefaultServerWebExchange(request, new MockServerHttpResponse(), <del> manager, ServerCodecConfigurer.create()); <add> manager, ServerCodecConfigurer.create(), new AcceptHeaderLocaleContextResolver()); <ide> <ide> MethodParameter param = this.testMethod.arg(WebSession.class); <ide> Object actual = this.resolver.resolveArgument(param, context, exchange).block(); <ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/result/view/LocaleContextResolverIntegrationTests.java <add>/* <add> * Copyright 2002-2017 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> <add>package org.springframework.web.reactive.result.view; <add> <add>import java.util.Collections; <add>import java.util.List; <add>import java.util.Locale; <add>import java.util.Map; <add> <add>import org.junit.Test; <add>import reactor.core.publisher.Mono; <add>import reactor.test.StepVerifier; <add> <add>import org.springframework.context.ApplicationContext; <add>import org.springframework.context.annotation.AnnotationConfigApplicationContext; <add>import org.springframework.context.annotation.ComponentScan; <add>import org.springframework.context.annotation.Configuration; <add>import org.springframework.http.HttpStatus; <add>import org.springframework.http.MediaType; <add>import org.springframework.lang.Nullable; <add>import org.springframework.stereotype.Controller; <add>import org.springframework.web.bind.annotation.GetMapping; <add>import org.springframework.web.reactive.config.ViewResolverRegistry; <add>import org.springframework.web.reactive.config.WebFluxConfigurationSupport; <add>import org.springframework.web.reactive.function.client.ClientResponse; <add>import org.springframework.web.reactive.function.client.WebClient; <add>import org.springframework.web.reactive.result.method.annotation.AbstractRequestMappingIntegrationTests; <add>import org.springframework.web.server.i18n.LocaleContextResolver; <add>import org.springframework.web.server.ServerWebExchange; <add>import org.springframework.web.server.i18n.FixedLocaleContextResolver; <add> <add>import static org.junit.Assert.assertEquals; <add> <add>/** <add> * @author Sebastien Deleuze <add> */ <add>public class LocaleContextResolverIntegrationTests extends AbstractRequestMappingIntegrationTests { <add> <add> private final WebClient webClient = WebClient.create(); <add> <add> @Test <add> public void fixedLocale() { <add> Mono<ClientResponse> result = webClient <add> .get() <add> .uri("http://localhost:" + this.port + "/") <add> .exchange(); <add> <add> StepVerifier <add> .create(result) <add> .consumeNextWith(response -> { <add> assertEquals(HttpStatus.OK, response.statusCode()); <add> assertEquals(Locale.GERMANY, response.headers().asHttpHeaders().getContentLanguage()); <add> }) <add> .verifyComplete(); <add> } <add> <add> @Override <add> protected ApplicationContext initApplicationContext() { <add> AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); <add> context.register(WebConfig.class); <add> context.refresh(); <add> return context; <add> } <add> <add> <add> @Configuration <add> @ComponentScan(resourcePattern = "**/LocaleContextResolverIntegrationTests*.class") <add> @SuppressWarnings({"unused", "WeakerAccess"}) <add> static class WebConfig extends WebFluxConfigurationSupport { <add> <add> @Override <add> protected LocaleContextResolver createLocaleContextResolver() { <add> return new FixedLocaleContextResolver(Locale.GERMANY); <add> } <add> <add> @Override <add> protected void configureViewResolvers(ViewResolverRegistry registry) { <add> registry.viewResolver((viewName, locale) -> Mono.just(new DummyView(locale))); <add> } <add> <add> private static class DummyView implements View { <add> <add> private final Locale locale; <add> <add> public DummyView(Locale locale) { <add> this.locale = locale; <add> } <add> <add> @Override <add> public List<MediaType> getSupportedMediaTypes() { <add> return Collections.singletonList(MediaType.TEXT_HTML); <add> } <add> <add> @Override <add> public Mono<Void> render(@Nullable Map<String, ?> model, @Nullable MediaType contentType, <add> ServerWebExchange exchange) { <add> exchange.getResponse().getHeaders().setContentLanguage(locale); <add> return Mono.empty(); <add> } <add> } <add> <add> } <add> <add> @Controller <add> @SuppressWarnings("unused") <add> static class TestController { <add> <add> @GetMapping("/") <add> public String foo() { <add> return "foo"; <add> } <add> <add> } <add> <add>}
28
Javascript
Javascript
combine two test cases into one
56a1da5b3b56ed84f6de2193a4fb0c01c0c7d4f2
<ide><path>packages/@ember/application/tests/readiness_test.js <ide> moduleFor( <ide> run(() => { <ide> application = Application.create({ router: false }); <ide> application.deferReadiness(); <add> assert.equal(readyWasCalled, 0, "ready wasn't called yet"); <ide> }); <ide> <ide> assert.equal(readyWasCalled, 0, "ready wasn't called yet"); <ide> moduleFor( <ide> }); <ide> <ide> assert.equal(readyWasCalled, 1, 'ready was called now all readiness deferrals are advanced'); <del> } <del> <del> ["@test Application's ready event can be deferred by other components (jQuery.isReady === false)"]( <del> assert <del> ) { <del> jQuery.isReady = false; <del> <del> run(() => { <del> application = Application.create({ router: false }); <del> application.deferReadiness(); <del> assert.equal(readyWasCalled, 0, "ready wasn't called yet"); <del> }); <del> <del> domReady(); <del> <del> assert.equal(readyWasCalled, 0, "ready wasn't called yet"); <del> <del> run(() => { <del> application.advanceReadiness(); <del> }); <del> <del> assert.equal(readyWasCalled, 1, 'ready was called now all readiness deferrals are advanced'); <ide> <ide> expectAssertion(() => { <ide> application.deferReadiness();
1
Python
Python
remove outdated exclude pattenr in docs/conf.py
902db631b18dd0642e5d9a3b211e6755006c3c21
<ide><path>docs/conf.py <ide> exclude_patterns: List[str] = [ <ide> # We only link to selected subpackages. <ide> '_api/airflow/index.rst', <del> # Required by airflow/contrib/plugins <del> '_api/main', <ide> # We have custom page - operators-and-hooks-ref.rst <ide> '_api/airflow/providers/index.rst', <ide> # Packages with subpackages
1
Javascript
Javascript
add a test
d48d6cf99db8feefec4ee3961ff1cb9e7b2c5ad2
<ide><path>test/unit/events.js <ide> test('should bubble up DOM unless bubbles == false', function(){ <ide> }); <ide> vjs.trigger(inner, { type:'nobub', target:inner, bubbles:false }); <ide> }); <add> <add>test('should have a defaultPrevented property on an event that was prevent from doing default action', function() { <add> expect(2); <add> <add> var el = document.createElement('div'); <add> <add> vjs.on(el, 'test', function(e){ <add> ok(true, 'First listener fired'); <add> e.preventDefault(); <add> }); <add> <add> vjs.on(el, 'test', function(e){ <add> ok(e.defaultPrevented, 'Should have `defaultPrevented` to signify preventDefault being called'); <add> }); <add> <add> vjs.trigger(el, 'test'); <add>});
1
Python
Python
add a flag to control the number of train examples
2454e6ea3d23d2d9c2c0ecb1b0213d48abc33438
<ide><path>official/nlp/bert/input_pipeline.py <ide> def decode_record(record, name_to_features): <ide> return example <ide> <ide> <del>def single_file_dataset(input_file, name_to_features): <add>def single_file_dataset(input_file, name_to_features, num_samples=None): <ide> """Creates a single-file dataset to be passed for BERT custom training.""" <ide> # For training, we want a lot of parallel reading and shuffling. <ide> # For eval, we want no shuffling and parallel reading doesn't matter. <ide> d = tf.data.TFRecordDataset(input_file) <add> if num_samples: <add> d = d.take(num_samples) <ide> d = d.map( <ide> lambda record: decode_record(record, name_to_features), <ide> num_parallel_calls=tf.data.experimental.AUTOTUNE) <ide> def create_classifier_dataset(file_path, <ide> is_training=True, <ide> input_pipeline_context=None, <ide> label_type=tf.int64, <del> include_sample_weights=False): <add> include_sample_weights=False, <add> num_samples=None): <ide> """Creates input dataset from (tf)records files for train/eval.""" <ide> name_to_features = { <ide> 'input_ids': tf.io.FixedLenFeature([seq_length], tf.int64), <ide> def create_classifier_dataset(file_path, <ide> } <ide> if include_sample_weights: <ide> name_to_features['weight'] = tf.io.FixedLenFeature([], tf.float32) <del> dataset = single_file_dataset(file_path, name_to_features) <add> dataset = single_file_dataset(file_path, name_to_features, <add> num_samples=num_samples) <ide> <ide> # The dataset is always sharded by number of hosts. <ide> # num_input_pipelines is the number of hosts rather than number of cores. <ide><path>official/nlp/bert/run_classifier.py <ide> 'input_meta_data_path', None, <ide> 'Path to file that contains meta data about input ' <ide> 'to be used for training and evaluation.') <add>flags.DEFINE_integer('train_data_size', None, 'Number of training samples ' <add> 'to use. If None, uses the full train data. ' <add> '(default: None).') <ide> flags.DEFINE_string('predict_checkpoint_path', None, <ide> 'Path to the checkpoint for predictions.') <ide> flags.DEFINE_integer( <ide> def get_dataset_fn(input_file_pattern, <ide> global_batch_size, <ide> is_training, <ide> label_type=tf.int64, <del> include_sample_weights=False): <add> include_sample_weights=False, <add> num_samples=None): <ide> """Gets a closure to create a dataset.""" <ide> <ide> def _dataset_fn(ctx=None): <ide> def _dataset_fn(ctx=None): <ide> is_training=is_training, <ide> input_pipeline_context=ctx, <ide> label_type=label_type, <del> include_sample_weights=include_sample_weights) <add> include_sample_weights=include_sample_weights, <add> num_samples=num_samples) <ide> return dataset <ide> <ide> return _dataset_fn <ide> def run_bert(strategy, <ide> epochs = FLAGS.num_train_epochs * FLAGS.num_eval_per_epoch <ide> train_data_size = ( <ide> input_meta_data['train_data_size'] // FLAGS.num_eval_per_epoch) <add> if FLAGS.train_data_size: <add> train_data_size = min(train_data_size, FLAGS.train_data_size) <add> logging.info('Updated train_data_size: %s', train_data_size) <ide> steps_per_epoch = int(train_data_size / FLAGS.train_batch_size) <ide> warmup_steps = int(epochs * train_data_size * 0.1 / FLAGS.train_batch_size) <ide> eval_steps = int( <ide> def custom_main(custom_callbacks=None, custom_metrics=None): <ide> FLAGS.train_batch_size, <ide> is_training=True, <ide> label_type=label_type, <del> include_sample_weights=include_sample_weights) <add> include_sample_weights=include_sample_weights, <add> num_samples=FLAGS.train_data_size) <ide> run_bert( <ide> strategy, <ide> input_meta_data,
2
Python
Python
add a notice to the balancer_detach_member method
43e7dff7a678ee2923d0d858b33221d31624ecee
<ide><path>libcloud/loadbalancer/drivers/rackspace.py <ide> def balancer_attach_member(self, balancer, member): <ide> return self._to_members(resp.object)[0] <ide> <ide> def balancer_detach_member(self, balancer, member): <add> # Loadbalancer always needs to have at least 1 member. <add> # Last member cannot be detached. You can only disable it or destroy the <add> # balancer. <ide> uri = '/loadbalancers/%s/nodes/%s' % (balancer.id, member.id) <ide> resp = self.connection.request(uri, method='DELETE') <ide>
1
Python
Python
fix graph.set_previous with dict connection_map
c515dc90d4be04454193e1b774018de28c6bcf48
<ide><path>keras/layers/containers.py <ide> def set_previous(self, layer, connection_map={}): <ide> else: <ide> if not connection_map: <ide> raise Exception('Cannot attach multi-input layer: no connection_map provided.') <del> for k, v in connection_map: <add> for k, v in connection_map.items(): <ide> if k in self.inputs and v in layer.outputs: <ide> self.inputs[k].set_previous(layer.outputs[v]) <ide> else:
1
Python
Python
add test for recent bug in indexing optimization
75981b8a97760e91295ef8b64148816a897c9b7d
<ide><path>numpy/core/tests/test_regression.py <ide> def check_repeat_discont(self, level=rlevel): <ide> """Ticket #352""" <ide> a = N.arange(12).reshape(4,3)[:,2] <ide> assert_equal(a.repeat(3), [2,2,2,5,5,5,8,8,8,11,11,11]) <del> <add> <add> def check_array_index(self, level=rlevel): <add> """Make sure optimization is not called in this case.""" <add> a = N.array([1,2,3]) <add> a2 = N.array([[1,2,3]]) <add> assert_equal(a[N.where(a==3)], a2[N.where(a2==3)]) <ide> <ide> if __name__ == "__main__": <ide> NumpyTest().run()
1
Ruby
Ruby
add `deuniversalize_machos` method
5e0b786da21564011be7df165ce20a61d639de77
<ide><path>Library/Homebrew/extend/os/linux/formula.rb <ide> class Formula <ide> undef shared_library <ide> undef rpath <add> undef deuniversalize_machos <ide> <add> sig { params(name: String, version: T.nilable(T.any(String, Integer))).returns(String) } <ide> def shared_library(name, version = nil) <ide> suffix = if version == "*" || (name == "*" && version.blank?) <ide> "{,.*}" <ide> def shared_library(name, version = nil) <ide> "#{name}.so#{suffix}" <ide> end <ide> <add> sig { returns(String) } <ide> def rpath <ide> "'$ORIGIN/../lib'" <ide> end <ide> <add> sig { params(targets: T.nilable(T.any(Pathname, String))).void } <add> def deuniversalize_machos(*targets); end <add> <ide> class << self <ide> undef ignore_missing_libraries <ide> <ide><path>Library/Homebrew/formula.rb <ide> def time <ide> end <ide> end <ide> <add> sig { params(targets: T.nilable(T.any(Pathname, String))).void } <add> def deuniversalize_machos(*targets) <add> if targets.blank? <add> targets = any_installed_keg.mach_o_files.select do |file| <add> file.arch == :universal && file.archs.include?(Hardware::CPU.arch) <add> end <add> end <add> <add> targets.each do |t| <add> macho = MachO::FatFile.new(t) <add> native_slice = macho.extract(Hardware::CPU.arch) <add> native_slice.write t <add> end <add> end <add> <ide> # an array of all core {Formula} names <ide> # @private <ide> def self.core_names
2
Python
Python
correct slow test
e615269cb864392b15073f80ce32643b704776a3
<ide><path>tests/test_modeling_flaubert.py <ide> def test_flaubert_sequence_classif(self): <ide> <ide> @slow <ide> def test_model_from_pretrained(self): <del> for model_name in list(Flaubert_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]: <add> for model_name in list(FLAUBERT_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]: <ide> model = FlaubertModel.from_pretrained(model_name, cache_dir=CACHE_DIR) <ide> self.assertIsNotNone(model)
1
Text
Text
improve rewrites documentation
ae2d901eed3537e46a24e6e1963815230b92d6da
<ide><path>docs/api-reference/next.config.js/rewrites.md <ide> module.exports = { <ide> <summary><b>Examples</b></summary> <ide> <ul> <ide> <li><a href="https://github.com/vercel/next.js/tree/canary/examples/custom-routes-proxying">Incremental adoption of Next.js</a></li> <add> <li><a href="https://github.com/vercel/next.js/tree/canary/examples/with-zones">Using Multiple Zones</a></li> <ide> </ul> <ide> </details> <ide> <del>Rewrites allow you to rewrite to an external url. This is especially useful for incrementally adopting Next.js. <add>Rewrites allow you to rewrite to an external url. This is especially useful for incrementally adopting Next.js. The following is an example rewrite for redirecting the `/blog` route of your main app to an external site. <ide> <ide> ```js <ide> module.exports = { <ide> async rewrites() { <ide> return [ <add> { <add> source: '/blog', <add> destination: 'https://example.com/blog', <add> }, <ide> { <ide> source: '/blog/:slug', <ide> destination: 'https://example.com/blog/:slug', // Matched parameters can be used in the destination <ide> module.exports = { <ide> } <ide> ``` <ide> <add>If you're using `trailingSlash: true`, you also need to insert a trailing slash in the `source` paramater. If the destination server is also expecting a trailing slash it should be included in the `destination` parameter as well. <add> <add>```js <add>module.exports = { <add> trailingSlash: 'true', <add> async rewrites() { <add> return [ <add> { <add> source: '/blog/', <add> destination: 'https://example.com/blog/', <add> }, <add> { <add> source: '/blog/:path*/', <add> destination: 'https://example.com/blog/:path*/', <add> }, <add> ] <add> }, <add>} <add>``` <add> <ide> ### Incremental adoption of Next.js <ide> <ide> You can also have Next.js fall back to proxying to an existing website after checking all Next.js routes.
1
Python
Python
show migration elapsed time when verbosity>1
285bd02c921d3ba731c74a2f5eca278c7941ac5c
<ide><path>django/core/management/commands/migrate.py <ide> from collections import OrderedDict <ide> from importlib import import_module <ide> import itertools <add>import time <ide> import traceback <ide> import warnings <ide> <ide> def handle(self, *args, **options): <ide> <ide> def migration_progress_callback(self, action, migration, fake=False): <ide> if self.verbosity >= 1: <add> compute_time = self.verbosity > 1 <ide> if action == "apply_start": <add> if compute_time: <add> self.start = time.time() <ide> self.stdout.write(" Applying %s..." % migration, ending="") <ide> self.stdout.flush() <ide> elif action == "apply_success": <add> elapsed = " (%.3fs)" % (time.time() - self.start) if compute_time else "" <ide> if fake: <del> self.stdout.write(self.style.MIGRATE_SUCCESS(" FAKED")) <add> self.stdout.write(self.style.MIGRATE_SUCCESS(" FAKED" + elapsed)) <ide> else: <del> self.stdout.write(self.style.MIGRATE_SUCCESS(" OK")) <add> self.stdout.write(self.style.MIGRATE_SUCCESS(" OK" + elapsed)) <ide> elif action == "unapply_start": <add> if compute_time: <add> self.start = time.time() <ide> self.stdout.write(" Unapplying %s..." % migration, ending="") <ide> self.stdout.flush() <ide> elif action == "unapply_success": <add> elapsed = " (%.3fs)" % (time.time() - self.start) if compute_time else "" <ide> if fake: <del> self.stdout.write(self.style.MIGRATE_SUCCESS(" FAKED")) <add> self.stdout.write(self.style.MIGRATE_SUCCESS(" FAKED" + elapsed)) <ide> else: <del> self.stdout.write(self.style.MIGRATE_SUCCESS(" OK")) <add> self.stdout.write(self.style.MIGRATE_SUCCESS(" OK" + elapsed)) <ide> <ide> def sync_apps(self, connection, app_labels): <ide> "Runs the old syncdb-style operation on a list of app_labels."
1
Javascript
Javascript
remove default 'drain' listener on upgrade
2b7f920e26171f05fac437d867a30209f57c6bad
<ide><path>lib/_http_client.js <ide> const { OutgoingMessage } = require('_http_outgoing'); <ide> const Agent = require('_http_agent'); <ide> const { Buffer } = require('buffer'); <ide> const { urlToOptions, searchParamsSymbol } = require('internal/url'); <del>const { outHeadersKey } = require('internal/http'); <add>const { outHeadersKey, ondrain } = require('internal/http'); <ide> const { nextTick } = require('internal/process/next_tick'); <ide> const errors = require('internal/errors'); <ide> <ide> function socketOnData(d) { <ide> <ide> socket.removeListener('data', socketOnData); <ide> socket.removeListener('end', socketOnEnd); <add> socket.removeListener('drain', ondrain); <ide> parser.finish(); <ide> freeParser(parser, req, socket); <ide> <ide><path>test/parallel/test-http-connect.js <ide> server.listen(0, common.mustCall(() => { <ide> assert.strictEqual(socket._httpMessage, null); <ide> assert.strictEqual(socket.listeners('connect').length, 0); <ide> assert.strictEqual(socket.listeners('data').length, 0); <add> assert.strictEqual(socket.listeners('drain').length, 0); <ide> <ide> // the stream.Duplex onend listener <ide> // allow 0 here, so that i can run the same test on streams1 impl
2
Text
Text
fix import in example
e8f4a6653dc3f5d9702236a3abed887ca44dcfbb
<ide><path>packages/react/README.md <ide> The `react` package contains only the functionality necessary to define React co <ide> <ide> ```js <ide> import { useState } from 'react'; <del>import { createRoot } from 'react-dom'; <add>import { createRoot } from 'react-dom/client'; <ide> <ide> function Counter() { <ide> const [count, setCount] = useState(0);
1
Text
Text
add meta for invalid merge from
7997ff8f514ad4bb9d66059e5c4e6f069f40f8b0
<ide><path>guide/russian/react/context-api/index.md <add>--- <add>title: Context API <add>--- <add> <ide> # Context API <ide> <ide> Новый Context API был реализован в версии React 16.3.
1
Ruby
Ruby
delete more flaky tests
1462f4760976742746ccc93c9ef23ff960ce7d9a
<ide><path>Library/Homebrew/test/cask/cmd/uninstall_spec.rb <ide> expect(transmission.config.appdir.join("Caffeine.app")).not_to exist <ide> end <ide> <del> it "calls `uninstall` before removing artifacts" do <del> cask = Cask::CaskLoader.load(cask_path("with-uninstall-script-app")) <del> <del> Cask::Installer.new(cask).install <del> <del> expect(cask).to be_installed <del> expect(cask.config.appdir.join("MyFancyApp.app")).to exist <del> <del> expect { <del> described_class.run("with-uninstall-script-app") <del> }.not_to raise_error <del> <del> expect(cask).not_to be_installed <del> expect(cask.config.appdir.join("MyFancyApp.app")).not_to exist <del> end <del> <ide> it "can uninstall Casks when the uninstall script is missing, but only when using `--force`" do <ide> cask = Cask::CaskLoader.load(cask_path("with-uninstall-script-app")) <ide> <ide> expect(cask).not_to be_installed <ide> end <ide> <del> context "when Casks use script path with `~` as `HOME`" do <del> let(:home_dir) { mktmpdir } <del> let(:app) { Pathname.new("#{home_dir}/MyFancyApp.app") } <del> let(:cask) { Cask::CaskLoader.load(cask_path("with-uninstall-script-user-relative")) } <del> <del> before do <del> ENV["HOME"] = home_dir <del> end <del> <del> it "can still uninstall them" do <del> Cask::Installer.new(cask).install <del> <del> expect(cask).to be_installed <del> expect(app).to exist <del> <del> expect { <del> described_class.run("with-uninstall-script-user-relative") <del> }.not_to raise_error <del> <del> expect(cask).not_to be_installed <del> expect(app).not_to exist <del> end <del> end <del> <ide> describe "when multiple versions of a cask are installed" do <ide> let(:token) { "versioned-cask" } <ide> let(:first_installed_version) { "1.2.3" }
1
Text
Text
replace methods used in the example code
4eb9365d6641ab0aaface2528404d00ec20f98c5
<ide><path>doc/api/buffer.md <ide> Examples: <ide> ```js <ide> const buf = Buffer.allocUnsafe(6); <ide> <del>buf.writeUIntBE(0x1234567890ab, 0, 6); <add>buf.writeIntBE(0x1234567890ab, 0, 6); <ide> <ide> // Prints: <Buffer 12 34 56 78 90 ab> <ide> console.log(buf); <ide> <del>buf.writeUIntLE(0x1234567890ab, 0, 6); <add>buf.writeIntLE(0x1234567890ab, 0, 6); <ide> <ide> // Prints: <Buffer ab 90 78 56 34 12> <ide> console.log(buf);
1
Text
Text
add more details in jsx-in-depth.md
f5144121f97253496248d26e61f1e69497e0a02a
<ide><path>docs/docs/jsx-in-depth.md <ide> function NumberDescriber(props) { <ide> } <ide> ``` <ide> <add>You can learn more about [conditional rendering](/react/docs/conditional-rendering.html) and [loops](/react/docs/lists-and-keys.html) in the corresponding sections. <add> <ide> ### String Literals <ide> <ide> You can pass a string literal as a prop. These two JSX expressions are equivalent:
1
Ruby
Ruby
fix ruby warnings in actionmailbox
3adb2619857fabdbd40de8fd4199f3b7ffdaed36
<ide><path>actionmailbox/app/models/action_mailbox/inbound_email/message_id.rb <ide> module ActionMailbox::InboundEmail::MessageId <ide> # attachment called `raw_email`. Before the upload, extract the Message-ID from the `source` and set <ide> # it as an attribute on the new `InboundEmail`. <ide> def create_and_extract_message_id!(source, **options) <del> create! message_id: extract_message_id(source), **options do |inbound_email| <add> create! options.merge(message_id: extract_message_id(source)) do |inbound_email| <ide> inbound_email.raw_email.attach io: StringIO.new(source), filename: "message.eml", content_type: "message/rfc822" <ide> end <ide> end
1
Ruby
Ruby
fix typo in metal/live [ci skip]
eae19033fbec07bdec3dd532fe29989fc137ba24
<ide><path>actionpack/lib/action_controller/metal/live.rb <ide> <ide> module ActionController # :nodoc: <ide> # Mix this module in to your controller, and all actions in that controller <del> # will be able to stream data to the client as it's written. For example: <add> # will be able to stream data to the client as it's written. <ide> # <ide> # class MyController < ActionController::Base <ide> # include ActionController::Live <ide> module ActionController # :nodoc: <ide> # end <ide> # end <ide> # <del> # There are a few caveats with this use. You *cannot* write headers after the <add> # There are a few caveats with this use. You *cannot* write headers after the <ide> # response has been committed (Response#committed? will return truthy). <ide> # Calling +write+ or +close+ on the response stream will cause the response <del> # object to be committed. Make sure all headers are set before calling write <add> # object to be committed. Make sure all headers are set before calling write <ide> # or close on your stream. <ide> # <ide> # You *must* call close on your stream when you're finished, otherwise the <ide> # socket may be left open forever. <ide> # <del> # The final caveat is that you actions are executed in a separate thread than <del> # the main thread. Make sure your actions are thread safe, and this shouldn't <add> # The final caveat is that your actions are executed in a separate thread than <add> # the main thread. Make sure your actions are thread safe, and this shouldn't <ide> # be a problem (don't share state across threads, etc). <ide> module Live <ide> class Buffer < ActionDispatch::Response::Buffer # :nodoc: <ide> def process(name) <ide> t1 = Thread.current <ide> locals = t1.keys.map { |key| [key, t1[key]] } <ide> <del> # This processes the action in a child thread. It lets us return the <add> # This processes the action in a child thread. It lets us return the <ide> # response code and headers back up the rack stack, and still process <ide> # the body in parallel with sending data to the client <ide> Thread.new {
1
Text
Text
update docker swarm cli
78ebfaff1a426425573c440c24eb0f36ffed4d8c
<ide><path>docs/reference/commandline/swarm_init.md <ide> in the newly created one node Swarm cluster. <ide> <ide> ```bash <ide> $ docker swarm init --listen-addr 192.168.99.121:2377 <del>Initializing a new swarm <add>Swarm initialized: current node (1ujecd0j9n3ro9i6628smdmth) is now a manager. <ide> $ docker node ls <del>ID NAME STATUS AVAILABILITY/MEMBERSHIP MANAGER STATUS LEADER <del>3l1f6uzcuoa3 * swarm-master READY ACTIVE REACHABLE Yes <add>ID NAME MEMBERSHIP STATUS AVAILABILITY MANAGER STATUS LEADER <add>1ujecd0j9n3ro9i6628smdmth * manager1 Accepted Ready Active Reachable Yes <ide> ``` <ide> <ide> ### --auto-accept value <ide> <ide> This flag controls node acceptance into the cluster. By default, both `worker` and `manager` <ide> nodes are auto accepted by the cluster. This can be changed by specifing what kinds of nodes <del>can be auto-accepted into the cluster. If auto-accept is not turned on, then <add>can be auto-accepted into the cluster. If auto-accept is not turned on, then <ide> [node accept](node_accept.md) can be used to explicitly accept a node into the cluster. <ide> <ide> For example, the following initializes a cluster with auto-acceptance of workers, but not managers <ide> <ide> <ide> ```bash <ide> $ docker swarm init --listen-addr 192.168.99.121:2377 --auto-accept worker <del>Initializing a new swarm <add>Swarm initialized: current node (1m8cdsylxbf3lk8qriqt07hx1) is now a manager. <ide> ``` <ide> <ide> ### `--force-new-cluster` <ide><path>docs/reference/commandline/swarm_join.md <ide> targeted by this command becomes a `manager`. If it is not specified, it becomes <ide> <ide> ```bash <ide> $ docker swarm join --manager --listen-addr 192.168.99.122:2377 192.168.99.121:2377 <del>This node is attempting to join a Swarm as a manager. <add>This node joined a Swarm as a manager. <ide> $ docker node ls <del>ID NAME STATUS AVAILABILITY/MEMBERSHIP MANAGER STATUS LEADER <del>2fg70txcrde2 swarm-node-01 READY ACTIVE REACHABLE <del>3l1f6uzcuoa3 * swarm-master READY ACTIVE REACHABLE Yes <add>ID NAME MEMBERSHIP STATUS AVAILABILITY MANAGER STATUS LEADER <add>dkp8vy1dq1kxleu9g4u78tlag * manager2 Accepted Ready Active Reachable <add>dvfxp4zseq4s0rih1selh0d20 manager1 Accepted Ready Active Reachable Yes <ide> ``` <ide> <ide> ### Join a node to swarm as a worker <ide> <ide> ```bash <ide> $ docker swarm join --listen-addr 192.168.99.123:2377 192.168.99.121:2377 <del>This node is attempting to join a Swarm. <add>This node joined a Swarm as a worker. <ide> $ docker node ls <del>ID NAME STATUS AVAILABILITY/MEMBERSHIP MANAGER STATUS LEADER <del>04zm7ue1fd1q swarm-node-02 READY ACTIVE <del>2fg70txcrde2 swarm-node-01 READY ACTIVE REACHABLE <del>3l1f6uzcuoa3 * swarm-master READY ACTIVE REACHABLE Yes <add>ID NAME MEMBERSHIP STATUS AVAILABILITY MANAGER STATUS LEADER <add>7ln70fl22uw2dvjn2ft53m3q5 worker2 Accepted Ready Active <add>dkp8vy1dq1kxleu9g4u78tlag worker1 Accepted Ready Active Reachable <add>dvfxp4zseq4s0rih1selh0d20 * manager1 Accepted Ready Active Reachable Yes <ide> ``` <ide> <ide> ### `--manager` <ide><path>docs/reference/commandline/swarm_leave.md <ide> This command causes the node to leave the swarm. <ide> On a manager node: <ide> ```bash <ide> $ docker node ls <del>ID NAME STATUS AVAILABILITY/MEMBERSHIP MANAGER STATUS LEADER <del>04zm7ue1fd1q swarm-node-02 READY ACTIVE <del>2fg70txcrde2 swarm-node-01 READY ACTIVE REACHABLE <del>3l1f6uzcuoa3 * swarm-master READY ACTIVE REACHABLE Yes <add>ID NAME MEMBERSHIP STATUS AVAILABILITY MANAGER STATUS LEADER <add>7ln70fl22uw2dvjn2ft53m3q5 worker2 Accepted Ready Active <add>dkp8vy1dq1kxleu9g4u78tlag worker1 Accepted Ready Active Reachable <add>dvfxp4zseq4s0rih1selh0d20 * manager1 Accepted Ready Active Reachable Yes <ide> ``` <ide> <ide> On a worker node: <ide> Node left the default swarm. <ide> On a manager node: <ide> ```bash <ide> $ docker node ls <del>ID NAME STATUS AVAILABILITY/MEMBERSHIP MANAGER STATUS LEADER <del>04zm7ue1fd1q swarm-node-02 DOWN ACTIVE <del>2fg70txcrde2 swarm-node-01 READY ACTIVE REACHABLE <del>3l1f6uzcuoa3 * swarm-master READY ACTIVE REACHABLE Yes <add>ID NAME MEMBERSHIP STATUS AVAILABILITY MANAGER STATUS LEADER <add>7ln70fl22uw2dvjn2ft53m3q5 worker2 Accepted Down Active <add>dkp8vy1dq1kxleu9g4u78tlag worker1 Accepted Ready Active Reachable <add>dvfxp4zseq4s0rih1selh0d20 * manager1 Accepted Ready Active Reachable Yes <ide> ``` <ide> <ide> ## Related information <ide><path>docs/reference/commandline/swarm_update.md <ide> parent = "smn_cli" <ide> # swarm update <ide> <ide> Usage: docker swarm update [OPTIONS] <del> <add> <ide> update the Swarm. <del> <add> <ide> Options: <ide> --auto-accept value Auto acceptance policy (worker, manager or none) <ide> --dispatcher-heartbeat duration Dispatcher heartbeat period (default 5s) <ide> --help Print usage <ide> --secret string Set secret value needed to accept nodes into cluster <ide> --task-history-limit int Task history retention limit (default 10) <del> --cert-expiry duration Validity period for node certificates (default 2160h0m0s) <ide> <ide> Updates a Swarm cluster with new parameter values. This command must target a manager node. <ide> <ide> $ docker swarm update --auto-accept manager <ide> * [swarm init](swarm_init.md) <ide> * [swarm join](swarm_join.md) <ide> * [swarm leave](swarm_leave.md) <del>
4
Javascript
Javascript
remove legacypromise in src/shared/annotation.js
cb59e7f872f9b9f25aedb2ab6617b8342d22abbb
<ide><path>src/shared/annotation.js <ide> /* globals Util, isDict, isName, stringToPDFString, warn, Dict, Stream, <ide> stringToBytes, PDFJS, isWorker, assert, NotImplementedException, <ide> Promise, isArray, ObjectLoader, isValidUrl, OperatorList, OPS, <del> LegacyPromise */ <add> createPromiseCapability */ <ide> <ide> 'use strict'; <ide> <ide> var Annotation = (function AnnotationClosure() { <ide> data.rect); // rectangle is nessessary <ide> }, <ide> <del> loadResources: function(keys) { <del> var promise = new LegacyPromise(); <del> this.appearance.dict.getAsync('Resources').then(function(resources) { <del> if (!resources) { <del> promise.resolve(); <del> return; <del> } <del> var objectLoader = new ObjectLoader(resources.map, <del> keys, <del> resources.xref); <del> objectLoader.load().then(function() { <del> promise.resolve(resources); <del> }); <add> loadResources: function Annotation_loadResources(keys) { <add> return new Promise(function (resolve, reject) { <add> this.appearance.dict.getAsync('Resources').then(function (resources) { <add> if (!resources) { <add> resolve(); <add> return; <add> } <add> var objectLoader = new ObjectLoader(resources.map, <add> keys, <add> resources.xref); <add> objectLoader.load().then(function() { <add> resolve(resources); <add> }, reject); <add> }, reject); <ide> }.bind(this)); <del> <del> return promise; <ide> }, <ide> <ide> getOperatorList: function Annotation_getOperatorList(evaluator) { <del> <del> var promise = new LegacyPromise(); <add> var capability = createPromiseCapability(); <ide> <ide> if (!this.appearance) { <del> promise.resolve(new OperatorList()); <del> return promise; <add> capability.resolve(new OperatorList()); <add> return capability.promise; <ide> } <ide> <ide> var data = this.data; <ide> var Annotation = (function AnnotationClosure() { <ide> opList.addOp(OPS.beginAnnotation, [data.rect, transform, matrix]); <ide> evaluator.getOperatorList(this.appearance, resources, opList); <ide> opList.addOp(OPS.endAnnotation, []); <del> promise.resolve(opList); <add> capability.resolve(opList); <ide> <ide> this.appearance.reset(); <del> }.bind(this)); <add> }.bind(this), capability.reject); <ide> <del> return promise; <add> return capability.promise; <ide> } <ide> }; <ide> <ide> var Annotation = (function AnnotationClosure() { <ide> annotations, opList, pdfManager, partialEvaluator, intent) { <ide> <ide> function reject(e) { <del> annotationsReadyPromise.reject(e); <add> annotationsReadyCapability.reject(e); <ide> } <ide> <del> var annotationsReadyPromise = new LegacyPromise(); <add> var annotationsReadyCapability = createPromiseCapability(); <ide> <ide> var annotationPromises = []; <ide> for (var i = 0, n = annotations.length; i < n; ++i) { <ide> var Annotation = (function AnnotationClosure() { <ide> opList.addOpList(annotOpList); <ide> } <ide> opList.addOp(OPS.endAnnotations, []); <del> annotationsReadyPromise.resolve(); <add> annotationsReadyCapability.resolve(); <ide> }, reject); <ide> <del> return annotationsReadyPromise; <add> return annotationsReadyCapability.promise; <ide> }; <ide> <ide> return Annotation; <ide> var TextWidgetAnnotation = (function TextWidgetAnnotationClosure() { <ide> return Annotation.prototype.getOperatorList.call(this, evaluator); <ide> } <ide> <del> var promise = new LegacyPromise(); <ide> var opList = new OperatorList(); <ide> var data = this.data; <ide> <ide> var TextWidgetAnnotation = (function TextWidgetAnnotationClosure() { <ide> <ide> var defaultAppearance = data.defaultAppearance; <ide> if (!defaultAppearance) { <del> promise.resolve(opList); <del> return promise; <add> return Promise.resolve(opList); <ide> } <ide> <ide> // Include any font resources found in the default appearance <ide> var TextWidgetAnnotation = (function TextWidgetAnnotationClosure() { <ide> data.rgb = [rgbValue, rgbValue, rgbValue]; <ide> } <ide> } <del> promise.resolve(opList); <del> return promise; <add> return Promise.resolve(opList); <ide> } <ide> }); <ide>
1
PHP
PHP
add support for null values
fdbe128107232235629e7442cfbdb53a2772cbf2
<ide><path>src/Core/StaticConfigTrait.php <ide> public static function parseDsn($config) { <ide> $config[$key] = true; <ide> } elseif ($value === 'false') { <ide> $config[$key] = false; <add> } elseif ($value === 'null') { <add> $config[$key] = null; <ide> } <ide> } <ide>
1
Java
Java
add onterminatedetach to single and completable
ea4d43a7967e0db8425528289a870345ab985f71
<ide><path>src/main/java/io/reactivex/Completable.java <ide> public final Completable onErrorResumeNext(final Function<? super Throwable, ? e <ide> return RxJavaPlugins.onAssembly(new CompletableResumeNext(this, errorMapper)); <ide> } <ide> <add> /** <add> * Nulls out references to the upstream producer and downstream CompletableObserver if <add> * the sequence is terminated or downstream calls dispose(). <add> * <dl> <add> * <dt><b>Scheduler:</b></dt> <add> * <dd>{@code onTerminateDetach} does not operate by default on a particular {@link Scheduler}.</dd> <add> * </dl> <add> * @return a Completable which nulls out references to the upstream producer and downstream CompletableObserver if <add> * the sequence is terminated or downstream calls dispose() <add> * @since 2.1.5 - experimental <add> */ <add> @Experimental <add> @CheckReturnValue <add> @SchedulerSupport(SchedulerSupport.NONE) <add> public final Completable onTerminateDetach() { <add> return RxJavaPlugins.onAssembly(new CompletableDetach(this)); <add> } <add> <ide> /** <ide> * Returns a Completable that repeatedly subscribes to this Completable until cancelled. <ide> * <dl> <ide><path>src/main/java/io/reactivex/Maybe.java <ide> public final Maybe<T> onExceptionResumeNext(final MaybeSource<? extends T> next) <ide> ObjectHelper.requireNonNull(next, "next is null"); <ide> return RxJavaPlugins.onAssembly(new MaybeOnErrorNext<T>(this, Functions.justFunction(next), false)); <ide> } <add> <ide> /** <ide> * Nulls out references to the upstream producer and downstream MaybeObserver if <ide> * the sequence is terminated or downstream calls dispose(). <ide> * <dl> <ide> * <dt><b>Scheduler:</b></dt> <ide> * <dd>{@code onTerminateDetach} does not operate by default on a particular {@link Scheduler}.</dd> <ide> * </dl> <del> * @return a Maybe which out references to the upstream producer and downstream MaybeObserver if <add> * @return a Maybe which nulls out references to the upstream producer and downstream MaybeObserver if <ide> * the sequence is terminated or downstream calls dispose() <ide> */ <ide> @CheckReturnValue <ide><path>src/main/java/io/reactivex/Single.java <ide> public final Single<T> onErrorResumeNext( <ide> return RxJavaPlugins.onAssembly(new SingleResumeNext<T>(this, resumeFunctionInCaseOfError)); <ide> } <ide> <add> /** <add> * Nulls out references to the upstream producer and downstream SingleObserver if <add> * the sequence is terminated or downstream calls dispose(). <add> * <dl> <add> * <dt><b>Scheduler:</b></dt> <add> * <dd>{@code onTerminateDetach} does not operate by default on a particular {@link Scheduler}.</dd> <add> * </dl> <add> * @return a Single which nulls out references to the upstream producer and downstream SingleObserver if <add> * the sequence is terminated or downstream calls dispose() <add> * @since 2.1.5 - experimental <add> */ <add> @Experimental <add> @CheckReturnValue <add> @SchedulerSupport(SchedulerSupport.NONE) <add> public final Single<T> onTerminateDetach() { <add> return RxJavaPlugins.onAssembly(new SingleDetach<T>(this)); <add> } <add> <ide> /** <ide> * Repeatedly re-subscribes to the current Single and emits each success value. <ide> * <dl> <ide><path>src/main/java/io/reactivex/internal/operators/completable/CompletableDetach.java <add>/** <add> * Copyright (c) 2016-present, RxJava Contributors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in <add> * compliance 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, software distributed under the License is <add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See <add> * the License for the specific language governing permissions and limitations under the License. <add> */ <add> <add>package io.reactivex.internal.operators.completable; <add> <add>import io.reactivex.*; <add>import io.reactivex.annotations.Experimental; <add>import io.reactivex.disposables.Disposable; <add>import io.reactivex.internal.disposables.DisposableHelper; <add> <add>/** <add> * Breaks the references between the upstream and downstream when the Completable terminates. <add> * <add> * @since 2.1.5 - experimental <add> */ <add>@Experimental <add>public final class CompletableDetach extends Completable { <add> <add> final CompletableSource source; <add> <add> public CompletableDetach(CompletableSource source) { <add> this.source = source; <add> } <add> <add> @Override <add> protected void subscribeActual(CompletableObserver observer) { <add> source.subscribe(new DetachCompletableObserver(observer)); <add> } <add> <add> static final class DetachCompletableObserver implements CompletableObserver, Disposable { <add> <add> CompletableObserver actual; <add> <add> Disposable d; <add> <add> DetachCompletableObserver(CompletableObserver actual) { <add> this.actual = actual; <add> } <add> <add> @Override <add> public void dispose() { <add> actual = null; <add> d.dispose(); <add> d = DisposableHelper.DISPOSED; <add> } <add> <add> @Override <add> public boolean isDisposed() { <add> return d.isDisposed(); <add> } <add> <add> @Override <add> public void onSubscribe(Disposable d) { <add> if (DisposableHelper.validate(this.d, d)) { <add> this.d = d; <add> <add> actual.onSubscribe(this); <add> } <add> } <add> <add> @Override <add> public void onError(Throwable e) { <add> d = DisposableHelper.DISPOSED; <add> CompletableObserver a = actual; <add> if (a != null) { <add> actual = null; <add> a.onError(e); <add> } <add> } <add> <add> @Override <add> public void onComplete() { <add> d = DisposableHelper.DISPOSED; <add> CompletableObserver a = actual; <add> if (a != null) { <add> actual = null; <add> a.onComplete(); <add> } <add> } <add> } <add>} <ide><path>src/main/java/io/reactivex/internal/operators/maybe/MaybeDetach.java <ide> public void onSuccess(T value) { <ide> d = DisposableHelper.DISPOSED; <ide> MaybeObserver<? super T> a = actual; <ide> if (a != null) { <add> actual = null; <ide> a.onSuccess(value); <ide> } <ide> } <ide> public void onError(Throwable e) { <ide> d = DisposableHelper.DISPOSED; <ide> MaybeObserver<? super T> a = actual; <ide> if (a != null) { <add> actual = null; <ide> a.onError(e); <ide> } <ide> } <ide> public void onComplete() { <ide> d = DisposableHelper.DISPOSED; <ide> MaybeObserver<? super T> a = actual; <ide> if (a != null) { <add> actual = null; <ide> a.onComplete(); <ide> } <ide> } <ide><path>src/main/java/io/reactivex/internal/operators/single/SingleDetach.java <add>/** <add> * Copyright (c) 2016-present, RxJava Contributors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in <add> * compliance 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, software distributed under the License is <add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See <add> * the License for the specific language governing permissions and limitations under the License. <add> */ <add> <add>package io.reactivex.internal.operators.single; <add> <add>import io.reactivex.*; <add>import io.reactivex.annotations.Experimental; <add>import io.reactivex.disposables.Disposable; <add>import io.reactivex.internal.disposables.DisposableHelper; <add> <add>/** <add> * Breaks the references between the upstream and downstream when the Maybe terminates. <add> * <add> * @param <T> the value type <add> * @since 2.1.5 - experimental <add> */ <add>@Experimental <add>public final class SingleDetach<T> extends Single<T> { <add> <add> final SingleSource<T> source; <add> <add> public SingleDetach(SingleSource<T> source) { <add> this.source = source; <add> } <add> <add> @Override <add> protected void subscribeActual(SingleObserver<? super T> observer) { <add> source.subscribe(new DetachSingleObserver<T>(observer)); <add> } <add> <add> static final class DetachSingleObserver<T> implements SingleObserver<T>, Disposable { <add> <add> SingleObserver<? super T> actual; <add> <add> Disposable d; <add> <add> DetachSingleObserver(SingleObserver<? super T> actual) { <add> this.actual = actual; <add> } <add> <add> @Override <add> public void dispose() { <add> actual = null; <add> d.dispose(); <add> d = DisposableHelper.DISPOSED; <add> } <add> <add> @Override <add> public boolean isDisposed() { <add> return d.isDisposed(); <add> } <add> <add> @Override <add> public void onSubscribe(Disposable d) { <add> if (DisposableHelper.validate(this.d, d)) { <add> this.d = d; <add> <add> actual.onSubscribe(this); <add> } <add> } <add> <add> @Override <add> public void onSuccess(T value) { <add> d = DisposableHelper.DISPOSED; <add> SingleObserver<? super T> a = actual; <add> if (a != null) { <add> actual = null; <add> a.onSuccess(value); <add> } <add> } <add> <add> @Override <add> public void onError(Throwable e) { <add> d = DisposableHelper.DISPOSED; <add> SingleObserver<? super T> a = actual; <add> if (a != null) { <add> actual = null; <add> a.onError(e); <add> } <add> } <add> } <add>} <ide><path>src/test/java/io/reactivex/internal/operators/completable/CompletableDetachTest.java <add>/** <add> * Copyright (c) 2016-present, RxJava Contributors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in <add> * compliance 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, software distributed under the License is <add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See <add> * the License for the specific language governing permissions and limitations under the License. <add> */ <add> <add>package io.reactivex.internal.operators.completable; <add> <add>import static org.junit.Assert.assertNull; <add> <add>import java.io.IOException; <add>import java.lang.ref.WeakReference; <add> <add>import org.junit.Test; <add> <add>import io.reactivex.*; <add>import io.reactivex.disposables.*; <add>import io.reactivex.exceptions.TestException; <add>import io.reactivex.functions.Function; <add>import io.reactivex.observers.TestObserver; <add>import io.reactivex.processors.PublishProcessor; <add> <add>public class CompletableDetachTest { <add> <add> @Test <add> public void doubleSubscribe() { <add> <add> TestHelper.checkDoubleOnSubscribeCompletable(new Function<Completable, CompletableSource>() { <add> @Override <add> public CompletableSource apply(Completable m) throws Exception { <add> return m.onTerminateDetach(); <add> } <add> }); <add> } <add> <add> @Test <add> public void dispose() { <add> TestHelper.checkDisposed(PublishProcessor.create().ignoreElements().onTerminateDetach()); <add> } <add> <add> @Test <add> public void onError() { <add> Completable.error(new TestException()) <add> .onTerminateDetach() <add> .test() <add> .assertFailure(TestException.class); <add> } <add> <add> @Test <add> public void onComplete() { <add> Completable.complete() <add> .onTerminateDetach() <add> .test() <add> .assertResult(); <add> } <add> <add> @Test <add> public void cancelDetaches() throws Exception { <add> Disposable d = Disposables.empty(); <add> final WeakReference<Disposable> wr = new WeakReference<Disposable>(d); <add> <add> TestObserver<Void> to = new Completable() { <add> @Override <add> protected void subscribeActual(CompletableObserver observer) { <add> observer.onSubscribe(wr.get()); <add> }; <add> } <add> .onTerminateDetach() <add> .test(); <add> <add> d = null; <add> <add> to.cancel(); <add> <add> System.gc(); <add> Thread.sleep(200); <add> <add> to.assertEmpty(); <add> <add> assertNull(wr.get()); <add> } <add> <add> @Test <add> public void completeDetaches() throws Exception { <add> Disposable d = Disposables.empty(); <add> final WeakReference<Disposable> wr = new WeakReference<Disposable>(d); <add> <add> TestObserver<Void> to = new Completable() { <add> @Override <add> protected void subscribeActual(CompletableObserver observer) { <add> observer.onSubscribe(wr.get()); <add> observer.onComplete(); <add> observer.onComplete(); <add> }; <add> } <add> .onTerminateDetach() <add> .test(); <add> <add> d = null; <add> <add> System.gc(); <add> Thread.sleep(200); <add> <add> to.assertResult(); <add> <add> assertNull(wr.get()); <add> } <add> <add> @Test <add> public void errorDetaches() throws Exception { <add> Disposable d = Disposables.empty(); <add> final WeakReference<Disposable> wr = new WeakReference<Disposable>(d); <add> <add> TestObserver<Void> to = new Completable() { <add> @Override <add> protected void subscribeActual(CompletableObserver observer) { <add> observer.onSubscribe(wr.get()); <add> observer.onError(new TestException()); <add> observer.onError(new IOException()); <add> }; <add> } <add> .onTerminateDetach() <add> .test(); <add> <add> d = null; <add> <add> System.gc(); <add> Thread.sleep(200); <add> <add> to.assertFailure(TestException.class); <add> <add> assertNull(wr.get()); <add> } <add>} <ide><path>src/test/java/io/reactivex/internal/operators/maybe/MaybeDetachTest.java <ide> <ide> package io.reactivex.internal.operators.maybe; <ide> <add>import static org.junit.Assert.assertNull; <add> <add>import java.io.IOException; <add>import java.lang.ref.WeakReference; <add> <ide> import org.junit.Test; <ide> <ide> import io.reactivex.*; <add>import io.reactivex.disposables.*; <ide> import io.reactivex.exceptions.TestException; <ide> import io.reactivex.functions.Function; <add>import io.reactivex.observers.TestObserver; <ide> import io.reactivex.processors.PublishProcessor; <ide> <ide> public class MaybeDetachTest { <ide> public void onComplete() { <ide> .test() <ide> .assertResult(); <ide> } <add> <add> @Test <add> public void cancelDetaches() throws Exception { <add> Disposable d = Disposables.empty(); <add> final WeakReference<Disposable> wr = new WeakReference<Disposable>(d); <add> <add> TestObserver<Object> to = new Maybe<Object>() { <add> @Override <add> protected void subscribeActual(MaybeObserver<? super Object> observer) { <add> observer.onSubscribe(wr.get()); <add> }; <add> } <add> .onTerminateDetach() <add> .test(); <add> <add> d = null; <add> <add> to.cancel(); <add> <add> System.gc(); <add> Thread.sleep(200); <add> <add> to.assertEmpty(); <add> <add> assertNull(wr.get()); <add> } <add> <add> @Test <add> public void completeDetaches() throws Exception { <add> Disposable d = Disposables.empty(); <add> final WeakReference<Disposable> wr = new WeakReference<Disposable>(d); <add> <add> TestObserver<Integer> to = new Maybe<Integer>() { <add> @Override <add> protected void subscribeActual(MaybeObserver<? super Integer> observer) { <add> observer.onSubscribe(wr.get()); <add> observer.onComplete(); <add> observer.onComplete(); <add> }; <add> } <add> .onTerminateDetach() <add> .test(); <add> <add> d = null; <add> <add> System.gc(); <add> Thread.sleep(200); <add> <add> to.assertResult(); <add> <add> assertNull(wr.get()); <add> } <add> <add> @Test <add> public void errorDetaches() throws Exception { <add> Disposable d = Disposables.empty(); <add> final WeakReference<Disposable> wr = new WeakReference<Disposable>(d); <add> <add> TestObserver<Integer> to = new Maybe<Integer>() { <add> @Override <add> protected void subscribeActual(MaybeObserver<? super Integer> observer) { <add> observer.onSubscribe(wr.get()); <add> observer.onError(new TestException()); <add> observer.onError(new IOException()); <add> }; <add> } <add> .onTerminateDetach() <add> .test(); <add> <add> d = null; <add> <add> System.gc(); <add> Thread.sleep(200); <add> <add> to.assertFailure(TestException.class); <add> <add> assertNull(wr.get()); <add> } <add> <add> @Test <add> public void successDetaches() throws Exception { <add> Disposable d = Disposables.empty(); <add> final WeakReference<Disposable> wr = new WeakReference<Disposable>(d); <add> <add> TestObserver<Integer> to = new Maybe<Integer>() { <add> @Override <add> protected void subscribeActual(MaybeObserver<? super Integer> observer) { <add> observer.onSubscribe(wr.get()); <add> observer.onSuccess(1); <add> observer.onSuccess(2); <add> }; <add> } <add> .onTerminateDetach() <add> .test(); <add> <add> d = null; <add> <add> System.gc(); <add> Thread.sleep(200); <add> <add> to.assertResult(1); <add> <add> assertNull(wr.get()); <add> } <ide> } <ide><path>src/test/java/io/reactivex/internal/operators/single/SingleDetachTest.java <add>/** <add> * Copyright (c) 2016-present, RxJava Contributors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in <add> * compliance 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, software distributed under the License is <add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See <add> * the License for the specific language governing permissions and limitations under the License. <add> */ <add> <add>package io.reactivex.internal.operators.single; <add> <add>import static org.junit.Assert.assertNull; <add> <add>import java.io.IOException; <add>import java.lang.ref.WeakReference; <add> <add>import org.junit.Test; <add> <add>import io.reactivex.*; <add>import io.reactivex.disposables.*; <add>import io.reactivex.exceptions.TestException; <add>import io.reactivex.functions.Function; <add>import io.reactivex.observers.TestObserver; <add>import io.reactivex.processors.PublishProcessor; <add> <add>public class SingleDetachTest { <add> <add> @Test <add> public void doubleSubscribe() { <add> <add> TestHelper.checkDoubleOnSubscribeSingle(new Function<Single<Object>, SingleSource<Object>>() { <add> @Override <add> public SingleSource<Object> apply(Single<Object> m) throws Exception { <add> return m.onTerminateDetach(); <add> } <add> }); <add> } <add> <add> @Test <add> public void dispose() { <add> TestHelper.checkDisposed(PublishProcessor.create().singleOrError().onTerminateDetach()); <add> } <add> <add> @Test <add> public void onError() { <add> Single.error(new TestException()) <add> .onTerminateDetach() <add> .test() <add> .assertFailure(TestException.class); <add> } <add> <add> @Test <add> public void onSuccess() { <add> Single.just(1) <add> .onTerminateDetach() <add> .test() <add> .assertResult(1); <add> } <add> <add> @Test <add> public void cancelDetaches() throws Exception { <add> Disposable d = Disposables.empty(); <add> final WeakReference<Disposable> wr = new WeakReference<Disposable>(d); <add> <add> TestObserver<Object> to = new Single<Object>() { <add> @Override <add> protected void subscribeActual(SingleObserver<? super Object> observer) { <add> observer.onSubscribe(wr.get()); <add> }; <add> } <add> .onTerminateDetach() <add> .test(); <add> <add> d = null; <add> <add> to.cancel(); <add> <add> System.gc(); <add> Thread.sleep(200); <add> <add> to.assertEmpty(); <add> <add> assertNull(wr.get()); <add> } <add> <add> @Test <add> public void errorDetaches() throws Exception { <add> Disposable d = Disposables.empty(); <add> final WeakReference<Disposable> wr = new WeakReference<Disposable>(d); <add> <add> TestObserver<Integer> to = new Single<Integer>() { <add> @Override <add> protected void subscribeActual(SingleObserver<? super Integer> observer) { <add> observer.onSubscribe(wr.get()); <add> observer.onError(new TestException()); <add> observer.onError(new IOException()); <add> }; <add> } <add> .onTerminateDetach() <add> .test(); <add> <add> d = null; <add> <add> System.gc(); <add> Thread.sleep(200); <add> <add> to.assertFailure(TestException.class); <add> <add> assertNull(wr.get()); <add> } <add> <add> @Test <add> public void successDetaches() throws Exception { <add> Disposable d = Disposables.empty(); <add> final WeakReference<Disposable> wr = new WeakReference<Disposable>(d); <add> <add> TestObserver<Integer> to = new Single<Integer>() { <add> @Override <add> protected void subscribeActual(SingleObserver<? super Integer> observer) { <add> observer.onSubscribe(wr.get()); <add> observer.onSuccess(1); <add> observer.onSuccess(2); <add> }; <add> } <add> .onTerminateDetach() <add> .test(); <add> <add> d = null; <add> <add> System.gc(); <add> Thread.sleep(200); <add> <add> to.assertResult(1); <add> <add> assertNull(wr.get()); <add> } <add>}
9
Python
Python
hack a fixture in the vectors tests, for xfail
92dbf28c1ef825176f0e81533a84dcaacb5fd098
<ide><path>spacy/tests/vectors/test_similarity.py <ide> def vectors(): <ide> <ide> @pytest.fixture() <ide> def vocab(en_vocab, vectors): <del> return add_vecs_to_vocab(en_vocab, vectors) <add> #return add_vecs_to_vocab(en_vocab, vectors) <add> return None <ide> <ide> @pytest.mark.xfail <ide> def test_vectors_similarity_LL(vocab, vectors):
1
Ruby
Ruby
pull common stdlib checking code into a method
3d26b7584721c485d4c9df38fc7e2130c28ef75f
<ide><path>Library/Homebrew/build.rb <ide> def install <ide> <ide> def detect_stdlibs <ide> keg = Keg.new(f.prefix) <del> # This first test includes executables because we still <del> # want to record the stdlib for something that installs no <del> # dylibs. <del> stdlibs = keg.detect_cxx_stdlibs <del> # This currently only tracks a single C++ stdlib per dep, <del> # though it's possible for different libs/executables in <del> # a given formula to link to different ones. <del> stdlib_in_use = CxxStdlib.create(stdlibs.first, ENV.compiler) <del> begin <del> stdlib_in_use.check_dependencies(f, deps) <del> rescue IncompatibleCxxStdlibs => e <del> opoo e.message <del> end <add> CxxStdlib.check_compatibility(f, deps, keg, ENV.compiler) <ide> <del> # This second check is recorded for checking dependencies, <del> # so executable are irrelevant at this point. If a piece <del> # of software installs an executable that links against libstdc++ <del> # and dylibs against libc++, libc++-only dependencies can safely <del> # link against it. <add> # The stdlib recorded in the install receipt is used during dependency <add> # compatibility checks, so we only care about the stdlib that libraries <add> # link against. <ide> keg.detect_cxx_stdlibs(:skip_executables => true) <ide> end <ide> <ide><path>Library/Homebrew/cxxstdlib.rb <ide> def self.create(type, compiler) <ide> klass.new(type, compiler) <ide> end <ide> <add> def self.check_compatibility(formula, deps, keg, compiler) <add> return if formula.skip_cxxstdlib_check? <add> <add> stdlib = create(keg.detect_cxx_stdlibs.first, compiler) <add> <add> begin <add> stdlib.check_dependencies(formula, deps) <add> rescue IncompatibleCxxStdlibs => e <add> opoo e.message <add> end <add> end <add> <ide> attr_reader :type, :compiler <ide> <ide> def initialize(type, compiler) <ide> def compatible_with?(other) <ide> end <ide> <ide> def check_dependencies(formula, deps) <del> unless formula.skip_cxxstdlib_check? <del> deps.each do |dep| <del> # Software is unlikely to link against anything from its <del> # buildtime deps, so it doesn't matter at all if they link <del> # against different C++ stdlibs <del> next if dep.build? <del> <del> dep_stdlib = Tab.for_formula(dep.to_formula).cxxstdlib <del> if !compatible_with? dep_stdlib <del> raise IncompatibleCxxStdlibs.new(formula, dep, dep_stdlib, self) <del> end <add> deps.each do |dep| <add> # Software is unlikely to link against libraries from build-time deps, so <add> # it doesn't matter if they link against different C++ stdlibs. <add> next if dep.build? <add> <add> dep_stdlib = Tab.for_formula(dep.to_formula).cxxstdlib <add> if !compatible_with? dep_stdlib <add> raise IncompatibleCxxStdlibs.new(formula, dep, dep_stdlib, self) <ide> end <ide> end <ide> end <ide><path>Library/Homebrew/formula_installer.rb <ide> def install <ide> pour <ide> @poured_bottle = true <ide> <del> stdlibs = Keg.new(f.prefix).detect_cxx_stdlibs <del> stdlib_in_use = CxxStdlib.create(stdlibs.first, MacOS.default_compiler) <del> begin <del> stdlib_in_use.check_dependencies(f, f.recursive_dependencies) <del> rescue IncompatibleCxxStdlibs => e <del> opoo e.message <del> end <add> CxxStdlib.check_compatibility( <add> f, f.recursive_dependencies, <add> Keg.new(f.prefix), MacOS.default_compiler <add> ) <ide> <ide> tab = Tab.for_keg f.prefix <ide> tab.poured_from_bottle = true
3
Text
Text
add 1.6.1 to changelog
f71243b709de012b2ffd389790072f4a7a16db2b
<ide><path>CHANGELOG.md <ide> caveats with model/content, and also sets a simple ground rule: Never set a controllers content, <ide> rather always set it's model and ember will do the right thing. <ide> <add>### Ember 1.6.1 (July, 15, 2014) <add> <add>* Fix error routes/templates. Changes in router promise logging caused errors to be <add> thrown mid-transition into the `error` route. See [#5166](https://github.com/emberjs/ember.js/pull/5166) for further details. <add> <ide> ### Ember 1.6.0 (July, 7, 2014) <ide> <ide> * [BREAKING BUGFIX] An empty array is treated as falsy value in `bind-attr` to be in consistent
1
Python
Python
fix coding style
d41fc8f4437e585656ac50a2d73bcc8146e05579
<ide><path>research/object_detection/meta_architectures/faster_rcnn_meta_arch.py <ide> def _compute_second_stage_input_feature_maps(self, features_to_crop, <ide> num_levels = len(features_to_crop) <ide> box_levels = None <ide> if num_levels != 1: <del> # If there are mutiple levels to select, get the box levels <add> # If there are mutiple levels to select, get the box levels <ide> box_levels = ops.fpn_feature_levels(num_levels, num_levels - 1, <ide> 1.0/224, proposal_boxes_normalized) <ide> cropped_regions = self._flatten_first_two_dimensions( <ide><path>research/object_detection/utils/ops.py <ide> from object_detection.utils import static_shape <ide> <ide> <del>multilevel_matmul_crop_and_resize = spatial_ops.multilevel_matmul_crop_and_resize <add>multilevel_matmul_crop_and_resize = \ <add> spatial_ops.multilevel_matmul_crop_and_resize <ide> matmul_crop_and_resize = spatial_ops.matmul_crop_and_resize <ide> multilevel_roi_align = spatial_ops.multilevel_roi_align <del>multilevel_native_crop_and_resize = spatial_ops.multilevel_native_crop_and_resize <add>multilevel_native_crop_and_resize = \ <add> spatial_ops.multilevel_native_crop_and_resize <ide> native_crop_and_resize = spatial_ops.native_crop_and_resize <ide> <ide>
2
Javascript
Javascript
remove console log
f111eaa5436e8ac9f8628b16538fe2fcc5313d02
<ide><path>src/main-process/parse-command-line.js <ide> module.exports = function parseCommandLine (processArgs) { <ide> const paths = contents.paths.map((curPath) => <ide> relativizeToAtomProject(curPath, path.dirname(path.join(executedFrom, atomProject)) <ide> )) <del> console.log(paths) <ide> pathsToOpen.push(path.dirname(atomProject)) <ide> projectSettings = { originPath, paths, config } <ide> }
1
Text
Text
fix bad translation (auto-translation)
18fd2780d70c32f6a03689a1d7805975c30d83d6
<ide><path>guide/portuguese/haskell/misc/index.md <ide> title: miscellaneous <ide> localeTitle: Diversos <ide> --- <del>Quando você está um pouco confortável com o modo como Haskell trabalha você <add>Quando já estiver um pouco confortável com o modo como Haskell trabalha, você pode recorrer ao: <ide> <ide> ## hoogle <ide> <ide> É como o Google, mas para as bibliotecas da Haskell <ide> <del>Para instalar o hoogle com pilha: <add>Para instalar o hoogle com o Stack: <ide> <ide> ```shell <ide> stack build hoogle <ide> ``` <ide> <del>## lambda bot <ide>\ No newline at end of file <add>## lambda bot
1
PHP
PHP
fix more tests to use asserttextequals()
14228fa46902801a941f6589817a3cc16292e251
<ide><path>lib/Cake/Test/Case/Routing/DispatcherTest.php <ide> public function testFullPageCachingDispatch($url) { <ide> $dispatcher->cached($request->here()); <ide> $cached = ob_get_clean(); <ide> <del> $result = str_replace(array("\t", "\r\n", "\n"), "", $out); <ide> $cached = preg_replace('/<!--+[^<>]+-->/', '', $cached); <del> $expected = str_replace(array("\t", "\r\n", "\n"), "", $cached); <ide> <del> $this->assertEquals($expected, $result); <add> $this->assertTextEquals($cached, $out); <ide> <ide> $filename = $this->__cachePath($request->here()); <ide> unlink($filename); <ide><path>lib/Cake/Test/Case/View/ThemeViewTest.php <ide> public function testMissingView() { <ide> $View = new TestTheme2View($this->Controller); <ide> ob_start(); <ide> $result = $View->getViewFileName('does_not_exist'); <del> $expected = str_replace(array("\t", "\r\n", "\n"), "", ob_get_clean()); <add> $expected = ob_get_clean(); <ide> $this->assertRegExp("/PagesController::/", $expected); <ide> $this->assertRegExp("/views(\/|\\\)themed(\/|\\\)my_theme(\/|\\\)pages(\/|\\\)does_not_exist.ctp/", $expected); <ide> } <ide> public function testMissingLayout() { <ide> $View = new TestTheme2View($this->Controller); <ide> ob_start(); <ide> $result = $View->getLayoutFileName(); <del> $expected = str_replace(array("\t", "\r\n", "\n"), "", ob_get_clean()); <add> $expected = ob_get_clean(); <ide> $this->assertRegExp("/Missing Layout/", $expected); <ide> $this->assertRegExp("/views(\/|\\\)themed(\/|\\\)my_theme(\/|\\\)layouts(\/|\\\)whatever.ctp/", $expected); <ide> } <ide><path>lib/Cake/Test/Case/View/ViewTest.php <ide> public function testMissingView() { <ide> $View = new TestThemeView($this->ThemeController); <ide> ob_start(); <ide> $result = $View->getViewFileName('does_not_exist'); <del> $expected = str_replace(array("\t", "\r\n", "\n"), "", ob_get_clean()); <add> $expected = ob_get_clean(); <ide> $this->assertRegExp("/PagesController::/", $expected); <ide> $this->assertRegExp("/views(\/|\\\)themed(\/|\\\)my_theme(\/|\\\)pages(\/|\\\)does_not_exist.ctp/", $expected); <ide> } <ide> public function testMissingLayout() { <ide> $View = new TestView($this->Controller); <ide> ob_start(); <ide> $result = $View->getLayoutFileName(); <del> $expected = str_replace(array("\t", "\r\n", "\n"), "", ob_get_clean()); <add> $expected = ob_get_clean(); <ide> <ide> $this->ThemeController->plugin = null; <ide> $this->ThemeController->name = 'Posts'; <ide> public function testMissingLayout() { <ide> $View = new TestThemeView($this->ThemeController); <ide> ob_start(); <ide> $result = $View->getLayoutFileName(); <del> $expected = str_replace(array("\t", "\r\n", "\n"), "", ob_get_clean()); <add> $expected = ob_get_clean(); <ide> $this->assertRegExp("/Missing Layout/", $expected); <ide> $this->assertRegExp("/views(\/|\\\)themed(\/|\\\)my_theme(\/|\\\)layouts(\/|\\\)whatever.ctp/", $expected); <ide> } <ide> public function testRenderLoadHelper() { <ide> */ <ide> public function testRender() { <ide> $View = new TestView($this->PostsController); <del> $result = str_replace(array("\t", "\r\n", "\n"), "", $View->render('index')); <add> $result = $View->render('index'); <ide> <del> $this->assertRegExp("/<meta http-equiv=\"Content-Type\" content=\"text\/html; charset=utf-8\" \/><title>/", $result); <del> $this->assertRegExp("/<div id=\"content\">posts index<\/div>/", $result); <del> $this->assertRegExp("/<div id=\"content\">posts index<\/div>/", $result); <add> $this->assertRegExp("/<meta http-equiv=\"Content-Type\" content=\"text\/html; charset=utf-8\" \/>\s*<title>/", $result); <add> $this->assertRegExp("/<div id=\"content\">\s*posts index\s*<\/div>/", $result); <add> $this->assertRegExp("/<div id=\"content\">\s*posts index\s*<\/div>/", $result); <ide> <ide> $this->assertTrue(isset($View->viewVars['content_for_layout']), 'content_for_layout should be a view var'); <ide> $this->assertTrue(isset($View->viewVars['scripts_for_layout']), 'scripts_for_layout should be a view var'); <ide> public function testRender() { <ide> $this->PostsController->set('page_title', 'yo what up'); <ide> <ide> $View = new TestView($this->PostsController); <del> $result = str_replace(array("\t", "\r\n", "\n"), "", $View->render(false, 'flash')); <add> $result = $View->render(false, 'flash'); <ide> <ide> $this->assertRegExp("/<title>yo what up<\/title>/", $result); <ide> $this->assertRegExp("/<p><a href=\"flash\">yo what up<\/a><\/p>/", $result); <ide> public function testRender() { <ide> Configure::write('Cache.check', true); <ide> <ide> $View = new TestView($this->PostsController); <del> $result = str_replace(array("\t", "\r\n", "\n"), "", $View->render('index')); <add> $result = $View->render('index'); <ide> <del> $this->assertRegExp("/<meta http-equiv=\"Content-Type\" content=\"text\/html; charset=utf-8\" \/><title>/", $result); <del> $this->assertRegExp("/<div id=\"content\">posts index<\/div>/", $result); <del> $this->assertRegExp("/<div id=\"content\">posts index<\/div>/", $result); <add> $this->assertRegExp("/<meta http-equiv=\"Content-Type\" content=\"text\/html; charset=utf-8\" \/>\s*<title>/", $result); <add> $this->assertRegExp("/<div id=\"content\">\s*posts index\s*<\/div>/", $result); <add> $this->assertRegExp("/<div id=\"content\">\s*posts index\s*<\/div>/", $result); <ide> } <ide> <ide> /** <ide> public function testBadExt() { <ide> <ide> $View = new TestView($this->PostsController); <ide> $View->render('this_is_missing'); <del> $result = str_replace(array("\t", "\r\n", "\n"), "", ob_get_clean()); <ide> } <ide> <ide> /** <ide> public function testAltExt() { <ide> public function testAltBadExt() { <ide> $View = new TestView($this->PostsController); <ide> $View->render('alt_ext'); <del> $result = str_replace(array("\t", "\r\n", "\n"), "", ob_get_clean()); <ide> } <ide> <ide> /** <ide><path>lib/Cake/Test/Case/View/XmlViewTest.php <ide> public function testRenderWithoutView() { <ide> $View = new XmlView($Controller); <ide> $output = $View->render(false); <ide> <del> $expected = '<?xml version="1.0" encoding="UTF-8"?><users><user>user1</user><user>user2</user></users>'; <del> $this->assertIdentical($expected, str_replace(array("\r", "\n"), '', $output)); <add> $expected = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . '<users><user>user1</user><user>user2</user></users>'; <add> $this->assertTextEquals($expected, trim($output)); <ide> $this->assertIdentical('application/xml', $Response->type()); <ide> } <ide>
4
PHP
PHP
catch invalid validator types
5a8adbd57f568b25ed4982666c8845b68a70f308
<ide><path>src/ORM/Marshaller.php <ide> use Cake\ORM\Association; <ide> use Cake\ORM\AssociationsNormalizerTrait; <ide> use Cake\ORM\Table; <add>use \RuntimeException; <ide> <ide> /** <ide> * Contains logic to convert array data into entities. <ide> public function one(array $data, array $options = []) { <ide> * @param array $options The options passed to this marshaller. <ide> * @param bool $isNew Whether it is a new entity or one to be updated. <ide> * @return array The list of validation errors. <add> * @throws \RuntimeException If no validator can be created. <ide> */ <ide> protected function _validate($data, $options, $isNew) { <ide> if (!$options['validate']) { <ide> return []; <ide> } <del> <ide> if ($options['validate'] === true) { <ide> $options['validate'] = $this->_table->validator('default'); <ide> } <del> <ide> if (is_string($options['validate'])) { <ide> $options['validate'] = $this->_table->validator($options['validate']); <ide> } <add> if (!is_object($options['validate'])) { <add> throw new RuntimeException( <add> sprintf('validate must be a boolean, a string or an object. Got %s.', gettype($options['validate'])) <add> ); <add> } <ide> <ide> return $options['validate']->errors($data, $isNew); <ide> } <ide> protected function _loadBelongsToMany($assoc, $ids) { <ide> * ### Options: <ide> * <ide> * * associated: Associations listed here will be marshalled as well. <add> * * validate: Whether or not to validate data before hydrating the entities. Can <add> * also be set to a string to use a specific validator. Defaults to true/default. <ide> * * fieldList: A whitelist of fields to be assigned to the entity. If not present <ide> * the accessible fields list in the entity will be used. <ide> * <ide><path>tests/TestCase/ORM/MarshallerTest.php <ide> public function testValidationFail() { <ide> $this->assertNotEmpty($entity->errors('thing')); <ide> } <ide> <add>/** <add> * Test that invalid validate options raise exceptions <add> * <add> * @expectedException \RuntimeException <add> * @return void <add> */ <add> public function testValidateInvalidType() { <add> $data = ['title' => 'foo']; <add> $marshaller = new Marshaller($this->articles); <add> $marshaller->one($data, [ <add> 'validate' => ['derp'], <add> ]); <add> } <add> <ide> /** <ide> * Tests that associations are validated and custom validators can be used <ide> *
2
Go
Go
prevent fallback to v1 registry for digest pulls
642e6a377324c7873f278c6bd7fd5e60201139e2
<ide><path>graph/pull.go <ide> func (s *TagStore) Pull(image string, tag string, imagePullConfig *ImagePullConf <ide> logrus.Debug("image does not exist on v2 registry, falling back to v1") <ide> } <ide> <add> if utils.DigestReference(tag) { <add> return fmt.Errorf("pulling with digest reference failed from v2 registry") <add> } <add> <ide> logrus.Debugf("pulling v1 repository with local name %q", repoInfo.LocalName) <ide> if err = s.pullRepository(r, imagePullConfig.OutStream, repoInfo, tag, sf, imagePullConfig.Parallel); err != nil { <ide> return err <ide><path>integration-cli/docker_cli_by_digest_test.go <ide> func (s *DockerRegistrySuite) TestPullByDigest(c *check.C) { <ide> } <ide> } <ide> <add>func (s *DockerRegistrySuite) TestPullByDigestNoFallback(c *check.C) { <add> // pull from the registry using the <name>@<digest> reference <add> imageReference := fmt.Sprintf("%s@sha256:ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", repoName) <add> cmd := exec.Command(dockerBinary, "pull", imageReference) <add> out, _, err := runCommandWithOutput(cmd) <add> if err == nil || !strings.Contains(out, "pulling with digest reference failed from v2 registry") { <add> c.Fatalf("expected non-zero exit status and correct error message when pulling non-existing image: %s", out) <add> } <add>} <add> <ide> func (s *DockerRegistrySuite) TestCreateByDigest(c *check.C) { <ide> pushDigest, err := setupImage() <ide> if err != nil {
2
Javascript
Javascript
fix comment nits in tools/doc/*.js files
b88477ef4dc82b2a77c90b5de65efab4cf507d3c
<ide><path>tools/doc/addon-verify.js <ide> function once(fn) { <ide> } <ide> <ide> function verifyFiles(files, blockName, onprogress, ondone) { <del> // must have a .cc and a .js to be a valid test <add> // Must have a .cc and a .js to be a valid test. <ide> if (!Object.keys(files).some((name) => /\.cc$/.test(name)) || <ide> !Object.keys(files).some((name) => /\.js$/.test(name))) { <ide> return; <ide> ${files[name].replace( <ide> }); <ide> <ide> fs.mkdir(dir, function() { <del> // Ignore errors <add> // Ignore errors. <ide> <ide> const done = once(ondone); <ide> var waiting = files.length; <ide><path>tools/doc/common.js <ide> function extractAndParseYAML(text) { <ide> .replace(/^<!-- YAML/, '') <ide> .replace(/-->$/, ''); <ide> <del> // js-yaml.safeLoad() throws on error <add> // js-yaml.safeLoad() throws on error. <ide> const meta = yaml.safeLoad(text); <ide> <ide> if (meta.added) { <ide><path>tools/doc/generate.js <ide> const processIncludes = require('./preprocess.js'); <ide> const fs = require('fs'); <ide> <del>// parse the args. <del>// Don't use nopt or whatever for this. It's simple enough. <add>// Parse the args. <add>// Don't use nopt or whatever for this. It's simple enough. <ide> <ide> const args = process.argv.slice(2); <ide> let format = 'json'; <ide> if (!filename) { <ide> <ide> fs.readFile(filename, 'utf8', (er, input) => { <ide> if (er) throw er; <del> // process the input for @include lines <add> // Process the input for @include lines. <ide> processIncludes(filename, input, next); <ide> }); <ide> <ide><path>tools/doc/html.js <ide> module.exports = toHTML; <ide> const STABILITY_TEXT_REG_EXP = /(.*:)\s*(\d)([\s\S]*)/; <ide> const DOC_CREATED_REG_EXP = /<!--\s*introduced_in\s*=\s*v([0-9]+)\.([0-9]+)\.([0-9]+)\s*-->/; <ide> <del>// customized heading without id attribute <add>// Customized heading without id attribute. <ide> const renderer = new marked.Renderer(); <ide> renderer.heading = function(text, level) { <ide> return `<h${level}>${text}</h${level}>\n`; <ide> marked.setOptions({ <ide> renderer: renderer <ide> }); <ide> <del>// TODO(chrisdickinson): never stop vomitting / fix this. <add>// TODO(chrisdickinson): never stop vomiting / fix this. <ide> const gtocPath = path.resolve(path.join( <ide> __dirname, <ide> '..', <ide> function render(opts, cb) { <ide> var { lexed, filename, template } = opts; <ide> const nodeVersion = opts.nodeVersion || process.version; <ide> <del> // get the section <add> // Get the section. <ide> const section = getSection(lexed); <ide> <ide> filename = path.basename(filename, '.md'); <ide> <ide> parseText(lexed); <ide> lexed = parseLists(lexed); <ide> <del> // generate the table of contents. <del> // this mutates the lexed contents in-place. <add> // Generate the table of contents. <add> // This mutates the lexed contents in-place. <ide> buildToc(lexed, filename, function(er, toc) { <ide> if (er) return cb(er); <ide> <ide> function render(opts, cb) { <ide> <ide> template = template.replace(/__ALTDOCS__/, altDocs(filename)); <ide> <del> // content has to be the last thing we do with <del> // the lexed tokens, because it's destructive. <add> // Content has to be the last thing we do with the lexed tokens, <add> // because it's destructive. <ide> const content = marked.parser(lexed); <ide> template = template.replace(/__CONTENT__/g, content); <ide> <ide> function analyticsScript(analytics) { <ide> `; <ide> } <ide> <del>// replace placeholders in text tokens <add>// Replace placeholders in text tokens. <ide> function replaceInText(text) { <ide> return linkJsTypeDocs(linkManPages(text)); <ide> } <ide> function altDocs(filename) { <ide> `; <ide> } <ide> <del>// handle general body-text replacements <del>// for example, link man page references to the actual page <add>// Handle general body-text replacements. <add>// For example, link man page references to the actual page. <ide> function parseText(lexed) { <ide> lexed.forEach(function(tok) { <ide> if (tok.type === 'table') { <ide> function parseText(lexed) { <ide> }); <ide> } <ide> <del>// just update the list item text in-place. <del>// lists that come right after a heading are what we're after. <add>// Just update the list item text in-place. <add>// Lists that come right after a heading are what we're after. <ide> function parseLists(input) { <ide> var state = null; <ide> const savedState = []; <ide> function parseLists(input) { <ide> const stabilityMatch = tok.text.match(STABILITY_TEXT_REG_EXP); <ide> const stability = Number(stabilityMatch[2]); <ide> const isStabilityIndex = <del> index - 2 === headingIndex || // general <del> index - 3 === headingIndex; // with api_metadata block <add> index - 2 === headingIndex || // General. <add> index - 3 === headingIndex; // With api_metadata block. <ide> <ide> if (heading && isStabilityIndex) { <ide> heading.stability = stability; <ide> function parseYAML(text) { <ide> return html.join('\n'); <ide> } <ide> <del>// Syscalls which appear in the docs, but which only exist in BSD / OSX <add>// Syscalls which appear in the docs, but which only exist in BSD / macOS. <ide> const BSD_ONLY_SYSCALLS = new Set(['lchmod']); <ide> <del>// Handle references to man pages, eg "open(2)" or "lchmod(2)" <del>// Returns modified text, with such refs replace with HTML links, for example <del>// '<a href="http://man7.org/linux/man-pages/man2/open.2.html">open(2)</a>' <add>// Handle references to man pages, eg "open(2)" or "lchmod(2)". <add>// Returns modified text, with such refs replaced with HTML links, for example <add>// '<a href="http://man7.org/linux/man-pages/man2/open.2.html">open(2)</a>'. <ide> function linkManPages(text) { <ide> return text.replace( <ide> /(^|\s)([a-z.]+)\((\d)([a-z]?)\)/gm, <ide> (match, beginning, name, number, optionalCharacter) => { <del> // name consists of lowercase letters, number is a single digit <add> // Name consists of lowercase letters, number is a single digit. <ide> const displayAs = `${name}(${number}${optionalCharacter})`; <ide> if (BSD_ONLY_SYSCALLS.has(name)) { <ide> return `${beginning}<a href="https://www.freebsd.org/cgi/man.cgi?query=${name}` + <ide> function linkJsTypeDocs(text) { <ide> var typeMatches; <ide> <ide> // Handle types, for example the source Markdown might say <del> // "This argument should be a {Number} or {String}" <add> // "This argument should be a {Number} or {String}". <ide> for (i = 0; i < parts.length; i += 2) { <ide> typeMatches = parts[i].match(/\{([^}]+)\}/g); <ide> if (typeMatches) { <ide> function linkJsTypeDocs(text) { <ide> } <ide> } <ide> <del> //XXX maybe put more stuff here? <add> // TODO: maybe put more stuff here? <ide> return parts.join('`'); <ide> } <ide> <ide> function parseAPIHeader(text) { <ide> return text; <ide> } <ide> <del>// section is just the first heading <add>// Section is just the first heading. <ide> function getSection(lexed) { <ide> for (var i = 0, l = lexed.length; i < l; i++) { <ide> var tok = lexed[i]; <ide> const numberRe = /^(\d*)/; <ide> function versionSort(a, b) { <ide> a = a.trim(); <ide> b = b.trim(); <del> let i = 0; // common prefix length <add> let i = 0; // Common prefix length. <ide> while (i < a.length && i < b.length && a[i] === b[i]) i++; <ide> a = a.substr(i); <ide> b = b.substr(i); <ide><path>tools/doc/json.js <ide> <ide> module.exports = doJSON; <ide> <del>// Take the lexed input, and return a JSON-encoded object <del>// A module looks like this: https://gist.github.com/1777387 <add>// Take the lexed input, and return a JSON-encoded object. <add>// A module looks like this: https://gist.github.com/1777387. <ide> <ide> const common = require('./common.js'); <ide> const marked = require('marked'); <ide> <del>// customized heading without id attribute <add>// Customized heading without id attribute. <ide> const renderer = new marked.Renderer(); <ide> renderer.heading = function(text, level) { <ide> return `<h${level}>${text}</h${level}>\n`; <ide> function doJSON(input, filename, cb) { <ide> JSON.stringify(tok))); <ide> } <ide> <del> // Sometimes we have two headings with a single <del> // blob of description. Treat as a clone. <add> // Sometimes we have two headings with a single blob of description. <add> // Treat as a clone. <ide> if (current && <ide> state === 'AFTERHEADING' && <ide> depth === tok.depth) { <ide> var clone = current; <ide> current = newSection(tok); <ide> current.clone = clone; <del> // don't keep it around on the stack. <add> // Don't keep it around on the stack. <ide> stack.pop(); <ide> } else { <del> // if the level is greater than the current depth, <del> // then it's a child, so we should just leave the stack <del> // as it is. <add> // If the level is greater than the current depth, <add> // then it's a child, so we should just leave the stack as it is. <ide> // However, if it's a sibling or higher, then it implies <ide> // the closure of the other sections that came before. <ide> // root is always considered the level=0 section, <ide> function doJSON(input, filename, cb) { <ide> stack.push(current); <ide> state = 'AFTERHEADING'; <ide> return; <del> } // heading <add> } <ide> <del> // Immediately after a heading, we can expect the following <add> // Immediately after a heading, we can expect the following: <ide> // <del> // { type: 'blockquote_start' } <add> // { type: 'blockquote_start' }, <ide> // { type: 'paragraph', text: 'Stability: ...' }, <del> // { type: 'blockquote_end' } <add> // { type: 'blockquote_end' }, <ide> // <del> // a list: starting with list_start, ending with list_end, <add> // A list: starting with list_start, ending with list_end, <ide> // maybe containing other nested lists in each item. <ide> // <del> // If one of these isn't found, then anything that comes between <del> // here and the next heading should be parsed as the desc. <add> // If one of these isn't found, then anything that comes <add> // between here and the next heading should be parsed as the desc. <ide> var stability; <ide> if (state === 'AFTERHEADING') { <ide> if (type === 'blockquote_start') { <ide> function doJSON(input, filename, cb) { <ide> <ide> }); <ide> <del> // finish any sections left open <add> // Finish any sections left open. <ide> while (root !== (current = stack.pop())) { <ide> finishSection(current, stack[stack.length - 1]); <ide> } <ide> function doJSON(input, filename, cb) { <ide> } <ide> <ide> <del>// go from something like this: <add>// Go from something like this: <add>// <ide> // [ { type: 'list_item_start' }, <ide> // { type: 'text', <ide> // text: '`settings` Object, Optional' }, <ide> // { type: 'list_start', ordered: false }, <ide> // { type: 'list_item_start' }, <ide> // { type: 'text', <del>// text: 'exec: String, file path to worker file. Default: `__filename`' }, <add>// text: 'exec: String, file path to worker file. Default: `__filename`' }, <ide> // { type: 'list_item_end' }, <ide> // { type: 'list_item_start' }, <ide> // { type: 'text', <ide> function doJSON(input, filename, cb) { <ide> // { type: 'list_end' }, <ide> // { type: 'list_item_end' }, <ide> // { type: 'list_end' } ] <add>// <ide> // to something like: <add>// <ide> // [ { name: 'settings', <ide> // type: 'object', <ide> // optional: true, <ide> function processList(section) { <ide> var current; <ide> const stack = []; <ide> <del> // for now, *just* build the heirarchical list <add> // For now, *just* build the hierarchical list. <ide> list.forEach(function(tok) { <ide> const type = tok.type; <ide> if (type === 'space') return; <ide> function processList(section) { <ide> } <ide> }); <ide> <del> // shove the name in there for properties, since they are always <del> // just going to be the value etc. <add> // Shove the name in there for properties, <add> // since they are always just going to be the value etc. <ide> if (section.type === 'property' && values[0]) { <ide> values[0].textRaw = `\`${section.name}\` ${values[0].textRaw}`; <ide> } <ide> <del> // now pull the actual values out of the text bits. <add> // Now pull the actual values out of the text bits. <ide> values.forEach(parseListItem); <ide> <ide> // Now figure out what this list actually means. <del> // depending on the section type, the list could be different things. <add> // Depending on the section type, the list could be different things. <ide> <ide> switch (section.type) { <ide> case 'ctor': <ide> case 'classMethod': <ide> case 'method': <del> // each item is an argument, unless the name is 'return', <add> // Each item is an argument, unless the name is 'return', <ide> // in which case it's the return value. <ide> section.signatures = section.signatures || []; <ide> var sig = {}; <ide> function processList(section) { <ide> break; <ide> <ide> case 'property': <del> // there should be only one item, which is the value. <del> // copy the data up to the section. <add> // There should be only one item, which is the value. <add> // Copy the data up to the section. <ide> var value = values[0] || {}; <ide> delete value.name; <ide> section.typeof = value.type || section.typeof; <ide> function processList(section) { <ide> break; <ide> <ide> case 'event': <del> // event: each item is an argument. <add> // Event: each item is an argument. <ide> section.params = values; <ide> break; <ide> <ide> function parseSignature(text, sig) { <ide> var optional = false; <ide> var def; <ide> <del> // for grouped optional params such as someMethod(a[, b[, c]]) <add> // For grouped optional params such as someMethod(a[, b[, c]]). <ide> var pos; <ide> for (pos = 0; pos < p.length; pos++) { <ide> if (optionalCharDict[p[pos]] === undefined) { break; } <ide> function parseSignature(text, sig) { <ide> if (!param) { <ide> param = sig.params[i] = { name: p }; <ide> } <del> // at this point, the name should match. <add> // At this point, the name should match. <ide> if (p !== param.name) { <ide> console.error('Warning: invalid param "%s"', p); <ide> console.error(` > ${JSON.stringify(param)}`); <ide> function parseListItem(item) { <ide> if (item.options) item.options.forEach(parseListItem); <ide> if (!item.textRaw) return; <ide> <del> // the goal here is to find the name, type, default, and optional. <del> // anything left over is 'desc' <add> // The goal here is to find the name, type, default, and optional. <add> // Anything left over is 'desc'. <ide> var text = item.textRaw.trim(); <ide> // text = text.replace(/^(Argument|Param)s?\s*:?\s*/i, ''); <ide> <ide> function finishSection(section, parent) { <ide> if (!section.list) section.list = []; <ide> processList(section); <ide> <del> // classes sometimes have various 'ctor' children <del> // which are actually just descriptions of a constructor <del> // class signature. <add> // Classes sometimes have various 'ctor' children <add> // which are actually just descriptions of a constructor class signature. <ide> // Merge them into the parent. <ide> if (section.type === 'class' && section.ctors) { <ide> section.signatures = section.signatures || []; <ide> function finishSection(section, parent) { <ide> delete section.ctors; <ide> } <ide> <del> // properties are a bit special. <del> // their "type" is the type of object, not "property" <add> // Properties are a bit special. <add> // Their "type" is the type of object, not "property". <ide> if (section.properties) { <ide> section.properties.forEach(function(p) { <ide> if (p.typeof) p.type = p.typeof; <ide> function finishSection(section, parent) { <ide> }); <ide> } <ide> <del> // handle clones <add> // Handle clones. <ide> if (section.clone) { <ide> var clone = section.clone; <ide> delete section.clone; <ide> function finishSection(section, parent) { <ide> plur = `${section.type}s`; <ide> } <ide> <del> // if the parent's type is 'misc', then it's just a random <add> // If the parent's type is 'misc', then it's just a random <ide> // collection of stuff, like the "globals" section. <ide> // Make the children top-level items. <ide> if (section.type === 'misc') { <ide> function deepCopy_(src) { <ide> } <ide> <ide> <del>// these parse out the contents of an H# tag <add>// These parse out the contents of an H# tag. <ide> const eventExpr = /^Event(?::|\s)+['"]?([^"']+).*$/i; <ide> const classExpr = /^Class:\s*([^ ]+).*$/i; <ide> const propExpr = /^[^.]+\.([^ .()]+)\s*$/; <ide> var paramExpr = /\((.*)\);?$/; <ide> <ide> function newSection(tok) { <ide> const section = {}; <del> // infer the type from the text. <add> // Infer the type from the text. <ide> const text = section.textRaw = tok.text; <ide> if (text.match(eventExpr)) { <ide> section.type = 'event'; <ide><path>tools/doc/type-parser.js <ide> const jsDocPrefix = 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/'; <ide> const jsPrimitiveUrl = `${jsDocPrefix}Data_structures`; <ide> const jsPrimitives = { <ide> 'boolean': 'Boolean', <del> 'integer': 'Number', // not a primitive, used for clarification <add> 'integer': 'Number', // Not a primitive, used for clarification. <ide> 'null': 'Null', <ide> 'number': 'Number', <ide> 'string': 'String', <ide> function toLink(typeInput) { <ide> let typeUrl = null; <ide> <ide> // To support type[], type[][] etc., we store the full string <del> // and use the bracket-less version to lookup the type URL <add> // and use the bracket-less version to lookup the type URL. <ide> const typeTextFull = typeText; <ide> typeText = typeText.replace(arrayPart, ''); <ide>
6
Javascript
Javascript
add stl exporter in binary format to menu bar
b63ec3e8caf7e6ccefb1b4a9c38f61a02b4f2945
<ide><path>editor/js/Menubar.File.js <ide> Menubar.File = function ( editor ) { <ide> } ); <ide> options.add( option ); <ide> <del> // Export STL <add> // Export STL (ASCII) <ide> <ide> var option = new UI.Row(); <ide> option.setClass( 'option' ); <ide> Menubar.File = function ( editor ) { <ide> } ); <ide> options.add( option ); <ide> <add> // Export STL (Binary) <add> <add> var option = new UI.Row(); <add> option.setClass( 'option' ); <add> option.setTextContent( 'Export STL (Binary)' ); <add> option.onClick( function () { <add> <add> var exporter = new THREE.STLExporter(); <add> <add> saveString( exporter.parse( editor.scene, { binary: true } ), 'model-binary.stl' ); <add> <add> } ); <add> options.add( option ); <add> <ide> // <ide> <ide> options.add( new UI.HorizontalRule() );
1
Ruby
Ruby
fix to_datetime test broken by dst change. closes
93db1989fe1146ea79e3b0b2252542408ff86443
<ide><path>activesupport/test/core_ext/time_ext_test.rb <ide> def test_xmlschema_is_available <ide> def test_to_datetime <ide> assert_equal Time.utc(2005, 2, 21, 17, 44, 30).to_datetime, DateTime.civil(2005, 2, 21, 17, 44, 30, 0, 0) <ide> with_timezone 'US/Eastern' do <del> assert_equal Time.local(2005, 2, 21, 17, 44, 30).to_datetime, DateTime.civil(2005, 2, 21, 17, 44, 30, DateTime.now.offset, 0) <add> assert_equal Time.local(2005, 2, 21, 17, 44, 30).to_datetime, DateTime.civil(2005, 2, 21, 17, 44, 30, Rational(Time.local(2005, 2, 21, 17, 44, 30).utc_offset, 86400), 0) <ide> end <ide> with_timezone 'NZ' do <del> assert_equal Time.local(2005, 2, 21, 17, 44, 30).to_datetime, DateTime.civil(2005, 2, 21, 17, 44, 30, DateTime.now.offset, 0) <add> assert_equal Time.local(2005, 2, 21, 17, 44, 30).to_datetime, DateTime.civil(2005, 2, 21, 17, 44, 30, Rational(Time.local(2005, 2, 21, 17, 44, 30).utc_offset, 86400), 0) <ide> end <ide> end <ide>
1
PHP
PHP
apply fixes from styleci
46df31abe2e24a94a59062e334f5615c9a080962
<ide><path>tests/Integration/Database/EloquentHasManyThroughTest.php <ide> public function basic_create_and_retrieve() <ide> <ide> $notMember = User::create(['name' => str_random()]); <ide> <del> <ide> $this->assertEquals([$member1->id, $member2->id], $user->members->pluck('id')->toArray()); <ide> } <ide> } <ide> <del> <ide> class User extends Model <ide> { <ide> public $table = 'users';
1
Javascript
Javascript
remove task priority
3addf205bf6ad1333861d662ec955fcb11db9d24
<ide><path>packages/react-reconciler/src/ReactFiberExpirationTime.js <ide> export type ExpirationTime = number; <ide> <ide> const NoWork = 0; <ide> const Sync = 1; <del>const Task = 2; <ide> const Never = 2147483647; // Max int32: Math.pow(2, 31) - 1 <ide> <ide> const UNIT_SIZE = 10; <del>const MAGIC_NUMBER_OFFSET = 3; <add>const MAGIC_NUMBER_OFFSET = 2; <ide> <ide> exports.Sync = Sync; <del>exports.Task = Task; <ide> exports.NoWork = NoWork; <ide> exports.Never = Never; <ide> <ide><path>packages/react-reconciler/src/ReactFiberScheduler.js <ide> var {createWorkInProgress} = require('./ReactFiber'); <ide> var {onCommitRoot} = require('./ReactFiberDevToolsHook'); <ide> var { <ide> NoWork, <del> Task, <ide> Sync, <ide> Never, <ide> msToExpirationTime, <ide> module.exports = function<T, P, I, TI, PI, C, CC, CX, PL>( <ide> expirationTime = computeAsyncExpiration(); <ide> } <ide> } <del> <del> if ( <del> expirationTime === Sync && <del> isBatchingUpdates && <del> (!isUnbatchingUpdates || isCommitting) <del> ) { <del> // If we're in a batch, downgrade sync to task. <del> expirationTime = Task; <del> } <ide> return expirationTime; <ide> } <ide> <ide> module.exports = function<T, P, I, TI, PI, C, CC, CX, PL>( <ide> } <ide> <ide> function scheduleErrorRecovery(fiber: Fiber) { <del> scheduleWorkImpl(fiber, Task, true); <add> scheduleWorkImpl(fiber, Sync, true); <ide> } <ide> <ide> function recalculateCurrentTime(): ExpirationTime { <ide> module.exports = function<T, P, I, TI, PI, C, CC, CX, PL>( <ide> ); <ide> } <ide> <add> // Add the root to the schedule. <ide> // Check if this root is already part of the schedule. <del> if (root.remainingExpirationTime === NoWork) { <add> if (root.nextScheduledRoot === null) { <ide> // This root is not already scheduled. Add it. <ide> root.remainingExpirationTime = expirationTime; <ide> if (lastScheduledRoot === null) { <ide> firstScheduledRoot = lastScheduledRoot = root; <add> root.nextScheduledRoot = root; <ide> } else { <ide> lastScheduledRoot.nextScheduledRoot = root; <ide> lastScheduledRoot = root; <add> lastScheduledRoot.nextScheduledRoot = firstScheduledRoot; <ide> } <ide> } else { <ide> // This root is already scheduled, but its priority may have increased. <ide> module.exports = function<T, P, I, TI, PI, C, CC, CX, PL>( <ide> } <ide> } <ide> <del> // If we're not already rendering, schedule work to flush now (if it's <del> // sync) or later (if it's async). <del> if (!isRendering) { <del> // TODO: Remove distinction between sync and task. Maybe we can remove <del> // these magic numbers entirely by always comparing to the current time? <del> if (expirationTime === Sync) { <del> if (isUnbatchingUpdates) { <del> performWork(Sync, null); <del> } else { <del> performWork(Task, null); <del> } <del> } else if (!isCallbackScheduled) { <del> isCallbackScheduled = true; <del> scheduleDeferredCallback(flushAsyncWork); <add> if (isRendering) { <add> // Prevent reentrancy. Remaining work will be scheduled at the end of <add> // the currently rendering batch. <add> return; <add> } <add> <add> if (isBatchingUpdates) { <add> // Flush work at the end of the batch. <add> if (isUnbatchingUpdates) { <add> // ...unless we're inside unbatchedUpdates, in which case we should <add> // flush it now. <add> performWorkOnRoot(root, Sync); <ide> } <add> return; <add> } <add> <add> // TODO: Get rid of Sync and use current time? <add> if (expirationTime === Sync) { <add> performWork(Sync, null); <add> } else if (!isCallbackScheduled) { <add> isCallbackScheduled = true; <add> scheduleDeferredCallback(performAsyncWork); <ide> } <ide> } <ide> <ide> function findHighestPriorityRoot() { <ide> let highestPriorityWork = NoWork; <ide> let highestPriorityRoot = null; <ide> <del> let previousScheduledRoot = null; <del> let root = firstScheduledRoot; <del> while (root !== null) { <del> const remainingExpirationTime = root.remainingExpirationTime; <del> if (remainingExpirationTime === NoWork) { <del> // If this root no longer has work, remove it from the scheduler. <del> let next = root.nextScheduledRoot; <del> root.nextScheduledRoot = null; <del> if (previousScheduledRoot === null) { <del> firstScheduledRoot = next; <add> if (lastScheduledRoot !== null) { <add> let previousScheduledRoot = lastScheduledRoot; <add> let root = firstScheduledRoot; <add> while (root !== null) { <add> const remainingExpirationTime = root.remainingExpirationTime; <add> if (remainingExpirationTime === NoWork) { <add> // This root no longer has work. Remove it from the scheduler. <add> <add> // TODO: This check is redudant, but Flow is confused by the branch <add> // below where we set lastScheduledRoot to null, even though we break <add> // from the loop right after. <add> invariant( <add> previousScheduledRoot !== null && lastScheduledRoot !== null, <add> 'Should have a previous and last root. This error is likely ' + <add> 'caused by a bug in React. Please file an issue.', <add> ); <add> if (root === root.nextScheduledRoot) { <add> // This is the only root in the list. <add> root.nextScheduledRoot = null; <add> firstScheduledRoot = lastScheduledRoot = null; <add> break; <add> } else if (root === firstScheduledRoot) { <add> // This is the first root in the list. <add> const next = root.nextScheduledRoot; <add> firstScheduledRoot = next; <add> lastScheduledRoot.nextScheduledRoot = next; <add> root.nextScheduledRoot = null; <add> } else if (root === lastScheduledRoot) { <add> // This is the last root in the list. <add> lastScheduledRoot = previousScheduledRoot; <add> lastScheduledRoot.nextScheduledRoot = firstScheduledRoot; <add> root.nextScheduledRoot = null; <add> break; <add> } else { <add> previousScheduledRoot.nextScheduledRoot = root.nextScheduledRoot; <add> root.nextScheduledRoot = null; <add> } <add> root = previousScheduledRoot.nextScheduledRoot; <ide> } else { <del> previousScheduledRoot.nextScheduledRoot = next; <del> } <del> if (next === null) { <del> lastScheduledRoot = null; <add> if ( <add> highestPriorityWork === NoWork || <add> remainingExpirationTime < highestPriorityWork <add> ) { <add> // Update the priority, if it's higher <add> highestPriorityWork = remainingExpirationTime; <add> highestPriorityRoot = root; <add> } <add> if (root === lastScheduledRoot) { <add> break; <add> } <add> previousScheduledRoot = root; <add> root = root.nextScheduledRoot; <ide> } <del> root = next; <del> continue; <del> } else if ( <del> highestPriorityWork === NoWork || <del> remainingExpirationTime < highestPriorityWork <del> ) { <del> // Update the priority, if it's higher <del> highestPriorityWork = remainingExpirationTime; <del> highestPriorityRoot = root; <ide> } <del> previousScheduledRoot = root; <del> root = root.nextScheduledRoot; <ide> } <ide> <ide> // If the next root is the same as the previous root, this is a nested <ide> module.exports = function<T, P, I, TI, PI, C, CC, CX, PL>( <ide> nextFlushedExpirationTime = highestPriorityWork; <ide> } <ide> <del> function flushAsyncWork(dl) { <add> function performAsyncWork(dl) { <ide> performWork(NoWork, dl); <ide> } <ide> <ide> function performWork(minExpirationTime: ExpirationTime, dl: Deadline | null) { <del> invariant( <del> !isRendering, <del> 'performWork was called recursively. This error is likely caused ' + <del> 'by a bug in React. Please file an issue.', <del> ); <del> <del> isRendering = true; <ide> deadline = dl; <ide> <ide> // Keep working on roots until there's no more work, or until the we reach <ide> module.exports = function<T, P, I, TI, PI, C, CC, CX, PL>( <ide> nextFlushedExpirationTime <= minExpirationTime) && <ide> !deadlineDidExpire <ide> ) { <del> // Check if this is async work or sync/expired work. <del> // TODO: Pass current time as argument to renderRoot, commitRoot <del> if (nextFlushedExpirationTime <= recalculateCurrentTime()) { <del> // Flush sync work. <del> let finishedWork = nextFlushedRoot.finishedWork; <del> if (finishedWork !== null) { <del> // This root is already complete. We can commit it. <del> nextFlushedRoot.finishedWork = null; <del> nextFlushedRoot.remainingExpirationTime = commitRoot(finishedWork); <del> } else { <del> nextFlushedRoot.finishedWork = null; <del> finishedWork = renderRoot(nextFlushedRoot, nextFlushedExpirationTime); <del> if (finishedWork !== null) { <del> // We've completed the root. Commit it. <del> nextFlushedRoot.remainingExpirationTime = commitRoot(finishedWork); <del> } <del> } <del> } else { <del> // Flush async work. <del> let finishedWork = nextFlushedRoot.finishedWork; <del> if (finishedWork !== null) { <del> // This root is already complete. We can commit it. <del> nextFlushedRoot.finishedWork = null; <del> nextFlushedRoot.remainingExpirationTime = commitRoot(finishedWork); <del> } else { <del> nextFlushedRoot.finishedWork = null; <del> finishedWork = renderRoot(nextFlushedRoot, nextFlushedExpirationTime); <del> if (finishedWork !== null) { <del> // We've completed the root. Check the deadline one more time <del> // before committing. <del> if (!shouldYield()) { <del> // Still time left. Commit the root. <del> nextFlushedRoot.remainingExpirationTime = commitRoot( <del> finishedWork, <del> ); <del> } else { <del> // There's no time left. Mark this root as complete. We'll come <del> // back and commit it later. <del> nextFlushedRoot.finishedWork = finishedWork; <del> } <del> } <del> } <del> } <add> performWorkOnRoot(nextFlushedRoot, nextFlushedExpirationTime); <ide> // Find the next highest priority work. <ide> findHighestPriorityRoot(); <ide> } <ide> module.exports = function<T, P, I, TI, PI, C, CC, CX, PL>( <ide> // If there's work left over, schedule a new callback. <ide> if (nextFlushedRoot !== null && !isCallbackScheduled) { <ide> isCallbackScheduled = true; <del> scheduleDeferredCallback(flushAsyncWork); <add> scheduleDeferredCallback(performAsyncWork); <ide> } <ide> <ide> // Clean-up. <ide> deadline = null; <ide> deadlineDidExpire = false; <del> isRendering = false; <ide> nestedUpdateCount = 0; <ide> <ide> if (hasUnhandledError) { <ide> module.exports = function<T, P, I, TI, PI, C, CC, CX, PL>( <ide> } <ide> } <ide> <add> function performWorkOnRoot(root, expirationTime) { <add> invariant( <add> !isRendering, <add> 'performWorkOnRoot was called recursively. This error is likely caused ' + <add> 'by a bug in React. Please file an issue.', <add> ); <add> <add> isRendering = true; <add> <add> // Check if this is async work or sync/expired work. <add> // TODO: Pass current time as argument to renderRoot, commitRoot <add> if (expirationTime <= recalculateCurrentTime()) { <add> // Flush sync work. <add> let finishedWork = root.finishedWork; <add> if (finishedWork !== null) { <add> // This root is already complete. We can commit it. <add> root.finishedWork = null; <add> root.remainingExpirationTime = commitRoot(finishedWork); <add> } else { <add> root.finishedWork = null; <add> finishedWork = renderRoot(root, expirationTime); <add> if (finishedWork !== null) { <add> // We've completed the root. Commit it. <add> root.remainingExpirationTime = commitRoot(finishedWork); <add> } <add> } <add> } else { <add> // Flush async work. <add> let finishedWork = root.finishedWork; <add> if (finishedWork !== null) { <add> // This root is already complete. We can commit it. <add> root.finishedWork = null; <add> root.remainingExpirationTime = commitRoot(finishedWork); <add> } else { <add> root.finishedWork = null; <add> finishedWork = renderRoot(root, expirationTime); <add> if (finishedWork !== null) { <add> // We've completed the root. Check the deadline one more time <add> // before committing. <add> if (!shouldYield()) { <add> // Still time left. Commit the root. <add> root.remainingExpirationTime = commitRoot(finishedWork); <add> } else { <add> // There's no time left. Mark this root as complete. We'll come <add> // back and commit it later. <add> root.finishedWork = finishedWork; <add> } <add> } <add> } <add> } <add> <add> isRendering = false; <add> } <add> <ide> // When working on async work, the reconciler asks the renderer if it should <ide> // yield execution. For DOM, we implement this with requestIdleCallback. <ide> function shouldYield() { <ide> module.exports = function<T, P, I, TI, PI, C, CC, CX, PL>( <ide> } finally { <ide> isBatchingUpdates = previousIsBatchingUpdates; <ide> if (!isBatchingUpdates && !isRendering) { <del> performWork(Task, null); <add> performWork(Sync, null); <ide> } <ide> } <ide> } <ide> module.exports = function<T, P, I, TI, PI, C, CC, CX, PL>( <ide> 'flushSync was called from inside a lifecycle method. It cannot be ' + <ide> 'called when React is already rendering.', <ide> ); <del> performWork(Task, null); <add> performWork(Sync, null); <ide> } <ide> } <ide>
2
Python
Python
use symbols in tag map
afda532595651fce803bde9689edff64b0ebb6cf
<ide><path>spacy/nl/language_data.py <ide> # TODO insert TAG_MAP for Dutch <ide> <ide> TAG_MAP = { <del> "ADV": {POS: "ADV"}, <del> "NOUN": {POS: "NOUN"}, <del> "ADP": {POS: "ADP"}, <del> "PRON": {POS: "PRON"}, <del> "SCONJ": {POS: "SCONJ"}, <del> "PROPN": {POS: "PROPN"}, <del> "DET": {POS: "DET"}, <del> "SYM": {POS: "SYM"}, <del> "INTJ": {POS: "INTJ"}, <del> "PUNCT": {POS: "PUNCT"}, <del> "NUM": {POS: "NUM"}, <del> "AUX": {POS: "AUX"}, <del> "X": {POS: "X"}, <del> "CONJ": {POS: "CONJ"}, <del> "ADJ": {POS: "ADJ"}, <del> "VERB": {POS: "VERB"} <add> "ADV": {POS: ADV}, <add> "NOUN": {POS: NOUN}, <add> "ADP": {POS: ADP}, <add> "PRON": {POS: PRON}, <add> "SCONJ": {POS: SCONJ}, <add> "PROPN": {POS: PROPN}, <add> "DET": {POS: DET}, <add> "SYM": {POS: SYM}, <add> "INTJ": {POS: INTJ}, <add> "PUNCT": {POS: PUNCT}, <add> "NUM": {POS: NUM}, <add> "AUX": {POS: AUX}, <add> "X": {POS: X}, <add> "CONJ": {POS: CONJ}, <add> "ADJ": {POS: ADJ}, <add> "VERB": {POS: VERB} <ide> } <ide> <ide>
1
Javascript
Javascript
add ember.string.classify() to string extensions
972d310aebd73a85bad819121617d5adb506fa50
<ide><path>packages/ember-runtime/lib/ext/string.js <ide> var fmt = Ember.String.fmt, <ide> camelize = Ember.String.camelize, <ide> decamelize = Ember.String.decamelize, <ide> dasherize = Ember.String.dasherize, <del> underscore = Ember.String.underscore; <add> underscore = Ember.String.underscore, <add> classify = Ember.String.classify; <ide> <ide> if (Ember.EXTEND_PROTOTYPES === true || Ember.EXTEND_PROTOTYPES.String) { <ide> <ide> if (Ember.EXTEND_PROTOTYPES === true || Ember.EXTEND_PROTOTYPES.String) { <ide> return underscore(this); <ide> }; <ide> <add> /** <add> See {{#crossLink "Ember.String/classify"}}{{/crossLink}} <add> <add> @method classify <add> @for String <add> */ <add> String.prototype.classify = function() { <add> return classify(this); <add> }; <ide> } <ide> <ide><path>packages/ember-runtime/tests/system/string/classify.js <add>module('Ember.String.classify'); <add> <add>test("classify normal string", function() { <add> deepEqual(Ember.String.classify('my favorite items'), 'MyFavoriteItems'); <add> if (Ember.EXTEND_PROTOTYPES) { <add> deepEqual('my favorite items'.classify(), 'MyFavoriteItems'); <add> } <add>}); <add> <add>test("classify dasherized string", function() { <add> deepEqual(Ember.String.classify('css-class-name'), 'CssClassName'); <add> if (Ember.EXTEND_PROTOTYPES) { <add> deepEqual('css-class-name'.classify(), 'CssClassName'); <add> } <add>}); <add> <add>test("classify underscored string", function() { <add> deepEqual(Ember.String.classify('action_name'), 'ActionName'); <add> if (Ember.EXTEND_PROTOTYPES) { <add> deepEqual('action_name'.classify(), 'ActionName'); <add> } <add>}); <add> <add>test("does nothing with classified string", function() { <add> deepEqual(Ember.String.classify('InnerHTML'), 'InnerHTML'); <add> if (Ember.EXTEND_PROTOTYPES) { <add> deepEqual('InnerHTML'.classify(), 'InnerHTML'); <add> } <add>});
2
Text
Text
fix a typo in readme
f0f68afb613fcce97e81fbb3731ab0f65b9b9864
<ide><path>README.md <ide> The response for a request contains the following information. <ide> <ide> // `request` is the request that generated this response <ide> // It is the last ClientRequest instance in node.js (in redirects) <del> // and an XMLHttpRequest instance the browser <add> // and an XMLHttpRequest instance in the browser <ide> request: {} <ide> } <ide> ```
1
Python
Python
add missing manager fixture
f2556c45b22cae9d3c961639627a1f9053681393
<ide><path>t/integration/test_canvas.py <ide> def test_chord_in_chain_with_args(self, manager): <ide> assert res1.get(timeout=TIMEOUT) == [1, 1] <ide> <ide> @pytest.mark.xfail(reason="Issue #6200") <del> def test_chain_in_chain_with_args(self): <add> def test_chain_in_chain_with_args(self, manager): <ide> try: <ide> manager.app.backend.ensure_chords_allowed() <ide> except NotImplementedError as e:
1
PHP
PHP
tag a new version
893d125acae49f859f8f37d54c429ef875cbf815
<ide><path>src/Illuminate/Foundation/Application.php <ide> class Application extends Container implements HttpKernelInterface, TerminableIn <ide> * <ide> * @var string <ide> */ <del> const VERSION = '4.2.13'; <add> const VERSION = '4.2.14'; <ide> <ide> /** <ide> * Indicates if the application has "booted".
1
Ruby
Ruby
move method definition below callbacks
4d1f3f832485920a5bd49bc3a2c13debeaab5608
<ide><path>app/models/action_text/rich_text.rb <ide> class ActionText::RichText < ActiveRecord::Base <ide> <ide> serialize :body, ActionText::Content <ide> delegate :to_s, :nil?, to: :body <del> delegate :blank?, :empty?, :present?, to: :to_plain_text <del> <del> def to_plain_text <del> body&.to_plain_text.to_s <del> end <ide> <ide> belongs_to :record, polymorphic: true, touch: true <ide> has_many_attached :embeds <ide> <ide> before_save do <ide> self.embeds = body.attachments.map(&:attachable) if body.present? <ide> end <add> <add> def to_plain_text <add> body&.to_plain_text.to_s <add> end <add> <add> delegate :blank?, :empty?, :present?, to: :to_plain_text <ide> end
1
Javascript
Javascript
add transform objectmode test
6e05faa3d0de2b8540187de261dd848c7a5ca0cf
<ide><path>test/simple/test-stream2-transform.js <ide> function run() { <ide> fn({ <ide> same: assert.deepEqual, <ide> equal: assert.equal, <add> ok: assert, <ide> end: function () { <ide> count--; <ide> run(); <ide> test('passthrough facaded', function(t) { <ide> }, 10); <ide> }, 10); <ide> }); <add> <add>test('object transform (json parse)', function(t) { <add> console.error('json parse stream'); <add> var jp = new Transform({ objectMode: true }); <add> jp._transform = function(data, output, cb) { <add> try { <add> output(JSON.parse(data)); <add> cb(); <add> } catch (er) { <add> cb(er); <add> } <add> }; <add> <add> // anything except null/undefined is fine. <add> // those are "magic" in the stream API, because they signal EOF. <add> var objects = [ <add> { foo: 'bar' }, <add> 100, <add> "string", <add> { nested: { things: [ { foo: 'bar' }, 100, "string" ] } } <add> ]; <add> <add> var ended = false; <add> jp.on('end', function() { <add> ended = true; <add> }); <add> <add> objects.forEach(function(obj) { <add> jp.write(JSON.stringify(obj)); <add> var res = jp.read(); <add> t.same(res, obj); <add> }); <add> <add> jp.end(); <add> <add> process.nextTick(function() { <add> t.ok(ended); <add> t.end(); <add> }) <add>}); <add> <add>test('object transform (json stringify)', function(t) { <add> console.error('json parse stream'); <add> var js = new Transform({ objectMode: true }); <add> js._transform = function(data, output, cb) { <add> try { <add> output(JSON.stringify(data)); <add> cb(); <add> } catch (er) { <add> cb(er); <add> } <add> }; <add> <add> // anything except null/undefined is fine. <add> // those are "magic" in the stream API, because they signal EOF. <add> var objects = [ <add> { foo: 'bar' }, <add> 100, <add> "string", <add> { nested: { things: [ { foo: 'bar' }, 100, "string" ] } } <add> ]; <add> <add> var ended = false; <add> js.on('end', function() { <add> ended = true; <add> }); <add> <add> objects.forEach(function(obj) { <add> js.write(obj); <add> var res = js.read(); <add> t.equal(res, JSON.stringify(obj)); <add> }); <add> <add> js.end(); <add> <add> process.nextTick(function() { <add> t.ok(ended); <add> t.end(); <add> }) <add>});
1
Go
Go
add "type" type for event-type enum
247f4796d21d98909974410ff27b61233776ae3a
<ide><path>api/types/events/events.go <ide> package events // import "github.com/docker/docker/api/types/events" <ide> <add>// Type is used for event-types. <add>type Type = string <add> <add>// List of known event types. <ide> const ( <del> // BuilderEventType is the event type that the builder generates <del> BuilderEventType = "builder" <del> // ContainerEventType is the event type that containers generate <del> ContainerEventType = "container" <del> // DaemonEventType is the event type that daemon generate <del> DaemonEventType = "daemon" <del> // ImageEventType is the event type that images generate <del> ImageEventType = "image" <del> // NetworkEventType is the event type that networks generate <del> NetworkEventType = "network" <del> // PluginEventType is the event type that plugins generate <del> PluginEventType = "plugin" <del> // VolumeEventType is the event type that volumes generate <del> VolumeEventType = "volume" <del> // ServiceEventType is the event type that services generate <del> ServiceEventType = "service" <del> // NodeEventType is the event type that nodes generate <del> NodeEventType = "node" <del> // SecretEventType is the event type that secrets generate <del> SecretEventType = "secret" <del> // ConfigEventType is the event type that configs generate <del> ConfigEventType = "config" <add> BuilderEventType Type = "builder" // BuilderEventType is the event type that the builder generates. <add> ConfigEventType Type = "config" // ConfigEventType is the event type that configs generate. <add> ContainerEventType Type = "container" // ContainerEventType is the event type that containers generate. <add> DaemonEventType Type = "daemon" // DaemonEventType is the event type that daemon generate. <add> ImageEventType Type = "image" // ImageEventType is the event type that images generate. <add> NetworkEventType Type = "network" // NetworkEventType is the event type that networks generate. <add> NodeEventType Type = "node" // NodeEventType is the event type that nodes generate. <add> PluginEventType Type = "plugin" // PluginEventType is the event type that plugins generate. <add> SecretEventType Type = "secret" // SecretEventType is the event type that secrets generate. <add> ServiceEventType Type = "service" // ServiceEventType is the event type that services generate. <add> VolumeEventType Type = "volume" // VolumeEventType is the event type that volumes generate. <ide> ) <ide> <ide> // Actor describes something that generates events, <ide> // like a container, or a network, or a volume. <del>// It has a defined name and a set or attributes. <add>// It has a defined name and a set of attributes. <ide> // The container attributes are its labels, other actors <ide> // can generate these attributes from other properties. <ide> type Actor struct { <ide> type Actor struct { <ide> type Message struct { <ide> // Deprecated information from JSONMessage. <ide> // With data only in container events. <del> Status string `json:"status,omitempty"` <del> ID string `json:"id,omitempty"` <del> From string `json:"from,omitempty"` <add> Status string `json:"status,omitempty"` // Deprecated: use Action instead. <add> ID string `json:"id,omitempty"` // Deprecated: use Actor.ID instead. <add> From string `json:"from,omitempty"` // Deprecated: use Actor.Attributes["image"] instead. <ide> <del> Type string <add> Type Type <ide> Action string <ide> Actor Actor <ide> // Engine events are local scope. Cluster events are swarm scope. <ide><path>client/events_test.go <ide> func TestEvents(t *testing.T) { <ide> }, <ide> events: []events.Message{ <ide> { <del> Type: "container", <add> Type: events.BuilderEventType, <ide> ID: "1", <ide> Action: "create", <ide> }, <ide> { <del> Type: "container", <add> Type: events.BuilderEventType, <ide> ID: "2", <ide> Action: "die", <ide> }, <ide> { <del> Type: "container", <add> Type: events.BuilderEventType, <ide> ID: "3", <ide> Action: "create", <ide> }, <ide><path>daemon/events/events.go <ide> func (e *Events) Evict(l chan interface{}) { <ide> } <ide> <ide> // Log creates a local scope message and publishes it <del>func (e *Events) Log(action, eventType string, actor eventtypes.Actor) { <add>func (e *Events) Log(action string, eventType eventtypes.Type, actor eventtypes.Actor) { <ide> now := time.Now().UTC() <ide> jm := eventtypes.Message{ <ide> Action: action, <ide><path>daemon/events/filter.go <ide> func (ef *Filter) matchConfig(ev events.Message) bool { <ide> return ef.fuzzyMatchName(ev, events.ConfigEventType) <ide> } <ide> <del>func (ef *Filter) fuzzyMatchName(ev events.Message, eventType string) bool { <add>func (ef *Filter) fuzzyMatchName(ev events.Message, eventType events.Type) bool { <ide> return ef.filter.FuzzyMatch(eventType, ev.Actor.ID) || <ide> ef.filter.FuzzyMatch(eventType, ev.Actor.Attributes["name"]) <ide> }
4
PHP
PHP
use local config options if possible
39985508183c017d5e3ed234996b0239b743e572
<ide><path>src/Illuminate/Mail/MailManager.php <ide> protected function createSendmailTransport(array $config) <ide> /** <ide> * Create an instance of the Amazon SES Swift Transport driver. <ide> * <add> * @param array $config <ide> * @return \Illuminate\Mail\Transport\SesTransport <ide> */ <del> protected function createSesTransport() <add> protected function createSesTransport(array $config) <ide> { <del> $config = array_merge($this->app['config']->get('services.ses', []), [ <add> $config = array_merge($this->app['config']->get($config['service'] ?? 'services.ses', []), [ <ide> 'version' => 'latest', 'service' => 'email', <ide> ]); <ide> <ide> protected function createMailTransport() <ide> /** <ide> * Create an instance of the Mailgun Swift Transport driver. <ide> * <add> * @param array $config <ide> * @return \Illuminate\Mail\Transport\MailgunTransport <ide> */ <del> protected function createMailgunTransport() <add> protected function createMailgunTransport(array $config) <ide> { <del> $config = $this->app['config']->get('services.mailgun', []); <add> $config = $this->app['config']->get($config['service'] ?? 'services.mailgun', []); <ide> <ide> return new MailgunTransport( <ide> $this->guzzle($config), <ide> protected function createMailgunTransport() <ide> /** <ide> * Create an instance of the Postmark Swift Transport driver. <ide> * <add> * @param array $config <ide> * @return \Swift_Transport <ide> */ <del> protected function createPostmarkTransport() <add> protected function createPostmarkTransport(array $config) <ide> { <ide> return tap(new PostmarkTransport( <del> $this->app['config']->get('services.postmark.token') <add> $config['token'] ?? $this->app['config']->get('services.postmark.token') <ide> ), function ($transport) { <ide> $transport->registerPlugin(new ThrowExceptionOnFailurePlugin()); <ide> });
1
Python
Python
add test for unicodeyamlrenderer
617c9825913cfc0cdeaa4405df0b885db0a9ff60
<ide><path>rest_framework/tests/test_renderers.py <ide> from rest_framework.response import Response <ide> from rest_framework.views import APIView <ide> from rest_framework.renderers import BaseRenderer, JSONRenderer, YAMLRenderer, \ <del> XMLRenderer, JSONPRenderer, BrowsableAPIRenderer, UnicodeJSONRenderer <add> XMLRenderer, JSONPRenderer, BrowsableAPIRenderer, UnicodeJSONRenderer, UnicodeYAMLRenderer <ide> from rest_framework.parsers import YAMLParser, XMLParser <ide> from rest_framework.settings import api_settings <ide> from rest_framework.test import APIRequestFactory <ide> def assertYAMLContains(self, content, string): <ide> self.assertTrue(string in content, '%r not in %r' % (string, content)) <ide> <ide> <add> class UnicodeYAMLRendererTests(TestCase): <add> """ <add> Tests specific for the Unicode YAML Renderer <add> """ <add> def test_proper_encoding(self): <add> obj = {'countries': ['United Kingdom', 'France', 'España']} <add> renderer = UnicodeYAMLRenderer() <add> content = renderer.render(obj, 'application/yaml') <add> self.assertEqual(content.strip(), 'countries: [United Kingdom, France, España]'.encode('utf-8')) <add> <add> <ide> class XMLRendererTestCase(TestCase): <ide> """ <ide> Tests specific to the XML Renderer
1
Javascript
Javascript
improve readability on conditional assignment
64b177377c2aa8ae97c6f8752b69424d70a4fb4e
<ide><path>src/ng/http.js <ide> function parseHeaders(headers) { <ide> val = trim(line.substr(i + 1)); <ide> <ide> if (key) { <del> if (parsed[key]) { <del> parsed[key] += ', ' + val; <del> } else { <del> parsed[key] = val; <del> } <add> parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; <ide> } <ide> }); <ide>
1
Python
Python
fix review findings
07adca5db92b0dedc90ef04a414cc9b49d7b8aaa
<ide><path>libcloud/container/drivers/lxd.py <ide> def list_images(self): <ide> images.append(self.get_image(fingerprint=fingerprint)) <ide> return images <ide> <del> def exc_list_storage_pools(self, detailed=True): <add> def ex_list_storage_pools(self, detailed=True): <ide> """ <ide> Returns a list of storage pools defined currently defined on the host <del> e.g. [ "/1.0/storage-pools/default", ] <ide> <ide> Description: list of storage pools <ide> Authentication: trusted <ide> Operation: sync <ide> <add> ":rtype: list of StoragePool items <ide> """ <add> <ide> # Return: list of storage pools that are currently defined on the host <ide> response = self.connection.request("/%s/storage-pools" % self.version) <ide> <ide> def exc_list_storage_pools(self, detailed=True): <ide> pool_name = pool_item.split('/')[-1] <ide> <ide> if not detailed: <add> # attempt to create a minimal StoragePool <ide> pools.append(self._to_storage_pool({"name": pool_name, <ide> "driver":None, "used_by":None, <ide> "config":None, "managed": None})) <ide> else: <del> pools.append(self.get_storage_pool(id=pool_name)) <add> pools.append(self.ex_get_storage_pool(id=pool_name)) <ide> <ide> return pools <ide> <del> def exc_get_storage_pool(self, id): <add> def ex_get_storage_pool(self, id): <ide> """ <ide> Returns information about a storage pool <ide> :param id: the name of the storage pool <ide> def exc_get_storage_pool(self, id): <ide> <ide> return self._to_storage_pool(data=response_dict['metadata']) <ide> <del> def exc_create_storage_pool(self, definition): <add> def ex_create_storage_pool(self, definition): <ide> <ide> """Create a storage_pool from config. <ide> <ide> def exc_create_storage_pool(self, definition): <ide> <ide> raise NotImplementedError("This function has not been finished yet") <ide> <del> def delete_storage_pool(self, id): <add> def ex_delete_storage_pool(self, id): <ide> """Delete the storage pool. <ide> <ide> Implements DELETE /1.0/storage-pools/<self.name> <ide> def delete_storage_pool(self, id): <ide> response_dict = response.parse_body() <ide> assert_response(response_dict=response_dict, status_code=200) <ide> <del> def exc_list_storage_pool_volumes(self, storage_pool_id, detailed=True): <add> def ex_list_storage_pool_volumes(self, storage_pool_id, detailed=True): <ide> """ <ide> Description: list of storage volumes associated with the given storage pool <ide> <ide> def exc_list_storage_pool_volumes(self, storage_pool_id, detailed=True): <ide> <ide> return volumes <ide> <del> def get_storage_pool_volume(self, storage_pool_id, type, name): <add> def ex_get_storage_pool_volume(self, storage_pool_id, type, name): <ide> """ <ide> Description: information about a storage volume of a given type on a storage pool <ide> Introduced: with API extension storage <ide> def _do_get_image(self, metadata): <ide> return ContainerImage(id=id, name=name, path=None, version=version, <ide> driver=self.connection.driver, extra=extra) <ide> <del> def _to_storage_pool(self, **data): <add> def _to_storage_pool(self, data): <ide> """ <ide> Given a dictionary with the storage pool configuration <ide> it returns a StoragePool object <ide><path>libcloud/test/container/test_lxd.py <ide> def test_deploy_container(self): <ide> <ide> def test_list_storage_pools(self): <ide> for driver in self.drivers: <del> pools = driver.list_storage_pools() <add> pools = driver.ex_list_storage_pools() <ide> self.assertEqual(len(pools), 2) <ide> self.assertIsInstance(pools[0], StoragePool) <ide> self.assertIsInstance(pools[1], StoragePool) <ide> def test_list_storage_pools(self): <ide> def test_get_storage_pool_no_metadata(self): <ide> with self.assertRaises(LXDAPIException) as exc: <ide> for driver in self.drivers: <del> driver.get_storage_pool(id='pool3') <add> driver.ex_get_storage_pool(id='pool3') <ide> self.assertEqual(str(exc), 'Storage pool with name pool3 has no data') <ide> <ide> """ <ide> def test_create_storage_pool(self): <ide> <ide> def test_delete_storage_pool(self): <ide> for driver in self.drivers: <del> driver.delete_storage_pool(id='pool1') <add> driver.ex_delete_storage_pool(id='pool1') <ide> <ide> def test_delete_storage_pool_fail(self): <ide> with self.assertRaises(LXDAPIException) as exc: <ide> for driver in self.drivers: <del> driver.delete_storage_pool(id='pool2') <add> driver.ex_delete_storage_pool(id='pool2') <ide> <ide> <ide> class LXDMockHttp(MockHttp):
2
Ruby
Ruby
remove unnecessary check
36458b2356388a299d6b4a8b1d1053baf910efae
<ide><path>Library/Homebrew/patch.rb <ide> def apply <ide> end <ide> end <ide> rescue ErrorDuringExecution => e <del> raise unless (f = resource.owner&.owner) <del> <add> f = resource.owner.owner <ide> cmd, *args = e.cmd <ide> raise BuildError.new(f, cmd, args, ENV.to_hash) <ide> end
1
Mixed
Javascript
implement cancelable option for alerts
8e2906ae89660c977e66f2f8fae883d70acac9bf
<ide><path>Examples/UIExplorer/js/AlertExample.js <ide> class SimpleAlertExampleBlock extends React.Component { <ide> <Text>Alert with too many buttons</Text> <ide> </View> <ide> </TouchableHighlight> <add> <TouchableHighlight style={styles.wrapper} <add> onPress={() => Alert.alert( <add> 'Alert Title', <add> null, <add> [ <add> {text: 'OK', onPress: () => console.log('OK Pressed!')}, <add> ], <add> { <add> cancelable: false <add> } <add> )}> <add> <View style={styles.button}> <add> <Text>Alert that cannot be dismissed</Text> <add> </View> <add> </TouchableHighlight> <ide> </View> <ide> ); <ide> } <ide><path>Libraries/Utilities/Alert.js <ide> type Buttons = Array<{ <ide> style?: AlertButtonStyle; <ide> }>; <ide> <add>type Options = { <add> cancelable?: ?boolean; <add>}; <add> <ide> /** <ide> * Launches an alert dialog with the specified title and message. <ide> * <ide> class Alert { <ide> title: ?string, <ide> message?: ?string, <ide> buttons?: Buttons, <add> options?: Options, <ide> type?: AlertType, <ide> ): void { <ide> if (Platform.OS === 'ios') { <ide> class Alert { <ide> } <ide> AlertIOS.alert(title, message, buttons); <ide> } else if (Platform.OS === 'android') { <del> AlertAndroid.alert(title, message, buttons); <add> AlertAndroid.alert(title, message, buttons, options); <ide> } <ide> } <ide> } <ide> class AlertAndroid { <ide> title: ?string, <ide> message?: ?string, <ide> buttons?: Buttons, <add> options?: Options, <ide> ): void { <ide> var config = { <ide> title: title || '', <ide> message: message || '', <ide> }; <add> <add> if (options) { <add> config = {...config, cancelable: options.cancelable}; <add> } <ide> // At most three buttons (neutral, negative, positive). Ignore rest. <ide> // The text 'OK' should be probably localized. iOS Alert does that in native. <ide> var validButtons: Buttons = buttons ? buttons.slice(0, 3) : [{text: 'OK'}]; <ide><path>ReactAndroid/src/main/java/com/facebook/react/modules/dialog/DialogModule.java <ide> public class DialogModule extends ReactContextBaseJavaModule implements Lifecycl <ide> /* package */ static final String KEY_BUTTON_NEGATIVE = "buttonNegative"; <ide> /* package */ static final String KEY_BUTTON_NEUTRAL = "buttonNeutral"; <ide> /* package */ static final String KEY_ITEMS = "items"; <add> /* package */ static final String KEY_CANCELABLE = "cancelable"; <ide> <ide> /* package */ static final Map<String, Object> CONSTANTS = MapBuilder.<String, Object>of( <ide> ACTION_BUTTON_CLICKED, ACTION_BUTTON_CLICKED, <ide> public void showNewAlert(boolean isInForeground, Bundle arguments, Callback acti <ide> if (isUsingSupportLibrary()) { <ide> SupportAlertFragment alertFragment = new SupportAlertFragment(actionListener, arguments); <ide> if (isInForeground) { <add> if (arguments.containsKey(KEY_CANCELABLE)) { <add> alertFragment.setCancelable(arguments.getBoolean(KEY_CANCELABLE)); <add> } <ide> alertFragment.show(mSupportFragmentManager, FRAGMENT_TAG); <ide> } else { <ide> mFragmentToShow = alertFragment; <ide> } <ide> } else { <ide> AlertFragment alertFragment = new AlertFragment(actionListener, arguments); <ide> if (isInForeground) { <add> if (arguments.containsKey(KEY_CANCELABLE)) { <add> alertFragment.setCancelable(arguments.getBoolean(KEY_CANCELABLE)); <add> } <ide> alertFragment.show(mFragmentManager, FRAGMENT_TAG); <ide> } else { <ide> mFragmentToShow = alertFragment; <ide> public void showAlert( <ide> } <ide> args.putCharSequenceArray(AlertFragment.ARG_ITEMS, itemsArray); <ide> } <add> if (options.hasKey(KEY_CANCELABLE)) { <add> args.putBoolean(KEY_CANCELABLE, options.getBoolean(KEY_CANCELABLE)); <add> } <ide> <ide> fragmentManagerHelper.showNewAlert(mIsInForeground, args, actionCallback); <ide> } <ide><path>ReactAndroid/src/test/java/com/facebook/react/modules/dialog/DialogModuleTest.java <ide> public void testAllOptions() { <ide> options.putString("buttonPositive", "OK"); <ide> options.putString("buttonNegative", "Cancel"); <ide> options.putString("buttonNeutral", "Later"); <add> options.putBoolean("cancelable", false); <ide> <ide> mDialogModule.showAlert(options, null, null); <ide> <ide> final AlertFragment fragment = getFragment(); <ide> assertNotNull("Fragment was not displayed", fragment); <add> assertEquals(false, fragment.isCancelable()); <ide> <ide> final AlertDialog dialog = (AlertDialog) fragment.getDialog(); <ide> assertEquals("OK", dialog.getButton(DialogInterface.BUTTON_POSITIVE).getText().toString());
4
Python
Python
add an modeladmin for easy management of tokens
db863be10cca5d43e37cace88fd2a500f6ee96f8
<ide><path>rest_framework/authtoken/admin.py <add>from django.contrib import admin <add>from .models import Token <add> <add> <add>class TokenAdmin(admin.ModelAdmin): <add> list_display = ('key', 'user', 'created') <add> fields = ('user',) <add> ordering = ('-created',) <add> <add> <add>admin.site.register(Token, TokenAdmin)
1
Python
Python
compare platform.architecture() correctly
972eb4dfd31571bf4b6d3d0f4575036b360d9975
<ide><path>numpy/distutils/system_info.py <ide> def add_system_root(library_root): <ide> vcpkg = shutil.which('vcpkg') <ide> if vcpkg: <ide> vcpkg_dir = os.path.dirname(vcpkg) <del> if platform.architecture() == '32bit': <add> if platform.architecture()[0] == '32bit': <ide> specifier = 'x86' <ide> else: <ide> specifier = 'x64'
1
Text
Text
add changelog entry for
0cc4ff77cca24dddeb9af42056ca735e588ce098
<ide><path>actionview/CHANGELOG.md <add>* Fix `collection_check_boxes` generated hidden input to use the name attribute provided <add> in the options hash. <add> <add> *Angel N. Sciortino* <add> <ide> * Fix some edge cases for AV `select` helper with `:selected` option <ide> <ide> *Bogdan Gusiev*
1
Javascript
Javascript
fix typo in `adapters.js`
70305bbe4276697776e3cef9158b27d4c3534d5e
<ide><path>lib/internal/webstreams/adapters.js <ide> function newStreamReadableFromReadableStream(readableStream, options = kEmptyObj <ide> */ <ide> function newReadableWritablePairFromDuplex(duplex) { <ide> // Not using the internal/streams/utils isWritableNodeStream and <del> // isReadableNodestream utilities here because they will return false <add> // isReadableNodeStream utilities here because they will return false <ide> // if the duplex was created with writable or readable options set to <ide> // false. Instead, we'll check the readable and writable state after <ide> // and return closed WritableStream or closed ReadableStream as
1
Text
Text
use consistent references
b708a6050c640217e3431ff5de73fad91576705b
<ide><path>activesupport/CHANGELOG.md <ide> private <ide> def set_current <ide> Current.account = Account.find(params[:account_id]) <del> Current.person = Current.account.people.find(params[:person_id]) <add> Current.user = Current.account.users.find(params[:user_id]) <ide> end <ide> end <ide> <ide> end <ide> <ide> class Event < ApplicationRecord <del> belongs_to :creator, class_name: 'Person' <del> before_validation { self.creator ||= Current.person } <add> belongs_to :creator, class_name: 'User' <add> before_validation { self.creator ||= Current.user } <ide> end <ide> <ide> *DHH*
1
Python
Python
fix coertion for verbose and dry_run env variables
8ea77a5980dea0ffe0ad5928db6bcdff636aadce
<ide><path>dev/breeze/src/airflow_breeze/utils/coertions.py <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>from __future__ import annotations <add> <add> <add>def coerce_bool_value(value: str | bool) -> bool: <add> if isinstance(value, bool): <add> return value <add> elif not value: # handle "" and other false-y coerce-able values <add> return False <add> else: <add> return value[0].lower() in ["t", "y"] # handle all kinds of truth-y/yes-y/false-y/non-sy strings <ide><path>dev/breeze/src/airflow_breeze/utils/custom_param_types.py <ide> read_from_cache_file, <ide> write_to_cache_file, <ide> ) <add>from airflow_breeze.utils.coertions import coerce_bool_value <ide> from airflow_breeze.utils.console import get_console <ide> from airflow_breeze.utils.recording import generating_command_images <ide> from airflow_breeze.utils.shared_options import set_dry_run, set_forced_answer, set_verbose <ide> class VerboseOption(ParamType): <ide> """ <ide> <ide> def convert(self, value, param, ctx): <del> set_verbose(value) <add> set_verbose(coerce_bool_value(value)) <ide> return super().convert(value, param, ctx) <ide> <ide> <ide> class DryRunOption(ParamType): <ide> """ <ide> <ide> def convert(self, value, param, ctx): <del> set_dry_run(value) <add> set_dry_run(coerce_bool_value(value)) <ide> return super().convert(value, param, ctx) <ide> <ide> <ide><path>dev/breeze/src/airflow_breeze/utils/shared_options.py <ide> <ide> import os <ide> <del>__verbose_value: bool = os.environ.get("VERBOSE", "false")[0].lower() == "t" <add>from airflow_breeze.utils.coertions import coerce_bool_value <add> <add> <add>def __get_default_bool_value(env_var: str) -> bool: <add> string_val = os.environ.get(env_var, "") <add> return coerce_bool_value(string_val) <add> <add> <add>__verbose_value: bool = __get_default_bool_value("VERBOSE") <ide> <ide> <ide> def set_verbose(verbose: bool): <ide> def get_verbose(verbose_override: bool | None = None) -> bool: <ide> return verbose_override <ide> <ide> <del>__dry_run_value: bool = os.environ.get("DRY_RUN", "false")[0].lower() == "t" <add>__dry_run_value: bool = __get_default_bool_value("DRY_RUN") <ide> <ide> <ide> def set_dry_run(dry_run: bool):
3
Text
Text
fix word in text
f4ca23a6e0491df2681f3e72d05aa8f0ea8a37b3
<ide><path>guide/english/vim/search-and-replace/index.md <ide> where... <ide> - `[range]` indicates the lines to search (e.g. `1`: first line, `$`: last line, `%`: all lines). <ide> - `[pattern]` is the text pattern to be searched. <ide> - `[string]` is the string that will replace the text pattern. <del>- `[flags]` turn on additional search and replace options (e.g. `c`: confirm substitution, `g`: replace all occurences in each line, `i`: ignore case). <add>- `[flags]` turn on additional search and replace options (e.g. `c`: confirm substitution, `g`: replace all occurrences in each line, `i`: ignore case). <ide> - `[count]` replaces in `[count]` lines starting from the last line in `[range]` (or current line if `[range]` omitted). <ide> <ide> ### Common Examples
1
Ruby
Ruby
reduce array allocations
7e299ce230b3928609415a9797c6abef00561c45
<ide><path>activesupport/lib/active_support/inflector/methods.rb <ide> def const_regexp(camel_cased_word) <ide> <ide> last = parts.pop <ide> <del> parts.reverse.inject(last) do |acc, part| <add> parts.reverse!.inject(last) do |acc, part| <ide> part.empty? ? acc : "#{part}(::#{acc})?" <ide> end <ide> end
1
Go
Go
use pivot_root instead of chroot""
c38635020accaffa6868f19f308042be051132a0
<ide><path>pkg/libcontainer/nsinit/mount.go <ide> package nsinit <ide> import ( <ide> "fmt" <ide> "github.com/dotcloud/docker/pkg/system" <add> "io/ioutil" <ide> "os" <ide> "path/filepath" <ide> "syscall" <ide> func setupNewMountNamespace(rootfs, console string, readonly bool) error { <ide> if err := system.Chdir(rootfs); err != nil { <ide> return fmt.Errorf("chdir into %s %s", rootfs, err) <ide> } <del> if err := system.Mount(rootfs, "/", "", syscall.MS_MOVE, ""); err != nil { <del> return fmt.Errorf("mount move %s into / %s", rootfs, err) <add> <add> pivotDir, err := ioutil.TempDir(rootfs, ".pivot_root") <add> if err != nil { <add> return fmt.Errorf("can't create pivot_root dir %s", pivotDir, err) <ide> } <del> if err := system.Chroot("."); err != nil { <del> return fmt.Errorf("chroot . %s", err) <add> if err := system.Pivotroot(rootfs, pivotDir); err != nil { <add> return fmt.Errorf("pivot_root %s", err) <ide> } <ide> if err := system.Chdir("/"); err != nil { <ide> return fmt.Errorf("chdir / %s", err) <ide> } <ide> <add> // path to pivot dir now changed, update <add> pivotDir = filepath.Join("/", filepath.Base(pivotDir)) <add> <add> if err := system.Unmount(pivotDir, syscall.MNT_DETACH); err != nil { <add> return fmt.Errorf("unmount pivot_root dir %s", err) <add> } <add> <add> if err := os.Remove(pivotDir); err != nil { <add> return fmt.Errorf("remove pivot_root dir %s", err) <add> } <add> <ide> system.Umask(0022) <ide> <ide> return nil
1
Python
Python
set version to v2.1.0a3
87da5bcf5b11762605c60f57b3cb2019d458fcd3
<ide><path>spacy/about.py <ide> # https://github.com/pypa/warehouse/blob/master/warehouse/__about__.py <ide> <ide> __title__ = 'spacy-nightly' <del>__version__ = '2.1.0a3.dev0' <add>__version__ = '2.1.0a3' <ide> __summary__ = 'Industrial-strength Natural Language Processing (NLP) with Python and Cython' <ide> __uri__ = 'https://spacy.io' <ide> __author__ = 'Explosion AI'
1
Ruby
Ruby
remove setter for the dispatcher class
31cc4d621f57f35356b3395cf78d7cf043d6795c
<ide><path>actionpack/lib/action_dispatch/routing/route_set.rb <ide> def define_url_helper(mod, route, name, opts, route_key, url_strategy) <ide> <ide> attr_accessor :formatter, :set, :named_routes, :default_scope, :router <ide> attr_accessor :disable_clear_and_finalize, :resources_path_names <del> attr_accessor :default_url_options, :dispatcher_class <add> attr_accessor :default_url_options <ide> attr_reader :env_key <ide> <ide> alias :routes :set <ide> def clear! <ide> end <ide> <ide> def dispatcher(raise_on_name_error) <del> dispatcher_class.new(raise_on_name_error) <add> @dispatcher_class.new(raise_on_name_error) <ide> end <ide> <ide> module MountedHelpers
1
Python
Python
remove names in todo
18e5ce8d9ea5abd5eb549a923d74826ad9461016
<ide><path>compression/entropy_coder/core/code_loader.py <ide> def LoadBinaryCode(input_config, batch_size): <ide> """ <ide> data = input_config.data <ide> <del> # TODO(damienv): Possibly use multiple files (instead of just one). <add> # TODO: Possibly use multiple files (instead of just one). <ide> file_list = [data] <ide> filename_queue = tf.train.string_input_producer(file_list, <ide> capacity=4) <ide><path>compression/entropy_coder/lib/blocks_std.py <ide> def __init__(self, <ide> self._bias = BiasAdd(bias) if bias else PassThrough() <ide> self._act = act if act else PassThrough() <ide> <del> # TODO(sjhwang): Stop using **kwargs, if we ever switch to python3. <ide> def _Apply(self, *args): <ide> if not self._matrices: <ide> self._matrices = [ <ide><path>compression/entropy_coder/lib/blocks_std_test.py <ide> def testLinear(self): <ide> def testLinearShared(self): <ide> # Create a linear map which is applied twice on different inputs <ide> # (i.e. the weights of the map are shared). <del> # TODO(sjhwang): Make this test deterministic. <ide> linear_map = blocks_std.Linear(6) <ide> x1 = tf.random_normal(shape=[1, 5]) <ide> x2 = tf.random_normal(shape=[1, 5]) <ide><path>compression/entropy_coder/model/entropy_coder_model.py <ide> def BuildGraph(self, input_codes): <ide> corresponding to the codes to compress. <ide> The input codes are {-1, +1} codes. <ide> """ <del> # TODO(damienv): <add> # TODO: <ide> # - consider switching to {0, 1} codes. <ide> # - consider passing an extra tensor which gives for each (b, y, x) <ide> # what is the actual depth (which would allow to use more or less bits
4
PHP
PHP
update request usage in view classes
50e8b21249dded5d8bd0671f8f19015e7309dd22
<ide><path>src/View/JsonView.php <ide> public function render($view = null, $layout = null) <ide> if ($this->viewVars['_jsonp'] === true) { <ide> $jsonpParam = 'callback'; <ide> } <del> if (isset($this->request->query[$jsonpParam])) { <del> $return = sprintf('%s(%s)', h($this->request->query[$jsonpParam]), $return); <add> if ($this->request->query($jsonpParam)) { <add> $return = sprintf('%s(%s)', h($this->request->query($jsonpParam)), $return); <ide> $this->response->type('js'); <ide> } <ide> } <ide><path>src/View/View.php <ide> class View implements EventDispatcherInterface <ide> * Current passed params. Passed to View from the creating Controller for convenience. <ide> * <ide> * @var array <del> * @deprecated 3.1.0 Use `$this->request->params['pass']` instead. <add> * @deprecated 3.1.0 Use `$this->request->param('pass')` instead. <ide> */ <ide> public $passedArgs = []; <ide> <ide> public function __construct( <ide> } <ide> } <ide> $this->eventManager($eventManager); <del> $this->request = $request; <del> $this->response = $response; <add> $this->request = $request ?: Router::getRequest(true); <add> $this->response = $response ?: new Response(); <ide> if (empty($this->request)) { <del> $this->request = Router::getRequest(true); <del> } <del> if (empty($this->request)) { <del> $this->request = new Request(); <del> $this->request->base = ''; <del> $this->request->here = $this->request->webroot = '/'; <del> } <del> if (empty($this->response)) { <del> $this->response = new Response(); <add> $this->request = new Request([ <add> 'base' => '', <add> 'url' => '', <add> 'webroot' => '/' <add> ]); <ide> } <ide> $this->Blocks = new ViewBlock(); <ide> $this->initialize(); <ide> protected function _getElementFileName($name, $pluginCheck = true) <ide> protected function _getSubPaths($basePath) <ide> { <ide> $paths = [$basePath]; <del> if (!empty($this->request->params['prefix'])) { <del> $prefixPath = explode('/', $this->request->params['prefix']); <add> if ($this->request->param('prefix')) { <add> $prefixPath = explode('/', $this->request->param('prefix')); <ide> $path = ''; <ide> foreach ($prefixPath as $prefixPart) { <ide> $path .= Inflector::camelize($prefixPart) . DIRECTORY_SEPARATOR;
2
Java
Java
remove animationregistry from uimanagemodule
16350ae09b4fb5bbeb3edc8cc9df623e4048c6b1
<ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/NativeViewHierarchyManager.java <ide> private final JSResponderHandler mJSResponderHandler = new JSResponderHandler(); <ide> private final RootViewManager mRootViewManager = new RootViewManager(); <ide> <del> public NativeViewHierarchyManager( <del> AnimationRegistry animationRegistry, <del> ViewManagerRegistry viewManagers) { <del> mAnimationRegistry = animationRegistry; <add> public NativeViewHierarchyManager(ViewManagerRegistry viewManagers) { <add> mAnimationRegistry = new AnimationRegistry(); <ide> mViewManagers = viewManagers; <ide> mTagsToViews = new SparseArray<>(); <ide> mTagsToViewManagers = new SparseArray<>(); <ide> mRootTags = new SparseBooleanArray(); <ide> mRootViewsContext = new SparseArray<>(); <ide> } <ide> <add> public AnimationRegistry getAnimationRegistry() { <add> return mAnimationRegistry; <add> } <add> <ide> public void updateProperties(int tag, CatalystStylesDiffMap props) { <ide> UiThreadUtil.assertOnUiThread(); <ide> <ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/UIManagerModule.java <ide> import com.facebook.csslayout.CSSLayoutContext; <ide> import com.facebook.infer.annotation.Assertions; <ide> import com.facebook.react.animation.Animation; <del>import com.facebook.react.animation.AnimationRegistry; <ide> import com.facebook.react.bridge.Arguments; <ide> import com.facebook.react.bridge.Callback; <ide> import com.facebook.react.bridge.LifecycleEventListener; <ide> public class UIManagerModule extends ReactContextBaseJavaModule implements <ide> <ide> private final NativeViewHierarchyManager mNativeViewHierarchyManager; <ide> private final EventDispatcher mEventDispatcher; <del> private final AnimationRegistry mAnimationRegistry = new AnimationRegistry(); <ide> private final ShadowNodeRegistry mShadowNodeRegistry = new ShadowNodeRegistry(); <ide> private final ViewManagerRegistry mViewManagers; <ide> private final CSSLayoutContext mLayoutContext = new CSSLayoutContext(); <ide> public UIManagerModule(ReactApplicationContext reactContext, List<ViewManager> v <ide> super(reactContext); <ide> mViewManagers = new ViewManagerRegistry(viewManagerList); <ide> mEventDispatcher = new EventDispatcher(reactContext); <del> mNativeViewHierarchyManager = new NativeViewHierarchyManager( <del> mAnimationRegistry, <del> mViewManagers); <add> mNativeViewHierarchyManager = new NativeViewHierarchyManager(mViewManagers); <ide> mOperationsQueue = new UIViewOperationQueue( <ide> reactContext, <del> mNativeViewHierarchyManager, <del> mAnimationRegistry); <add> mNativeViewHierarchyManager); <ide> mNativeViewHierarchyOptimizer = new NativeViewHierarchyOptimizer( <ide> mOperationsQueue, <ide> mShadowNodeRegistry); <ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/UIViewOperationQueue.java <ide> public void execute() { <ide> <ide> /* package */ UIViewOperationQueue( <ide> ReactApplicationContext reactContext, <del> NativeViewHierarchyManager nativeViewHierarchyManager, <del> AnimationRegistry animationRegistry) { <add> NativeViewHierarchyManager nativeViewHierarchyManager) { <ide> mNativeViewHierarchyManager = nativeViewHierarchyManager; <del> mAnimationRegistry = animationRegistry; <add> mAnimationRegistry = nativeViewHierarchyManager.getAnimationRegistry(); <ide> mDispatchUIFrameCallback = new DispatchUIFrameCallback(reactContext); <ide> } <ide>
3
Python
Python
fix train loop for train_textcat example
4c5f265884776f7c643a2f37150f339a09549231
<ide><path>examples/training/train_textcat.py <ide> def main(model=None, output_dir=None, n_iter=20, n_texts=2000, init_tok2vec=None <ide> textcat.model.tok2vec.from_bytes(file_.read()) <ide> print("Training the model...") <ide> print("{:^5}\t{:^5}\t{:^5}\t{:^5}".format("LOSS", "P", "R", "F")) <add> batch_sizes = compounding(4.0, 32.0, 1.001) <ide> for i in range(n_iter): <ide> losses = {} <ide> # batch up the examples using spaCy's minibatch <del> batches = minibatch(train_data, size=compounding(4.0, 32.0, 1.001)) <add> random.shuffle(train_data) <add> batches = minibatch(train_data, size=batch_sizes) <ide> for batch in batches: <ide> texts, annotations = zip(*batch) <ide> nlp.update(texts, annotations, sgd=optimizer, drop=0.2, losses=losses)
1
Python
Python
fix implementation errors.
e3aa0f65e8a5a453e967ac2dc343c7cb96217548
<ide><path>ciphers/rsa_factorization.py <ide> The program can efficiently factor RSA prime number given the private key d and <ide> public key e. <ide> Source: on page 3 of https://crypto.stanford.edu/~dabo/papers/RSA-survey.pdf <add>More readable source: https://www.di-mgt.com.au/rsa_factorize_n.html <ide> large number can take minutes to factor, therefore are not included in doctest. <ide> """ <ide> import math <ide> def rsafactor(d: int, e: int, N: int) -> List[int]: <ide> """ <ide> This function returns the factors of N, where p*q=N <ide> Return: [p, q] <del> <add> <ide> We call N the RSA modulus, e the encryption exponent, and d the decryption exponent. <ide> The pair (N, e) is the public key. As its name suggests, it is public and is used to <ide> encrypt messages. <ide> def rsafactor(d: int, e: int, N: int) -> List[int]: <ide> while p == 0: <ide> g = random.randint(2, N - 1) <ide> t = k <del> if t % 2 == 0: <del> t = t // 2 <del> x = (g ** t) % N <del> y = math.gcd(x - 1, N) <del> if x > 1 and y > 1: <del> p = y <del> q = N // y <add> while True: <add> if t % 2 == 0: <add> t = t // 2 <add> x = (g ** t) % N <add> y = math.gcd(x - 1, N) <add> if x > 1 and y > 1: <add> p = y <add> q = N // y <add> break # find the correct factors <add> else: <add> break # t is not divisible by 2, break and choose another g <ide> return sorted([p, q]) <ide> <ide>
1
Javascript
Javascript
simplify the testcase
8a1b008a4631a4197f4f101a5e3eec0981fb693a
<ide><path>test/configCases/source-map/namespace-source-path-no-truncate/index.js <del>it("should include webpack://mynamespace/./[id].js in SourceMap", function () { <add>it("should include [id].js in SourceMap", function () { <ide> var fs = require("fs"); <ide> var source = fs.readFileSync(__filename + ".map", "utf-8"); <ide> var map = JSON.parse(source); <del> expect(map.sources).toContain("webpack://mynamespace/./[id].js"); <add> expect(map.sources).toContain("webpack:///./[id].js"); <ide> }); <ide> <ide> if (Math.random() < 0) require("./[id].js"); <ide><path>test/configCases/source-map/namespace-source-path-no-truncate/webpack.config.js <ide> /** @type {import("../../../../").Configuration} */ <ide> module.exports = { <del> mode: "development", <del> output: { <del> devtoolNamespace: "mynamespace" <del> }, <ide> node: { <ide> __dirname: false, <ide> __filename: false <ide> }, <del> devtool: "cheap-source-map" <add> devtool: "source-map", <add> optimization: { <add> minimize: true <add> } <ide> };
2
Java
Java
declare serialversionuid on defaultaopproxyfactory
1af21bb4513e27add1b32a024fd10e9e69253776
<ide><path>spring-aop/src/main/java/org/springframework/aop/framework/DefaultAopProxyFactory.java <ide> * @see AdvisedSupport#setProxyTargetClass <ide> * @see AdvisedSupport#setInterfaces <ide> */ <del>@SuppressWarnings("serial") <ide> public class DefaultAopProxyFactory implements AopProxyFactory, Serializable { <ide> <add> private static final long serialVersionUID = 7930414337282325166L; <add> <ide> <ide> @Override <ide> public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
1