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 |
|---|---|---|---|---|---|
Java | Java | simplify sourcefileassert assertion methods | 74caa9213a44e2b613025b2387d41389c9344953 | <ide><path>spring-core-test/src/main/java/org/springframework/aot/test/generator/file/MethodAssert.java
<del>/*
<del> * Copyright 2002-2022 the original author or authors.
<del> *
<del> * Licensed under the Apache License, Version 2.0 (the "License");
<del> * you may not use this file except in compliance with the License.
<del> * You may obtain a copy of the License at
<del> *
<del> * https://www.apache.org/licenses/LICENSE-2.0
<del> *
<del> * Unless required by applicable law or agreed to in writing, software
<del> * distributed under the License is distributed on an "AS IS" BASIS,
<del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<del> * See the License for the specific language governing permissions and
<del> * limitations under the License.
<del> */
<del>
<del>package org.springframework.aot.test.generator.file;
<del>
<del>import java.util.stream.Collectors;
<del>
<del>import com.thoughtworks.qdox.model.JavaMethod;
<del>import com.thoughtworks.qdox.model.JavaParameter;
<del>import org.assertj.core.api.AbstractAssert;
<del>
<del>import static org.assertj.core.api.Assertions.assertThat;
<del>
<del>/**
<del> * Assertion methods for {@code SourceFile} methods.
<del> *
<del> * @author Phillip Webb
<del> * @since 6.0
<del> */
<del>public class MethodAssert extends AbstractAssert<MethodAssert, JavaMethod> {
<del>
<del>
<del> MethodAssert(JavaMethod actual) {
<del> super(actual, MethodAssert.class);
<del> as(describe(actual));
<del> }
<del>
<del>
<del> private String describe(JavaMethod actual) {
<del> return actual.getName() + "("
<del> + actual.getParameters().stream().map(
<del> this::getFullyQualifiedName).collect(Collectors.joining(", "))
<del> + ")";
<del> }
<del>
<del> private String getFullyQualifiedName(JavaParameter parameter) {
<del> return parameter.getType().getFullyQualifiedName();
<del> }
<del>
<del> public void withBody(String expected) {
<del> assertThat(this.actual.getSourceCode()).as(
<del> this.info.description()).isEqualToNormalizingWhitespace(expected);
<del> }
<del>
<del> public void withBodyContaining(CharSequence... values) {
<del> assertThat(this.actual.getSourceCode()).as(this.info.description()).contains(
<del> values);
<del> }
<del>
<del>}
<ide><path>spring-core-test/src/main/java/org/springframework/aot/test/generator/file/SourceFile.java
<ide>
<ide> import com.thoughtworks.qdox.JavaProjectBuilder;
<ide> import com.thoughtworks.qdox.model.JavaClass;
<del>import com.thoughtworks.qdox.model.JavaPackage;
<ide> import com.thoughtworks.qdox.model.JavaSource;
<ide> import org.assertj.core.api.AssertProvider;
<del>import org.assertj.core.util.Strings;
<ide>
<ide> import org.springframework.core.io.InputStreamSource;
<ide> import org.springframework.lang.Nullable;
<add>import org.springframework.util.Assert;
<add>import org.springframework.util.ClassUtils;
<ide> import org.springframework.util.FileCopyUtils;
<add>import org.springframework.util.StringUtils;
<ide>
<ide> /**
<ide> * {@link DynamicFile} that holds Java source code and provides
<ide> public final class SourceFile extends DynamicFile
<ide> implements AssertProvider<SourceFileAssert> {
<ide>
<ide>
<del> private final JavaSource javaSource;
<add> private final String className;
<ide>
<ide>
<del> private SourceFile(String path, String content, JavaSource javaSource) {
<add> private SourceFile(String path, String content, String className) {
<ide> super(path, content);
<del> this.javaSource = javaSource;
<add> this.className = className;
<ide> }
<ide>
<ide>
<ide> public static SourceFile of(WritableContent writableContent) {
<ide> */
<ide> public static SourceFile of(@Nullable String path, WritableContent writableContent) {
<ide> String content = toString(writableContent);
<del> if (Strings.isNullOrEmpty(content)) {
<del> throw new IllegalStateException("WritableContent did not append any content");
<add> Assert.state(StringUtils.hasLength(content), "WritableContent did not append any content");
<add> String className = getClassName(content);
<add> if (!StringUtils.hasLength(path)) {
<add> path = ClassUtils.convertClassNameToResourcePath(className) + ".java";
<ide> }
<del> JavaSource javaSource = parse(content);
<del> if (path == null || path.isEmpty()) {
<del> path = deducePath(javaSource);
<del> }
<del> return new SourceFile(path, content, javaSource);
<add> return new SourceFile(path, content, className);
<ide> }
<ide>
<del> private static JavaSource parse(String content) {
<add> /**
<add> * Return the fully-qualified class name.
<add> * @return the fully qualified class name
<add> */
<add> public String getClassName() {
<add> return this.className;
<add> }
<add>
<add> private static String getClassName(String content) {
<ide> JavaProjectBuilder builder = new JavaProjectBuilder();
<ide> try {
<ide> JavaSource javaSource = builder.addSource(new StringReader(content));
<del> if (javaSource.getClasses().size() != 1) {
<del> throw new IllegalStateException("Source must define a single class");
<del> }
<del> return javaSource;
<add> Assert.state(javaSource.getClasses().size() == 1, "Source must define a single class");
<add> JavaClass javaClass = javaSource.getClasses().get(0);
<add> return (javaSource.getPackage() != null)
<add> ? javaSource.getPackageName() + "." + javaClass.getName()
<add> : javaClass.getName();
<ide> }
<ide> catch (Exception ex) {
<ide> throw new IllegalStateException(
<ide> "Unable to parse source file content:\n\n" + content, ex);
<ide> }
<ide> }
<ide>
<del> private static String deducePath(JavaSource javaSource) {
<del> JavaPackage javaPackage = javaSource.getPackage();
<del> JavaClass javaClass = javaSource.getClasses().get(0);
<del> String path = javaClass.getName() + ".java";
<del> if (javaPackage != null) {
<del> path = javaPackage.getName().replace('.', '/') + "/" + path;
<del> }
<del> return path;
<del> }
<del>
<del> JavaSource getJavaSource() {
<del> return this.javaSource;
<del> }
<del>
<del> /**
<del> * Return the class name of the source file.
<del> * @return the class name
<del> */
<del> public String getClassName() {
<del> return this.javaSource.getClasses().get(0).getFullyQualifiedName();
<del> }
<del>
<ide> /**
<ide> * AssertJ {@code assertThat} support.
<ide> * @deprecated use {@code assertThat(sourceFile)} rather than calling this
<ide> public SourceFileAssert assertThat() {
<ide> return new SourceFileAssert(this);
<ide> }
<ide>
<add>
<add>
<ide> }
<ide><path>spring-core-test/src/main/java/org/springframework/aot/test/generator/file/SourceFileAssert.java
<ide>
<ide> package org.springframework.aot.test.generator.file;
<ide>
<del>import java.util.Arrays;
<del>import java.util.List;
<del>import java.util.stream.Collectors;
<del>
<del>import com.thoughtworks.qdox.model.JavaClass;
<del>import com.thoughtworks.qdox.model.JavaMethod;
<del>import com.thoughtworks.qdox.model.JavaParameter;
<del>import com.thoughtworks.qdox.model.JavaType;
<del>import org.assertj.core.error.BasicErrorMessageFactory;
<del>import org.assertj.core.internal.Failures;
<del>
<del>import org.springframework.lang.Nullable;
<del>
<del>import static org.assertj.core.api.Assertions.assertThat;
<del>
<ide> /**
<ide> * Assertion methods for {@code SourceFile} instances.
<ide> *
<ide> public class SourceFileAssert extends DynamicFileAssert<SourceFileAssert, Source
<ide> super(actual, SourceFileAssert.class);
<ide> }
<ide>
<del>
<del> public SourceFileAssert implementsInterface(@Nullable Class<?> type) {
<del> return implementsInterface((type != null ? type.getName() : null));
<del> }
<del>
<del> public SourceFileAssert implementsInterface(@Nullable String name) {
<del> JavaClass javaClass = getJavaClass();
<del> assertThat(javaClass.getImplements()).as("implements").map(
<del> JavaType::getFullyQualifiedName).contains(name);
<del> return this;
<del> }
<del>
<del> public MethodAssert hasMethodNamed(String name) {
<del> JavaClass javaClass = getJavaClass();
<del> JavaMethod method = null;
<del> for (JavaMethod candidate : javaClass.getMethods()) {
<del> if (candidate.getName().equals(name)) {
<del> if (method != null) {
<del> throw Failures.instance().failure(this.info,
<del> new BasicErrorMessageFactory(String.format(
<del> "%nExpecting actual:%n %s%nto contain unique method:%n %s%n",
<del> this.actual.getContent(), name)));
<del> }
<del> method = candidate;
<del> }
<del> }
<del> if (method == null) {
<del> throw Failures.instance().failure(this.info,
<del> new BasicErrorMessageFactory(String.format(
<del> "%nExpecting actual:%n %s%nto contain method:%n %s%n",
<del> this.actual.getContent(), name)));
<del> }
<del> return new MethodAssert(method);
<del> }
<del>
<del> public MethodAssert hasMethod(String name, Class<?>... parameters) {
<del> JavaClass javaClass = getJavaClass();
<del> JavaMethod method = null;
<del> for (JavaMethod candidate : javaClass.getMethods()) {
<del> if (candidate.getName().equals(name)
<del> && hasParameters(candidate, parameters)) {
<del> if (method != null) {
<del> throw Failures.instance().failure(this.info,
<del> new BasicErrorMessageFactory(String.format(
<del> "%nExpecting actual:%n %s%nto contain unique method:%n %s%n",
<del> this.actual.getContent(), name)));
<del> }
<del> method = candidate;
<del> }
<del> }
<del> if (method == null) {
<del> String methodDescription = getMethodDescription(name, parameters);
<del> throw Failures.instance().failure(this.info,
<del> new BasicErrorMessageFactory(String.format(
<del> "%nExpecting actual:%n %s%nto contain method:%n %s%n",
<del> this.actual.getContent(), methodDescription)));
<del> }
<del> return new MethodAssert(method);
<del> }
<del>
<del> private boolean hasParameters(JavaMethod method, Class<?>[] requiredParameters) {
<del> List<JavaParameter> parameters = method.getParameters();
<del> if (parameters.size() != requiredParameters.length) {
<del> return false;
<del> }
<del> for (int i = 0; i < requiredParameters.length; i++) {
<del> if (!requiredParameters[i].getName().equals(
<del> parameters.get(i).getFullyQualifiedName())) {
<del> return false;
<del> }
<del> }
<del> return true;
<del> }
<del>
<del> private String getMethodDescription(String name, Class<?>... parameters) {
<del> return name + "(" + Arrays.stream(parameters).map(Class::getName).collect(
<del> Collectors.joining(", ")) + ")";
<del> }
<del>
<del> private JavaClass getJavaClass() {
<del> return this.actual.getJavaSource().getClasses().get(0);
<del> }
<del>
<ide> }
<ide><path>spring-core-test/src/main/java/org/springframework/aot/test/generator/file/SourceFiles.java
<ide> import java.util.stream.Stream;
<ide>
<ide> import org.springframework.lang.Nullable;
<add>import org.springframework.util.ClassUtils;
<ide>
<ide> /**
<ide> * An immutable collection of {@link SourceFile} instances.
<ide> private SourceFile getSingle(Pattern pattern) {
<ide> */
<ide> public SourceFile getSingleFromPackage(String packageName) {
<ide> return this.files.getSingle(candidate -> Objects.equals(packageName,
<del> candidate.getJavaSource().getPackageName()));
<add> ClassUtils.getPackageName(candidate.getClassName())));
<ide> }
<ide>
<ide> @Override
<ide><path>spring-core-test/src/test/java/org/springframework/aot/test/generator/compile/TestCompilerTests.java
<ide> void compileWhenHasDifferentClassesWithSameClassNameCompilesBoth() {
<ide> @Test
<ide> void compileAndGetSourceFile() {
<ide> TestCompiler.forSystem().withSources(SourceFile.of(HELLO_SPRING)).compile(
<del> compiled -> assertThat(compiled.getSourceFile()).hasMethodNamed(
<del> "get").withBodyContaining("// !!"));
<add> compiled -> assertThat(compiled.getSourceFile()).contains("// !!"));
<ide> }
<ide>
<ide> @Test
<ide><path>spring-core-test/src/test/java/org/springframework/aot/test/generator/file/MethodAssertTests.java
<del>/*
<del> * Copyright 2002-2022 the original author or authors.
<del> *
<del> * Licensed under the Apache License, Version 2.0 (the "License");
<del> * you may not use this file except in compliance with the License.
<del> * You may obtain a copy of the License at
<del> *
<del> * https://www.apache.org/licenses/LICENSE-2.0
<del> *
<del> * Unless required by applicable law or agreed to in writing, software
<del> * distributed under the License is distributed on an "AS IS" BASIS,
<del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<del> * See the License for the specific language governing permissions and
<del> * limitations under the License.
<del> */
<del>
<del>package org.springframework.aot.test.generator.file;
<del>
<del>import org.junit.jupiter.api.Test;
<del>
<del>import static org.assertj.core.api.Assertions.assertThat;
<del>import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
<del>
<del>/**
<del> * Tests for {@link MethodAssert}.
<del> *
<del> * @author Phillip Webb
<del> */
<del>class MethodAssertTests {
<del>
<del> private static final String SAMPLE = """
<del> package com.example;
<del>
<del> public class Sample {
<del>
<del> public void run() {
<del> System.out.println("Hello World!");
<del> }
<del>
<del> }
<del> """;
<del>
<del> private final SourceFile sourceFile = SourceFile.of(SAMPLE);
<del>
<del> @Test
<del> void withBodyWhenMatches() {
<del> assertThat(this.sourceFile).hasMethodNamed("run").withBody("""
<del> System.out.println("Hello World!");""");
<del> }
<del>
<del> @Test
<del> void withBodyWhenDoesNotMatchThrowsException() {
<del> assertThatExceptionOfType(AssertionError.class).isThrownBy(
<del> () -> assertThat(this.sourceFile).hasMethodNamed("run").withBody("""
<del> System.out.println("Hello Spring!");""")).withMessageContaining(
<del> "to be equal to");
<del> }
<del>
<del> @Test
<del> void withBodyContainingWhenContainsAll() {
<del> assertThat(this.sourceFile).hasMethodNamed("run").withBodyContaining("Hello",
<del> "World!");
<del> }
<del>
<del> @Test
<del> void withBodyWhenDoesNotContainOneThrowsException() {
<del> assertThatExceptionOfType(AssertionError.class).isThrownBy(
<del> () -> assertThat(this.sourceFile).hasMethodNamed(
<del> "run").withBodyContaining("Hello",
<del> "Spring!")).withMessageContaining("to contain");
<del> }
<del>
<del>}
<ide><path>spring-core-test/src/test/java/org/springframework/aot/test/generator/file/SourceFileAssertTests.java
<ide>
<ide> package org.springframework.aot.test.generator.file;
<ide>
<del>import java.util.concurrent.Callable;
<del>
<ide> import org.junit.jupiter.api.Test;
<ide>
<ide> import static org.assertj.core.api.Assertions.assertThat;
<ide> void isEqualToWhenNotEqualThrowsException() {
<ide> "expected", "but was");
<ide> }
<ide>
<del> @Test
<del> void implementsInterfaceWhenImplementsInterface() {
<del> assertThat(this.sourceFile).implementsInterface(Runnable.class);
<del> }
<del>
<del> @Test
<del> void implementsInterfaceWhenDoesNotImplementInterfaceThrowsException() {
<del> assertThatExceptionOfType(AssertionError.class).isThrownBy(
<del> () -> assertThat(this.sourceFile).implementsInterface(
<del> Callable.class)).withMessageContaining("to contain:");
<del> }
<del>
<del> @Test
<del> void hasMethodNamedWhenHasName() {
<del> MethodAssert methodAssert = assertThat(this.sourceFile).hasMethodNamed("main");
<del> assertThat(methodAssert).isNotNull();
<del> }
<del>
<del> @Test
<del> void hasMethodNameWhenDoesNotHaveMethodThrowsException() {
<del> assertThatExceptionOfType(AssertionError.class).isThrownBy(
<del> () -> assertThat(this.sourceFile).hasMethodNamed(
<del> "missing")).withMessageContaining("to contain method");
<del> }
<del>
<del> @Test
<del> void hasMethodNameWhenHasMultipleMethodsWithNameThrowsException() {
<del> assertThatExceptionOfType(AssertionError.class).isThrownBy(
<del> () -> assertThat(this.sourceFile).hasMethodNamed(
<del> "run")).withMessageContaining("to contain unique method");
<del> }
<del>
<del> @Test
<del> void hasMethodWhenHasMethod() {
<del> MethodAssert methodAssert = assertThat(this.sourceFile).hasMethod("run",
<del> String.class);
<del> assertThat(methodAssert).isNotNull();
<del> }
<del>
<del> @Test
<del> void hasMethodWhenDoesNotHaveMethod() {
<del> assertThatExceptionOfType(AssertionError.class).isThrownBy(
<del> () -> assertThat(this.sourceFile).hasMethod("run",
<del> Integer.class)).withMessageContaining(
<del> "to contain").withMessageContaining(
<del> "run(java.lang.Integer");
<del> }
<del>
<ide> }
<ide><path>spring-core-test/src/test/java/org/springframework/aot/test/generator/file/SourceFileTests.java
<ide>
<ide> import java.io.IOException;
<ide>
<del>import com.thoughtworks.qdox.model.JavaSource;
<ide> import org.junit.jupiter.api.Test;
<ide>
<ide> import static org.assertj.core.api.Assertions.assertThat;
<ide> void getContentReturnsContent() {
<ide> assertThat(sourceFile.getContent()).isEqualTo(HELLO_WORLD);
<ide> }
<ide>
<del> @Test
<del> void getJavaSourceReturnsJavaSource() {
<del> SourceFile sourceFile = SourceFile.of(HELLO_WORLD);
<del> assertThat(sourceFile.getJavaSource()).isInstanceOf(JavaSource.class);
<del> }
<del>
<ide> @Test
<ide> @SuppressWarnings("deprecation")
<ide> void assertThatReturnsAssert() { | 8 |
Javascript | Javascript | remove unused gulp target for testing | 145c0cea39c542beee4a3d98be6c1dd90c835afc | <ide><path>gulpfile.js
<ide> gulp.task('browsertest', function () {
<ide> return createTestSource('browser');
<ide> });
<ide>
<del>gulp.task('browsertest-noreftest', function () {
<del> return createTestSource('browser (no reftest)');
<del>});
<del>
<ide> gulp.task('unittest', function () {
<ide> return createTestSource('unit');
<ide> });
<ide><path>make.js
<ide> target.bottest = function() {
<ide> // make browsertest
<ide> //
<ide> target.browsertest = function(options) {
<del> if (options && options.noreftest) {
<del> execGulp('browsertest-noreftest');
<del> } else {
<del> execGulp('browsertest');
<del> }
<add> execGulp('browsertest');
<ide> };
<ide>
<ide> // | 2 |
Javascript | Javascript | add test case for no emit in watch mode | 0abdc0aed0867d8f14a1a6afc45daa8ff5e8ccf7 | <ide><path>test/Compiler.test.js
<ide> describe("Compiler", () => {
<ide> done();
<ide> });
<ide> });
<add> it("should not emit on errors (watch)", function(done) {
<add> const compiler = webpack({
<add> context: __dirname,
<add> mode: "production",
<add> entry: "./missing",
<add> output: {
<add> path: "/",
<add> filename: "bundle.js"
<add> }
<add> });
<add> compiler.outputFileSystem = new MemoryFs();
<add> const watching = compiler.watch({}, (err, stats) => {
<add> watching.close();
<add> if(err) return done(err);
<add> if(compiler.outputFileSystem.existsSync("/bundle.js"))
<add> return done(new Error("Bundle should not be created on error"));
<add> done();
<add> });
<add> });
<ide> describe("Watching", () => {
<ide> let compiler;
<ide> beforeEach(() => { | 1 |
PHP | PHP | remove misleading deprecation message | 37bb873bd8932ed1629df45049bde56750dbbbac | <ide><path>src/Database/Schema/TableSchemaInterface.php
<ide>
<ide> /**
<ide> * An interface used by database TableSchema objects.
<del> *
<del> * Deprecated 3.5.0: Use Cake\Database\TableSchemaAwareInterface instead.
<ide> */
<ide> interface TableSchemaInterface extends SchemaInterface
<ide> { | 1 |
PHP | PHP | apply style ci fixes | a153c59ae7d9c254b2c17eb321066f6b4da32f33 | <ide><path>src/Illuminate/Container/Container.php
<ide> protected function getClosure($abstract, $concrete)
<ide> }
<ide>
<ide> /**
<del> * Bind a callback to resolve with Container::call
<add> * Bind a callback to resolve with Container::call.
<ide> *
<ide> * @param string $method
<ide> * @param \Closure $concrete
<ide> public function bindMethod($method, $callback)
<ide> }
<ide>
<ide> /**
<del> * Call a method that has been bound to the container
<add> * Call a method that has been bound to the container.
<ide> *
<ide> * @param callable $callback
<ide> * @param mixed $default
<ide> * @return mixed
<ide> */
<ide> protected function callBoundMethod($callback, $default)
<ide> {
<del> if (!is_array($callback)) {
<add> if (! is_array($callback)) {
<ide> return value($default);
<ide> }
<ide>
<ide> $class = is_string($callback[0]) ? $callback[0] : get_class($callback[0]);
<ide>
<ide> $method = $this->normalize("{$class}@{$callback[1]}");
<ide>
<del> if (!isset($this->methodBindings[$method])) {
<add> if (! isset($this->methodBindings[$method])) {
<ide> return value($default);
<ide> }
<ide>
<ide> public function call($callback, array $parameters = [], $defaultMethod = null)
<ide>
<ide> return $this->callBoundMethod($callback, function () use ($callback, $parameters) {
<ide> $dependencies = $this->getMethodDependencies($callback, $parameters);
<add>
<ide> return call_user_func_array($callback, $dependencies);
<ide> });
<ide> } | 1 |
Text | Text | remove redundant instruction from the readme | 3c9277086742fe3a38a268ef97184be34e294655 | <ide><path>README.md
<ide> npm install
<ide> Start `grunt watch` or `npm start` to auto-build jQuery as you work:
<ide>
<ide> ```bash
<del>cd jquery && grunt watch
<add>grunt watch
<ide> ```
<ide>
<ide> | 1 |
Python | Python | use _umath_linalg for cholesky() | 2dd64051fa3f81bea0f9fe5098f7e1c24aa3f2f8 | <ide><path>numpy/linalg/linalg.py
<ide> def cholesky(a):
<ide>
<ide> Parameters
<ide> ----------
<del> a : (M, M) array_like
<add> a : (..., M, M) array_like
<ide> Hermitian (symmetric if all elements are real), positive-definite
<ide> input matrix.
<ide>
<ide> Returns
<ide> -------
<del> L : {(M, M) ndarray, (M, M) matrix}
<del> Lower-triangular Cholesky factor of `a`. Returns a matrix object
<del> if `a` is a matrix object.
<add> L : (..., M, M) array_like
<add> Upper or lower-triangular Cholesky factor of `a`. Returns a
<add> matrix object if `a` is a matrix object.
<ide>
<ide> Raises
<ide> ------
<ide> def cholesky(a):
<ide>
<ide> Notes
<ide> -----
<add> Broadcasting rules apply, see the `numpy.linalg` documentation for
<add> details.
<add>
<ide> The Cholesky decomposition is often used as a fast way of solving
<ide>
<ide> .. math:: A \\mathbf{x} = \\mathbf{b}
<ide> def cholesky(a):
<ide> [ 0.+2.j, 1.+0.j]])
<ide>
<ide> """
<add> extobj = get_linalg_error_extobj(_raise_linalgerror_nonposdef)
<add> gufunc = _umath_linalg.cholesky_lo
<ide> a, wrap = _makearray(a)
<del> _assertRank2(a)
<del> _assertSquareness(a)
<add> _assertRankAtLeast2(a)
<add> _assertNdSquareness(a)
<ide> t, result_t = _commonType(a)
<del> a = _fastCopyAndTranspose(t, a)
<del> a = _to_native_byte_order(a)
<del> m = a.shape[0]
<del> n = a.shape[1]
<del> if isComplexType(t):
<del> lapack_routine = lapack_lite.zpotrf
<del> else:
<del> lapack_routine = lapack_lite.dpotrf
<del> results = lapack_routine(_L, n, a, m, 0)
<del> if results['info'] > 0:
<del> raise LinAlgError('Matrix is not positive definite - '
<del> 'Cholesky decomposition cannot be computed')
<del> s = triu(a, k=0).transpose()
<del> if (s.dtype != result_t):
<del> s = s.astype(result_t)
<del> return wrap(s)
<add> return wrap(gufunc(a.astype(t), extobj=extobj).astype(result_t))
<ide>
<ide> # QR decompostion
<ide> | 1 |
Python | Python | assign ips upon machine creation | c8727bf4d9c916a6fed3d7abab964cd6e9d956fa | <ide><path>libcloud/compute/drivers/packet.py
<ide> def create_node(self, name, size, image, location,
<ide> # if project has been specified on initialization of driver, then
<ide> # create on this project
<ide>
<del> import ipdb; ipdb.set_trace();
<ide> if self.project_id:
<ide> ex_project_id = self.project_id
<ide> else: | 1 |
Ruby | Ruby | add type option to atom feed entry builder | e3d1585c8f2eb08e9e8bfa283a54a949f0ec5467 | <ide><path>actionpack/lib/action_view/helpers/atom_feed_helper.rb
<ide> def updated(date_or_time = nil)
<ide> # * <tt>:updated</tt>: Time of update. Defaults to the updated_at attribute on the record if one such exists.
<ide> # * <tt>:url</tt>: The URL for this entry. Defaults to the polymorphic_url for the record.
<ide> # * <tt>:id</tt>: The ID for this entry. Defaults to "tag:#{@view.request.host},#{@feed_options[:schema_date]}:#{record.class}/#{record.id}"
<add> # * <tt>:type</tt>: The TYPE for this entry. Defaults to "text/html".
<ide> def entry(record, options = {})
<ide> @xml.entry do
<ide> @xml.id(options[:id] || "tag:#{@view.request.host},#{@feed_options[:schema_date]}:#{record.class}/#{record.id}")
<ide> def entry(record, options = {})
<ide> @xml.updated((options[:updated] || record.updated_at).xmlschema)
<ide> end
<ide>
<del> @xml.link(:rel => 'alternate', :type => 'text/html', :href => options[:url] || @view.polymorphic_url(record))
<add> type = options.fetch(:type) { 'text/html' }
<add>
<add> @xml.link(:rel => 'alternate', :type => type, :href => options[:url] || @view.polymorphic_url(record))
<ide>
<ide> yield AtomBuilder.new(@xml)
<ide> end
<ide><path>actionpack/test/template/atom_feed_helper_test.rb
<ide> class ScrollsController < ActionController::Base
<ide> end
<ide> end
<ide> EOT
<add> FEEDS["entry_type_options"] = <<-EOT
<add> atom_feed(:schema_date => '2008') do |feed|
<add> feed.title("My great blog!")
<add> feed.updated((@scrolls.first.created_at))
<add>
<add> @scrolls.each do |scroll|
<add> feed.entry(scroll, :type => 'text/xml') do |entry|
<add> entry.title(scroll.title)
<add> entry.content(scroll.body, :type => 'html')
<add>
<add> entry.author do |author|
<add> author.name("DHH")
<add> end
<add> end
<add> end
<add> end
<add> EOT
<ide> FEEDS["xml_block"] = <<-EOT
<ide> atom_feed do |feed|
<ide> feed.title("My great blog!")
<ide> def test_feed_xhtml
<ide> end
<ide> end
<ide>
<add> def test_feed_entry_type_option_default_to_text_html
<add> with_restful_routing(:scrolls) do
<add> get :index, :id => 'defaults'
<add> assert_select "entry link[rel=alternate][type=text/html]"
<add> end
<add> end
<add>
<add> def test_feed_entry_type_option_specified
<add> with_restful_routing(:scrolls) do
<add> get :index, :id => 'entry_type_options'
<add> assert_select "entry link[rel=alternate][type=text/xml]"
<add> end
<add> end
<add>
<ide> private
<ide> def with_restful_routing(resources)
<ide> with_routing do |set| | 2 |
Javascript | Javascript | remove redundant code | e5e7f89f4b3ae7b94991476e80c0cfd31d22d900 | <ide><path>client/src/redux/index.js
<ide> export const reducer = handleActions(
<ide> ...state,
<ide> currentChallengeId: payload
<ide> }),
<del> [settingsTypes.updateLegacyCertComplete]: (state, { payload }) => {
<del> const { appUsername } = state;
<del> return {
<del> ...state,
<del> completionCount: state.completionCount + 1,
<del> user: {
<del> ...state.user,
<del> [appUsername]: {
<del> ...state.user[appUsername],
<del> completedChallenges: uniqBy(
<del> [...state.user[appUsername].completedChallenges, payload],
<del> 'id'
<del> )
<del> }
<del> }
<del> };
<del> },
<ide> [settingsTypes.submitNewUsernameComplete]: (state, { payload }) =>
<ide> payload
<ide> ? {
<ide><path>client/src/redux/settings/action-types.js
<ide> export const actionTypes = createTypes(
<ide> ...createAsyncTypes('submitNewAbout'),
<ide> ...createAsyncTypes('submitNewUsername'),
<ide> ...createAsyncTypes('updateMyEmail'),
<del> ...createAsyncTypes('updateLegacyCert'),
<ide> ...createAsyncTypes('updateUserFlag'),
<ide> ...createAsyncTypes('submitProfileUI'),
<ide> ...createAsyncTypes('verifyCert'), | 2 |
PHP | PHP | add method comments | c59d9c3f686b3947e06d7a7c821972c21528f9df | <ide><path>src/View/View.php
<ide> public function layout($name = null)
<ide> * - `callbacks` - Set to true to fire beforeRender and afterRender helper callbacks for this element.
<ide> * Defaults to false.
<ide> * - `ignoreMissing` - Used to allow missing elements. Set to true to not throw exceptions.
<add> * - `plugin` - setting to false will force to use the application's element from plugin templates, when the
<add> * plugin has element with same name. Defaults to true
<ide> * @return string Rendered Element
<ide> * @throws \Cake\View\Exception\MissingElementException When an element is missing and `ignoreMissing`
<ide> * is false.
<ide> public function pluginSplit($name, $fallback = true)
<ide> $name = $second;
<ide> $plugin = $first;
<ide> }
<del>
<ide> if (isset($this->plugin) && !$plugin && $fallback) {
<ide> $plugin = $this->plugin;
<ide> }
<ide> protected function _getLayoutFileName($name = null)
<ide> * Finds an element filename, returns false on failure.
<ide> *
<ide> * @param string $name The name of the element to find.
<add> * @param bool $pluginCheck - if false will ignore the request's plugin if parsed plugin is not loaded
<ide> * @return string|false Either a string to the element filename or false when one can't be found.
<ide> */
<ide> protected function _getElementFileName($name, $pluginCheck = true) | 1 |
Ruby | Ruby | handle complex $editor values | e3c6d9bf0008b3f32b2ad370cf9639be4c80f0d9 | <ide><path>Library/Homebrew/utils.rb
<ide> def exec_editor *args
<ide> '/usr/bin/vim' # Default to vim
<ide> end
<ide> end
<del> # we split the editor because especially on mac "mate -w" is common
<del> # but we still want to use the comma-delimited version of exec because then
<del> # we don't have to escape args, and escaping 100% is tricky
<del> exec *(editor.split + args) unless args.empty?
<add>
<add> # Invoke bash to evaluate env vars in $EDITOR
<add> # This also gets us proper argument quoting.
<add> # See: https://github.com/mxcl/homebrew/issues/5123
<add> system "bash", "-c", editor + ' "$@"', "--", *args
<ide> end
<ide>
<ide> # GZips the given paths, and returns the gzipped paths | 1 |
Javascript | Javascript | expose link-list from timers.js; add tests | 09994438e58bef3c04dfb851f54fb547d9c22f02 | <ide><path>lib/timers.js
<ide> if (process.env.NODE_debug && /timer/.test(process.env.NODE_debug)) {
<ide> }
<ide>
<ide>
<del>// IDLE TIMEOUTS
<del>//
<del>// Because often many sockets will have the same idle timeout we will not
<del>// use one timeout watcher per item. It is too much overhead. Instead
<del>// we'll use a single watcher for all sockets with the same timeout value
<del>// and a linked list. This technique is described in the libev manual:
<del>// http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod#Be_smart_about_timeouts
<add>// Export the linklist code for testing.
<add>
<add>
<add>exports.linkedList = {};
<add>
<add>
<add>function init(list) {
<add> list._idleNext = list;
<add> list._idlePrev = list;
<add>}
<add>exports.linkedList.init = init;
<ide>
<del>// Object containing all lists, timers
<del>// key = time in milliseconds
<del>// value = list
<del>var lists = {};
<ide>
<ide> // show the most idle item
<ide> function peek(list) {
<ide> if (list._idlePrev == list) return null;
<ide> return list._idlePrev;
<ide> }
<add>exports.linkedList.peek = peek;
<ide>
<ide>
<ide> // remove the most idle item from the list
<ide> function shift(list) {
<ide> remove(first);
<ide> return first;
<ide> }
<add>exports.linkedList.shift = shift;
<ide>
<ide>
<ide> // remove a item from its list
<ide> function remove(item) {
<del> item._idleNext._idlePrev = item._idlePrev;
<del> item._idlePrev._idleNext = item._idleNext;
<add> if (item._idleNext) {
<add> item._idleNext._idlePrev = item._idlePrev;
<add> }
<add>
<add> if (item._idlePrev) {
<add> item._idlePrev._idleNext = item._idleNext;
<add> }
<add>
<add> item._idleNext = null;
<add> item._idlePrev = null;
<ide> }
<add>exports.linkedList.remove = remove;
<ide>
<ide>
<ide> // remove a item from its list and place at the end.
<ide> function append(list, item) {
<add> remove(item);
<ide> item._idleNext = list._idleNext;
<ide> list._idleNext._idlePrev = item;
<ide> item._idlePrev = list;
<ide> list._idleNext = item;
<ide> }
<add>exports.linkedList.append = append;
<add>
<add>
<add>function isEmpty(list) {
<add> return list._idleNext === list;
<add>}
<add>exports.linkedList.isEmpty = isEmpty;
<add>
<add>
<add>// IDLE TIMEOUTS
<add>//
<add>// Because often many sockets will have the same idle timeout we will not
<add>// use one timeout watcher per item. It is too much overhead. Instead
<add>// we'll use a single watcher for all sockets with the same timeout value
<add>// and a linked list. This technique is described in the libev manual:
<add>// http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod#Be_smart_about_timeouts
<add>
<add>// Object containing all lists, timers
<add>// key = time in milliseconds
<add>// value = list
<add>var lists = {};
<ide>
<ide>
<ide> // the main function - creates lists on demand and the watchers associated
<ide> function insert(item, msecs) {
<ide> list = lists[msecs];
<ide> } else {
<ide> list = new Timer();
<del> list._idleNext = list;
<del> list._idlePrev = list;
<add> init(list);
<ide>
<ide> lists[msecs] = list;
<ide>
<ide> function insert(item, msecs) {
<ide> // just set its repeat
<ide> var now = new Date();
<ide> debug('now: ' + now);
<add>
<ide> var first;
<ide> while (first = peek(list)) {
<ide> var diff = now - first._idleStart;
<ide> function insert(item, msecs) {
<ide> if (first._onTimeout) first._onTimeout();
<ide> }
<ide> }
<add>
<ide> debug(msecs + ' list empty');
<del> assert(list._idleNext === list); // list is empty
<add> assert(isEmpty(list));
<ide> list.stop();
<ide> };
<ide> }
<ide> function insert(item, msecs) {
<ide> }
<ide>
<ide> append(list, item);
<del> assert(list._idleNext !== list); // list is not empty
<add> assert(!isEmpty(list)); // list is not empty
<ide> }
<ide>
<ide>
<ide> var unenroll = exports.unenroll = function(item) {
<ide> var list = lists[item._idleTimeout];
<ide> // if empty then stop the watcher
<ide> debug('unenroll');
<del> if (list && list._idlePrev == list) {
<add> if (list && isEmpty(list)) {
<ide> debug('unenroll: list empty');
<ide> list.stop();
<ide> }
<ide> exports.enroll = function(item, msecs) {
<ide> if (item._idleNext) unenroll(item);
<ide>
<ide> item._idleTimeout = msecs;
<del> item._idleNext = item;
<del> item._idlePrev = item;
<add> init(item);
<ide> };
<ide>
<ide> // call this whenever the item is active (not idle)
<ide> exports.active = function(item) {
<ide> if (item._idleNext == item) {
<ide> insert(item, msecs);
<ide> } else {
<del> // inline append
<ide> item._idleStart = new Date();
<del> item._idleNext._idlePrev = item._idlePrev;
<del> item._idlePrev._idleNext = item._idleNext;
<del> item._idleNext = list._idleNext;
<del> item._idleNext._idlePrev = item;
<del> item._idlePrev = list;
<del> list._idleNext = item;
<add> append(list, item);
<ide> }
<ide> }
<ide> };
<ide><path>test/simple/test-timers-linked-list.js
<add>var common = require('../common');
<add>var assert = require('assert');
<add>var L = require('timers').linkedList;
<add>
<add>
<add>var list = { name: "list" };
<add>var A = { name: "A" };
<add>var B = { name: "B" };
<add>var C = { name: "C" };
<add>var D = { name: "D" };
<add>
<add>
<add>L.init(list);
<add>assert.ok(L.isEmpty(list));
<add>assert.equal(null, L.peek(list));
<add>
<add>L.append(list, A);
<add>// list -> A
<add>assert.equal(A, L.peek(list));
<add>
<add>L.append(list, B);
<add>// list -> A -> B
<add>assert.equal(A, L.peek(list));
<add>
<add>L.append(list, C);
<add>// list -> A -> B -> C
<add>assert.equal(A, L.peek(list));
<add>
<add>L.append(list, D);
<add>// list -> A -> B -> C -> D
<add>assert.equal(A, L.peek(list));
<add>
<add>var x = L.shift(list);
<add>assert.equal(A, x);
<add>// list -> B -> C -> D
<add>assert.equal(B, L.peek(list));
<add>
<add>x = L.shift(list);
<add>assert.equal(B, x);
<add>// list -> C -> D
<add>assert.equal(C, L.peek(list));
<add>
<add>// B is already removed, so removing it again shouldn't hurt.
<add>L.remove(B);
<add>// list -> C -> D
<add>assert.equal(C, L.peek(list));
<add>
<add>// Put B back on the list
<add>L.append(list, B);
<add>// list -> C -> D -> B
<add>assert.equal(C, L.peek(list));
<add>
<add>L.remove(C);
<add>// list -> D -> B
<add>assert.equal(D, L.peek(list));
<add>
<add>L.remove(B);
<add>// list -> D
<add>assert.equal(D, L.peek(list));
<add>
<add>L.remove(D);
<add>// list
<add>assert.equal(null, L.peek(list));
<add>
<add>
<add>assert.ok(L.isEmpty(list));
<add>
<add>
<add>L.append(list, D);
<add>// list -> D
<add>assert.equal(D, L.peek(list));
<add>
<add>L.append(list, C);
<add>L.append(list, B);
<add>L.append(list, A);
<add>// list -> D -> C -> B -> A
<add>
<add>// Append should REMOVE C from the list and append it to the end.
<add>L.append(list, C);
<add>
<add>// list -> D -> B -> A -> C
<add>assert.equal(D, L.shift(list));
<add>// list -> B -> A -> C
<add>assert.equal(B, L.peek(list));
<add>assert.equal(B, L.shift(list));
<add>// list -> A -> C
<add>assert.equal(A, L.peek(list));
<add>assert.equal(A, L.shift(list));
<add>// list -> C
<add>assert.equal(C, L.peek(list));
<add>assert.equal(C, L.shift(list));
<add>// list
<add>assert.ok(L.isEmpty(list));
<add> | 2 |
Text | Text | add lucamaraschi to collaborators | ce986de829457c39257cd205067602e765768fb0 | <ide><path>README.md
<ide> more information about the governance of the Node.js project, see
<ide> **Minwoo Jung** <minwoo@nodesource.com> (he/him)
<ide> * [lance](https://github.com/lance) -
<ide> **Lance Ball** <lball@redhat.com>
<add>* [lucamaraschi](https://github.com/lucamaraschi) -
<add>**Luca Maraschi** <luca.maraschi@gmail.com> (he/him)
<ide> * [lpinca](https://github.com/lpinca) -
<ide> **Luigi Pinca** <luigipinca@gmail.com> (he/him)
<ide> * [lxe](https://github.com/lxe) - | 1 |
Ruby | Ruby | ignore shared-mime-info and mactex | 7dd69d2c94ed801285a164439f3fcbf17a2a6894 | <ide><path>Library/Homebrew/cmd/--prefix.rb
<ide> def __prefix
<ide> share/pypy3/*
<ide> share/info/dir
<ide> share/man/whatis
<add> share/mime/*
<add> texlive/*
<ide> ].freeze
<ide>
<ide> def list_unbrewed | 1 |
Javascript | Javascript | remove unnecessary use of array.from | 94a552149d09b442be47679ecd50d14abcc7364f | <ide><path>src/project.js
<ide> /*
<ide> * decaffeinate suggestions:
<del> * DS101: Remove unnecessary use of Array.from
<ide> * DS103: Rewrite code to no longer use __guard__
<ide> * DS104: Avoid inline assignments
<ide> * DS204: Change includes calls to have a more natural evaluation order
<ide> class Project extends Model {
<ide> this.addPath(projectPath, {emitEvent: false, mustExist: true, exact: options.exact === true})
<ide> } catch (e) {
<ide> if (e.missingProjectPaths != null) {
<del> missingProjectPaths.push(...Array.from(e.missingProjectPaths || []))
<add> missingProjectPaths.push(...e.missingProjectPaths)
<ide> } else {
<ide> throw e
<ide> }
<ide> class Project extends Model {
<ide>
<ide> if (indexToRemove != null) {
<ide> this.rootDirectories.splice(indexToRemove, 1)
<del> const [removedRepository] = Array.from(this.repositories.splice(indexToRemove, 1))
<add> const [removedRepository] = this.repositories.splice(indexToRemove, 1)
<ide> if (!this.repositories.includes(removedRepository)) {
<ide> if (removedRepository) removedRepository.destroy()
<ide> }
<ide> class Project extends Model {
<ide> }
<ide>
<ide> removeBufferAtIndex (index, options = {}) {
<del> const [buffer] = Array.from(this.buffers.splice(index, 1))
<add> const [buffer] = this.buffers.splice(index, 1)
<ide> return (buffer != null ? buffer.destroy() : undefined)
<ide> }
<ide> | 1 |
Text | Text | add chinese translation of jsx-in-depth | 8621b4d338f72687b5ee66221a580f9473ccd5b6 | <ide><path>docs/docs/02.1-jsx-in-depth.zh-CN.md
<add>---
<add>id: jsx-in-depth-zh-CN
<add>title: 深入 JSX
<add>permalink: jsx-in-depth-zh-CN.html
<add>prev: displaying-data-zh-CN.html
<add>next: jsx-spread-zh-CN.html
<add>---
<add>
<add>[JSX](http://facebook.github.io/jsx/) 是一个看起来很像 XML 的 JavaScript 语法扩展。React 可以用来做简单的 JSX 句法转换。
<add>
<add>## 为什么要用 JSX?
<add>
<add>你不需要为了 React 使用 JSX,可以直接使用原生 JS。但是,我们建议使用 JSX 是因为它能精确,也是常用的定义包含属性的树状结构的语法。
<add>
<add>它对于非专职开发者比如设计师也比较熟悉。
<add>
<add>XML 有固定的标签开启和闭合的优点。这能让复杂的树更易于阅读,优于方法调用和对象字面量的形式。
<add>
<add>它没有修改 JavaScript 语义。
<add>
<add>## HTML 标签 对比 React 模块
<add>
<add>React 可以渲染 HTML 标签 (strings) 或 React 模块 (classes)。
<add>
<add>要渲染 HTML 标签,只需在 JSX 里使用小写字母开头的标签名。
<add>
<add>```javascript
<add>var myDivElement = <div className="foo" />;
<add>React.render(myDivElement, document.body);
<add>```
<add>
<add>要渲染 React 模块,只需创建一个大写字母开头的本地变量。
<add>
<add>```javascript
<add>var MyComponent = React.createClass({/*...*/});
<add>var myElement = <MyComponent someProperty={true} />;
<add>React.render(myElement, document.body);
<add>```
<add>
<add>React 的 JSX 里约定分别使用首字母大、小写来区分本地模块的类和 HTML 标签。
<add>
<add>> 提示:
<add>>
<add>> 由于 JSX 就是 JavaScript,一些标识符像 `class` 和 `for` 不建议作为 XML
<add>> 属性名。作为替代,React DOM 使用 `className` 和 `htmlFor` 来做对应的属性。
<add>
<add>## 转换(Transform)
<add>
<add>JSX 把类 XML 的语法转成原生 JavaScript,XML 元素、属性和子节点被转换成 `React.createElement` 的参数。
<add>
<add>```javascript
<add>var Nav;
<add>// 输入 (JSX):
<add>var app = <Nav color="blue" />;
<add>// 输出 (JS):
<add>var app = React.createElement(Nav, {color:"blue"});
<add>```
<add>
<add>注意,要想使用 `<Nav />`,`Nav` 变量一定要在作用区间内。
<add>
<add>JSX 也支持使用 XML 语法定义子结点:
<add>
<add>```javascript
<add>var Nav, Profile;
<add>// 输入 (JSX):
<add>var app = <Nav color="blue"><Profile>click</Profile></Nav>;
<add>// 输出 (JS):
<add>var app = React.createElement(
<add> Nav,
<add> {color:"blue"},
<add> React.createElement(Profile, null, "click")
<add>);
<add>```
<add>
<add>使用 [JSX 编译器](/react/jsx-compiler.html) 来试用 JSX 并理解它是如何转换到原生 JavaScript,还有 [HTML 到 JSX 转换器](/react/html-jsx.html) 来把现有 HTML 转成 JSX。
<add>
<add>如果你要使用 JSX,这篇 [新手入门](/react/docs/getting-started.html) 教程来教你如何搭建环境。
<add>
<add>> 提示:
<add>>
<add>> JSX 表达式总是会当作 ReactElement 执行。具体的实际细节可能不同。一种优化
<add>> 的模式是把 ReactElement 当作一个行内的对象字面量形式来绕过
<add>> `React.createElement` 里的校验代码。
<add>
<add>## JavaScript 表达式
<add>
<add>### 属性表达式
<add>
<add>要使用 JavaScript 表达式作为属性值,只需把这个表达式用一对大括号 (`{}`) 包起来,不要用引号 (`""`)。
<add>
<add>```javascript
<add>// 输入 (JSX):
<add>var person = <Person name={window.isLoggedIn ? window.name : ''} />;
<add>// 输出 (JS):
<add>var person = React.createElement(
<add> Person,
<add> {name: window.isLoggedIn ? window.name : ''}
<add>);
<add>```
<add>
<add>### 子节点表达式
<add>
<add>同样地,JavaScript 表达式可用于描述子结点:
<add>
<add>```javascript
<add>// 输入 (JSX):
<add>var content = <Container>{window.isLoggedIn ? <Nav /> : <Login />}</Container>;
<add>// 输出 (JS):
<add>var content = React.createElement(
<add> Container,
<add> null,
<add> window.isLoggedIn ? React.createElement(Nav) : React.createElement(Login)
<add>);
<add>```
<add>
<add>### 注释
<add>
<add>JSX 里添加注释很容易;它们只是 JS 表达式而已。你只需要在一个标签的子节点内(非最外层)小心地用 `{}` 包围要注释的部分。
<add>
<add>```javascript
<add>var content = (
<add> <Nav>
<add> {/* 一般注释, 用 {} 包围 */}
<add> <Person
<add> /* 多
<add> 行
<add> 注释 */
<add> name={window.isLoggedIn ? window.name : ''} // 行尾注释
<add> />
<add> </Nav>
<add>);
<add>```
<add>
<add>> 提示:
<add>>
<add>> JSX 类似于 HTML,但不完全一样。参考 [JSX 陷阱](/react/docs/jsx-gotchas.html) 了解主要不同。
<ide>\ No newline at end of file | 1 |
Text | Text | fix signature for napi_create_range_error | 7dcfe72a2595331c2c5b2cc008bc2c63df6c95fa | <ide><path>doc/api/n-api.md
<ide> This API returns a JavaScript `TypeError` with the text provided.
<ide> added: v8.0.0
<ide> -->
<ide> ```C
<del>NODE_EXTERN napi_status napi_create_range_error(napi_env env,
<add>NAPI_EXTERN napi_status napi_create_range_error(napi_env env,
<ide> napi_value code,
<del> const char* msg,
<add> napi_value msg,
<ide> napi_value* result);
<ide> ```
<ide> - `[in] env`: The environment that the API is invoked under. | 1 |
Javascript | Javascript | fix a unnecessary conditional statement in .stop() | 110802c7f22b677ef658963aa95ebdf5cb9c5573 | <ide><path>src/effects.js
<ide> jQuery.fn.extend( {
<ide> clearQueue = type;
<ide> type = undefined;
<ide> }
<del> if ( clearQueue && type !== false ) {
<add> if ( clearQueue ) {
<ide> this.queue( type || "fx", [] );
<ide> }
<ide> | 1 |
Text | Text | fix styles of headings to follow guide rules | d0a5f878d32a4b95f5e866d3b5612acd4b7d16c7 | <ide><path>guides/source/upgrading_ruby_on_rails.md
<ide> For more information on changes made to Rails 5.0 please see the [release notes]
<ide> From Ruby on Rails 5.0 onwards, Ruby 2.2.2+ is the only supported Ruby version.
<ide> Make sure you are on Ruby 2.2.2 version or greater, before you proceed.
<ide>
<del>### Active Record models now inherit from ApplicationRecord by default
<add>### Active Record Models Now Inherit from ApplicationRecord by Default
<ide>
<ide> In Rails 4.2, an Active Record model inherits from `ActiveRecord::Base`. In Rails 5.0,
<ide> all models inherit from `ApplicationRecord`.
<ide> class ApplicationRecord < ActiveRecord::Base
<ide> end
<ide> ```
<ide>
<del>### Halting callback chains via `throw(:abort)`
<add>### Halting Callback Chains via `throw(:abort)`
<ide>
<ide> In Rails 4.2, when a 'before' callback returns `false` in Active Record
<ide> and Active Model, then the entire callback chain is halted. In other words,
<ide> halted the chain when any value was returned.
<ide>
<ide> See [#17227](https://github.com/rails/rails/pull/17227) for more details.
<ide>
<del>### ActiveJob jobs now inherit from ApplicationJob by default
<add>### ActiveJob Now Inherits from ApplicationJob by Default
<ide>
<ide> In Rails 4.2, an Active Job inherits from `ActiveJob::Base`. In Rails 5.0, this
<ide> behavior has changed to now inherit from `ApplicationJob`.
<ide> your Gemfile.
<ide> If you are using Rspec for testing, please see the extra configuration required in the gem's
<ide> documentation.
<ide>
<del>### Autoloading is disabled after booting in the production environment
<add>### Autoloading is Disabled After Booting in the Production Environment
<ide>
<ide> Autoloading is now disabled after booting in the production environment by
<ide> default.
<ide> true.
<ide> gem. To continue using XML serialization in your application, add `gem 'activemodel-serializers-xml'`
<ide> to your Gemfile.
<ide>
<del>### Removed support for legacy MySQL
<add>### Removed Support for Legacy `mysql` Database Adapter
<ide>
<ide> Rails 5 removes support for the legacy `mysql` database adapter. Most users should be able to
<ide> use `mysql2` instead. It will be converted to a separate gem when we find someone to maintain
<ide> it.
<ide>
<del>### Removed support for debugger
<add>### Removed Support for Debugger
<ide>
<ide> `debugger` is not supported by Ruby 2.2 which is required by Rails 5. Use `byebug` instead.
<ide>
<ide> To use the new test runner simply type `bin/rails test`.
<ide>
<ide> Run `bin/rails` to see the list of commands available.
<ide>
<del>### `ActionController::Parameters` no longer inherits from `HashWithIndifferentAccess`
<add>### `ActionController::Parameters` No Longer Inherits from `HashWithIndifferentAccess`
<ide>
<ide> Calling `params` in your application will now return an object instead of a hash. If your
<ide> parameters are already permitted, then you will not need to make any changes. If you are using `slice`
<ide> need to upgrade your application to first permit and then convert to a hash.
<ide>
<ide> params.permit([:proceed_to, :return_to]).to_h
<ide>
<del>### `protect_from_forgery` now defaults to `prepend: false`
<add>### `protect_from_forgery` Now Defaults to `prepend: false`
<ide>
<ide> `protect_from_forgery` defaults to `prepend: false` which means that it will be inserted into
<ide> the callback chain at the point in which you call it in your application. If you want
<ide> `protect_from_forgery` to always run first you should change your application to use
<ide> `protect_from_forgery prepend: true`.
<ide>
<del>### Default template handler is now RAW
<add>### Default Template Handler is Now RAW
<ide>
<ide> Files without a template handler in their extension will be rendered using the raw handler.
<ide> Previously Rails would render files using the ERB template handler.
<ide>
<ide> If you do not want your file to be handled via the raw handler, you should add an extension
<ide> to your file that can be parsed by the appropriate template handler.
<ide>
<del>### Add wildcard matching for template dependencies
<add>### Added Wildcard Matching for Template Dependencies
<ide>
<ide> You can now use wildcard matching for your template dependencies. For example if you were
<ide> defining your templates as such:
<ide> You can now just call the dependency once with a wildcard.
<ide> <% # Template Dependency: recordings/threads/events/* %>
<ide> ```
<ide>
<del>### Remove support for `protected_attributes` gem
<add>### Removed Support for `protected_attributes` Gem
<ide>
<ide> The `protected_attributes` gem is no longer supported in Rails 5.
<ide>
<del>### Remove support for `activerecord-deprecated_finders` gem
<add>### Removed support for `activerecord-deprecated_finders` gem
<ide>
<ide> The `activerecord-deprecated_finders` gem is no longer supported in Rails 5.
<ide>
<del>### `ActiveSupport::TestCase` default test order is now random
<add>### `ActiveSupport::TestCase` Default Test Rrder is Now Random
<ide>
<ide> When tests are run in your application the default order is now `:random`
<ide> instead of `:sorted`. Use the following config option to set it back to `:sorted`.
<ide> want to add this feature it will need to be turned on in an initializer.
<ide>
<ide> config.active_record.belongs_to_required_by_default = true
<ide>
<del>#### Per-form CSRF tokens
<add>#### Per-form CSRF Tokens
<ide>
<ide> Rails 5 now supports per-form CSRF tokens to mitigate against code-injection attacks with forms
<ide> created by JavaScript. With this option turned on forms in your application will each have their
<ide> own CSRF token that is specified to the action and method for that form.
<ide>
<ide> config.action_controller.per_form_csrf_tokens = true
<ide>
<del>#### Forgery protection with origin check
<add>#### Forgery Protection with Origin Check
<ide>
<ide> You can how configure your application to check if the HTTP `Origin` header should be checked
<ide> against the site's origin as an additional CSRF defense. Set the following in your config to
<ide> true:
<ide>
<ide> config.action_controller.forgery_protection_origin_check = true
<ide>
<del>#### Allow configuration of Action Mailer queue name
<add>#### Allow Configuration of Action Mailer Queue Name
<ide>
<ide> The default mailer queue name is `mailers`. This configuration option allows you to globally change
<ide> the queue name. Set the following in your config.
<ide>
<ide> config.action_mailer.deliver_later_queue_name = :new_queue_name
<ide>
<del>#### Support fragment caching in Action Mailer views
<add>#### Support Fragment Caching in Action Mailer Views
<ide>
<ide> Set `config.action_mailer.perform_caching` in your config to determine whether your Action Mailer views
<ide> should support caching.
<ide>
<ide> config.action_mailer.perform_caching = true
<ide>
<del>#### Configure the output of `db:structure:dump`
<add>#### Configure the Output of `db:structure:dump`
<ide>
<ide> If you're using `schema_search_path` or other PostgreSQL extentions, you can control how the schema is
<ide> dumped. Set to `:all` to generate all dumps, or `:schema_search_path` to generate from schema search path.
<ide>
<ide> config.active_record.dump_schemas = :all
<ide>
<del>#### Configure SSL options to enable HSTS with subdomains
<add>#### Configure SSL Options to Enable HSTS with Subdomains
<ide>
<ide> Set the following in your config to enable HSTS when using subdomains.
<ide>
<ide> config.ssl_options = { hsts: { subdomains: true } }
<ide>
<del>#### Preserve timezone of the receiver
<add>#### Preserve Timezone of the Receiver
<ide>
<ide> When using Ruby 2.4 you can preserve the timezone of the receiver when calling `to_time`.
<ide> | 1 |
Javascript | Javascript | remove debug code | 9166f852858c79bec6441ff797f92fa96f36df39 | <ide><path>lib/child_process_uv.js
<ide> var spawn = exports.spawn = function(file, args, options) {
<ide>
<ide>
<ide> function maybeExit(subprocess) {
<del> console.log("maybeExit");
<ide> subprocess._closesGot++;
<ide>
<ide> if (subprocess._closesGot == subprocess._closesNeeded) {
<ide> function ChildProcess() {
<ide> if (signalCode) self.signalCode = signalCode;
<ide> self.exitCode = exitCode;
<ide>
<del> console.error("onexit ", exitCode, signalCode);
<del>
<ide> if (self.stdin) {
<ide> self.stdin.destroy();
<ide> }
<ide> ChildProcess.prototype.spawn = function(options) {
<ide>
<ide> this.pid = this._internal.pid;
<ide>
<del> console.log("started pid ", this.pid);
<del>
<ide> if (options.stdinStream) {
<ide> this.stdin = createSocket(options.stdinStream, false);
<ide> } | 1 |
Ruby | Ruby | add more examples to collectionproxy#find | e0859e569c007cd108797883eec402c876b9e8a0 | <ide><path>activerecord/lib/active_record/associations/collection_proxy.rb
<ide> class CollectionProxy < Relation
<ide> #
<ide> # person.pets.find(1) # => #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>
<ide> # person.pets.find(4) # => ActiveRecord::RecordNotFound: Couldn't find Pet with id=4
<add> #
<add> # person.pets.find(2) { |pet| pet.name.downcase! }
<add> # # => #<Pet id: 2, name: "fancy-fancy", person_id: 1>
<add> #
<add> # person.pets.find(2, 3)
<add> # # => [
<add> # # #<Pet id: 2, name: "Spook", person_id: 1>,
<add> # # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
<add> # # ]
<ide>
<ide> ##
<ide> # :method: first | 1 |
Go | Go | fix panic with wrong dockercfg file | 649605915428e0ee81cf49d15e949d48da20110c | <ide><path>auth/auth.go
<ide> func LoadConfig(rootPath string) (*ConfigFile, error) {
<ide> }
<ide> authConfig := AuthConfig{}
<ide> origAuth := strings.Split(arr[0], " = ")
<add> if len(origAuth) != 2 {
<add> return &configFile, fmt.Errorf("Invalid Auth config file")
<add> }
<ide> authConfig.Username, authConfig.Password, err = decodeAuth(origAuth[1])
<ide> if err != nil {
<ide> return &configFile, err
<ide> }
<ide> origEmail := strings.Split(arr[1], " = ")
<add> if len(origEmail) != 2 {
<add> return &configFile, fmt.Errorf("Invalid Auth config file")
<add> }
<ide> authConfig.Email = origEmail[1]
<ide> authConfig.ServerAddress = IndexServerAddress()
<ide> configFile.Configs[IndexServerAddress()] = authConfig | 1 |
PHP | PHP | fix failing tests | 17737e307f9ec940c6998f3ee711dd127b62137d | <ide><path>tests/TestCase/Console/CommandTest.php
<ide> public function testRunOptionParserFailure()
<ide>
<ide> $messages = implode("\n", $output->messages());
<ide> $this->assertStringContainsString(
<del> 'Error: Missing required arguments. The `name` argument is required',
<add> 'Error: Missing required argument. The `name` argument is required',
<ide> $messages
<ide> );
<ide> }
<ide><path>tests/TestCase/Console/HelpFormatterTest.php
<ide> public function testXmlHelpWithChoices()
<ide> <description />
<ide> <subcommands />
<ide> <options>
<del> <option name="--help" short="-h" help="Display this help." boolean="1">
<add> <option name="--help" short="-h" help="Display this help." boolean="1" required="0">
<ide> <default>false</default>
<ide> <choices></choices>
<ide> </option>
<del> <option name="--test" short="" help="A test option." boolean="0">
<add> <option name="--test" short="" help="A test option." boolean="0" required="0">
<ide> <default></default>
<ide> <choices>
<ide> <choice>one</choice>
<ide> public function testXmlHelpDescriptionAndEpilog()
<ide> <description>Description text</description>
<ide> <subcommands />
<ide> <options>
<del> <option name="--help" short="-h" help="Display this help." boolean="1">
<add> <option name="--help" short="-h" help="Display this help." boolean="1" required="0">
<ide> <default>false</default>
<ide> <choices></choices>
<ide> </option>
<del> <option name="--test" short="" help="A test option." boolean="0">
<add> <option name="--test" short="" help="A test option." boolean="0" required="0">
<ide> <default></default>
<ide> <choices></choices>
<ide> </option>
<ide> public function testXmlHelpSubcommand()
<ide> <command name="method" help="This is another command" />
<ide> </subcommands>
<ide> <options>
<del> <option name="--help" short="-h" help="Display this help." boolean="1">
<add> <option name="--help" short="-h" help="Display this help." boolean="1" required="0">
<ide> <default>false</default>
<ide> <choices></choices>
<ide> </option>
<del> <option name="--test" short="" help="A test option." boolean="0">
<add> <option name="--test" short="" help="A test option." boolean="0" required="0">
<ide> <default></default>
<ide> <choices></choices>
<ide> </option>
<ide> public function testXmlHelpWithOptions()
<ide> <description/>
<ide> <subcommands/>
<ide> <options>
<del> <option name="--connection" short="-c" help="The connection to use." boolean="0">
<add> <option name="--connection" short="-c" help="The connection to use." boolean="0" required="0">
<ide> <default>default</default>
<ide> <choices></choices>
<ide> </option>
<del> <option name="--help" short="-h" help="Display this help." boolean="1">
<add> <option name="--help" short="-h" help="Display this help." boolean="1" required="0">
<ide> <default>false</default>
<ide> <choices></choices>
<ide> </option>
<del> <option name="--test" short="" help="A test option." boolean="0">
<add> <option name="--test" short="" help="A test option." boolean="0" required="0">
<ide> <default></default>
<ide> <choices></choices>
<ide> </option>
<ide> public function testXmlHelpWithOptionsAndArguments()
<ide> <description/>
<ide> <subcommands/>
<ide> <options>
<del> <option name="--help" short="-h" help="Display this help." boolean="1">
<add> <option name="--help" short="-h" help="Display this help." boolean="1" required="0">
<ide> <default>false</default>
<ide> <choices></choices>
<ide> </option>
<del> <option name="--test" short="" help="A test option." boolean="0">
<add> <option name="--test" short="" help="A test option." boolean="0" required="0">
<ide> <default></default>
<ide> <choices></choices>
<ide> </option> | 2 |
Javascript | Javascript | provide contextual error messages | d804bbcd51ec83bee1f4a3ccd42c3bd7eb38a988 | <ide><path>src/ng/interpolate.js
<ide> function $InterpolateProvider() {
<ide> };
<ide>
<ide>
<del> this.$get = ['$parse', function($parse) {
<add> this.$get = ['$parse', '$exceptionHandler', function($parse, $exceptionHandler) {
<ide> var startSymbolLength = startSymbol.length,
<ide> endSymbolLength = endSymbol.length;
<ide>
<ide> function $InterpolateProvider() {
<ide> if (!mustHaveExpression || hasInterpolation) {
<ide> concat.length = length;
<ide> fn = function(context) {
<del> for(var i = 0, ii = length, part; i<ii; i++) {
<del> if (typeof (part = parts[i]) == 'function') {
<del> part = part(context);
<del> if (part == null || part == undefined) {
<del> part = '';
<del> } else if (typeof part != 'string') {
<del> part = toJson(part);
<add> try {
<add> for(var i = 0, ii = length, part; i<ii; i++) {
<add> if (typeof (part = parts[i]) == 'function') {
<add> part = part(context);
<add> if (part == null || part == undefined) {
<add> part = '';
<add> } else if (typeof part != 'string') {
<add> part = toJson(part);
<add> }
<ide> }
<add> concat[i] = part;
<ide> }
<del> concat[i] = part;
<add> return concat.join('');
<add> }
<add> catch(err) {
<add> var newErr = new Error('Error while interpolating: ' + text + '\n' + err.toString());
<add> $exceptionHandler(newErr);
<ide> }
<del> return concat.join('');
<ide> };
<ide> fn.exp = text;
<ide> fn.parts = parts;
<ide><path>test/BinderSpec.js
<ide> describe('Binder', function() {
<ide> $rootScope.error['throw'] = function() {throw 'MyError';};
<ide> errorLogs.length = 0;
<ide> $rootScope.$apply();
<del> expect(errorLogs.shift()).toBe('MyError');
<add> expect(errorLogs.shift().message).toBe('Error while interpolating: {{error.throw()}}\nMyError');
<ide>
<ide> $rootScope.error['throw'] = function() {return 'ok';};
<ide> $rootScope.$apply();
<ide><path>test/ng/interpolateSpec.js
<ide> describe('$interpolate', function() {
<ide> expect($interpolate('{{ false }}')()).toEqual('false');
<ide> }));
<ide>
<add> it('should rethrow exceptions', inject(function($interpolate, $rootScope) {
<add> $rootScope.err = function () {
<add> throw new Error('oops');
<add> };
<add> expect(function () {
<add> $interpolate('{{err()}}')($rootScope);
<add> }).toThrow('Error while interpolating: {{err()}}\nError: oops');
<add> }));
<add>
<add> it('should stop interpolation when encountering an exception', inject(function($interpolate, $compile, $rootScope) {
<add> $rootScope.err = function () {
<add> throw new Error('oops');
<add> };
<add> var dom = jqLite('<div>{{1 + 1}}</div><div>{{err()}}</div><div>{{1 + 2}}</div>');
<add> $compile(dom)($rootScope);
<add> expect(function () {
<add> $rootScope.$apply();
<add> }).toThrow('Error while interpolating: {{err()}}\nError: oops');
<add> expect(dom[0].innerHTML).toEqual('2');
<add> expect(dom[1].innerHTML).toEqual('{{err()}}');
<add> expect(dom[2].innerHTML).toEqual('{{1 + 2}}');
<add> }));
<add>
<ide>
<ide> it('should return interpolation function', inject(function($interpolate, $rootScope) {
<ide> $rootScope.name = 'Misko'; | 3 |
Javascript | Javascript | remove usage of three.imageutils.loadtexture | 1a85493265460fb2db69da259ed841d0d2faa829 | <ide><path>examples/js/loaders/AssimpLoader.js
<ide> path = path.substr( path.lastIndexOf( "/" ) + 1 );
<ide>
<ide> }
<del>
<del> return THREE.ImageUtils.loadTexture( baseURL + path );
<add> return ( new TextureLoader() ).load( baseURL + path );
<ide>
<ide> };
<ide>
<ide>
<ide> THREE.AssimpLoader = AssimpLoader;
<ide>
<del>} )();
<ide>\ No newline at end of file
<add>} )(); | 1 |
Python | Python | remove useless super delegation | ba6f4945858bdf02bf10fc833430fb77894693db | <ide><path>keras/callbacks.py
<ide> class TerminateOnNaN(Callback):
<ide> """Callback that terminates training when a NaN loss is encountered.
<ide> """
<ide>
<del> def __init__(self):
<del> super(TerminateOnNaN, self).__init__()
<del>
<ide> def on_batch_end(self, batch, logs=None):
<ide> logs = logs or {}
<ide> loss = logs.get('loss') | 1 |
Javascript | Javascript | fix additional spacing issues | 5db725d82c6ebfa0a8f89d76af804f37059fad7d | <ide><path>seed/bonfireMDNlinks.js
<ide> *
<ide> **/
<ide>
<del>var links =
<del> {
<add>var links = {
<ide> // ========= NON MDN REFS
<ide> "Currying": "https://leanpub.com/javascript-allonge/read#pabc",
<ide> "Smallest Common Multiple": "https://www.mathsisfun.com/least-common-multiple.html",
<ide> var links =
<ide> "Roman Numerals": "http://www.mathsisfun.com/roman-numerals.html",
<ide>
<ide> // ========= GLOBAL OBJECTS
<del> "Global Array Object" : "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array",
<del> "Global Object" : "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object",
<del> "Global String Object" : "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String",
<del> "Boolean Objects" : "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean",
<del> "RegExp" : "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp",
<add> "Global Array Object": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array",
<add> "Global Object": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object",
<add> "Global String Object": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String",
<add> "Boolean Objects": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean",
<add> "RegExp": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp",
<ide> "Global Function Object": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function",
<del> "Arguments object" : "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments",
<add> "Arguments object": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments",
<ide> "Closures": "https://developer.mozilla.org/en-US/docs/" +
<ide> "Web/JavaScript/Closures",
<ide>
<ide> // ========= GLOBAL OBJECT METHODS
<del> "parseInt()" : "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt",
<add> "parseInt()": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt",
<ide>
<ide>
<ide> // ========= PROPERTIES/MISC
<del> "String.length" : "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length",
<add> "String.length": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length",
<ide>
<ide>
<ide> // ========== OBJECT METHODS
<del> "Object.getOwnPropertyNames()" : "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames",
<del> "Object.keys()" : "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys",
<del> "Object.hasOwnProperty()" : "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty",
<add> "Object.getOwnPropertyNames()": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames",
<add> "Object.keys()": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys",
<add> "Object.hasOwnProperty()": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty",
<ide>
<ide>
<ide> // ======== STRING METHODS
<del> "String.charAt()" : "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charAt",
<del> "String.charCodeAt()" : "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charCodeAt",
<del> "String.concat()" : "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/concat",
<del> "String.indexOf()" : "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf",
<del> "String.fromCharCode()" : "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCharCode",
<del> "String.lastIndexOf()" : "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf",
<del> "String.match()" : "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match",
<del> "String.replace()" : "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace",
<del> "String.slice()" : "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice",
<del> "String.split()" : "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split",
<del> "String.substring()" : "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring",
<del> "String.substr()" : "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr",
<del> "String.toLowerCase()" : "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase",
<del> "String.toString()" : "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toString",
<del> "String.toUpperCase()" : "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase",
<add> "String.charAt()": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charAt",
<add> "String.charCodeAt()": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charCodeAt",
<add> "String.concat()": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/concat",
<add> "String.indexOf()": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf",
<add> "String.fromCharCode()": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCharCode",
<add> "String.lastIndexOf()": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf",
<add> "String.match()": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match",
<add> "String.replace()": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace",
<add> "String.slice()": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice",
<add> "String.split()": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split",
<add> "String.substring()": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring",
<add> "String.substr()": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr",
<add> "String.toLowerCase()": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase",
<add> "String.toString()": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toString",
<add> "String.toUpperCase()": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase",
<ide>
<ide> // ======== ARRAY METHODS
<del> "Array.concat()" : "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat",
<del> "Array.every()" : "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every",
<add> "Array.concat()": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat",
<add> "Array.every()": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every",
<ide> "Array.filter()": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter",
<del> "Array.forEach()" : "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach",
<del> "Array.indexOf()" : "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf",
<del> "Array.isArray()" : "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray",
<del> "Array.join()" : "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join",
<del> "Array.lastIndexOf()" : "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/lastIndexOf",
<del> "Array.map()" : "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map",
<del> "Array.pop()" : "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop",
<del> "Array.push()" : "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push",
<del> "Array.reduce()" : "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce",
<add> "Array.forEach()": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach",
<add> "Array.indexOf()": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf",
<add> "Array.isArray()": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray",
<add> "Array.join()": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join",
<add> "Array.lastIndexOf()": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/lastIndexOf",
<add> "Array.map()": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map",
<add> "Array.pop()": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop",
<add> "Array.push()": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push",
<add> "Array.reduce()": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce",
<ide> "Array.reverse()": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse",
<del> "Array.shift()" : "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift",
<del> "Array.slice()" : "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice",
<del> "Array.some()" : "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some",
<del> "Array.sort()" : "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort",
<del> "Array.splice()" : "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice",
<del> "Array.toString()" : "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toString",
<add> "Array.shift()": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift",
<add> "Array.slice()": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice",
<add> "Array.some()": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some",
<add> "Array.sort()": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort",
<add> "Array.splice()": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice",
<add> "Array.toString()": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toString",
<ide>
<ide> // ======== MATH METHODS
<del> "Math.max()" : "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max",
<del> "Math.min()" : "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/min",
<del> "Math.pow()" : "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/pow",
<del> "Remainder" : "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Remainder_(.25)",
<add> "Math.max()": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max",
<add> "Math.min()": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/min",
<add> "Math.pow()": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/pow",
<add> "Remainder": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Remainder_(.25)",
<ide>
<ide> // ======== GENERAL JAVASCRIPT REFERENCES
<del> "Arithmetic Operators" : "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators",
<del> "Comparison Operators" : "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators",
<del> "Details of the Object Model" : "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Details_of_the_Object_Model",
<add> "Arithmetic Operators": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators",
<add> "Comparison Operators": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators",
<add> "Details of the Object Model": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Details_of_the_Object_Model",
<ide> "For Loops": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for"
<del> };
<add>};
<ide>
<ide> module.exports = links; | 1 |
PHP | PHP | update the doc links | e55927c007f26f9f04cfada11c32def0365872c7 | <ide><path>lib/Cake/Utility/Hash.php
<ide> public static function remove(array $data, $path) {
<ide> * @param string $valuePath A dot-separated string.
<ide> * @param string $groupPath A dot-separated string.
<ide> * @return array Combined array
<del> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/set.html#Set::combine
<add> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::combine
<ide> */
<ide> public static function combine(array $data, $keyPath, $valuePath = null, $groupPath = null) {
<ide> if (empty($data)) {
<ide> public static function combine(array $data, $keyPath, $valuePath = null, $groupP
<ide> * @param string $paths An array containing one or more Hash::extract()-style key paths
<ide> * @param string $format Format string into which values will be inserted, see sprintf()
<ide> * @return array An array of strings extracted from `$path` and formatted with `$format`
<del> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/set.html#Set::format
<add> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::format
<ide> * @see sprintf()
<ide> * @see Hash::extract()
<ide> */
<ide> public static function format(array $data, array $paths, $format) {
<ide> * @param array $data The data to search through.
<ide> * @param array $needle The values to file in $data
<ide> * @return boolean true if $data contains $needle, false otherwise
<del> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/set.html#Set::contains
<add> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::contains
<ide> */
<ide> public static function contains(array $data, array $needle) {
<ide> if (empty($data) || empty($needle)) {
<ide> public static function check(array $data, $path) {
<ide> * @param callable $callback A function to filter the data with. Defaults to
<ide> * `self::_filter()` Which strips out all non-zero empty values.
<ide> * @return array Filtered array
<del> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/set.html#Set::filter
<add> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::filter
<ide> */
<ide> public static function filter(array $data, $callback = array('self', '_filter')) {
<ide> foreach ($data as $k => $v) {
<ide> protected static function _filter($var) {
<ide> * @param array $data Array to flatten
<ide> * @param string $separator String used to separate array key elements in a path, defaults to '.'
<ide> * @return array
<del> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/set.html#Set::flatten
<add> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::flatten
<ide> */
<ide> public static function flatten(array $data, $separator = '.') {
<ide> $result = array();
<ide> public static function flatten(array $data, $separator = '.') {
<ide> * @param array $data Array to be merged
<ide> * @param mixed $merge Array to merge with. The argument and all trailing arguments will be array cast when merged
<ide> * @return array Merged array
<del> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/set.html#Set::merge
<add> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::merge
<ide> */
<ide> public static function merge(array $data, $merge) {
<ide> $args = func_get_args();
<ide> public static function merge(array $data, $merge) {
<ide> *
<ide> * @param array $array The array to check.
<ide> * @return boolean true if values are numeric, false otherwise
<del> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/set.html#Set::numeric
<add> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::numeric
<ide> */
<ide> public static function numeric(array $data) {
<ide> if (empty($data)) {
<ide> public static function numeric(array $data) {
<ide> *
<ide> * @param array $array Array to count dimensions on
<ide> * @return integer The number of dimensions in $data
<del> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/set.html#Set::countDim
<add> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::dimensions
<ide> */
<ide> public static function dimensions(array $data) {
<ide> if (empty($data)) {
<ide> public static function dimensions(array $data) {
<ide> *
<ide> * @param array $data Array to count dimensions on
<ide> * @return integer The maximum number of dimensions in $data
<del> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/set.html#Set::countDim
<add> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::maxDimensions
<ide> */
<ide> public static function maxDimensions(array $data) {
<ide> $depth = array();
<ide> public static function apply(array $data, $path, $function) {
<ide> * @param string $path A Set-compatible path to the array value
<ide> * @param string $dir Direction of sorting - either ascending (ASC), or descending (DESC)
<ide> * @return array Sorted array of data
<del> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/set.html#Set::sort
<add> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::sort
<ide> */
<ide> public static function sort(array $data, $path, $dir) {
<ide> $originalKeys = array_keys($data);
<ide> protected static function _squash($data, $key = null) {
<ide> * @param mixed $compare Second value
<ide> * @return array Returns the key => value pairs that are not common in $data and $compare
<ide> * The expression for this function is ($data - $compare) + ($compare - ($data - $compare))
<del> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/set.html#Set::diff
<add> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::diff
<ide> */
<ide> public static function diff(array $data, $compare) {
<ide> if (empty($data)) {
<ide> public static function mergeDiff(array $data, $compare) {
<ide> * @param mixed $data List to normalize
<ide> * @param boolean $assoc If true, $data will be converted to an associative array.
<ide> * @return array
<del> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/set.html#Set::normalize
<add> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::normalize
<ide> */
<ide> public static function normalize(array $data, $assoc = true) {
<ide> $keys = array_keys($data); | 1 |
PHP | PHP | reduce method calls | b98cf473a35d5d0ea822ae5f0f6721ce2d22f6e1 | <ide><path>src/Auth/BaseAuthenticate.php
<ide> protected function _findUser($username, $password = null)
<ide> $this->_needsPasswordRehash = $hasher->needsRehash($hashedPassword);
<ide> $result->unsetProperty($passwordField);
<ide> }
<del> if ($password === null && in_array($passwordField, $result->getHidden())) {
<del> $hidden = $result->getHidden();
<add> $hidden = $result->getHidden();
<add> if ($password === null && in_array($passwordField, $hidden)) {
<ide> $key = array_search($passwordField, $hidden);
<ide> unset($hidden[$key]);
<ide> $result->setHidden($hidden); | 1 |
Python | Python | remove labels from the ragmodel example | 95f792afb0f0ce5a7b4f0e8df108b10157a69134 | <ide><path>src/transformers/modeling_rag.py
<ide> def forward(
<ide>
<ide> >>> input_dict = tokenizer.prepare_seq2seq_batch("How many people live in Paris?", "In Paris, there are 10 million people.", return_tensors="pt")
<ide> >>> input_ids = input_dict["input_ids"]
<del> >>> outputs = model(input_ids=input_ids, labels=input_dict["labels"])
<add> >>> outputs = model(input_ids=input_ids)
<ide>
<ide> """
<ide> use_cache = use_cache if use_cache is not None else self.config.use_cache | 1 |
Python | Python | remove unneeded parentheses after black formatting | 6f0cf3f72480cb94cc8bdb361c44a2130c77d731 | <ide><path>airflow/cli/cli_parser.py
<ide> def positive_int(value):
<ide> )
<ide> ARG_SAVE_DAGRUN = Arg(
<ide> ("--save-dagrun",),
<del> help=("After completing the backfill, saves the diagram for current DAG Run to the indicated file.\n\n"),
<add> help="After completing the backfill, saves the diagram for current DAG Run to the indicated file.\n\n",
<ide> )
<ide>
<ide> # list_tasks
<ide> def positive_int(value):
<ide> # show_dag
<ide> ARG_SAVE = Arg(("-s", "--save"), help="Saves the result to the indicated file.")
<ide>
<del>ARG_IMGCAT = Arg(("--imgcat",), help=("Displays graph using the imgcat tool."), action='store_true')
<add>ARG_IMGCAT = Arg(("--imgcat",), help="Displays graph using the imgcat tool.", action='store_true')
<ide>
<ide> # trigger_dag
<ide> ARG_RUN_ID = Arg(("-r", "--run-id"), help="Helps to identify this run")
<ide> def positive_int(value):
<ide> )
<ide> ARG_CELERY_HOSTNAME = Arg(
<ide> ("-H", "--celery-hostname"),
<del> help=("Set the hostname of celery worker if you have multiple workers on a single machine"),
<add> help="Set the hostname of celery worker if you have multiple workers on a single machine",
<ide> )
<ide> ARG_UMASK = Arg(
<ide> ("-u", "--umask"),
<ide> def positive_int(value):
<ide> action='store_true',
<ide> )
<ide> ARG_FILE_IO = Arg(
<del> ('--file-io',), help=('Send output to file.io service and returns link.'), action='store_true'
<add> ('--file-io',), help='Send output to file.io service and returns link.', action='store_true'
<ide> )
<ide>
<ide> # config
<ide> class GroupCommand(NamedTuple):
<ide> ActionCommand(
<ide> name="check-migrations",
<ide> help="Check if migration have finished",
<del> description=("Check if migration have finished (or continually check until timeout)"),
<add> description="Check if migration have finished (or continually check until timeout)",
<ide> func=lazy_load_command('airflow.cli.commands.db_command.check_migrations'),
<ide> args=(ARG_MIGRATION_TIMEOUT,),
<ide> ), | 1 |
Javascript | Javascript | resolve all of nothing to nothing | ac75079e2113949d5d64adbcf23d56f3cf295d41 | <ide><path>src/service/q.js
<ide> function qFactory(nextTick, exceptionHandler) {
<ide> counter = promises.length,
<ide> results = [];
<ide>
<del> forEach(promises, function(promise, index) {
<del> promise.then(function(value) {
<del> if (index in results) return;
<del> results[index] = value;
<del> if (!(--counter)) deferred.resolve(results);
<del> }, function(reason) {
<del> if (index in results) return;
<del> deferred.reject(reason);
<add> if (counter) {
<add> forEach(promises, function(promise, index) {
<add> ref(promise).then(function(value) {
<add> if (index in results) return;
<add> results[index] = value;
<add> if (!(--counter)) deferred.resolve(results);
<add> }, function(reason) {
<add> if (index in results) return;
<add> deferred.reject(reason);
<add> });
<ide> });
<del> });
<add> } else {
<add> deferred.resolve(results);
<add> }
<ide>
<ide> return deferred.promise;
<ide> }
<ide><path>test/service/qSpec.js
<ide> describe('q', function() {
<ide>
<ide>
<ide> describe('all', function() {
<add> it('should resolve all of nothing', function() {
<add> var result;
<add> q.all([]).then(function(r) { result = r; });
<add> mockNextTick.flush();
<add> expect(result).toEqual([]);
<add> });
<add>
<add>
<ide> it('should take an array of promises and return a promise for an array of results', function() {
<ide> var deferred1 = defer(),
<ide> deferred2 = defer(); | 2 |
Javascript | Javascript | convert callbackqueue to a class | a70acb37d9dc392b395bd921d90d5488542c2402 | <ide><path>src/renderers/shared/stack/event/ReactSyntheticEvent.js
<ide> export type DispatchConfig = any;
<ide>
<ide> export class ReactSyntheticEvent extends SyntheticEvent {
<ide> dispatchConfig: DispatchConfig;
<del>};
<add>}
<ide><path>src/renderers/shared/utils/CallbackQueue.js
<ide> var invariant = require('invariant');
<ide> * @implements PooledClass
<ide> * @internal
<ide> */
<del>function CallbackQueue() {
<del> this._callbacks = null;
<del> this._contexts = null;
<del>}
<add>class CallbackQueue<T> {
<add> _callbacks: ?Array<() => void>;
<add> _contexts: ?Array<T>;
<ide>
<del>Object.assign(CallbackQueue.prototype, {
<add> constructor() {
<add> this._callbacks = null;
<add> this._contexts = null;
<add> }
<ide>
<ide> /**
<ide> * Enqueues a callback to be invoked when `notifyAll` is invoked.
<ide> Object.assign(CallbackQueue.prototype, {
<ide> * @param {?object} context Context to call `callback` with.
<ide> * @internal
<ide> */
<del> enqueue: function(callback, context) {
<add> enqueue(callback: () => void, context: T) {
<ide> this._callbacks = this._callbacks || [];
<del> this._contexts = this._contexts || [];
<ide> this._callbacks.push(callback);
<add> this._contexts = this._contexts || [];
<ide> this._contexts.push(context);
<del> },
<add> }
<ide>
<ide> /**
<ide> * Invokes all enqueued callbacks and clears the queue. This is invoked after
<ide> * the DOM representation of a component has been created or updated.
<ide> *
<ide> * @internal
<ide> */
<del> notifyAll: function() {
<add> notifyAll() {
<ide> var callbacks = this._callbacks;
<ide> var contexts = this._contexts;
<del> if (callbacks) {
<add> if (callbacks && contexts) {
<ide> invariant(
<ide> callbacks.length === contexts.length,
<ide> 'Mismatched list of contexts in callback queue'
<ide> Object.assign(CallbackQueue.prototype, {
<ide> callbacks.length = 0;
<ide> contexts.length = 0;
<ide> }
<del> },
<add> }
<ide>
<del> checkpoint: function() {
<add> checkpoint() {
<ide> return this._callbacks ? this._callbacks.length : 0;
<del> },
<add> }
<ide>
<del> rollback: function(len) {
<del> if (this._callbacks) {
<add> rollback(len: number) {
<add> if (this._callbacks && this._contexts) {
<ide> this._callbacks.length = len;
<ide> this._contexts.length = len;
<ide> }
<del> },
<add> }
<ide>
<ide> /**
<ide> * Resets the internal queue.
<ide> *
<ide> * @internal
<ide> */
<del> reset: function() {
<add> reset() {
<ide> this._callbacks = null;
<ide> this._contexts = null;
<del> },
<add> }
<ide>
<ide> /**
<ide> * `PooledClass` looks for this.
<ide> */
<del> destructor: function() {
<add> destructor() {
<ide> this.reset();
<del> },
<del>
<del>});
<add> }
<add>}
<ide>
<ide> module.exports = PooledClass.addPoolingTo(CallbackQueue); | 2 |
Ruby | Ruby | remove unnecessary condition in content_type | f091bd67b3ef5f4cd85dbd70cbd11e9ad2711562 | <ide><path>actionmailer/lib/action_mailer/base.rb
<ide> def collect_responses(headers)
<ide> def collect_responses_from_text(headers)
<ide> [{
<ide> body: headers.delete(:body),
<del> content_type: headers[:content_type] || self.class.default[:content_type] || "text/plain"
<add> content_type: headers[:content_type] || "text/plain"
<ide> }]
<ide> end
<ide> | 1 |
Ruby | Ruby | add caller to deprecation notices | 54302ef55bffd1a93f20f5d1ae81217b2e4149c4 | <ide><path>actionpack/lib/action_controller/metal/compatibility.rb
<ide> def self.deprecated_config_reader(option, message = nil)
<ide>
<ide> ClassMethods.class_eval <<-RUBY, __FILE__, __LINE__ + 1
<ide> def #{option}
<del> ActiveSupport::Deprecation.warn #{message.inspect}
<add> ActiveSupport::Deprecation.warn #{message.inspect}, caller
<ide> config.#{option}
<ide> end
<ide> RUBY
<ide> def self.deprecated_config_writer(option, message = nil)
<ide>
<ide> ClassMethods.class_eval <<-RUBY, __FILE__, __LINE__ + 1
<ide> def #{option}=(val)
<del> ActiveSupport::Deprecation.warn #{message.inspect}
<add> ActiveSupport::Deprecation.warn #{message.inspect}, caller
<ide> config.#{option} = val
<ide> end
<ide> RUBY
<ide> def process_action(*)
<ide> module ClassMethods
<ide> def consider_all_requests_local
<ide> ActiveSupport::Deprecation.warn "ActionController::Base.consider_all_requests_local is deprecated, " <<
<del> "use Rails.application.config.consider_all_requests_local instead"
<add> "use Rails.application.config.consider_all_requests_local instead", caller
<ide> Rails.application.config.consider_all_requests_local
<ide> end
<ide>
<ide> def consider_all_requests_local=(value)
<ide> ActiveSupport::Deprecation.warn "ActionController::Base.consider_all_requests_local= is deprecated. " <<
<del> "Please configure it on your application with config.consider_all_requests_local="
<add> "Please configure it on your application with config.consider_all_requests_local=", caller
<ide> Rails.application.config.consider_all_requests_local = value
<ide> end
<ide>
<ide> def allow_concurrency
<ide> ActiveSupport::Deprecation.warn "ActionController::Base.allow_concurrency is deprecated, " <<
<del> "use Rails.application.config.allow_concurrency instead"
<add> "use Rails.application.config.allow_concurrency instead", caller
<ide> Rails.application.config.allow_concurrency
<ide> end
<ide>
<ide> def allow_concurrency=(value)
<ide> ActiveSupport::Deprecation.warn "ActionController::Base.allow_concurrency= is deprecated. " <<
<del> "Please configure it on your application with config.allow_concurrency="
<add> "Please configure it on your application with config.allow_concurrency=", caller
<ide> Rails.application.config.allow_concurrency = value
<ide> end
<ide>
<ide> def ip_spoofing_check=(value)
<ide> ActiveSupport::Deprecation.warn "ActionController::Base.ip_spoofing_check= is deprecated. " <<
<del> "Please configure it on your application with config.action_dispatch.ip_spoofing_check="
<add> "Please configure it on your application with config.action_dispatch.ip_spoofing_check=", caller
<ide> Rails.application.config.action_disaptch.ip_spoofing_check = value
<ide> end
<ide>
<ide> def ip_spoofing_check
<del> ActiveSupport::Deprecation.warn "ActionController::Base.ip_spoofing_check is deprecated. "
<del> "Configuring ip_spoofing_check on the application configures a middleware."
<add> ActiveSupport::Deprecation.warn "ActionController::Base.ip_spoofing_check is deprecated. " <<
<add> "Configuring ip_spoofing_check on the application configures a middleware.", caller
<ide> Rails.application.config.action_disaptch.ip_spoofing_check
<ide> end
<ide>
<ide> def trusted_proxies=(value)
<ide> ActiveSupport::Deprecation.warn "ActionController::Base.trusted_proxies= is deprecated. " <<
<del> "Please configure it on your application with config.action_dispatch.trusted_proxies="
<add> "Please configure it on your application with config.action_dispatch.trusted_proxies=", caller
<ide> Rails.application.config.action_dispatch.ip_spoofing_check = value
<ide> end
<ide>
<ide> def trusted_proxies
<ide> ActiveSupport::Deprecation.warn "ActionController::Base.trusted_proxies is deprecated. " <<
<del> "Configuring trusted_proxies on the application configures a middleware."
<add> "Configuring trusted_proxies on the application configures a middleware.", caller
<ide> Rails.application.config.action_dispatch.ip_spoofing_check = value
<ide> end
<ide> | 1 |
PHP | PHP | implement strict subcommands | 7ab75a901518297dad56c95430dd3eaf33d1751b | <ide><path>src/Console/ConsoleOptionParser.php
<ide> <?php
<ide> /**
<del> * ConsoleOptionParser file
<del> *
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide> *
<ide><path>src/Console/Shell.php
<ide> public function dispatchShell() {
<ide> * If a shell implements a `main()` method, all missing method calls will be sent to
<ide> * `main()` with the original method name in the argv.
<ide> *
<add> * For tasks to be invoked they *must* be exposed as subcommands. If you define any subcommands,
<add> * you must define all the subcommands your shell needs, whether they be methods on this class
<add> * or methods on tasks.
<add> *
<ide> * @param string $command The command name to run on this shell. If this argument is empty,
<ide> * and the shell has a `main()` method, that will be called instead.
<ide> * @param array $argv Array of arguments to run the shell with. This array should be missing the shell name.
<ide> * @return void
<ide> * @link http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::runCommand
<ide> */
<ide> public function runCommand($command, $argv) {
<del> $isTask = $this->hasTask($command);
<del> $isMethod = $this->hasMethod($command);
<del> $isMain = $this->hasMethod('main');
<del>
<del> if ($isTask || $isMethod && $command !== 'execute') {
<del> array_shift($argv);
<del> }
<ide>
<ide> $this->OptionParser = $this->getOptionParser();
<ide> try {
<ide> public function runCommand($command, $argv) {
<ide> return $this->_displayHelp($command);
<ide> }
<ide>
<del> if (($isTask || $isMethod || $isMain) && $command !== 'execute') {
<add> $subcommands = $this->OptionParser->subcommands();
<add>
<add> // Method when there are no subcommands.
<add> $isMethod = $this->hasMethod($command);
<add> if ($isMethod && count($subcommands) === 0) {
<add> array_shift($this->args);
<ide> $this->startup();
<add> return call_user_func_array([$this, $command], $this->args);
<ide> }
<ide>
<del> if ($isTask) {
<add> // Method when there is a subcommand
<add> if ($isMethod && isset($subcommands[$command])) {
<add> array_shift($this->args);
<add> $this->startup();
<add> return call_user_func_array([$this, $command], $this->args);
<add> }
<add>
<add> // Exposed task.
<add> if ($this->hasTask($command) && isset($subcommands[$command])) {
<add> array_shift($argv);
<add> $this->startup();
<ide> $command = Inflector::camelize($command);
<ide> return $this->{$command}->runCommand('execute', $argv);
<ide> }
<del> if ($isMethod) {
<del> return call_user_func_array([$this, $command], $this->args);
<del> }
<del> if ($isMain) {
<add>
<add> if ($this->hasMethod('main')) {
<add> $this->startup();
<ide> return call_user_func_array([$this, 'main'], $this->args);
<ide> }
<add>
<ide> $this->out($this->OptionParser->help($command));
<ide> return false;
<ide> }
<ide><path>tests/TestCase/Console/ShellTest.php
<ide> */
<ide> namespace Cake\Test\TestCase\Console;
<ide>
<add>use Cake\Console\ConsoleOptionParser;
<ide> use Cake\Console\Shell;
<ide> use Cake\Core\App;
<ide> use Cake\Core\Configure;
<ide> public function testHasMethod() {
<ide> */
<ide> public function testRunCommandMain() {
<ide> $io = $this->getMock('Cake\Console\ConsoleIo');
<del> $Mock = $this->getMock('Cake\Console\Shell', ['main', 'startup'], [$io]);
<add> $shell = $this->getMock('Cake\Console\Shell', ['main', 'startup'], [$io]);
<ide>
<del> $Mock->expects($this->once())->method('startup');
<del> $Mock->expects($this->once())->method('main')
<add> $shell->expects($this->once())->method('startup');
<add> $shell->expects($this->once())->method('main')
<ide> ->with('cakes')
<ide> ->will($this->returnValue(true));
<del> $result = $Mock->runCommand(null, ['cakes', '--verbose']);
<add> $result = $shell->runCommand('cakes', ['cakes', '--verbose']);
<ide> $this->assertTrue($result);
<ide> }
<ide>
<ide> /**
<del> * test run command calling a legit method.
<add> * test run command calling a real method with no subcommands defined.
<ide> *
<ide> * @return void
<ide> */
<ide> public function testRunCommandWithMethod() {
<ide> $io = $this->getMock('Cake\Console\ConsoleIo');
<del> $Mock = $this->getMock('Cake\Console\Shell', ['hit_me', 'startup'], [$io]);
<add> $shell = $this->getMock('Cake\Console\Shell', ['hit_me', 'startup'], [$io]);
<ide>
<del> $Mock->expects($this->once())->method('startup');
<del> $Mock->expects($this->once())->method('hit_me')
<add> $shell->expects($this->once())->method('startup');
<add> $shell->expects($this->once())->method('hit_me')
<ide> ->with('cakes')
<ide> ->will($this->returnValue(true));
<del> $result = $Mock->runCommand('hit_me', ['hit_me', 'cakes', '--verbose']);
<add> $result = $shell->runCommand('hit_me', ['hit_me', 'cakes', '--verbose']);
<ide> $this->assertTrue($result);
<ide> }
<ide>
<add>/**
<add> * test run command calling a real method with mismatching subcommands defined.
<add> *
<add> * @return void
<add> */
<add> public function testRunCommandWithMethodNotInSubcommands() {
<add> $parser = $this->getMock('Cake\Console\ConsoleOptionParser', ['help'], ['knife']);
<add> $io = $this->getMock('Cake\Console\ConsoleIo');
<add> $shell = $this->getMock('Cake\Console\Shell', ['getOptionParser', 'roll', 'startup'], [$io]);
<add>
<add> $parser->addSubCommand('slice');
<add>
<add> $shell->expects($this->any())
<add> ->method('getOptionParser')
<add> ->will($this->returnValue($parser));
<add>
<add> $parser->expects($this->once())
<add> ->method('help');
<add>
<add> $shell->expects($this->never())->method('startup');
<add> $shell->expects($this->never())->method('roll');
<add>
<add> $result = $shell->runCommand('roll', ['roll', 'cakes', '--verbose']);
<add> $this->assertFalse($result);
<add> }
<add>
<add>/**
<add> * test run command calling a real method with subcommands defined.
<add> *
<add> * @return void
<add> */
<add> public function testRunCommandWithMethodInSubcommands() {
<add> $parser = $this->getMock('Cake\Console\ConsoleOptionParser', ['help'], ['knife']);
<add> $io = $this->getMock('Cake\Console\ConsoleIo');
<add> $shell = $this->getMock('Cake\Console\Shell', ['getOptionParser', 'slice', 'startup'], [$io]);
<add>
<add> $parser->addSubCommand('slice');
<add>
<add> $shell->expects($this->any())
<add> ->method('getOptionParser')
<add> ->will($this->returnValue($parser));
<add>
<add> $shell->expects($this->once())->method('startup');
<add> $shell->expects($this->once())
<add> ->method('slice')
<add> ->with('cakes');
<add>
<add> $shell->runCommand('slice', ['slice', 'cakes', '--verbose']);
<add> }
<add>
<add>/**
<add> * test run command calling a missing method with subcommands defined.
<add> *
<add> * @return void
<add> */
<add> public function testRunCommandWithMissingMethodInSubcommands() {
<add> $parser = $this->getMock('Cake\Console\ConsoleOptionParser', ['help'], ['knife']);
<add> $parser->addSubCommand('slice');
<add>
<add> $io = $this->getMock('Cake\Console\ConsoleIo');
<add> $shell = $this->getMock('Cake\Console\Shell', ['getOptionParser', 'startup'], [$io]);
<add> $shell->expects($this->any())
<add> ->method('getOptionParser')
<add> ->will($this->returnValue($parser));
<add>
<add> $shell->expects($this->never())
<add> ->method('startup');
<add>
<add> $parser->expects($this->once())
<add> ->method('help');
<add>
<add> $shell->runCommand('slice', ['slice', 'cakes', '--verbose']);
<add> }
<add>
<ide> /**
<ide> * test run command causing exception on Shell method.
<ide> *
<ide> * @return void
<ide> */
<ide> public function testRunCommandBaseclassMethod() {
<del> $Mock = $this->getMock('Cake\Console\Shell', array('startup', 'getOptionParser', 'out'), array(), '', false);
<del> $Parser = $this->getMock('Cake\Console\ConsoleOptionParser', array(), array(), '', false);
<add> $shell = $this->getMock('Cake\Console\Shell', array('startup', 'getOptionParser', 'out'), array(), '', false);
<add> $parser = $this->getMock('Cake\Console\ConsoleOptionParser', array(), array(), '', false);
<ide>
<del> $Parser->expects($this->once())->method('help');
<del> $Mock->expects($this->once())->method('getOptionParser')
<del> ->will($this->returnValue($Parser));
<del> $Mock->expects($this->never())->method('hr');
<del> $Mock->expects($this->once())->method('out');
<add> $parser->expects($this->once())->method('help');
<add> $shell->expects($this->once())->method('getOptionParser')
<add> ->will($this->returnValue($parser));
<add> $shell->expects($this->never())->method('hr');
<add> $shell->expects($this->once())->method('out');
<ide>
<del> $Mock->runCommand('hr', array());
<add> $shell->runCommand('hr', array());
<ide> }
<ide>
<ide> /**
<ide> public function testRunCommandBaseclassMethod() {
<ide> * @return void
<ide> */
<ide> public function testRunCommandMissingMethod() {
<del> $Mock = $this->getMock('Cake\Console\Shell', array('startup', 'getOptionParser', 'out'), array(), '', false);
<del> $Parser = $this->getMock('Cake\Console\ConsoleOptionParser', array(), array(), '', false);
<add> $shell = $this->getMock('Cake\Console\Shell', array('startup', 'getOptionParser', 'out'), array(), '', false);
<add> $parser = $this->getMock('Cake\Console\ConsoleOptionParser', array(), array(), '', false);
<ide>
<del> $Parser->expects($this->once())->method('help');
<del> $Mock->expects($this->never())->method('idontexist');
<del> $Mock->expects($this->once())->method('getOptionParser')
<del> ->will($this->returnValue($Parser));
<del> $Mock->expects($this->once())->method('out');
<add> $parser->expects($this->once())->method('help');
<add> $shell->expects($this->once())->method('getOptionParser')
<add> ->will($this->returnValue($parser));
<add> $shell->expects($this->once())->method('out');
<ide>
<del> $result = $Mock->runCommand('idontexist', array());
<add> $result = $shell->runCommand('idontexist', array());
<ide> $this->assertFalse($result);
<ide> }
<ide>
<ide> public function testRunCommandTriggeringHelp() {
<ide> $Shell->runCommand(null, array('--help'));
<ide> }
<ide>
<add>/**
<add> * test that runCommand will not call runCommand on tasks that are not subcommands.
<add> *
<add> * @return void
<add> */
<add> public function testRunCommandNotCallUnexposedTask() {
<add> $shell = $this->getMock('Cake\Console\Shell', ['startup', 'hasTask', 'out'], [], '', false);
<add> $task = $this->getMock('Cake\Console\Shell', ['runCommand'], [], '', false);
<add>
<add> $task->expects($this->never())
<add> ->method('runCommand');
<add>
<add> $shell->expects($this->any())
<add> ->method('hasTask')
<add> ->will($this->returnValue(true));
<add> $shell->expects($this->never())->method('startup');
<add> $shell->expects($this->once())->method('out');
<add> $shell->RunCommand = $task;
<add>
<add> $result = $shell->runCommand('run_command', ['run_command', 'one']);
<add> $this->assertFalse($result);
<add> }
<add>
<ide> /**
<ide> * test that runCommand will call runCommand on the task.
<ide> *
<ide> * @return void
<ide> */
<del> public function testRunCommandHittingTask() {
<del> $Shell = $this->getMock('Cake\Console\Shell', ['hasTask', 'startup'], [], '', false);
<add> public function testRunCommandHittingTaskInSubcommand() {
<add> $parser = new ConsoleOptionParser('knife');
<add> $parser->addSubcommand('slice');
<add>
<add> $shell = $this->getMock('Cake\Console\Shell', ['hasTask', 'startup', 'getOptionParser'], [], '', false);
<ide> $task = $this->getMock('Cake\Console\Shell', ['execute', 'runCommand'], [], '', false);
<ide> $task->expects($this->any())
<ide> ->method('runCommand')
<del> ->with('execute', ['one', 'value']);
<add> ->with('execute', ['one']);
<add>
<add> $shell->expects($this->once())->method('getOptionParser')
<add> ->will($this->returnValue($parser));
<ide>
<del> $Shell->expects($this->once())->method('startup');
<del> $Shell->expects($this->any())
<add> $shell->expects($this->once())->method('startup');
<add> $shell->expects($this->any())
<ide> ->method('hasTask')
<ide> ->will($this->returnValue(true));
<ide>
<del> $Shell->RunCommand = $task;
<del>
<del> $Shell->runCommand('run_command', ['run_command', 'one', 'value']);
<add> $shell->Slice = $task;
<add> $shell->runCommand('slice', ['slice', 'one']);
<ide> }
<ide>
<ide> /** | 3 |
Java | Java | improve javadoc in configuration | 821a8eebdda514e1c6e4602509a8dc1e69d1849c | <ide><path>spring-context/src/main/java/org/springframework/context/annotation/Configuration.java
<ide> /*
<del> * Copyright 2002-2019 the original author or authors.
<add> * Copyright 2002-2020 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> * requires method interception, implemented through a runtime-generated CGLIB
<ide> * subclass which comes with limitations such as the configuration class and
<ide> * its methods not being allowed to declare {@code final}.
<del> * <p>The default is {@code true}, allowing for 'inter-bean references' within
<del> * the configuration class as well as for external calls to this configuration's
<del> * {@code @Bean} methods, e.g. from another configuration class. If this is not
<del> * needed since each of this particular configuration's {@code @Bean} methods
<del> * is self-contained and designed as a plain factory method for container use,
<add> * <p>The default is {@code true}, allowing for 'inter-bean references' via direct
<add> * method call within the configuration class as well as for external calls to
<add> * this configuration's {@code @Bean} methods, e.g. from another configuration class.
<add> * If this is not needed since each of this particular configuration's {@code @Bean}
<add> * methods is self-contained and designed as a plain factory method for container use,
<ide> * switch this flag to {@code false} in order to avoid CGLIB subclass processing.
<ide> * <p>Turning off bean method interception effectively processes {@code @Bean}
<ide> * methods individually like when declared on non-{@code @Configuration} classes, | 1 |
Javascript | Javascript | avoid timing brittleness in ember.select test | 20df8632b4361cb1b1d552e067084bbb9746888e | <ide><path>packages/ember-views/tests/views/select_test.js
<ide> QUnit.test('selection can be set from a Promise when multiple=false', function()
<ide> equal(select.$()[0].selectedIndex, 1, 'Should select from Promise content');
<ide> });
<ide>
<del>QUnit.test('selection from a Promise don\'t overwrite newer selection once resolved, when multiple=false', function() {
<del> expect(1);
<add>QUnit.test('selection from a Promise don\'t overwrite newer selection once resolved, when multiple=false', function(assert) {
<add> assert.expect(1);
<ide>
<ide> var yehuda = { id: 1, firstName: 'Yehuda' };
<ide> var tom = { id: 2, firstName: 'Tom' };
<ide> var seb = { id: 3, firstName: 'Seb' };
<ide>
<del> QUnit.stop();
<add> let firstPromise = new RSVP.Promise(function(resolve) {
<add> run.next(function() {
<add> resolve(seb);
<add> });
<add> });
<add>
<add> let secondPromise = firstPromise.then(function() {
<add> return tom;
<add> });
<ide>
<ide> run(function() {
<ide> select.set('content', emberA([yehuda, tom, seb]));
<ide> select.set('multiple', false);
<del> select.set('selection', new RSVP.Promise(function(resolve, reject) {
<del> run.later(function() {
<del> run(function() {
<del> resolve(tom);
<del> });
<del> QUnit.start();
<del> equal(select.$()[0].selectedIndex, 2, 'Should not select from Promise if newer selection');
<del> }, 40);
<del> }));
<del> select.set('selection', new RSVP.Promise(function(resolve, reject) {
<del> run.later(function() {
<del> run(function() {
<del> resolve(seb);
<del> });
<del> }, 30);
<del> }));
<add> select.set('selection', secondPromise);
<add> select.set('selection', firstPromise);
<ide> });
<ide>
<ide> append();
<add>
<add> return RSVP.all([firstPromise, secondPromise])
<add> .then(() => {
<add> assert.equal(select.$()[0].selectedIndex, 2, 'Should not select from Promise if newer selection');
<add> });
<ide> });
<ide>
<ide> QUnit.test('selection from a Promise resolving to null should not select when multiple=false', function() { | 1 |
Text | Text | update code samples | 6d37efbb8ae805577659e988aa9c09d138e4c6e2 | <ide><path>docs/basics/UsageWithReact.md
<ide> npm install --save react-redux
<ide>
<ide> React bindings for Redux embrace the idea of [separating container and presentational components](https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0).
<ide>
<del>It is advisable that only top-level components of your app (such as route handlers) are aware of Redux. Components below them should be presentational and receive all data via props.
<add>This table describes the characteristics of container and presentational components.
<ide>
<ide> <table>
<ide> <thead>
<ide> It is advisable that only top-level components of your app (such as route handle
<ide> </tbody>
<ide> </table>
<ide>
<del>In this todo app, we will only have a single container component at the top of our view hierarchy. In more complex apps, you might have several of them. While you may nest container components, we suggest that you pass props down whenever possible.
<add>In this todo app, we will have three container components that pass props to presentational components. We suggest that you do not nest container components and that you pass props down whenever possible.
<ide>
<ide> ## Designing Component Hierarchy
<ide>
<ide> Remember how we [designed the shape of the root state object](Reducers.md)? It’s time we design the UI hierarchy to match it. This is not a Redux-specific task. [Thinking in React](https://facebook.github.io/react/docs/thinking-in-react.html) is a great tutorial that explains the process.
<ide>
<del>Our design brief is simple. We want to show a list of todo items. On click, a todo item is crossed out as completed. We want to show a field where the user may add a new todo. In the footer, we want to show a toggle to show all / only completed / only incomplete todos.
<add>Our design brief is simple. We want to show a list of todo items. On click, a todo item is crossed out as completed. We want to show a field where the user may add a new todo. In the footer, we want to show a toggle to show all / only completed / only active todos.
<ide>
<del>I see the following components (and their props) emerge from this brief:
<add>I see the following components and their props emerge from this brief:
<ide>
<del>* **`AddTodo`** is an input field with a button.
<del> - `onAddClick(text: string)` is a callback to invoke when a button is pressed.
<ide> * **`TodoList`** is a list showing visible todos.
<ide> - `todos: Array` is an array of todo items with `{ text, completed }` shape.
<ide> - `onTodoClick(index: number)` is a callback to invoke when a todo is clicked.
<ide> I see the following components (and their props) emerge from this brief:
<ide> * **`Footer`** is a component where we let user change visible todo filter.
<ide> - `filter: string` is the current filter: `'SHOW_ALL'`, `'SHOW_COMPLETED'` or `'SHOW_ACTIVE'`.
<ide> - `onFilterChange(nextFilter: string)`: Callback to invoke when user chooses a different filter.
<add>* **`Link`** is a link with a callback.
<add> - `onClick()` is a callback to invoke when link is clicked.
<add>
<add>
<add>* **`AddTodo`** is an input field with a button.
<add> - `onAddClick(text: string)` is a callback to invoke when a button is pressed.
<add>
<add>* **`FilterLink`**
<add>
<add>* **`VisibleTodoList`**
<ide>
<ide> These are all presentational components. They don’t know *where* the data comes from, or *how* to change it. They only render what’s given to them.
<ide>
<ide> If you migrate from Redux to something else, you’ll be able to keep all these components exactly the same. They have no dependency on Redux.
<ide>
<del>Let’s write them! We don’t need to think about binding to Redux yet. You can just give them fake data while you experiment until they render correctly.
<add>Let’s write them! We don’t need to think about binding to Redux yet.
<ide>
<ide> ## Presentational Components
<ide>
<del>These are all normal React components, so we won’t stop to examine them in detail. Here they go:
<add>These are all normal React components, so we'll not stop and examine them in detail. Here they are:
<ide>
<del>#### `components/AddTodo.js`
<add>#### `components/Todo.js`
<ide>
<ide> ```js
<del>import React, { Component, PropTypes } from 'react'
<del>
<del>export default class AddTodo extends Component {
<del> render() {
<del> return (
<del> <div>
<del> <input type='text' ref='input' />
<del> <button onClick={e => this.handleClick(e)}>
<del> Add
<del> </button>
<del> </div>
<del> )
<del> }
<add>import React from "react";
<add>
<add>const Todo = ({
<add> onClick,
<add> completed,
<add> text
<add>}) => (
<add> <li
<add> onClick={onClick}
<add> style={{
<add> textDecoration:
<add> completed ?
<add> "line-through" :
<add> "none"
<add> }}
<add> >
<add> {text}
<add> </li>
<add>);
<add>
<add>export default Todo
<add>```
<ide>
<del> handleClick(e) {
<del> const node = this.refs.input
<del> const text = node.value.trim()
<del> this.props.onAddClick(text)
<del> node.value = ''
<del> }
<del>}
<add>#### `components/TodoList.js`
<ide>
<del>AddTodo.propTypes = {
<del> onAddClick: PropTypes.func.isRequired
<del>}
<add>```js
<add>import React from "react";
<add>import Todo from "./Todo";
<add>
<add>const TodoList = ({
<add> todos,
<add> onTodoClick
<add>}) => (
<add> <ul>
<add> {todos.map(todo =>
<add> <Todo
<add> key={todo.id}
<add> {...todo}
<add> onClick={() => onTodoClick(todo.id)}
<add> />
<add> )}
<add> </ul>
<add>);
<add>
<add>export default TodoList
<ide> ```
<ide>
<del>#### `components/Todo.js`
<add>#### `components/Footer.js`
<ide>
<ide> ```js
<del>import React, { Component, PropTypes } from 'react'
<del>
<del>export default class Todo extends Component {
<del> render() {
<del> return (
<del> <li
<del> onClick={this.props.onClick}
<del> style={{
<del> textDecoration: this.props.completed ? 'line-through' : 'none',
<del> cursor: this.props.completed ? 'default' : 'pointer'
<del> }}>
<del> {this.props.text}
<del> </li>
<del> )
<del> }
<del>}
<add>import React from "react";
<add>import FilterLink from "./FilterLink";
<add>
<add>const Footer = () => (
<add> <p>
<add> Show:
<add> {" "}
<add> <FilterLink filter="SHOW_ALL">
<add> All
<add> </FilterLink>
<add> {", "}
<add> <FilterLink filter="SHOW_ACTIVE">
<add> Active
<add> </FilterLink>
<add> {", "}
<add> <FilterLink filter="SHOW_COMPLETED">
<add> Completed
<add> </FilterLink>
<add> </p>
<add>);
<add>
<add>export default Footer
<add>```
<ide>
<del>Todo.propTypes = {
<del> onClick: PropTypes.func.isRequired,
<del> text: PropTypes.string.isRequired,
<del> completed: PropTypes.bool.isRequired
<del>}
<add>We'll now write some container components.
<add>
<add>#### `containers/AddTodo.js`
<add>
<add>```js
<add>import React from "react";
<add>import { connect } from "react-redux";
<add>import { addTodo } from "../actions";
<add>
<add>let AddTodo = ({ dispatch }) => {
<add> let input;
<add>
<add> return (
<add> <div>
<add> <input ref={node => {
<add> input = node;
<add> }} />
<add> <button onClick={() => {
<add> dispatch(addTodo(input.value));
<add> input.value = "";
<add> }}>
<add> Add Todo
<add> </button>
<add> </div>
<add> );
<add>};
<add>AddTodo = connect()(AddTodo);
<add>
<add>export default AddTodo
<ide> ```
<ide>
<del>#### `components/TodoList.js`
<add>#### `containers/FilterLink.js`
<ide>
<ide> ```js
<del>import React, { Component, PropTypes } from 'react'
<del>import Todo from './Todo'
<del>
<del>export default class TodoList extends Component {
<del> render() {
<del> return (
<del> <ul>
<del> {this.props.todos.map((todo, index) =>
<del> <Todo {...todo}
<del> key={index}
<del> onClick={() => this.props.onTodoClick(index)} />
<del> )}
<del> </ul>
<del> )
<del> }
<add>import React from "react";
<add>import { connect } from "react-redux";
<add>import { setVisibilityFilter } from "../actions";
<add>import Link from "../components/Link";
<add>
<add>const mapStateToProps = (
<add> state,
<add> ownProps
<add>) => {
<add> return {
<add> active:
<add> ownProps.filter ===
<add> state.visibilityFilter
<add> };
<add>};
<add>
<add>const mapDispatchToProps = (
<add> dispatch,
<add> ownProps
<add>) => {
<add> return {
<add> onClick: () => {
<add> dispatch(
<add> setVisibilityFilter(ownProps.filter)
<add> );
<add> }
<add> };
<ide> }
<ide>
<del>TodoList.propTypes = {
<del> onTodoClick: PropTypes.func.isRequired,
<del> todos: PropTypes.arrayOf(PropTypes.shape({
<del> text: PropTypes.string.isRequired,
<del> completed: PropTypes.bool.isRequired
<del> }).isRequired).isRequired
<del>}
<add>const FilterLink = connect(
<add> mapStateToProps,
<add> mapDispatchToProps
<add>)(Link);
<add>
<add>export default FilterLink
<ide> ```
<ide>
<del>#### `components/Footer.js`
<add>#### `containers/VisibleTodoList.js`
<ide>
<ide> ```js
<del>import React, { Component, PropTypes } from 'react'
<del>
<del>export default class Footer extends Component {
<del> renderFilter(filter, name) {
<del> if (filter === this.props.filter) {
<del> return name
<del> }
<del>
<del> return (
<del> <a href='#' onClick={e => {
<del> e.preventDefault()
<del> this.props.onFilterChange(filter)
<del> }}>
<del> {name}
<del> </a>
<del> )
<add>import React from "react";
<add>import { connect } from "react-redux";
<add>import { toggleTodo } from "../actions";
<add>import TodoList from "../components/TodoList";
<add>
<add>const getVisibleTodos = (
<add> todos,
<add> filter
<add>) => {
<add> switch (filter) {
<add> case "SHOW_ALL":
<add> return todos;
<add> case "SHOW_COMPLETED":
<add> return todos.filter(
<add> t => t.completed
<add> );
<add> case "SHOW_ACTIVE":
<add> return todos.filter(
<add> t => !t.completed
<add> );
<ide> }
<add>}
<ide>
<del> render() {
<del> return (
<del> <p>
<del> Show:
<del> {' '}
<del> {this.renderFilter('SHOW_ALL', 'All')}
<del> {', '}
<del> {this.renderFilter('SHOW_COMPLETED', 'Completed')}
<del> {', '}
<del> {this.renderFilter('SHOW_ACTIVE', 'Active')}
<del> .
<del> </p>
<add>const mapStateToProps = (
<add> state
<add>) => {
<add> return {
<add> todos: getVisibleTodos(
<add> state.todos,
<add> state.visibilityFilter
<ide> )
<del> }
<del>}
<add> };
<add>};
<ide>
<del>Footer.propTypes = {
<del> onFilterChange: PropTypes.func.isRequired,
<del> filter: PropTypes.oneOf([
<del> 'SHOW_ALL',
<del> 'SHOW_COMPLETED',
<del> 'SHOW_ACTIVE'
<del> ]).isRequired
<del>}
<add>const mapDispatchToProps = (
<add> dispatch
<add>) => {
<add> return {
<add> onTodoClick: (id) => {
<add> dispatch(toggleTodo(id));
<add> }
<add> };
<add>};
<add>
<add>const VisibleTodoList = connect(
<add> mapStateToProps,
<add> mapDispatchToProps
<add>)(TodoList);
<add>
<add>export default VisibleTodoList
<ide> ```
<ide>
<del>That’s it! We can verify that they work correctly by writing a dummy `App` to render them:
<add>Then we'll write the `TodoApp` component that assembles the app.
<ide>
<del>#### `containers/App.js`
<add>#### `components/TodoApp.js`
<ide>
<ide> ```js
<del>import React, { Component } from 'react'
<del>import AddTodo from '../components/AddTodo'
<del>import TodoList from '../components/TodoList'
<del>import Footer from '../components/Footer'
<del>
<del>export default class App extends Component {
<del> render() {
<del> return (
<del> <div>
<del> <AddTodo
<del> onAddClick={text =>
<del> console.log('add todo', text)
<del> } />
<del> <TodoList
<del> todos={
<del> [
<del> {
<del> text: 'Use Redux',
<del> completed: true
<del> },
<del> {
<del> text: 'Learn to connect it to React',
<del> completed: false
<del> }
<del> ]
<del> }
<del> onTodoClick={index =>
<del> console.log('todo clicked', index)
<del> } />
<del> <Footer
<del> filter='SHOW_ALL'
<del> onFilterChange={filter =>
<del> console.log('filter change', filter)
<del> } />
<del> </div>
<del> )
<del> }
<del>}
<add>import React from "react";
<add>import AddTodo from "../containers/AddTodo";
<add>import Footer from "./Footer";
<add>import VisibleTodoList from "../containers/VisibleTodoList";
<add>
<add>const TodoApp = () => (
<add> <div>
<add> <AddTodo />
<add> <VisibleTodoList />
<add> <Footer />
<add> </div>
<add>);
<add>
<add>export default TodoApp
<ide> ```
<ide>
<del>This is what I see when I render `<App />`:
<add>This is what I see when I render `<TodoApp />`:
<ide>
<ide> <img src='http://i.imgur.com/lj4QTfD.png' width='40%'>
<ide>
<ide> By itself, it’s not very interesting. Let’s connect it to Redux!
<ide>
<ide> ## Connecting to Redux
<ide>
<del>We need to make two changes to connect our `App` component to Redux and make it dispatch actions and read state from the Redux store.
<add>We need to make two changes to connect our `TodoApp` component to Redux and make it dispatch actions and read state from the Redux store.
<ide>
<ide> First, we need to import `Provider` from [`react-redux`](http://github.com/gaearon/react-redux), which we installed earlier, and **wrap the root component in `<Provider>`** before rendering.
<ide>
<ide> #### `index.js`
<ide>
<ide> ```js
<del>import React from 'react'
<del>import { render } from 'react-dom'
<del>import { createStore } from 'redux'
<del>import { Provider } from 'react-redux'
<del>import App from './containers/App'
<del>import todoApp from './reducers'
<add>import "babel-core/polyfill";
<add>import React from "react";
<add>import { render } from "react-dom";
<add>import { Provider } from "react-redux";
<add>import { todoStore } from "./store";
<add>import TodoApp from "./components/TodoApp";
<ide>
<del>let store = createStore(todoApp)
<del>
<del>let rootElement = document.getElementById('root')
<ide> render(
<del> <Provider store={store}>
<del> <App />
<add> <Provider store={todoStore}>
<add> <TodoApp />
<ide> </Provider>,
<del> rootElement
<del>)
<add> document.getElementById("app")
<add>);
<ide> ```
<ide>
<add>That’s it! Our todo app now functions correctly.
<add>
<ide> This makes our store instance available to the components below. (Internally, this is done via React’s [“context” feature](http://facebook.github.io/react/docs/context.html).)
<ide>
<ide> Then, we **wrap the components we want to connect to Redux with the `connect()` function from [`react-redux`](http://github.com/gaearon/react-redux)**. Try to only do this for a top-level component, or route handlers. While technically you can `connect()` any component in your app to Redux store, avoid doing this too deeply, because it will make the data flow harder to trace.
<ide>
<ide> **Any component wrapped with `connect()` call will receive a [`dispatch`](../api/Store.md#dispatch) function as a prop, and any state it needs from the global state.** In most cases you will only pass the first argument to `connect()`, which is a function we call a **selector**. This function takes the global Redux store’s state, and returns the props you need for the component. In the simplest case, you can just return the `state` given to you (i.e. pass identity function), but you may also wish to transform it first.
<ide>
<del>To make performant memoized transformations with composable selectors, check out [reselect](https://github.com/faassen/reselect). In this example, we won’t use it, but it works great for larger apps.
<del>
<del>#### `containers/App.js`
<del>
<del>```js
<del>import React, { Component, PropTypes } from 'react'
<del>import { connect } from 'react-redux'
<del>import { addTodo, completeTodo, setVisibilityFilter, VisibilityFilters } from '../actions'
<del>import AddTodo from '../components/AddTodo'
<del>import TodoList from '../components/TodoList'
<del>import Footer from '../components/Footer'
<del>
<del>class App extends Component {
<del> render() {
<del> // Injected by connect() call:
<del> const { dispatch, visibleTodos, visibilityFilter } = this.props
<del> return (
<del> <div>
<del> <AddTodo
<del> onAddClick={text =>
<del> dispatch(addTodo(text))
<del> } />
<del> <TodoList
<del> todos={visibleTodos}
<del> onTodoClick={index =>
<del> dispatch(completeTodo(index))
<del> } />
<del> <Footer
<del> filter={visibilityFilter}
<del> onFilterChange={nextFilter =>
<del> dispatch(setVisibilityFilter(nextFilter))
<del> } />
<del> </div>
<del> )
<del> }
<del>}
<del>
<del>App.propTypes = {
<del> visibleTodos: PropTypes.arrayOf(PropTypes.shape({
<del> text: PropTypes.string.isRequired,
<del> completed: PropTypes.bool.isRequired
<del> }).isRequired).isRequired,
<del> visibilityFilter: PropTypes.oneOf([
<del> 'SHOW_ALL',
<del> 'SHOW_COMPLETED',
<del> 'SHOW_ACTIVE'
<del> ]).isRequired
<del>}
<del>
<del>function selectTodos(todos, filter) {
<del> switch (filter) {
<del> case VisibilityFilters.SHOW_ALL:
<del> return todos
<del> case VisibilityFilters.SHOW_COMPLETED:
<del> return todos.filter(todo => todo.completed)
<del> case VisibilityFilters.SHOW_ACTIVE:
<del> return todos.filter(todo => !todo.completed)
<del> }
<del>}
<del>
<del>// Which props do we want to inject, given the global state?
<del>// Note: use https://github.com/faassen/reselect for better performance.
<del>function select(state) {
<del> return {
<del> visibleTodos: selectTodos(state.todos, state.visibilityFilter),
<del> visibilityFilter: state.visibilityFilter
<del> }
<del>}
<del>
<del>// Wrap the component to inject dispatch and state into it
<del>export default connect(select)(App)
<del>```
<del>
<del>That’s it! The tiny todo app now functions correctly.
<add>To make performant memorized transformations with composing selectors, check out [reselect](https://github.com/faassen/reselect). In this example, we won’t use it, but it works great for larger apps.
<ide>
<ide> ## Next Steps
<ide> | 1 |
Python | Python | fix psutil.process comparison | e84ce1905fc87470067b37d84281aedf55956083 | <ide><path>glances/core/glances_processes.py
<ide> def __str__(self):
<ide> def findProcess(self, process):
<ide> """ Search in tree for the ProcessTreeNode owning process, and return it or None if not found. """
<ide> assert(process is not None)
<del> if self.process is process:
<add> if (self.process is not None) and (self.process.pid == process.pid):
<ide> return self
<ide> for child in self.children:
<ide> node = child.findProcess(process) | 1 |
Javascript | Javascript | use key while rendering arrays | 381522223825b51778fae3ed3eba2c1233a99e7e | <ide><path>examples/with-react-multi-carousel/pages/index.js
<ide> class Index extends Component {
<ide> deviceType={''}
<ide> >
<ide> {images.map((image) => {
<del> return <Image url={image} alt={image} />
<add> return <Image key={image} url={image} alt={image} />
<ide> })}
<ide> </Carousel>
<ide> </div> | 1 |
Go | Go | remove unused type mapping | a292c04c01cbe4a6c9f74e7cf3b0315249ed8993 | <ide><path>pkg/devicemapper/devmapper_wrapper.go
<ide> import (
<ide> type (
<ide> cdmTask C.struct_dm_task
<ide>
<del> cLoopInfo64 C.struct_loop_info64
<del> loopInfo64 struct {
<add> loopInfo64 struct {
<ide> loDevice uint64 /* ioctl r/o */
<ide> loInode uint64 /* ioctl r/o */
<ide> loRdevice uint64 /* ioctl r/o */ | 1 |
Javascript | Javascript | update 404 static cache header to not cache | 3f650e154923f4d03ff868a63891c5a89b91bf56 | <ide><path>server/index.js
<ide> export default class Server {
<ide> async render404 (req, res, parsedUrl = parseUrl(req.url, true)) {
<ide> const { pathname, query } = parsedUrl
<ide> res.statusCode = 404
<add> res.setHeader('Cache-Control', 'no-cache, no-store, max-age=0, must-revalidate')
<ide> return this.renderError(null, req, res, pathname, query)
<ide> }
<ide>
<ide><path>test/integration/production/test/index.test.js
<ide> describe('Production Usage', () => {
<ide> })
<ide> })
<ide>
<add> it('should set correct Cache-Control header for static 404s', async () => {
<add> // this is to fix where 404 headers are set to 'public, max-age=31536000, immutable'
<add> const res = await fetch(`http://localhost:${appPort}/_next//static/common/bad-static.js`)
<add>
<add> expect(res.status).toBe(404)
<add> expect(res.headers.get('Cache-Control')).toBe('no-cache, no-store, max-age=0, must-revalidate')
<add> })
<add>
<ide> it('should block special pages', async () => {
<ide> const urls = ['/_document', '/_error']
<ide> for (const url of urls) { | 2 |
Go | Go | assign proxy fields directly | 1df0bb5a1309af0402d83061d4404afe7396e657 | <ide><path>daemon/info.go
<ide> func (daemon *Daemon) SystemInfo() (*types.Info, error) {
<ide> ServerVersion: dockerversion.Version,
<ide> ClusterStore: daemon.config().ClusterStore,
<ide> ClusterAdvertise: daemon.config().ClusterAdvertise,
<add> HTTPProxy: os.Getenv("http_proxy"),
<add> HTTPSProxy: os.Getenv("https_proxy"),
<add> NoProxy: os.Getenv("no_proxy"),
<ide> }
<ide>
<ide> // TODO Windows. Refactor this more once sysinfo is refactored into
<ide> func (daemon *Daemon) SystemInfo() (*types.Info, error) {
<ide> v.CPUCfsQuota = sysInfo.CPUCfsQuota
<ide> }
<ide>
<del> if httpProxy := os.Getenv("http_proxy"); httpProxy != "" {
<del> v.HTTPProxy = httpProxy
<del> }
<del> if httpsProxy := os.Getenv("https_proxy"); httpsProxy != "" {
<del> v.HTTPSProxy = httpsProxy
<del> }
<del> if noProxy := os.Getenv("no_proxy"); noProxy != "" {
<del> v.NoProxy = noProxy
<del> }
<ide> if hostname, err := os.Hostname(); err == nil {
<ide> v.Name = hostname
<ide> } | 1 |
Go | Go | make --device works at privileged mode | 03b3ec1dd52bb45eaa73864b62177c13c348c639 | <ide><path>daemon/container.go
<ide> func validateHostConfig(hostConfig *containertypes.HostConfig, platform string)
<ide> if hostConfig == nil {
<ide> return nil
<ide> }
<add>
<add> if hostConfig.Privileged {
<add> for _, deviceMapping := range hostConfig.Devices {
<add> if deviceMapping.PathOnHost == deviceMapping.PathInContainer {
<add> continue
<add> }
<add> if _, err := os.Stat(deviceMapping.PathInContainer); err != nil {
<add> if os.IsNotExist(err) {
<add> continue
<add> }
<add> return errors.Wrap(err, "error stating device path in container")
<add> }
<add> return errors.Errorf("container device path: %s must be different from any host device path for privileged mode containers", deviceMapping.PathInContainer)
<add> }
<add> }
<add>
<ide> if hostConfig.AutoRemove && !hostConfig.RestartPolicy.IsNone() {
<ide> return errors.Errorf("can't create 'AutoRemove' container with restart policy")
<ide> }
<ide><path>daemon/oci_linux.go
<ide> import (
<ide> containertypes "github.com/docker/docker/api/types/container"
<ide> "github.com/docker/docker/container"
<ide> daemonconfig "github.com/docker/docker/daemon/config"
<add> "github.com/docker/docker/errdefs"
<ide> "github.com/docker/docker/oci"
<ide> "github.com/docker/docker/oci/caps"
<ide> "github.com/docker/docker/pkg/idtools" | 2 |
Go | Go | use 0711 for /var/lib/docker | e91ca0e239f1e6c71a5a6c789ec8177806773355 | <ide><path>daemon/daemon_unix.go
<ide> func setupRemappedRoot(config *Config) ([]idtools.IDMap, []idtools.IDMap, error)
<ide>
<ide> func setupDaemonRoot(config *Config, rootDir string, rootUID, rootGID int) error {
<ide> config.Root = rootDir
<del> // the docker root metadata directory needs to have execute permissions for all users (o+x)
<add> // the docker root metadata directory needs to have execute permissions for all users (g+x,o+x)
<ide> // so that syscalls executing as non-root, operating on subdirectories of the graph root
<ide> // (e.g. mounted layers of a container) can traverse this path.
<ide> // The user namespace support will create subdirectories for the remapped root host uid:gid
<ide> // pair owned by that same uid:gid pair for proper write access to those needed metadata and
<ide> // layer content subtrees.
<ide> if _, err := os.Stat(rootDir); err == nil {
<ide> // root current exists; verify the access bits are correct by setting them
<del> if err = os.Chmod(rootDir, 0701); err != nil {
<add> if err = os.Chmod(rootDir, 0711); err != nil {
<ide> return err
<ide> }
<ide> } else if os.IsNotExist(err) {
<del> // no root exists yet, create it 0701 with root:root ownership
<del> if err := os.MkdirAll(rootDir, 0701); err != nil {
<add> // no root exists yet, create it 0711 with root:root ownership
<add> if err := os.MkdirAll(rootDir, 0711); err != nil {
<ide> return err
<ide> }
<ide> } | 1 |
Java | Java | add getter for js executor factory | e764361f939f01b2a206412e58675259948f4869 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/ReactNativeHost.java
<ide> import android.app.Application;
<ide>
<ide> import com.facebook.infer.annotation.Assertions;
<add>import com.facebook.react.bridge.JavaScriptExecutorFactory;
<ide> import com.facebook.react.common.LifecycleState;
<ide> import com.facebook.react.devsupport.RedBoxHandler;
<ide> import com.facebook.react.uimanager.UIImplementationProvider;
<ide> protected ReactInstanceManager createReactInstanceManager() {
<ide> .setJSMainModulePath(getJSMainModuleName())
<ide> .setUseDeveloperSupport(getUseDeveloperSupport())
<ide> .setRedBoxHandler(getRedBoxHandler())
<add> .setJavaScriptExecutorFactory(getJavaScriptExecutorFactory())
<ide> .setUIImplementationProvider(getUIImplementationProvider())
<ide> .setInitialLifecycleState(LifecycleState.BEFORE_CREATE);
<ide>
<ide> protected ReactInstanceManager createReactInstanceManager() {
<ide> return null;
<ide> }
<ide>
<add> /**
<add> * Get the {@link JavaScriptExecutorFactory}. Override this to use a custom
<add> * Executor.
<add> */
<add> protected @Nullable JavaScriptExecutorFactory getJavaScriptExecutorFactory() {
<add> return null;
<add> }
<add>
<ide> protected final Application getApplication() {
<ide> return mApplication;
<ide> } | 1 |
Python | Python | improve test and add a test to python | 17828c6ede1982ffab11e7277c80c7f21a907a75 | <ide><path>numpy/lib/tests/test_financial.py
<ide> def test_npv(self):
<ide> def test_mirr(self):
<ide> v1 = [-4500,-800,800,800,600,600,800,800,700,3000]
<ide> assert_almost_equal(np.mirr(v1,0.08,0.055),
<del> 0.0665, 4)
<add> 0.0666, 4)
<ide>
<ide> v2 = [-120000,39000,30000,21000,37000,46000]
<ide> assert_almost_equal(np.mirr(v2,0.10,0.12),
<ide> 0.1344, 4)
<add>
<add> v3 = [100,200,-50,300,-200]
<add> assert_almost_equal(np.mirr(v3,0.05,0.06), 0.3428, 4)
<ide>
<ide>
<ide> def test_unimplemented(): | 1 |
Ruby | Ruby | remove useless `test_string_with_crazy_column` | edf92f3a0d57942ea84ebac6b9b9f4d7bec3d898 | <ide><path>activerecord/test/cases/quoting_test.rb
<ide> def test_crazy_object
<ide> end
<ide>
<ide> def test_quote_string_no_column
<del> assert_equal "'lo\\\\l'", @quoter.quote('lo\l', nil)
<add> assert_equal "'lo\\\\l'", @quoter.quote('lo\l')
<ide> end
<ide>
<ide> def test_quote_as_mb_chars_no_column
<ide> string = ActiveSupport::Multibyte::Chars.new('lo\l')
<del> assert_equal "'lo\\\\l'", @quoter.quote(string, nil)
<del> end
<del>
<del> def test_string_with_crazy_column
<del> assert_equal "'lo\\\\l'", @quoter.quote('lo\l')
<add> assert_equal "'lo\\\\l'", @quoter.quote(string)
<ide> end
<ide>
<ide> def test_quote_duration | 1 |
Python | Python | add description of get/seterrobj | bcd679767d28c482e2e4bebf987d27b3200c6702 | <ide><path>numpy/add_newdocs.py
<ide> Type can be either a new sub-type object or a data-descriptor object
<ide>
<ide> """))
<add>
<add>add_newdoc('numpy.core.umath','geterrobj',
<add> """geterrobj()
<add>
<add> Used internally by `geterr`.
<add>
<add> Returns
<add> -------
<add> errobj : list
<add> Internal numpy buffer size, error mask, error callback function.
<add>
<add> """)
<add>
<add>add_newdoc('numpy.core.umath','seterrobj',
<add> """seterrobj()
<add>
<add> Used internally by `seterr`.
<add>
<add> Parameters
<add> ----------
<add> errobj : list
<add> [buffer_size, error_mask, callback_func]
<add>
<add> See Also
<add> --------
<add> seterrcall
<add>
<add> """) | 1 |
Text | Text | add code preview for textcat_multilabel [ci skip] | 39c8f7949ea5787eaddb964a5478144cf00d4342 | <ide><path>website/docs/api/textcategorizer.md
<ide> architectures and their arguments and hyperparameters.
<ide> %%GITHUB_SPACY/spacy/pipeline/textcat.py
<ide> ```
<ide>
<add>```python
<add>%%GITHUB_SPACY/spacy/pipeline/textcat_multilabel.py
<add>```
<add>
<ide> ## TextCategorizer.\_\_init\_\_ {#init tag="method"}
<ide>
<ide> > #### Example | 1 |
Javascript | Javascript | use common encoding utils | f6e4bf74cbdb7e36b00d3709f57d8a28ae7a57a2 | <ide><path>server/boot/user.js
<ide> import {
<ide> calcLongestStreak
<ide> } from '../utils/user-stats';
<ide> import supportedLanguages from '../../common/utils/supported-languages';
<add>import { encodeFcc } from '../../common/utils/encode-decode.js';
<ide> import { getChallengeInfo, cachedMap } from '../utils/map';
<ide>
<ide> const debug = debugFactory('fcc:boot:user');
<ide> const certText = {
<ide>
<ide> const dateFormat = 'MMM DD, YYYY';
<ide>
<del>function replaceScriptTags(value) {
<del> return value
<del> .replace(/<script>/gi, 'fccss')
<del> .replace(/<\/script>/gi, 'fcces');
<del>}
<del>
<del>function replaceFormAction(value) {
<del> return value.replace(/<form[^>]*>/, function(val) {
<del> return val.replace(/action(\s*?)=/, 'fccfaa$1=');
<del> });
<del>}
<del>
<del>function encodeFcc(value = '') {
<del> return replaceScriptTags(replaceFormAction(value));
<del>}
<del>
<ide> function isAlgorithm(challenge) {
<ide> // test if name starts with hike/waypoint/basejump/zipline
<ide> // fix for bug that saved different challenges with incorrect | 1 |
Ruby | Ruby | push target down to the classes that care about it | fd2d78dbc89a5875fb6e70416b991b371ea33468 | <ide><path>activemodel/lib/active_model/mass_assignment_security/sanitizer.rb
<ide> module ActiveModel
<ide> module MassAssignmentSecurity
<ide> class Sanitizer
<del> def initialize(target=nil)
<del> end
<del>
<ide> # Returns all attributes not denied by the authorizer.
<ide> def sanitize(attributes, authorizer)
<ide> sanitized_attributes = attributes.reject { |key, value| authorizer.deny?(key) }
<ide> def process_removed_attributes(attrs)
<ide> class LoggerSanitizer < Sanitizer
<ide> def initialize(target)
<ide> @target = target
<del> super
<add> super()
<ide> end
<ide>
<ide> def logger
<ide> def process_removed_attributes(attrs)
<ide> end
<ide>
<ide> class StrictSanitizer < Sanitizer
<add> def initialize(target = nil)
<add> super()
<add> end
<add>
<ide> def process_removed_attributes(attrs)
<ide> return if (attrs - insensitive_attributes).empty?
<ide> raise ActiveModel::MassAssignmentSecurity::Error, "Can't mass-assign protected attributes: #{attrs.join(', ')}" | 1 |
PHP | PHP | fix formhelper tests related to new _token[debug] | 6d40c7e3fb55bd88111955d7d7b9240ace37508d | <ide><path>tests/TestCase/View/Helper/FormHelperTest.php
<ide> public function testFormSecurityFields()
<ide> $hash = Security::hash(serialize($fields) . Security::salt());
<ide> $hash .= ':' . 'Model.valid';
<ide> $hash = urlencode($hash);
<add> $tokenDebug = urlencode(json_encode([
<add> '',
<add> $fields,
<add> []
<add> ]));
<add> $expected = [
<add> 'div' => ['style' => 'display:none;'],
<add> ['input' => [
<add> 'type' => 'hidden',
<add> 'name' => '_Token[fields]',
<add> 'value' => $hash
<add> ]],
<add> ['input' => [
<add> 'type' => 'hidden',
<add> 'name' => '_Token[unlocked]',
<add> 'value' => '',
<add> ]],
<add> ['input' => [
<add> 'type' => 'hidden',
<add> 'name' => '_Token[debug]',
<add> 'value' => $tokenDebug
<add> ]],
<add> '/div'
<add> ];
<add> $this->assertHtml($expected, $result);
<add> }
<add>
<add> /**
<add> * testFormSecurityFields method
<add> *
<add> * Test debug token is not generated if debug is false
<add> *
<add> * @return void
<add> */
<add> public function testFormSecurityFieldsNoDebugMode()
<add> {
<add> $debug = Configure::read('debug');
<add> Configure::write('debug', false);
<add> $fields = ['Model.password', 'Model.username', 'Model.valid' => '0'];
<ide>
<add> $this->Form->request->params['_Token'] = 'testKey';
<add> $result = $this->Form->secure($fields);
<add>
<add> $hash = Security::hash(serialize($fields) . Security::salt());
<add> $hash .= ':' . 'Model.valid';
<add> $hash = urlencode($hash);
<ide> $expected = [
<ide> 'div' => ['style' => 'display:none;'],
<ide> ['input' => [
<ide> public function testFormSecurityFields()
<ide> '/div'
<ide> ];
<ide> $this->assertHtml($expected, $result);
<add> Configure::write('debug', $debug);
<ide> }
<ide>
<ide> /**
<ide> public function testFormSecurityMultipleFields()
<ide>
<ide> $hash = '51e3b55a6edd82020b3f29c9ae200e14bbeb7ee5%3AModel.0.hidden%7CModel.0.valid';
<ide> $hash .= '%7CModel.1.hidden%7CModel.1.valid';
<add> $tokenDebug = urlencode(json_encode([
<add> '',
<add> $fields,
<add> []
<add> ]));
<ide>
<ide> $expected = [
<ide> 'div' => ['style' => 'display:none;'],
<ide> public function testFormSecurityMultipleFields()
<ide> 'type' => 'hidden', 'name' => '_Token[unlocked]',
<ide> 'value' => ''
<ide> ]],
<add> ['input' => [
<add> 'type' => 'hidden', 'name' => '_Token[debug]',
<add> 'value' => $tokenDebug,
<add> ]],
<ide> '/div'
<ide> ];
<ide> $this->assertHtml($expected, $result);
<ide> public function testFormSecurityMultipleSubmitButtons()
<ide> $this->assertHtml($expected, $result);
<ide>
<ide> $result = $this->Form->end();
<add> $tokenDebug = urlencode(json_encode([
<add> '/articles/add',
<add> [
<add> 'Address.title',
<add> 'Address.first_name',
<add> ],
<add> ['save', 'cancel']
<add> ]));
<add>
<ide> $expected = [
<ide> 'div' => ['style' => 'display:none;'],
<ide> ['input' => [
<ide> public function testFormSecurityMultipleSubmitButtons()
<ide> 'name' => '_Token[unlocked]',
<ide> 'value' => 'cancel%7Csave'
<ide> ]],
<add> ['input' => [
<add> 'type' => 'hidden', 'name' => '_Token[debug]',
<add> 'value' => $tokenDebug,
<add> ]],
<ide> '/div'
<ide> ];
<ide> $this->assertHtml($expected, $result);
<ide> public function testFormSecurityMultipleInputFields()
<ide> $result = $this->Form->secure($this->Form->fields);
<ide>
<ide> $hash = '8bd3911b07b507408b1a969b31ee90c47b7d387e%3AAddresses.0.id%7CAddresses.1.id';
<del>
<add> $tokenDebug = urlencode(json_encode([
<add> '/articles/add',
<add> [
<add> 'Addresses.0.id' => '123456',
<add> 'Addresses.0.title',
<add> 'Addresses.0.first_name',
<add> 'Addresses.0.last_name',
<add> 'Addresses.0.address',
<add> 'Addresses.0.city',
<add> 'Addresses.0.phone',
<add> 'Addresses.0.primary',
<add> 'Addresses.1.id' => '654321',
<add> 'Addresses.1.title',
<add> 'Addresses.1.first_name',
<add> 'Addresses.1.last_name',
<add> 'Addresses.1.address',
<add> 'Addresses.1.city',
<add> 'Addresses.1.phone',
<add> 'Addresses.1.primary',
<add> ],
<add> []
<add> ]));
<ide> $expected = [
<ide> 'div' => ['style' => 'display:none;'],
<ide> ['input' => [
<ide> public function testFormSecurityMultipleInputFields()
<ide> 'type' => 'hidden', 'name' => '_Token[unlocked]',
<ide> 'value' => ''
<ide> ]],
<add> ['input' => [
<add> 'type' => 'hidden', 'name' => '_Token[debug]',
<add> 'value' => $tokenDebug,
<add> ]],
<ide> '/div'
<ide> ];
<ide> $this->assertHtml($expected, $result);
<ide> public function testFormSecurityMultipleInputDisabledFields()
<ide>
<ide> $result = $this->Form->secure($this->Form->fields);
<ide> $hash = '4fb10b46873df4ddd4ef5c3a19944a2f29b38991%3AAddresses.0.id%7CAddresses.1.id';
<add> $tokenDebug = urlencode(json_encode([
<add> '/articles/add',
<add> [
<add> 'Addresses.0.id' => '123456',
<add> 'Addresses.0.title',
<add> 'Addresses.0.last_name',
<add> 'Addresses.0.city',
<add> 'Addresses.0.phone',
<add> 'Addresses.1.id' => '654321',
<add> 'Addresses.1.title',
<add> 'Addresses.1.last_name',
<add> 'Addresses.1.city',
<add> 'Addresses.1.phone'
<add> ],
<add> [
<add> 'first_name',
<add> 'address'
<add> ]
<add> ]));
<ide>
<ide> $expected = [
<ide> 'div' => ['style' => 'display:none;'],
<ide> public function testFormSecurityMultipleInputDisabledFields()
<ide> 'name' => '_Token[unlocked]',
<ide> 'value' => 'address%7Cfirst_name',
<ide> ]],
<add> ['input' => [
<add> 'type' => 'hidden', 'name' => '_Token[debug]',
<add> 'value' => $tokenDebug,
<add> ]],
<ide> '/div'
<ide> ];
<ide> $this->assertHtml($expected, $result);
<ide> public function testFormSecurityInputUnlockedFields()
<ide> $result = $this->Form->secure($expected, ['data-foo' => 'bar']);
<ide>
<ide> $hash = 'a303becbdd99cb42ca14a1cf7e63dfd48696a3c5%3AAddresses.id';
<add> $tokenDebug = urlencode(json_encode([
<add> '/articles/add',
<add> [
<add> 'Addresses.id' => '123456',
<add> 'Addresses.title',
<add> 'Addresses.last_name',
<add> 'Addresses.city',
<add> 'Addresses.phone'
<add> ],
<add> [
<add> 'first_name',
<add> 'address'
<add> ]
<add> ]));
<add>
<ide> $expected = [
<ide> 'div' => ['style' => 'display:none;'],
<ide> ['input' => [
<ide> public function testFormSecurityInputUnlockedFields()
<ide> 'value' => 'address%7Cfirst_name',
<ide> 'data-foo' => 'bar',
<ide> ]],
<add> ['input' => [
<add> 'type' => 'hidden', 'name' => '_Token[debug]',
<add> 'value' => $tokenDebug,
<add> 'data-foo' => 'bar'
<add> ]],
<ide> '/div'
<ide> ];
<ide> $this->assertHtml($expected, $result);
<ide> public function testFormSecuredInput()
<ide> 'type' => 'hidden',
<ide> 'name' => 'stuff',
<ide> ]];
<del> $this->assertHtml($expected, $result);
<add> $this->assertHtml($expected, $result);
<ide>
<del> $result = $this->Form->hidden('hidden', ['value' => '0']);
<del> $expected = ['input' => [
<add> $result = $this->Form->hidden('hidden', ['value' => '0']);
<add> $expected = ['input' => [
<ide> 'type' => 'hidden',
<ide> 'name' => 'hidden',
<ide> 'value' => '0'
<del> ]];
<del> $this->assertHtml($expected, $result);
<add> ]];
<add> $this->assertHtml($expected, $result);
<ide>
<del> $result = $this->Form->input('something', ['type' => 'checkbox']);
<del> $expected = [
<add> $result = $this->Form->input('something', ['type' => 'checkbox']);
<add> $expected = [
<ide> 'div' => ['class' => 'input checkbox'],
<ide> ['input' => [
<ide> 'type' => 'hidden',
<ide> public function testFormSecuredInput()
<ide> 'Something',
<ide> '/label',
<ide> '/div'
<del> ];
<del> $this->assertHtml($expected, $result);
<del>
<del> $result = $this->Form->fields;
<del> $expected = [
<del> 'ratio',
<del> 'population',
<del> 'published',
<del> 'other',
<del> 'stuff' => '',
<del> 'hidden' => '0',
<del> 'something'
<del> ];
<del> $this->assertEquals($expected, $result);
<del>
<del> $result = $this->Form->secure($this->Form->fields);
<del> $expected = [
<add> ];
<add> $this->assertHtml($expected, $result);
<add>
<add> $result = $this->Form->fields;
<add> $expectedFields = [
<add> 'ratio',
<add> 'population',
<add> 'published',
<add> 'other',
<add> 'stuff' => '',
<add> 'hidden' => '0',
<add> 'something'
<add> ];
<add> $this->assertEquals($expectedFields, $result);
<add>
<add> $result = $this->Form->secure($this->Form->fields);
<add> $tokenDebug = urlencode(json_encode([
<add> '/articles/add',
<add> $expectedFields,
<add> []
<add> ]));
<add>
<add> $expected = [
<ide> 'div' => ['style' => 'display:none;'],
<ide> ['input' => [
<ide> 'type' => 'hidden',
<ide> public function testFormSecuredInput()
<ide> 'name' => '_Token[unlocked]',
<ide> 'value' => ''
<ide> ]],
<add> ['input' => [
<add> 'type' => 'hidden', 'name' => '_Token[debug]',
<add> 'value' => $tokenDebug,
<add> ]],
<ide> '/div'
<del> ];
<del> $this->assertHtml($expected, $result);
<add> ];
<add> $this->assertHtml($expected, $result);
<ide> }
<ide>
<ide> /**
<ide> public function testSecurePostButton()
<ide> $this->Form->request->params['_Token'] = ['unlockedFields' => []];
<ide>
<ide> $result = $this->Form->postButton('Delete', '/posts/delete/1');
<add> $tokenDebug = urlencode(json_encode([
<add> '/posts/delete/1',
<add> [],
<add> []
<add> ]));
<add>
<ide> $expected = [
<ide> 'form' => [
<ide> 'method' => 'post', 'action' => '/posts/delete/1', 'accept-charset' => 'utf-8',
<ide> public function testSecurePostButton()
<ide> ['div' => ['style' => 'display:none;']],
<ide> ['input' => ['type' => 'hidden', 'name' => '_Token[fields]', 'value' => 'preg:/[\w\d%]+/']],
<ide> ['input' => ['type' => 'hidden', 'name' => '_Token[unlocked]', 'value' => '']],
<add> ['input' => [
<add> 'type' => 'hidden', 'name' => '_Token[debug]',
<add> 'value' => $tokenDebug,
<add> ]],
<ide> '/div',
<ide> '/form',
<ide> ];
<ide> public function testPostLinkSecurityHash()
<ide> $hash .= '%3Aid';
<ide> $this->Form->request->params['_Token']['key'] = 'test';
<ide>
<add> $result = $this->Form->postLink(
<add> 'Delete',
<add> '/posts/delete/1',
<add> ['data' => ['id' => 1]]
<add> );
<add> $tokenDebug = urlencode(json_encode([
<add> '/posts/delete/1',
<add> [
<add> 'id' => 1
<add> ],
<add> []
<add> ]));
<add> $expected = [
<add> 'form' => [
<add> 'method' => 'post', 'action' => '/posts/delete/1',
<add> 'name', 'style' => 'display:none;'
<add> ],
<add> ['input' => ['type' => 'hidden', 'name' => '_method', 'value' => 'POST']],
<add> ['input' => ['type' => 'hidden', 'name' => 'id', 'value' => '1']],
<add> 'div' => ['style' => 'display:none;'],
<add> ['input' => ['type' => 'hidden', 'name' => '_Token[fields]', 'value' => $hash]],
<add> ['input' => ['type' => 'hidden', 'name' => '_Token[unlocked]', 'value' => '']],
<add> ['input' => [
<add> 'type' => 'hidden', 'name' => '_Token[debug]',
<add> 'value' => $tokenDebug,
<add> ]],
<add> '/div',
<add> '/form',
<add> 'a' => ['href' => '#', 'onclick' => 'preg:/document\.post_\w+\.submit\(\); event\.returnValue = false; return false;/'],
<add> 'Delete',
<add> '/a'
<add> ];
<add> $this->assertHtml($expected, $result);
<add> }
<add>
<add> /**
<add> * Test that security does not include debug token if debug is false.
<add> *
<add> * @return void
<add> */
<add> public function testPostLinkSecurityHashNoDebugMode()
<add> {
<add> $debug = Configure::read('debug');
<add> Configure::write('debug', false);
<add> $hash = Security::hash(
<add> '/posts/delete/1' .
<add> serialize(['id' => '1']) .
<add> '' .
<add> Security::salt()
<add> );
<add> $hash .= '%3Aid';
<add> $this->Form->request->params['_Token']['key'] = 'test';
<add>
<ide> $result = $this->Form->postLink(
<ide> 'Delete',
<ide> '/posts/delete/1',
<ide> public function testPostLinkSecurityHash()
<ide> '/a'
<ide> ];
<ide> $this->assertHtml($expected, $result);
<add> Configure::write('debug', $debug);
<ide> }
<ide>
<ide> /**
<ide> public function testPostLinkAfterGetForm()
<ide> $this->Form->end();
<ide>
<ide> $result = $this->Form->postLink('Delete', '/posts/delete/1');
<add> $tokenDebug = urlencode(json_encode([
<add> '/posts/delete/1',
<add> [],
<add> []
<add> ]));
<ide> $expected = [
<ide> 'form' => [
<ide> 'method' => 'post', 'action' => '/posts/delete/1',
<ide> public function testPostLinkAfterGetForm()
<ide> 'div' => ['style' => 'display:none;'],
<ide> ['input' => ['type' => 'hidden', 'name' => '_Token[fields]', 'value' => 'preg:/[\w\d%]+/']],
<ide> ['input' => ['type' => 'hidden', 'name' => '_Token[unlocked]', 'value' => '']],
<add> ['input' => [
<add> 'type' => 'hidden', 'name' => '_Token[debug]',
<add> 'value' => $tokenDebug,
<add> ]],
<ide> '/div',
<ide> '/form',
<ide> 'a' => ['href' => '#', 'onclick' => 'preg:/document\.post_\w+\.submit\(\); event\.returnValue = false; return false;/'], | 1 |
Ruby | Ruby | remove some useless code | 02f2e3d538f79d61ab5abdcdb3bea30843d3ee4a | <ide><path>actionpack/lib/action_dispatch/routing/route_set.rb
<ide> def initialize
<ide> @module = Module.new do
<ide> protected
<ide>
<del> def handle_positional_args(args, options, route)
<add> def handle_positional_args(args, options, segment_keys)
<ide> inner_options = args.extract_options!
<ide> result = options.dup
<ide>
<ide> if args.any?
<del> keys = route.segment_keys
<add> keys = segment_keys
<ide> if args.size < keys.size - 1 # take format into account
<ide> keys -= self.url_options.keys if self.respond_to?(:url_options)
<ide> keys -= options.keys
<ide> def url_helper_name(name, only_path)
<ide> end
<ide> end
<ide>
<del> def hash_access_name(name, only_path)
<del> if only_path
<del> :"hash_for_#{name}_path"
<del> else
<del> :"hash_for_#{name}_url"
<del> end
<del> end
<del>
<ide> def define_named_route_methods(name, route)
<ide> [true, false].each do |only_path|
<ide> hash = route.defaults.merge(:use_route => name, :only_path => only_path)
<del> define_hash_access route, name, hash
<ide> define_url_helper route, name, hash
<ide> end
<ide> end
<ide>
<del> def define_hash_access(route, name, options)
<del> selector = hash_access_name(name, options[:only_path])
<del>
<del> @module.module_eval do
<del> redefine_method(selector) do |*args|
<del> self.handle_positional_args(args, options, route)
<del> end
<del> protected selector
<del> end
<del> helpers << selector
<del> end
<del>
<ide> # Create a url helper allowing ordered parameters to be associated
<ide> # with corresponding dynamic segments, so you can do:
<ide> #
<ide> def define_hash_access(route, name, options)
<ide> #
<ide> def define_url_helper(route, name, options)
<ide> selector = url_helper_name(name, options[:only_path])
<del> hash_access_method = hash_access_name(name, options[:only_path])
<ide>
<ide> if optimize_helper?(route)
<ide> @module.module_eval <<-END_EVAL, __FILE__, __LINE__ + 1
<ide> def #{selector}(*args)
<ide> options[:path] = "#{optimized_helper(route)}"
<ide> ActionDispatch::Http::URL.url_for(options)
<ide> else
<del> url_for(#{hash_access_method}(*args))
<add> url_for(handle_positional_args(args, #{options.inspect}, #{route.segment_keys.inspect}))
<ide> end
<ide> end
<ide> END_EVAL
<ide> else
<ide> @module.module_eval <<-END_EVAL, __FILE__, __LINE__ + 1
<ide> remove_possible_method :#{selector}
<ide> def #{selector}(*args)
<del> url_for(#{hash_access_method}(*args))
<add> url_for(handle_positional_args(args, #{options.inspect}, #{route.segment_keys.inspect}))
<ide> end
<ide> END_EVAL
<ide> end | 1 |
Python | Python | add base norm exceptions | e5d426406ad3661a2863c06339f896da451d9450 | <ide><path>spacy/lang/norm_exceptions.py
<add># coding: utf8
<add>from __future__ import unicode_literals
<add>
<add>
<add># These exceptions are used to add NORM values based on a token's ORTH value.
<add># Individual languages can also add their own exceptions and overwrite them -
<add># for example, British vs. American spelling in English.
<add>
<add># Norms are only set if no alternative is provided in the tokenizer exceptions.
<add># Note that this does not change any other token attributes. Its main purpose
<add># is to normalise the word representations so that equivalent tokens receive
<add># similar representations. For example: $ and € are very different, but they're
<add># both currency symbols. By normalising currency symbols to $, all symbols are
<add># seen as similar, no matter how common they are in the training data.
<add>
<add>
<add>BASE_NORMS = {
<add> "'s": "'s",
<add> "'S": "'s",
<add> "’s": "'s",
<add> "’S": "'s",
<add> "’": "'",
<add> "‘": "'",
<add> "´": "'",
<add> "`": "'",
<add> "”": '"',
<add> "“": '"',
<add> "''": '"',
<add> "``": '"',
<add> "´´": '"',
<add> "„": '"',
<add> "»": '"',
<add> "«": '"',
<add> "…": "...",
<add> "—": "-",
<add> "–": "-",
<add> "--": "-",
<add> "---": "-",
<add> "€": "$",
<add> "£": "$",
<add> "¥": "$",
<add> "฿": "$",
<add> "US$": "$",
<add> "C$": "$",
<add> "A$": "$"
<add>} | 1 |
Java | Java | fix regression in determinetransactionmanager | 4a0ac97550c67c926e014903338f9c0e84fa9eee | <ide><path>spring-tx/src/main/java/org/springframework/transaction/interceptor/TransactionAspectSupport.java
<ide> protected PlatformTransactionManager determineTransactionManager(TransactionAttr
<ide> if (this.beanFactory != null) {
<ide> String qualifier = txAttr != null ? txAttr.getQualifier() : null;
<ide> if (StringUtils.hasText(qualifier)) {
<del> PlatformTransactionManager txManager = this.transactionManagerCache.get(qualifier);
<del> if (txManager == null) {
<del> txManager = BeanFactoryAnnotationUtils.qualifiedBeanOfType(
<del> this.beanFactory, PlatformTransactionManager.class, qualifier);
<del> this.transactionManagerCache.putIfAbsent(qualifier, txManager);
<del> }
<del> return txManager;
<add> return determineQualifiedTransactionManager(qualifier);
<ide> }
<ide> else if (StringUtils.hasText(this.transactionManagerBeanName)) {
<del> PlatformTransactionManager txManager = this.transactionManagerCache.get(this.transactionManagerBeanName);
<del> if (txManager == null) {
<del> txManager = this.beanFactory.getBean(
<del> this.transactionManagerBeanName, PlatformTransactionManager.class);
<del> this.transactionManagerCache.putIfAbsent(this.transactionManagerBeanName, txManager);
<del> }
<del> return txManager;
<del> } else {
<add> return determineQualifiedTransactionManager(this.transactionManagerBeanName);
<add> }
<add> else if (txAttr != null) { // Do not lookup default bean name if no tx attributes are set
<ide> PlatformTransactionManager defaultTransactionManager = getTransactionManager();
<ide> if (defaultTransactionManager == null) {
<ide> defaultTransactionManager = this.beanFactory.getBean(PlatformTransactionManager.class);
<ide> else if (StringUtils.hasText(this.transactionManagerBeanName)) {
<ide> return getTransactionManager();
<ide> }
<ide>
<add> private PlatformTransactionManager determineQualifiedTransactionManager(String qualifier) {
<add> PlatformTransactionManager txManager = this.transactionManagerCache.get(qualifier);
<add> if (txManager == null) {
<add> txManager = BeanFactoryAnnotationUtils.qualifiedBeanOfType(
<add> this.beanFactory, PlatformTransactionManager.class, qualifier);
<add> this.transactionManagerCache.putIfAbsent(qualifier, txManager);
<add> }
<add> return txManager;
<add> }
<add>
<ide> /**
<ide> * Convenience method to return a String representation of this Method
<ide> * for use in logging. Can be overridden in subclasses to provide a
<ide><path>spring-tx/src/test/java/org/springframework/transaction/interceptor/TransactionInterceptorTests.java
<ide> public void determineTransactionManagerWithNoBeanFactoryAndNoTransactionAttribut
<ide> assertSame(transactionManager, ti.determineTransactionManager(null));
<ide> }
<ide>
<add> @Test
<add> public void determineTransactionManagerWithNoTransactionAttribute() {
<add> BeanFactory beanFactory = mock(BeanFactory.class);
<add> TransactionInterceptor ti = createTestTransactionInterceptor(beanFactory, null);
<add>
<add> assertNull(ti.determineTransactionManager(null));
<add> }
<add>
<ide> @Test
<ide> public void determineTransactionManagerWithQualifierUnknown() {
<ide> BeanFactory beanFactory = mock(BeanFactory.class); | 2 |
Ruby | Ruby | move define_constructors to class level | bfa82499d633d586020af2333e68b2d85df190b2 | <ide><path>activerecord/lib/active_record/associations/builder/singular_association.rb
<ide> def valid_options
<ide>
<ide> def define_accessors(model, reflection)
<ide> super
<del> define_constructors(model.generated_feature_methods) if reflection.constructable?
<add> self.class.define_constructors(model.generated_feature_methods, name) if reflection.constructable?
<ide> end
<ide>
<ide> # Defines the (build|create)_association methods for belongs_to or has_one association
<del>
<del> def define_constructors(mixin)
<add> def self.define_constructors(mixin, name)
<ide> mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1
<ide> def build_#{name}(*args, &block)
<ide> association(:#{name}).build(*args, &block) | 1 |
Python | Python | upgrade celery.utils.encoding from kombu | b5cd4ff2b02151bca966c53b80dbea8911a7a6b2 | <ide><path>celery/utils/encoding.py
<ide> """
<del>
<ide> celery.utils.encoding
<del>=====================
<add>====================
<ide>
<del>Utilties to encode text, and to safely emit text from running
<add>Utilities to encode text, and to safely emit text from running
<ide> applications without crashing with the infamous :exc:`UnicodeDecodeError`
<ide> exception.
<ide>
<ide> is_py3k = sys.version_info >= (3, 0)
<ide>
<ide>
<del>if sys.version_info >= (3, 0):
<add>if is_py3k:
<ide>
<ide> def str_to_bytes(s):
<ide> if isinstance(s, str):
<ide> def from_utf8(s, *args, **kwargs):
<ide> return s
<ide>
<ide> else:
<add>
<ide> def str_to_bytes(s): # noqa
<add> if isinstance(s, unicode):
<add> return s.encode()
<ide> return s
<ide>
<ide> def bytes_to_str(s): # noqa
<ide> def from_utf8(s, *args, **kwargs): # noqa
<ide> def default_encoding():
<ide> return "utf-8"
<ide> else:
<add>
<ide> def default_encoding(): # noqa
<ide> return sys.getfilesystemencoding()
<ide> | 1 |
Ruby | Ruby | allow writing/committing new bottles | 134210d9ed0d5eec6f70ae999b50ef4d3dae6a1c | <ide><path>Library/Homebrew/cmd/bottle.rb
<ide> require 'tab'
<ide> require 'keg'
<ide> require 'cmd/versions'
<add>require 'utils/inreplace'
<ide> require 'erb'
<ide>
<ide> class BottleMerger < Formula
<ide> def self.reset_bottle; @bottle = Bottle.new; end
<ide> EOS
<ide>
<ide> module Homebrew extend self
<add> class << self
<add> include Utils::Inreplace
<add> end
<add>
<ide> def keg_contains string, keg
<ide> quiet_system 'fgrep', '--recursive', '--quiet', '--max-count=1', string, keg
<ide> end
<ide> def merge
<ide> BottleMerger.class_eval bottle_block
<ide> end
<ide> bottle = BottleMerger.new.bottle
<del> puts bottle_output bottle if bottle
<add> next unless bottle
<add> output = bottle_output bottle
<add> puts output
<add>
<add> if ARGV.include? '--write'
<add> f = Formula.factory formula_name
<add> formula_path = HOMEBREW_REPOSITORY+"Library/Formula/#{f.name}.rb"
<add> inreplace formula_path do |s|
<add> if f.bottle
<add> s.gsub!(/ bottle do.+?end\n/m, output)
<add> else
<add> s.gsub!(/( (url|sha1|head|version) '\S*'\n+)+/m, '\0' + output + "\n")
<add> end
<add> end
<add>
<add> update_or_add = f.bottle.nil? ? 'add' : 'update'
<add>
<add> safe_system 'git', 'commit', formula_path, '-m',
<add> "#{f.name}: #{update_or_add} bottle."
<add> end
<ide> end
<ide> exit 0
<ide> end | 1 |
Javascript | Javascript | use official iana status codes | 2d9456e3e61cf969d5cd11ad85484aa961844ff6 | <ide><path>lib/_http_server.js
<ide> const STATUS_CODES = exports.STATUS_CODES = {
<ide> 205 : 'Reset Content',
<ide> 206 : 'Partial Content',
<ide> 207 : 'Multi-Status', // RFC 4918
<add> 208 : 'Already Reported',
<add> 226 : 'IM Used',
<ide> 300 : 'Multiple Choices',
<ide> 301 : 'Moved Permanently',
<del> 302 : 'Moved Temporarily',
<add> 302 : 'Found',
<ide> 303 : 'See Other',
<ide> 304 : 'Not Modified',
<ide> 305 : 'Use Proxy',
<ide> const STATUS_CODES = exports.STATUS_CODES = {
<ide> 405 : 'Method Not Allowed',
<ide> 406 : 'Not Acceptable',
<ide> 407 : 'Proxy Authentication Required',
<del> 408 : 'Request Time-out',
<add> 408 : 'Request Timeout',
<ide> 409 : 'Conflict',
<ide> 410 : 'Gone',
<ide> 411 : 'Length Required',
<ide> 412 : 'Precondition Failed',
<del> 413 : 'Request Entity Too Large',
<del> 414 : 'Request-URI Too Large',
<add> 413 : 'Payload Too Large',
<add> 414 : 'URI Too Long',
<ide> 415 : 'Unsupported Media Type',
<del> 416 : 'Requested Range Not Satisfiable',
<add> 416 : 'Range Not Satisfiable',
<ide> 417 : 'Expectation Failed',
<ide> 418 : 'I\'m a teapot', // RFC 2324
<add> 421 : 'Misdirected Request',
<ide> 422 : 'Unprocessable Entity', // RFC 4918
<ide> 423 : 'Locked', // RFC 4918
<ide> 424 : 'Failed Dependency', // RFC 4918
<ide> const STATUS_CODES = exports.STATUS_CODES = {
<ide> 501 : 'Not Implemented',
<ide> 502 : 'Bad Gateway',
<ide> 503 : 'Service Unavailable',
<del> 504 : 'Gateway Time-out',
<add> 504 : 'Gateway Timeout',
<ide> 505 : 'HTTP Version Not Supported',
<ide> 506 : 'Variant Also Negotiates', // RFC 2295
<ide> 507 : 'Insufficient Storage', // RFC 4918
<add> 508 : 'Loop Detected',
<ide> 509 : 'Bandwidth Limit Exceeded',
<ide> 510 : 'Not Extended', // RFC 2774
<ide> 511 : 'Network Authentication Required' // RFC 6585 | 1 |
Java | Java | improve transaction management for @sql scripts | 2e75adb04c02b8904c59bd5820336104594ce3fb | <ide><path>spring-test/src/main/java/org/springframework/test/context/jdbc/Sql.java
<ide> import java.lang.annotation.Retention;
<ide> import java.lang.annotation.Target;
<ide>
<del>import org.springframework.jdbc.datasource.init.ScriptUtils;
<del>import org.springframework.util.ResourceUtils;
<del>
<ide> import static java.lang.annotation.ElementType.*;
<ide> import static java.lang.annotation.RetentionPolicy.*;
<ide>
<ide> *
<ide> * <p>The configuration options provided by this annotation and
<ide> * {@link SqlConfig @SqlConfig} are equivalent to those supported by
<del> * {@link ScriptUtils} and
<del> * {@link org.springframework.jdbc.datasource.init.ResourceDatabasePopulator}
<add> * {@link org.springframework.jdbc.datasource.init.ScriptUtils ScriptUtils} and
<add> * {@link org.springframework.jdbc.datasource.init.ResourceDatabasePopulator ResourceDatabasePopulator}
<ide> * but are a superset of those provided by the {@code <jdbc:initialize-database/>}
<ide> * XML namespace element. Consult the javadocs of individual attributes in this
<ide> * annotation and {@link SqlConfig @SqlConfig} for details.
<ide> static enum ExecutionPhase {
<ide> * <em>absolute</em> classpath resource, for example:
<ide> * {@code "/org/example/schema.sql"}. A path which references a
<ide> * URL (e.g., a path prefixed with
<del> * {@link ResourceUtils#CLASSPATH_URL_PREFIX classpath:},
<del> * {@link ResourceUtils#FILE_URL_PREFIX file:}, {@code http:}, etc.) will be
<del> * loaded using the specified resource protocol.
<add> * {@link org.springframework.util.ResourceUtils#CLASSPATH_URL_PREFIX classpath:},
<add> * {@link org.springframework.util.ResourceUtils#FILE_URL_PREFIX file:},
<add> * {@code http:}, etc.) will be loaded using the specified resource protocol.
<ide> * <h3>Default Script Detection</h3>
<ide> * <p>If no SQL scripts are specified, an attempt will be made to detect a
<ide> * <em>default</em> script depending on where this annotation is declared.
<ide><path>spring-test/src/main/java/org/springframework/test/context/jdbc/SqlConfig.java
<ide> import java.lang.annotation.Retention;
<ide> import java.lang.annotation.Target;
<ide>
<del>import org.springframework.jdbc.datasource.init.ScriptUtils;
<del>
<ide> import static java.lang.annotation.ElementType.*;
<ide> import static java.lang.annotation.RetentionPolicy.*;
<ide>
<ide> * attribute. Thus, in order to support overrides of <em>inherited</em> global
<ide> * configuration, {@code @SqlConfig} attributes have an <em>explicit</em>
<ide> * {@code default} value of either {@code ""} for Strings or {@code DEFAULT} for
<del> * Enums. This approach allows local declarations {@code @SqlConfig} to
<add> * Enums. This approach allows local declarations of {@code @SqlConfig} to
<ide> * selectively override individual attributes from global declarations of
<ide> * {@code @SqlConfig} by providing a value other than {@code ""} or {@code DEFAULT}.
<ide> *
<ide> static enum TransactionMode {
<ide> DEFAULT,
<ide>
<ide> /**
<del> * Indicates that the transaction mode to use when executing SQL scripts
<del> * should be <em>inferred</em> based on whether or not a Spring-managed
<del> * transaction is currently present.
<del> * <p>SQL scripts will be executed within the current transaction if present;
<del> * otherwise, scripts will be executed in a new transaction that will be
<del> * immediately committed.
<del> * <p>The <em>current</em> transaction will typically be managed by the
<del> * {@link org.springframework.test.context.transaction.TransactionalTestExecutionListener
<del> * TransactionalTestExecutionListener}.
<add> * Indicates that the transaction mode to use when executing SQL
<add> * scripts should be <em>inferred</em> using the rules listed below.
<add> * In the context of these rules, the term "<em>available</em>"
<add> * means that the bean for the data source or transaction manager
<add> * is either explicitly specified via a corresponding annotation
<add> * attribute in {@code @SqlConfig} or discoverable via conventions. See
<add> * {@link org.springframework.test.context.transaction.TestContextTransactionUtils TestContextTransactionUtils}
<add> * for details on the conventions used to discover such beans in
<add> * the {@code ApplicationContext}.
<add> *
<add> * <h4>Inference Rules</h4>
<add> * <ol>
<add> * <li>If neither a transaction manager nor a data source is
<add> * available, an exception will be thrown.
<add> * <li>If a transaction manager is not available but a data source
<add> * is available, SQL scripts will be executed directly against the
<add> * data source without a transaction.
<add> * <li>If a transaction manager is available:
<add> * <ul>
<add> * <li>If a data source is not available, an attempt will be made
<add> * to retrieve it from the transaction manager by using reflection
<add> * to invoke a public method named {@code getDataSource()} on the
<add> * transaction manager. If the attempt fails, an exception will be
<add> * thrown.
<add> * <li>Using the resolved transaction manager and data source, SQL
<add> * scripts will be executed within an existing transaction if
<add> * present; otherwise, scripts will be executed in a new transaction
<add> * that will be immediately committed. An <em>existing</em>
<add> * transaction will typically be managed by the
<add> * {@link org.springframework.test.context.transaction.TransactionalTestExecutionListener TransactionalTestExecutionListener}.
<add> * </ul>
<add> * </ol>
<ide> * @see #ISOLATED
<add> * @see org.springframework.test.context.transaction.TestContextTransactionUtils#retrieveDataSource
<add> * @see org.springframework.test.context.transaction.TestContextTransactionUtils#retrieveTransactionManager
<ide> */
<ide> INFERRED,
<ide>
<ide> /**
<ide> * Indicates that SQL scripts should always be executed in a new,
<ide> * <em>isolated</em> transaction that will be immediately committed.
<add> * <p>In contrast to {@link #INFERRED}, this mode requires the
<add> * presence of a transaction manager <strong>and</strong> a data
<add> * source.
<ide> */
<ide> ISOLATED
<ide> }
<ide> static enum ErrorMode {
<ide>
<ide>
<ide> /**
<del> * The bean name of the {@link javax.sql.DataSource} against which the scripts
<del> * should be executed.
<del> * <p>The name is only used if there is more than one bean of type
<del> * {@code DataSource} in the test's {@code ApplicationContext}. If there is
<del> * only one such bean, it is not necessary to specify a bean name.
<add> * The bean name of the {@link javax.sql.DataSource} against which the
<add> * scripts should be executed.
<add> * <p>The name is only required if there is more than one bean of type
<add> * {@code DataSource} in the test's {@code ApplicationContext}. If there
<add> * is only one such bean, it is not necessary to specify a bean name.
<ide> * <p>Defaults to an empty string, requiring that one of the following is
<ide> * true:
<ide> * <ol>
<add> * <li>An explicit bean name is defined in a global declaration of
<add> * {@code @SqlConfig}.
<add> * <li>The data source can be retrieved from the transaction manager
<add> * by using reflection to invoke a public method named
<add> * {@code getDataSource()} on the transaction manager.
<ide> * <li>There is only one bean of type {@code DataSource} in the test's
<ide> * {@code ApplicationContext}.</li>
<ide> * <li>The {@code DataSource} to use is named {@code "dataSource"}.</li>
<ide> * </ol>
<add> * @see org.springframework.test.context.transaction.TestContextTransactionUtils#retrieveDataSource
<ide> */
<ide> String dataSource() default "";
<ide>
<ide> static enum ErrorMode {
<ide> * <p>Defaults to an empty string, requiring that one of the following is
<ide> * true:
<ide> * <ol>
<add> * <li>An explicit bean name is defined in a global declaration of
<add> * {@code @SqlConfig}.
<ide> * <li>There is only one bean of type {@code PlatformTransactionManager} in
<ide> * the test's {@code ApplicationContext}.</li>
<ide> * <li>{@link org.springframework.transaction.annotation.TransactionManagementConfigurer
<ide> static enum ErrorMode {
<ide> * <li>The {@code PlatformTransactionManager} to use is named
<ide> * {@code "transactionManager"}.</li>
<ide> * </ol>
<add> * @see org.springframework.test.context.transaction.TestContextTransactionUtils#retrieveTransactionManager
<ide> */
<ide> String transactionManager() default "";
<ide>
<ide> static enum ErrorMode {
<ide> * SQL scripts.
<ide> * <p>Implicitly defaults to {@code ";"} if not specified and falls back to
<ide> * {@code "\n"} as a last resort.
<del> * <p>May be set to {@link ScriptUtils#EOF_STATEMENT_SEPARATOR} to signal
<del> * that each script contains a single statement without a separator.
<del> * @see ScriptUtils#DEFAULT_STATEMENT_SEPARATOR
<add> * <p>May be set to
<add> * {@link org.springframework.jdbc.datasource.init.ScriptUtils#EOF_STATEMENT_SEPARATOR}
<add> * to signal that each script contains a single statement without a
<add> * separator.
<add> * @see org.springframework.jdbc.datasource.init.ScriptUtils#DEFAULT_STATEMENT_SEPARATOR
<add> * @see org.springframework.jdbc.datasource.init.ScriptUtils#EOF_STATEMENT_SEPARATOR
<ide> */
<ide> String separator() default "";
<ide>
<ide> /**
<ide> * The prefix that identifies single-line comments within the SQL scripts.
<ide> * <p>Implicitly defaults to {@code "--"}.
<del> * @see ScriptUtils#DEFAULT_COMMENT_PREFIX
<add> * @see org.springframework.jdbc.datasource.init.ScriptUtils#DEFAULT_COMMENT_PREFIX
<ide> */
<ide> String commentPrefix() default "";
<ide>
<ide> /**
<ide> * The start delimiter that identifies block comments within the SQL scripts.
<ide> * <p>Implicitly defaults to {@code "/*"}.
<ide> * @see #blockCommentEndDelimiter
<del> * @see ScriptUtils#DEFAULT_BLOCK_COMMENT_START_DELIMITER
<add> * @see org.springframework.jdbc.datasource.init.ScriptUtils#DEFAULT_BLOCK_COMMENT_START_DELIMITER
<ide> */
<ide> String blockCommentStartDelimiter() default "";
<ide>
<ide> /**
<ide> * The end delimiter that identifies block comments within the SQL scripts.
<ide> * <p>Implicitly defaults to <code>"*/"</code>.
<ide> * @see #blockCommentStartDelimiter
<del> * @see ScriptUtils#DEFAULT_BLOCK_COMMENT_END_DELIMITER
<add> * @see org.springframework.jdbc.datasource.init.ScriptUtils#DEFAULT_BLOCK_COMMENT_END_DELIMITER
<ide> */
<ide> String blockCommentEndDelimiter() default "";
<ide>
<ide><path>spring-test/src/main/java/org/springframework/test/context/jdbc/SqlScriptsTestExecutionListener.java
<ide> import org.springframework.transaction.support.TransactionTemplate;
<ide> import org.springframework.util.ClassUtils;
<ide> import org.springframework.util.ObjectUtils;
<add>import org.springframework.util.ReflectionUtils;
<ide> import org.springframework.util.ResourceUtils;
<ide>
<ide> /**
<ide> private void executeSqlScripts(Sql sql, ExecutionPhase executionPhase, TestConte
<ide> logger.debug("Executing SQL scripts: " + ObjectUtils.nullSafeToString(scripts));
<ide> }
<ide>
<del> final DataSource dataSource = TestContextTransactionUtils.retrieveDataSource(testContext,
<del> mergedSqlConfig.getDataSource());
<add> String dsName = mergedSqlConfig.getDataSource();
<add> String tmName = mergedSqlConfig.getTransactionManager();
<add> DataSource dataSource = TestContextTransactionUtils.retrieveDataSource(testContext, dsName);
<ide> final PlatformTransactionManager transactionManager = TestContextTransactionUtils.retrieveTransactionManager(
<del> testContext, mergedSqlConfig.getTransactionManager());
<add> testContext, tmName);
<add> final boolean newTxRequired = mergedSqlConfig.getTransactionMode() == TransactionMode.ISOLATED;
<ide>
<del> int propagation = (mergedSqlConfig.getTransactionMode() == TransactionMode.ISOLATED) ? TransactionDefinition.PROPAGATION_REQUIRES_NEW
<del> : TransactionDefinition.PROPAGATION_REQUIRED;
<add> if (transactionManager == null) {
<add> if (newTxRequired) {
<add> throw new IllegalStateException(String.format("Failed to execute SQL scripts for test context %s: "
<add> + "cannot execute SQL scripts using Transaction Mode "
<add> + "[%s] without a PlatformTransactionManager.", testContext, TransactionMode.ISOLATED));
<add> }
<add>
<add> if (dataSource == null) {
<add> throw new IllegalStateException(String.format("Failed to execute SQL scripts for test context %s: "
<add> + "supply at least a DataSource or PlatformTransactionManager.", testContext));
<add> }
<ide>
<del> TransactionAttribute transactionAttribute = TestContextTransactionUtils.createDelegatingTransactionAttribute(
<del> testContext, new DefaultTransactionAttribute(propagation));
<add> // Execute scripts directly against the DataSource
<add> populator.execute(dataSource);
<add> }
<add> else {
<add> DataSource dataSourceFromTxMgr = getDataSourceFromTransactionManager(transactionManager);
<add>
<add> // Ensure user configured an appropriate DataSource/TransactionManager pair.
<add> if ((dataSource != null) && (dataSourceFromTxMgr != null) && !dataSource.equals(dataSourceFromTxMgr)) {
<add> throw new IllegalStateException(String.format("Failed to execute SQL scripts for test context %s: "
<add> + "the configured DataSource [%s] (named '%s') is not the one associated "
<add> + "with transaction manager [%s] (named '%s').", testContext, dataSource.getClass().getName(),
<add> dsName, transactionManager.getClass().getName(), tmName));
<add> }
<add>
<add> if (dataSource == null) {
<add> dataSource = dataSourceFromTxMgr;
<add> if (dataSource == null) {
<add> throw new IllegalStateException(String.format("Failed to execute SQL scripts for test context %s: "
<add> + "could not obtain DataSource from transaction manager [%s] (named '%s').", testContext,
<add> transactionManager.getClass().getName(), tmName));
<add> }
<add> }
<ide>
<del> new TransactionTemplate(transactionManager, transactionAttribute).execute(new TransactionCallbackWithoutResult() {
<add> final DataSource finalDataSource = dataSource;
<add> int propagation = newTxRequired ? TransactionDefinition.PROPAGATION_REQUIRES_NEW
<add> : TransactionDefinition.PROPAGATION_REQUIRED;
<ide>
<del> @Override
<del> public void doInTransactionWithoutResult(TransactionStatus status) {
<del> populator.execute(dataSource);
<del> };
<del> });
<add> TransactionAttribute transactionAttribute = TestContextTransactionUtils.createDelegatingTransactionAttribute(
<add> testContext, new DefaultTransactionAttribute(propagation));
<add>
<add> new TransactionTemplate(transactionManager, transactionAttribute).execute(new TransactionCallbackWithoutResult() {
<add>
<add> @Override
<add> public void doInTransactionWithoutResult(TransactionStatus status) {
<add> populator.execute(finalDataSource);
<add> }
<add> });
<add> }
<add> }
<add>
<add> private DataSource getDataSourceFromTransactionManager(PlatformTransactionManager transactionManager) {
<add> try {
<add> Method getDataSourceMethod = transactionManager.getClass().getMethod("getDataSource");
<add> Object obj = ReflectionUtils.invokeMethod(getDataSourceMethod, transactionManager);
<add> if (obj instanceof DataSource) {
<add> return (DataSource) obj;
<add> }
<add> }
<add> catch (Exception e) {
<add> /* ignore */
<add> }
<add> return null;
<ide> }
<ide>
<ide> private String[] getScripts(Sql sql, TestContext testContext, boolean classLevel) {
<ide><path>spring-test/src/main/java/org/springframework/test/context/transaction/TestContextTransactionUtils.java
<ide> private TestContextTransactionUtils() {
<ide> /**
<ide> * Retrieve the {@link DataSource} to use for the supplied {@linkplain TestContext
<ide> * test context}.
<del> * <p>The following algorithm is used to retrieve the {@code DataSource}
<del> * from the {@link org.springframework.context.ApplicationContext ApplicationContext}
<add> * <p>The following algorithm is used to retrieve the {@code DataSource} from
<add> * the {@link org.springframework.context.ApplicationContext ApplicationContext}
<ide> * of the supplied test context:
<ide> * <ol>
<ide> * <li>Look up the {@code DataSource} by type and name, if the supplied
<del> * {@code name} is non-empty.
<del> * <li>Look up the {@code DataSource} by type.
<del> * <li>Look up the {@code DataSource} by type and the
<add> * {@code name} is non-empty, throwing a {@link BeansException} if the named
<add> * {@code DataSource} does not exist.
<add> * <li>Attempt to look up a single {@code DataSource} by type.
<add> * <li>Attempt to look up the {@code DataSource} by type and the
<ide> * {@linkplain #DEFAULT_DATA_SOURCE_NAME default data source name}.
<ide> * @param testContext the test context for which the {@code DataSource}
<ide> * should be retrieved; never {@code null}
<ide> * @param name the name of the {@code DataSource} to retrieve; may be {@code null}
<ide> * or <em>empty</em>
<del> * @return the {@code DataSource} to use
<del> * @throws BeansException if an error occurs while retrieving the {@code DataSource}
<add> * @return the {@code DataSource} to use, or {@code null} if not found
<add> * @throws BeansException if an error occurs while retrieving an explicitly
<add> * named {@code DataSource}
<ide> */
<ide> public static DataSource retrieveDataSource(TestContext testContext, String name) {
<ide> Assert.notNull(testContext, "TestContext must not be null");
<ide> public static DataSource retrieveDataSource(TestContext testContext, String name
<ide> if (StringUtils.hasText(name)) {
<ide> return bf.getBean(name, DataSource.class);
<ide> }
<add> }
<add> catch (BeansException ex) {
<add> logger.error(
<add> String.format("Failed to retrieve DataSource named '%s' for test context %s", name, testContext), ex);
<add> throw ex;
<add> }
<ide>
<add> try {
<ide> if (bf instanceof ListableBeanFactory) {
<ide> ListableBeanFactory lbf = (ListableBeanFactory) bf;
<ide>
<ide> public static DataSource retrieveDataSource(TestContext testContext, String name
<ide> return bf.getBean(DEFAULT_DATA_SOURCE_NAME, DataSource.class);
<ide> }
<ide> catch (BeansException ex) {
<del> if (logger.isWarnEnabled()) {
<del> logger.warn("Caught exception while retrieving DataSource for test context " + testContext, ex);
<add> if (logger.isDebugEnabled()) {
<add> logger.debug("Caught exception while retrieving DataSource for test context " + testContext, ex);
<ide> }
<del> throw ex;
<add> return null;
<ide> }
<ide> }
<ide>
<ide> public static DataSource retrieveDataSource(TestContext testContext, String name
<ide> * from the {@link org.springframework.context.ApplicationContext ApplicationContext}
<ide> * of the supplied test context:
<ide> * <ol>
<del> * <li>Look up the transaction manager by type and name, if the supplied
<del> * {@code name} is non-empty.
<del> * <li>Look up the transaction manager by type.
<del> * <li>Look up the transaction manager via a {@link TransactionManagementConfigurer},
<del> * if present.
<del> * <li>Look up the transaction manager by type and the
<add> * <li>Look up the transaction manager by type and explicit name, if the supplied
<add> * {@code name} is non-empty, throwing a {@link BeansException} if the named
<add> * transaction manager does not exist.
<add> * <li>Attempt to look up the transaction manager by type.
<add> * <li>Attempt to look up the transaction manager via a
<add> * {@link TransactionManagementConfigurer}, if present.
<add> * <li>Attempt to look up the transaction manager by type and the
<ide> * {@linkplain #DEFAULT_TRANSACTION_MANAGER_NAME default transaction manager
<ide> * name}.
<ide> * @param testContext the test context for which the transaction manager
<ide> * should be retrieved; never {@code null}
<ide> * @param name the name of the transaction manager to retrieve; may be
<ide> * {@code null} or <em>empty</em>
<del> * @return the transaction manager to use
<del> * @throws BeansException if an error occurs while retrieving the transaction manager
<add> * @return the transaction manager to use, or {@code null} if not found
<add> * @throws BeansException if an error occurs while retrieving an explicitly
<add> * named transaction manager
<ide> */
<ide> public static PlatformTransactionManager retrieveTransactionManager(TestContext testContext, String name) {
<ide> Assert.notNull(testContext, "TestContext must not be null");
<ide> public static PlatformTransactionManager retrieveTransactionManager(TestContext
<ide> if (StringUtils.hasText(name)) {
<ide> return bf.getBean(name, PlatformTransactionManager.class);
<ide> }
<add> }
<add> catch (BeansException ex) {
<add> logger.error(String.format("Failed to retrieve transaction manager named '%s' for test context %s", name,
<add> testContext), ex);
<add> throw ex;
<add> }
<ide>
<add> try {
<ide> if (bf instanceof ListableBeanFactory) {
<ide> ListableBeanFactory lbf = (ListableBeanFactory) bf;
<ide>
<ide> public static PlatformTransactionManager retrieveTransactionManager(TestContext
<ide> return bf.getBean(DEFAULT_TRANSACTION_MANAGER_NAME, PlatformTransactionManager.class);
<ide> }
<ide> catch (BeansException ex) {
<del> if (logger.isWarnEnabled()) {
<del> logger.warn("Caught exception while retrieving transaction manager for test context " + testContext, ex);
<add> if (logger.isDebugEnabled()) {
<add> logger.debug("Caught exception while retrieving transaction manager for test context " + testContext,
<add> ex);
<ide> }
<del> throw ex;
<add> return null;
<ide> }
<ide> }
<ide>
<ide><path>spring-test/src/main/java/org/springframework/test/context/transaction/TransactionalTestExecutionListener.java
<ide> protected PlatformTransactionManager getTransactionManager(TestContext testConte
<ide> }
<ide> catch (RuntimeException ex) {
<ide> if (logger.isWarnEnabled()) {
<del> logger.warn("Caught exception while retrieving transaction manager for test context " + testContext
<del> + " and qualifier [" + qualifier + "]", ex);
<add> logger.warn(
<add> String.format(
<add> "Caught exception while retrieving transaction manager with qualifier '%s' for test context %s",
<add> qualifier, testContext), ex);
<ide> }
<ide> throw ex;
<ide> }
<ide> protected PlatformTransactionManager getTransactionManager(TestContext testConte
<ide> * @param testContext the test context for which the transaction manager
<ide> * should be retrieved
<ide> * @return the transaction manager to use, or {@code null} if not found
<del> * @throws BeansException if an error occurs while retrieving the transaction manager
<add> * @throws BeansException if an error occurs while retrieving an explicitly
<add> * named transaction manager
<ide> * @see #getTransactionManager(TestContext, String)
<ide> */
<ide> protected PlatformTransactionManager getTransactionManager(TestContext testContext) {
<ide><path>spring-test/src/test/java/org/springframework/test/context/jdbc/DataSourceOnlySqlScriptsTests.java
<add>/*
<add> * Copyright 2002-2014 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.test.context.jdbc;
<add>
<add>import javax.sql.DataSource;
<add>
<add>import org.junit.FixMethodOrder;
<add>import org.junit.Test;
<add>import org.junit.runner.RunWith;
<add>import org.junit.runners.MethodSorters;
<add>import org.springframework.beans.factory.annotation.Autowired;
<add>import org.springframework.context.annotation.Bean;
<add>import org.springframework.context.annotation.Configuration;
<add>import org.springframework.jdbc.core.JdbcTemplate;
<add>import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
<add>import org.springframework.test.annotation.DirtiesContext;
<add>import org.springframework.test.context.ContextConfiguration;
<add>import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
<add>import org.springframework.test.jdbc.JdbcTestUtils;
<add>
<add>import static org.junit.Assert.*;
<add>import static org.springframework.test.transaction.TransactionTestUtils.*;
<add>
<add>/**
<add> * Integration tests for {@link Sql @Sql} support with only a {@link DataSource}
<add> * present in the context (i.e., no transaction manager).
<add> *
<add> * @author Sam Brannen
<add> * @since 4.1
<add> */
<add>@RunWith(SpringJUnit4ClassRunner.class)
<add>@FixMethodOrder(MethodSorters.NAME_ASCENDING)
<add>@ContextConfiguration
<add>@Sql({ "schema.sql", "data.sql" })
<add>@DirtiesContext
<add>public class DataSourceOnlySqlScriptsTests {
<add>
<add> private JdbcTemplate jdbcTemplate;
<add>
<add>
<add> @Autowired
<add> public void setDataSource(DataSource dataSource) {
<add> this.jdbcTemplate = new JdbcTemplate(dataSource);
<add> }
<add>
<add> @Test
<add> // test##_ prefix is required for @FixMethodOrder.
<add> public void test01_classLevelScripts() {
<add> assertInTransaction(false);
<add> assertNumUsers(1);
<add> }
<add>
<add> @Test
<add> @Sql({ "drop-schema.sql", "schema.sql", "data.sql", "data-add-dogbert.sql" })
<add> // test##_ prefix is required for @FixMethodOrder.
<add> public void test02_methodLevelScripts() {
<add> assertInTransaction(false);
<add> assertNumUsers(2);
<add> }
<add>
<add> protected void assertNumUsers(int expected) {
<add> assertEquals("Number of rows in the 'user' table.", expected,
<add> JdbcTestUtils.countRowsInTable(jdbcTemplate, "user"));
<add> }
<add>
<add>
<add> @Configuration
<add> static class Config {
<add>
<add> @Bean
<add> public DataSource dataSource() {
<add> return new EmbeddedDatabaseBuilder()//
<add> .setName("empty-sql-scripts-without-tx-mgr-test-db")//
<add> .build();
<add> }
<add> }
<add>
<add>}
<ide><path>spring-test/src/test/java/org/springframework/test/context/jdbc/InferredDataSourceSqlScriptsTests.java
<add>/*
<add> * Copyright 2002-2014 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.test.context.jdbc;
<add>
<add>import java.util.Arrays;
<add>import java.util.Collections;
<add>import java.util.List;
<add>
<add>import javax.sql.DataSource;
<add>
<add>import org.junit.Test;
<add>import org.junit.runner.RunWith;
<add>import org.springframework.beans.factory.annotation.Autowired;
<add>import org.springframework.context.annotation.Bean;
<add>import org.springframework.context.annotation.Configuration;
<add>import org.springframework.jdbc.core.JdbcTemplate;
<add>import org.springframework.jdbc.datasource.DataSourceTransactionManager;
<add>import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
<add>import org.springframework.test.annotation.DirtiesContext;
<add>import org.springframework.test.context.ContextConfiguration;
<add>import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
<add>import org.springframework.transaction.PlatformTransactionManager;
<add>
<add>import static org.junit.Assert.*;
<add>import static org.springframework.test.transaction.TransactionTestUtils.*;
<add>
<add>/**
<add> * Integration tests for {@link Sql @Sql} that verify support for inferring
<add> * {@link DataSource}s from {@link PlatformTransactionManager}s.
<add> *
<add> * @author Sam Brannen
<add> * @since 4.1
<add> * @see InferredDataSourceTransactionalSqlScriptsTests
<add> */
<add>@RunWith(SpringJUnit4ClassRunner.class)
<add>@ContextConfiguration
<add>@DirtiesContext
<add>public class InferredDataSourceSqlScriptsTests {
<add>
<add> @Autowired
<add> private DataSource dataSource1;
<add>
<add> @Autowired
<add> private DataSource dataSource2;
<add>
<add>
<add> @Test
<add> @Sql(scripts = "data-add-dogbert.sql", config = @SqlConfig(transactionManager = "txMgr1"))
<add> public void database1() {
<add> assertInTransaction(false);
<add> assertUsers(new JdbcTemplate(dataSource1), "Dilbert", "Dogbert");
<add> }
<add>
<add> @Test
<add> @Sql(scripts = "data-add-catbert.sql", config = @SqlConfig(transactionManager = "txMgr2"))
<add> public void database2() {
<add> assertInTransaction(false);
<add> assertUsers(new JdbcTemplate(dataSource2), "Dilbert", "Catbert");
<add> }
<add>
<add> private void assertUsers(JdbcTemplate jdbcTemplate, String... users) {
<add> List<String> expected = Arrays.asList(users);
<add> Collections.sort(expected);
<add> List<String> actual = jdbcTemplate.queryForList("select name from user", String.class);
<add> Collections.sort(actual);
<add> assertEquals("Users in database;", expected, actual);
<add> }
<add>
<add>
<add> @Configuration
<add> static class Config {
<add>
<add> @Bean
<add> public PlatformTransactionManager txMgr1() {
<add> return new DataSourceTransactionManager(dataSource1());
<add> }
<add>
<add> @Bean
<add> public PlatformTransactionManager txMgr2() {
<add> return new DataSourceTransactionManager(dataSource2());
<add> }
<add>
<add> @Bean
<add> public DataSource dataSource1() {
<add> return new EmbeddedDatabaseBuilder()//
<add> .setName("database1")//
<add> .addScript("classpath:/org/springframework/test/context/jdbc/schema.sql")//
<add> .addScript("classpath:/org/springframework/test/context/jdbc/data.sql")//
<add> .build();
<add> }
<add>
<add> @Bean
<add> public DataSource dataSource2() {
<add> return new EmbeddedDatabaseBuilder()//
<add> .setName("database2")//
<add> .addScript("classpath:/org/springframework/test/context/jdbc/schema.sql")//
<add> .addScript("classpath:/org/springframework/test/context/jdbc/data.sql")//
<add> .build();
<add> }
<add> }
<add>
<add>}
<ide><path>spring-test/src/test/java/org/springframework/test/context/jdbc/InferredDataSourceTransactionalSqlScriptsTests.java
<add>/*
<add> * Copyright 2002-2014 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.test.context.jdbc;
<add>
<add>import java.util.Arrays;
<add>import java.util.Collections;
<add>import java.util.List;
<add>
<add>import javax.sql.DataSource;
<add>
<add>import org.junit.Test;
<add>import org.junit.runner.RunWith;
<add>import org.springframework.beans.factory.annotation.Autowired;
<add>import org.springframework.context.annotation.Bean;
<add>import org.springframework.context.annotation.Configuration;
<add>import org.springframework.jdbc.core.JdbcTemplate;
<add>import org.springframework.jdbc.datasource.DataSourceTransactionManager;
<add>import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
<add>import org.springframework.test.annotation.DirtiesContext;
<add>import org.springframework.test.context.ContextConfiguration;
<add>import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
<add>import org.springframework.transaction.PlatformTransactionManager;
<add>import org.springframework.transaction.annotation.Transactional;
<add>
<add>import static org.springframework.test.transaction.TransactionTestUtils.*;
<add>
<add>import static org.junit.Assert.*;
<add>
<add>/**
<add> * Exact copy of {@link InferredDataSourceSqlScriptsTests}, except that test
<add> * methods are transactional.
<add> *
<add> * @author Sam Brannen
<add> * @since 4.1
<add> * @see InferredDataSourceSqlScriptsTests
<add> */
<add>@RunWith(SpringJUnit4ClassRunner.class)
<add>@ContextConfiguration
<add>@DirtiesContext
<add>public class InferredDataSourceTransactionalSqlScriptsTests {
<add>
<add> @Autowired
<add> private DataSource dataSource1;
<add>
<add> @Autowired
<add> private DataSource dataSource2;
<add>
<add>
<add> @Test
<add> @Transactional("txMgr1")
<add> @Sql(scripts = "data-add-dogbert.sql", config = @SqlConfig(transactionManager = "txMgr1"))
<add> public void database1() {
<add> assertInTransaction(true);
<add> assertUsers(new JdbcTemplate(dataSource1), "Dilbert", "Dogbert");
<add> }
<add>
<add> @Test
<add> @Transactional("txMgr2")
<add> @Sql(scripts = "data-add-catbert.sql", config = @SqlConfig(transactionManager = "txMgr2"))
<add> public void database2() {
<add> assertInTransaction(true);
<add> assertUsers(new JdbcTemplate(dataSource2), "Dilbert", "Catbert");
<add> }
<add>
<add> private void assertUsers(JdbcTemplate jdbcTemplate, String... users) {
<add> List<String> expected = Arrays.asList(users);
<add> Collections.sort(expected);
<add> List<String> actual = jdbcTemplate.queryForList("select name from user", String.class);
<add> Collections.sort(actual);
<add> assertEquals("Users in database;", expected, actual);
<add> }
<add>
<add>
<add> @Configuration
<add> static class Config {
<add>
<add> @Bean
<add> public PlatformTransactionManager txMgr1() {
<add> return new DataSourceTransactionManager(dataSource1());
<add> }
<add>
<add> @Bean
<add> public PlatformTransactionManager txMgr2() {
<add> return new DataSourceTransactionManager(dataSource2());
<add> }
<add>
<add> @Bean
<add> public DataSource dataSource1() {
<add> return new EmbeddedDatabaseBuilder()//
<add> .setName("database1")//
<add> .addScript("classpath:/org/springframework/test/context/jdbc/schema.sql")//
<add> .addScript("classpath:/org/springframework/test/context/jdbc/data.sql")//
<add> .build();
<add> }
<add>
<add> @Bean
<add> public DataSource dataSource2() {
<add> return new EmbeddedDatabaseBuilder()//
<add> .setName("database2")//
<add> .addScript("classpath:/org/springframework/test/context/jdbc/schema.sql")//
<add> .addScript("classpath:/org/springframework/test/context/jdbc/data.sql")//
<add> .build();
<add> }
<add> }
<add>
<add>}
<ide><path>spring-test/src/test/java/org/springframework/test/context/jdbc/SqlScriptsTestExecutionListenerTests.java
<ide>
<ide> import org.junit.Test;
<ide> import org.mockito.Mockito;
<add>import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
<add>import org.springframework.context.ApplicationContext;
<add>import org.springframework.core.io.Resource;
<ide> import org.springframework.test.context.TestContext;
<add>import org.springframework.test.context.jdbc.SqlConfig.TransactionMode;
<ide>
<ide> import static org.junit.Assert.*;
<add>import static org.mockito.Matchers.*;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> /**
<ide> public void missingValueAndScriptsAtMethodLevel() throws Exception {
<ide> public void valueAndScriptsDeclared() throws Exception {
<ide> Class<?> clazz = ValueAndScriptsDeclared.class;
<ide> Mockito.<Class<?>> when(testContext.getTestClass()).thenReturn(clazz);
<del> when(testContext.getTestMethod()).thenReturn(clazz.getDeclaredMethod("valueAndScriptsDeclared"));
<add> when(testContext.getTestMethod()).thenReturn(clazz.getDeclaredMethod("foo"));
<ide>
<ide> assertExceptionContains("Only one declaration of SQL script paths is permitted");
<ide> }
<ide>
<add> @Test
<add> public void isolatedTxModeDeclaredWithoutTxMgr() throws Exception {
<add> ApplicationContext ctx = mock(ApplicationContext.class);
<add> when(ctx.getResource(anyString())).thenReturn(mock(Resource.class));
<add> when(ctx.getAutowireCapableBeanFactory()).thenReturn(mock(AutowireCapableBeanFactory.class));
<add>
<add> Class<?> clazz = IsolatedWithoutTxMgr.class;
<add> Mockito.<Class<?>> when(testContext.getTestClass()).thenReturn(clazz);
<add> when(testContext.getTestMethod()).thenReturn(clazz.getDeclaredMethod("foo"));
<add> when(testContext.getApplicationContext()).thenReturn(ctx);
<add>
<add> assertExceptionContains("cannot execute SQL scripts using Transaction Mode [ISOLATED] without a PlatformTransactionManager");
<add> }
<add>
<add> @Test
<add> public void missingDataSourceAndTxMgr() throws Exception {
<add> ApplicationContext ctx = mock(ApplicationContext.class);
<add> when(ctx.getResource(anyString())).thenReturn(mock(Resource.class));
<add> when(ctx.getAutowireCapableBeanFactory()).thenReturn(mock(AutowireCapableBeanFactory.class));
<add>
<add> Class<?> clazz = MissingDataSourceAndTxMgr.class;
<add> Mockito.<Class<?>> when(testContext.getTestClass()).thenReturn(clazz);
<add> when(testContext.getTestMethod()).thenReturn(clazz.getDeclaredMethod("foo"));
<add> when(testContext.getApplicationContext()).thenReturn(ctx);
<add>
<add> assertExceptionContains("supply at least a DataSource or PlatformTransactionManager");
<add> }
<add>
<ide> private void assertExceptionContains(String msg) throws Exception {
<ide> try {
<ide> listener.beforeTestMethod(testContext);
<ide> fail("Should have thrown an IllegalStateException.");
<ide> }
<ide> catch (IllegalStateException e) {
<add> // System.err.println(e.getMessage());
<ide> assertTrue("Exception message should contain: " + msg, e.getMessage().contains(msg));
<ide> }
<ide> }
<ide> public void foo() {
<ide> static class ValueAndScriptsDeclared {
<ide>
<ide> @Sql(value = "foo", scripts = "bar")
<del> public void valueAndScriptsDeclared() {
<add> public void foo() {
<add> }
<add> }
<add>
<add> static class IsolatedWithoutTxMgr {
<add>
<add> @Sql(scripts = "foo.sql", config = @SqlConfig(transactionMode = TransactionMode.ISOLATED))
<add> public void foo() {
<add> }
<add> }
<add>
<add> static class MissingDataSourceAndTxMgr {
<add>
<add> @Sql("foo.sql")
<add> public void foo() {
<ide> }
<ide> }
<ide> | 9 |
Python | Python | refactor the function - _convert_string_dtype | e0fefdae0cae9c97f318fca9717467f7faf071d9 | <ide><path>keras/backend/tensorflow_backend.py
<ide> def _convert_string_dtype(dtype):
<ide> # Raises
<ide> ValueError: if `dtype` is not supported.
<ide> """
<del> if dtype == 'float16':
<del> return tf.float16
<del> if dtype == 'float32':
<del> return tf.float32
<del> elif dtype == 'float64':
<del> return tf.float64
<del> elif dtype == 'int16':
<del> return tf.int16
<del> elif dtype == 'int32':
<del> return tf.int32
<del> elif dtype == 'int64':
<del> return tf.int64
<del> elif dtype == 'uint8':
<del> return tf.int8
<del> elif dtype == 'uint16':
<del> return tf.uint16
<del> else:
<add> mapping = {'float16': tf.float16,
<add> 'float32': tf.float32,
<add> 'float64': tf.float64,
<add> 'int16': tf.int16,
<add> 'int32': tf.int32,
<add> 'int64': tf.int64,
<add> 'uint8': tf.int8,
<add> 'uint16': tf.uint16}
<add>
<add> if dtype not in mapping:
<ide> raise ValueError('Unsupported dtype:', dtype)
<add> return mapping[dtype]
<ide>
<ide>
<ide> def _to_tensor(x, dtype): | 1 |
Javascript | Javascript | fix get{left|right|bottom}dock links | 02258a9994030579af31b8e05f0e8a4f080da510 | <ide><path>src/dock.js
<ide> const CURSOR_OVERLAY_VISIBLE_CLASS = 'atom-dock-cursor-overlay-visible'
<ide>
<ide> // Extended: A container at the edges of the editor window capable of holding items.
<ide> // You should not create a Dock directly. Instead, access one of the three docks of the workspace
<del>// via {::getLeftDock}, {::getRightDock}, and {::getBottomDock} or add an item to a dock via
<del>// {Workspace::open}.
<add>// via {Workspace::getLeftDock}, {Workspace::getRightDock}, and {Workspace::getBottomDock}
<add>// or add an item to a dock via {Workspace::open}.
<ide> module.exports = class Dock {
<ide> constructor (params) {
<ide> this.handleResizeHandleDragStart = this.handleResizeHandleDragStart.bind(this) | 1 |
Mixed | Text | change active storage destroy callbacks | 9431529011b0057bb8833dc16726714166547a28 | <ide><path>activestorage/CHANGELOG.md
<add>* Use `after_destroy_commit` instead of `before_destroy` for purging
<add> attachments when a record is destroyed.
<add>
<add> *Hiroki Zenigami*
<add>
<add>
<ide> * Force `:attachment` disposition for specific, configurable content types.
<ide> This mitigates possible security issues such as XSS or phishing when
<ide> serving them inline. A list of such content types is included by default,
<ide><path>activestorage/lib/active_storage/attached/macros.rb
<ide> def #{name}=(attachable)
<ide> scope :"with_attached_#{name}", -> { includes("#{name}_attachment": :blob) }
<ide>
<ide> if dependent == :purge_later
<del> before_destroy { public_send(name).purge_later }
<add> after_destroy_commit { public_send(name).purge_later }
<ide> end
<ide> end
<ide>
<ide> def #{name}=(attachables)
<ide> scope :"with_attached_#{name}", -> { includes("#{name}_attachments": :blob) }
<ide>
<ide> if dependent == :purge_later
<del> before_destroy { public_send(name).purge_later }
<add> after_destroy_commit { public_send(name).purge_later }
<ide> end
<ide> end
<ide> end | 2 |
PHP | PHP | fix array keys | f17864364ade5b8dabda9aa26bc2af13c6f832ff | <ide><path>src/Http/ResponseEmitter.php
<ide> protected function emitCookies(array $cookies): void
<ide> setcookie(
<ide> $cookie['name'],
<ide> $cookie['value'],
<del> $cookie['options']['expire'],
<add> $cookie['options']['expires'],
<ide> $cookie['options']['path'],
<ide> $cookie['options']['domain'],
<ide> $cookie['options']['secure'],
<del> $cookie['options']['httpOnly']
<add> $cookie['options']['httponly']
<ide> );
<ide> }
<ide> continue; | 1 |
Ruby | Ruby | ignore unparsable system languages | 48dcf1916928999776df36882a553f15a9f0ffe7 | <ide><path>Library/Homebrew/cask/lib/hbc/dsl.rb
<ide> def language_eval
<ide> raise CaskInvalidError.new(cask, "No default language specified.")
<ide> end
<ide>
<del> MacOS.languages.map(&Locale.method(:parse)).each do |locale|
<add> locales = MacOS.languages
<add> .map do |language|
<add> begin
<add> Locale.parse(language)
<add> rescue Locale::ParserError
<add> nil
<add> end
<add> end
<add> .compact
<add>
<add> locales.each do |locale|
<ide> key = locale.detect(@language_blocks.keys)
<ide>
<ide> next if key.nil? | 1 |
Javascript | Javascript | add sigwinch handler for readline | 0ef8a86af24be8e209a7b6747bde358bb878272e | <ide><path>lib/readline.js
<ide> function Interface (output, completer) {
<ide>
<ide> this.history = [];
<ide> this.historyIndex = -1;
<add>
<add> exports.columns = process.binding('stdio').getColumns();
<add>
<add> if (process.listeners("SIGWINCH").length === 0) {
<add> process.on("SIGWINCH", function () {
<add> exports.columns = process.binding('stdio').getColumns();
<add> });
<add> }
<ide> }
<ide> }
<ide>
<ide> inherits(Interface, EventEmitter);
<ide>
<ide> Interface.prototype.__defineGetter__("columns", function () {
<del> if (this.enabled) {
<del> return stdio.getColumns();
<del> }
<add> return exports.columns;
<ide> });
<ide>
<ide> Interface.prototype.setPrompt = function (prompt, length) { | 1 |
Ruby | Ruby | kill dead code | 7b8f4b3d19bd2f27096fe0d7b15666abc7072e2f | <ide><path>Library/Homebrew/download_strategy.rb
<ide> def self.detect(url, strategy=nil)
<ide> end
<ide> end
<ide>
<del> private
<del>
<ide> def self.detect_from_url(url)
<ide> case url
<ide> # We use a special URL pattern for cvs | 1 |
Javascript | Javascript | remove workaround code in debugger test | 12622c5f86fde7c878c7e4e7f441206cf0980457 | <ide><path>test/sequential/test-debugger-preserve-breaks.js
<ide> const path = require('path');
<ide> })
<ide> .then(() => cli.command('breakpoints'))
<ide> .then(() => {
<del> // TODO: There is a known issue on AIX and some other operating systems
<del> // where the breakpoints aren't properly resolved yet when we reach this
<del> // point. Eventually that should be figured out but for now we don't
<del> // want to fail builds because of it.
<del> // What it should be:
<del> //
<del> // const msg = `SCRIPT: ${script}, OUTPUT: ${cli.output}`;
<del> // assert.ok(cli.output.includes(`#0 ${script}:2`), msg);
<del> // assert.ok(cli.output.includes(`#1 ${script}:3`), msg);
<del> //
<del> // What we're doing for now instead:
<del> assert.match(cli.output, /#0 [^\n]+three-lines\.js\$?:2/);
<del> assert.match(cli.output, /#1 [^\n]+three-lines\.js\$?:3/);
<add> const msg = `SCRIPT: ${script}, OUTPUT: ${cli.output}`;
<add> assert.ok(cli.output.includes(`#0 ${script}:2`), msg);
<add> assert.ok(cli.output.includes(`#1 ${script}:3`), msg);
<ide> })
<ide> .then(() => cli.quit())
<ide> .then(null, onFatal); | 1 |
Javascript | Javascript | fix typo in reactdominput-test | 2521b4770708e5cd2bd9f0b04d1d8aec621d613e | <ide><path>src/dom/components/__tests__/ReactDOMInput-test.js
<ide> describe('ReactDOMInput', function() {
<ide> it('should support checkedLink', function() {
<ide> var container = document.createElement('div');
<ide> var link = new ReactLink(true, mocks.getMockFunction());
<del> var instance = <input type="checked" checkedLink={link} />;
<add> var instance = <input type="checkbox" checkedLink={link} />;
<ide>
<ide> React.renderComponent(instance, container);
<ide> | 1 |
Go | Go | use uintptr instead of int for fd | 31eb01ae8aac22a4d768418d3cc4da6f903a8694 | <ide><path>commands.go
<ide> func (cli *DockerCli) hijack(method, path string, setRawTerminal bool, in *os.Fi
<ide> return err
<ide> })
<ide>
<del> if in != nil && setRawTerminal && term.IsTerminal(int(in.Fd())) && os.Getenv("NORAW") == "" {
<add> if in != nil && setRawTerminal && term.IsTerminal(in.Fd()) && os.Getenv("NORAW") == "" {
<ide> if oldState, err := term.SetRawTerminal(); err != nil {
<ide> return err
<ide> } else {
<ide> func (cli *DockerCli) hijack(method, path string, setRawTerminal bool, in *os.Fi
<ide> return err
<ide> }
<ide>
<del> if !term.IsTerminal(int(os.Stdin.Fd())) {
<add> if !term.IsTerminal(os.Stdin.Fd()) {
<ide> if err := <-sendStdin; err != nil {
<ide> return err
<ide> }
<ide><path>term/term.go
<ide> func SetWinsize(fd uintptr, ws *Winsize) error {
<ide> }
<ide>
<ide> // IsTerminal returns true if the given file descriptor is a terminal.
<del>func IsTerminal(fd int) bool {
<add>func IsTerminal(fd uintptr) bool {
<ide> var termios Termios
<del> _, _, err := syscall.Syscall(syscall.SYS_IOCTL, uintptr(fd), uintptr(getTermios), uintptr(unsafe.Pointer(&termios)))
<add> _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, uintptr(getTermios), uintptr(unsafe.Pointer(&termios)))
<ide> return err == 0
<ide> }
<ide>
<ide> // Restore restores the terminal connected to the given file descriptor to a
<ide> // previous state.
<del>func Restore(fd int, state *State) error {
<del> _, _, err := syscall.Syscall(syscall.SYS_IOCTL, uintptr(fd), uintptr(setTermios), uintptr(unsafe.Pointer(&state.termios)))
<add>func Restore(fd uintptr, state *State) error {
<add> _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, uintptr(setTermios), uintptr(unsafe.Pointer(&state.termios)))
<ide> return err
<ide> }
<ide>
<ide> func SetRawTerminal() (*State, error) {
<del> oldState, err := MakeRaw(int(os.Stdin.Fd()))
<add> oldState, err := MakeRaw(os.Stdin.Fd())
<ide> if err != nil {
<ide> return nil, err
<ide> }
<ide> c := make(chan os.Signal, 1)
<ide> signal.Notify(c, os.Interrupt)
<ide> go func() {
<ide> _ = <-c
<del> Restore(int(os.Stdin.Fd()), oldState)
<add> Restore(os.Stdin.Fd(), oldState)
<ide> os.Exit(0)
<ide> }()
<ide> return oldState, err
<ide> }
<ide>
<ide> func RestoreTerminal(state *State) {
<del> Restore(int(os.Stdin.Fd()), state)
<add> Restore(os.Stdin.Fd(), state)
<ide> }
<ide><path>term/termios_linux.go
<ide> const (
<ide> // MakeRaw put the terminal connected to the given file descriptor into raw
<ide> // mode and returns the previous state of the terminal so that it can be
<ide> // restored.
<del>func MakeRaw(fd int) (*State, error) {
<add>func MakeRaw(fd uintptr) (*State, error) {
<ide> var oldState State
<del> if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, uintptr(fd), getTermios, uintptr(unsafe.Pointer(&oldState.termios))); err != 0 {
<add> if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, getTermios, uintptr(unsafe.Pointer(&oldState.termios))); err != 0 {
<ide> return nil, err
<ide> }
<ide>
<ide> func MakeRaw(fd int) (*State, error) {
<ide> newState.Cflag &^= (syscall.CSIZE | syscall.PARENB)
<ide> newState.Cflag |= syscall.CS8
<ide>
<del> if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, uintptr(fd), setTermios, uintptr(unsafe.Pointer(&newState))); err != 0 {
<add> if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, setTermios, uintptr(unsafe.Pointer(&newState))); err != 0 {
<ide> return nil, err
<ide> }
<ide> return &oldState, nil | 3 |
Python | Python | prepare 2.2.3 release | 5001a338bae23288b3217b36f9ec2af22f64b0f6 | <ide><path>keras/__init__.py
<ide> from .models import Model
<ide> from .models import Sequential
<ide>
<del>__version__ = '2.2.2'
<add>__version__ = '2.2.3'
<ide><path>setup.py
<ide> '''
<ide>
<ide> setup(name='Keras',
<del> version='2.2.2',
<add> version='2.2.3',
<ide> description='Deep Learning for humans',
<ide> long_description=long_description,
<ide> author='Francois Chollet',
<ide> author_email='francois.chollet@gmail.com',
<ide> url='https://github.com/keras-team/keras',
<del> download_url='https://github.com/keras-team/keras/tarball/2.2.2',
<add> download_url='https://github.com/keras-team/keras/tarball/2.2.3',
<ide> license='MIT',
<ide> install_requires=['numpy>=1.9.1',
<ide> 'scipy>=0.14',
<ide> 'six>=1.9.0',
<ide> 'pyyaml',
<ide> 'h5py',
<del> 'keras_applications>=1.0.4',
<del> 'keras_preprocessing==1.0.2'],
<add> 'keras_applications>=1.0.6',
<add> 'keras_preprocessing>=1.0.4'],
<ide> extras_require={
<ide> 'visualize': ['pydot>=1.2.4'],
<ide> 'tests': ['pytest', | 2 |
Javascript | Javascript | simplify the `wrapreason` helper function | 28fc8248f0fe6fdc5a69d2063b50f3cd7226ae23 | <ide><path>src/shared/message_handler.js
<ide> import {
<ide> PasswordException,
<ide> UnexpectedResponseException,
<ide> UnknownErrorException,
<del> warn,
<add> unreachable,
<ide> } from "./util.js";
<ide>
<ide> const CallbackKind = {
<ide> function wrapReason(reason) {
<ide> (typeof reason === "object" && reason !== null)
<ide> )
<ide> ) {
<del> if (
<del> typeof PDFJSDev === "undefined" ||
<del> PDFJSDev.test("!PRODUCTION || TESTING")
<del> ) {
<del> throw new Error(
<del> 'wrapReason: Expected "reason" to be a (possibly cloned) Error.'
<del> );
<del> }
<del> warn('wrapReason: Expected "reason" to be a (possibly cloned) Error.');
<del> return reason;
<add> unreachable(
<add> 'wrapReason: Expected "reason" to be a (possibly cloned) Error.'
<add> );
<ide> }
<ide> switch (reason.name) {
<ide> case "AbortException": | 1 |
Python | Python | standardize normalization dtypes | 5e1d640e20a74c00a73e23c00bb8040b86aba581 | <ide><path>keras/layers/preprocessing/normalization.py
<ide> def build(self, input_shape):
<ide> self.adapt_mean = self.add_weight(
<ide> name='mean',
<ide> shape=mean_and_var_shape,
<del> dtype=self.dtype,
<add> dtype=self.compute_dtype,
<ide> initializer='zeros',
<ide> trainable=False)
<ide> self.adapt_variance = self.add_weight(
<ide> name='variance',
<ide> shape=mean_and_var_shape,
<del> dtype=self.dtype,
<add> dtype=self.compute_dtype,
<ide> initializer='ones',
<ide> trainable=False)
<ide> self.count = self.add_weight(
<ide> def update_state(self, data):
<ide>
<ide> total_count = batch_count + self.count
<ide> batch_weight = (
<del> tf.cast(batch_count, dtype=self.dtype) /
<del> tf.cast(total_count, dtype=self.dtype))
<add> tf.cast(batch_count, dtype=self.compute_dtype) /
<add> tf.cast(total_count, dtype=self.compute_dtype))
<ide> existing_weight = 1. - batch_weight
<ide>
<ide> total_mean = self.adapt_mean * existing_weight + batch_mean * batch_weight
<ide> def get_config(self):
<ide>
<ide> def _standardize_inputs(self, inputs):
<ide> inputs = tf.convert_to_tensor(inputs)
<del> if inputs.dtype != self.dtype:
<del> inputs = tf.cast(inputs, self.dtype)
<add> if inputs.dtype != self.compute_dtype:
<add> inputs = tf.cast(inputs, self.compute_dtype)
<ide> return inputs
<ide><path>keras/layers/preprocessing/normalization_test.py
<ide> from keras import testing_utils
<ide> from keras.layers.preprocessing import normalization
<ide> from keras.layers.preprocessing import preprocessing_test_utils
<add>from keras.mixed_precision import policy
<ide>
<ide>
<ide> def _get_layer_computation_test_cases():
<ide> def test_scalar_input(self):
<ide> "axis.*values must be in the range"):
<ide> normalization.Normalization()(1)
<ide>
<add> def test_output_dtype(self):
<add> if not tf.__internal__.tf2.enabled():
<add> self.skipTest("set_global_policy only supported in TF2.")
<add> # Output should respect an explicit dtype, and default to the global policy.
<add> policy.set_global_policy("float64")
<add> input_data = keras.Input(batch_size=16, shape=(1,))
<add> layer = normalization.Normalization(mean=1.0, variance=1.0, dtype="float16")
<add> output = layer(input_data)
<add> self.assertAllEqual(output.dtype, tf.float16)
<add> layer = normalization.Normalization(mean=1.0, variance=1.0)
<add> output = layer(input_data)
<add> self.assertAllEqual(output.dtype, tf.float64)
<add>
<ide>
<ide> @keras_parameterized.run_all_keras_modes(always_skip_v1=True)
<ide> class NormalizationAdaptTest(keras_parameterized.TestCase, | 2 |
PHP | PHP | add parameter array to redirect test | 68b0dd4de809bc4cead1e872088849658060e6fd | <ide><path>src/Illuminate/Foundation/Testing/TestCase.php
<ide> public function assertRedirectedTo($uri, $with = array())
<ide> * Assert whether the client was redirected to a given route.
<ide> *
<ide> * @param string $name
<add> * @param array $parameters
<ide> * @param array $with
<ide> * @return void
<ide> */
<del> public function assertRedirectedToRoute($name, $with = array())
<add> public function assertRedirectedToRoute($name, $parameters = array(), $with = array())
<ide> {
<del> $this->assertRedirectedTo($this->app['url']->route($name), $with);
<add> $this->assertRedirectedTo($this->app['url']->route($name, $parameters), $with);
<ide> }
<ide>
<ide> /**
<ide> * Assert whether the client was redirected to a given action.
<ide> *
<ide> * @param string $name
<add> * @param array $parameters
<ide> * @param array $with
<ide> * @return void
<ide> */
<del> public function assertRedirectedToAction($name, $with = array())
<add> public function assertRedirectedToAction($name, $parameters = array(), $with = array())
<ide> {
<del> $this->assertRedirectedTo($this->app['url']->action($name), $with);
<add> $this->assertRedirectedTo($this->app['url']->action($name, $parameters), $with);
<ide> }
<ide>
<ide> /** | 1 |
Text | Text | add docs for module.paths | 9ab3172e5d058c47725fdd91e2722bfe1461a4fb | <ide><path>doc/api/modules.md
<ide> added: v0.1.16
<ide>
<ide> The module that first required this one.
<ide>
<add>### module.paths
<add><!-- YAML
<add>added: v0.4.0
<add>-->
<add>
<add>* {string[]}
<add>
<add>The search paths for the module.
<add>
<ide> ### module.require(id)
<ide> <!-- YAML
<ide> added: v0.5.1
<ide> be explicitly exported in order to be used.
<ide> [`path.dirname()`]: path.html#path_path_dirname_path
<ide> [exports shortcut]: #modules_exports_shortcut
<ide> [module resolution]: #modules_all_together
<del>[native addons]: addons.html
<ide>\ No newline at end of file
<add>[native addons]: addons.html | 1 |
Ruby | Ruby | pass a block to map instead of a proc | 98989560476db26165eef947b96e49d508240b97 | <ide><path>Library/Homebrew/cmd/uses.rb
<ide> def uses
<ide> keg.directory? and not keg.subdirs.empty?
<ide> end
<ide> end
<del> puts_columns uses.map(&:to_s).sort
<add> puts_columns uses.map{|f| f.to_s}.sort
<ide> end
<ide> end | 1 |
Python | Python | use timedelta.total_seconds when on python 2.7 | c9a07aefa689ac8bad91133fb203eaaff41d4be0 | <ide><path>celery/utils/timeutils.py
<del>from datetime import datetime
<add>from datetime import datetime, timedelta
<ide>
<ide> from carrot.utils import partition
<ide>
<ide> "m": lambda n: n / 60.0,
<ide> "h": lambda n: n / 60.0 / 60.0}
<ide>
<add>HAVE_TIMEDELTA_TOTAL_SECONDS = hasattr(timedelta, "total_seconds")
<add>
<ide>
<ide> def timedelta_seconds(delta):
<ide> """Convert :class:`datetime.timedelta` to seconds.
<ide>
<ide> Doesn't account for negative values.
<ide>
<ide> """
<add> if HAVE_TIMEDELTA_TOTAL_SECONDS:
<add> return delta.total_seconds()
<ide> if delta.days < 0:
<ide> return 0
<ide> return delta.days * 86400 + delta.seconds + (delta.microseconds / 10e5) | 1 |
Javascript | Javascript | improve test coverage | 2efffb8ae4b86045100252186cadaf41a1b1d93e | <ide><path>src/core/core.typedRegistry.js
<ide> export default class TypedRegistry {
<ide>
<ide> if (scope && id in defaults[scope]) {
<ide> delete defaults[scope][id];
<del> } else if (id in defaults) {
<del> delete defaults[id];
<ide> }
<ide> }
<ide> }
<ide><path>src/helpers/helpers.dom.js
<ide> function parseMaxStyle(styleValue, node, parentProperty) {
<ide> const getComputedStyle = (element) => window.getComputedStyle(element, null);
<ide>
<ide> export function getStyle(el, property) {
<del> return el.currentStyle ?
<del> el.currentStyle[property] :
<del> getComputedStyle(el).getPropertyValue(property);
<add> return getComputedStyle(el).getPropertyValue(property);
<ide> }
<ide>
<ide> const positions = ['top', 'right', 'bottom', 'left'];
<ide><path>test/specs/core.animations.tests.js
<ide> describe('Chart.animations', function() {
<ide> })).toBeUndefined();
<ide> });
<ide>
<add> it('should assing options directly, if target does not have previous options', function() {
<add> const chart = {};
<add> const anims = new Chart.Animations(chart, {option: {duration: 200}});
<add> const target = {};
<add> expect(anims.update(target, {options: {option: 1}})).toBeUndefined();
<add> });
<add>
<add> it('should clone the target options, if those are shared and new options are not', function() {
<add> const chart = {};
<add> const anims = new Chart.Animations(chart, {option: {duration: 200}});
<add> const options = {option: 0, $shared: true};
<add> const target = {options};
<add> expect(anims.update(target, {options: {option: 1}})).toBeTrue();
<add> expect(target.options.$shared).not.toBeTrue();
<add> expect(target.options !== options).toBeTrue();
<add> });
<add>
<ide> it('should assign shared options to target after animations complete', function(done) {
<ide> const chart = {
<ide> draw: function() {},
<ide><path>test/specs/core.defaults.tests.js
<add>describe('Chart.defaults', function() {
<add> describe('.set', function() {
<add> it('Should set defaults directly to root when scope is not provided', function() {
<add> expect(Chart.defaults.test).toBeUndefined();
<add> Chart.defaults.set({test: true});
<add> expect(Chart.defaults.test).toEqual(true);
<add> delete Chart.defaults.test;
<add> });
<add>
<add> it('Should create scope when it does not exist', function() {
<add> expect(Chart.defaults.test).toBeUndefined();
<add> Chart.defaults.set('test', {value: true});
<add> expect(Chart.defaults.test.value).toEqual(true);
<add> delete Chart.defaults.test;
<add> });
<add> });
<add>
<add> describe('.route', function() {
<add> it('Should read the source, but not change it', function() {
<add> expect(Chart.defaults.testscope).toBeUndefined();
<add>
<add> Chart.defaults.set('testscope', {test: true});
<add> Chart.defaults.route('testscope', 'test2', 'testscope', 'test');
<add>
<add> expect(Chart.defaults.testscope.test).toEqual(true);
<add> expect(Chart.defaults.testscope.test2).toEqual(true);
<add>
<add> Chart.defaults.set('testscope', {test2: false});
<add> expect(Chart.defaults.testscope.test).toEqual(true);
<add> expect(Chart.defaults.testscope.test2).toEqual(false);
<add>
<add> Chart.defaults.set('testscope', {test2: undefined});
<add> expect(Chart.defaults.testscope.test2).toEqual(true);
<add>
<add> delete Chart.defaults.testscope;
<add> });
<add> });
<add>}); | 4 |
Text | Text | use latest versions | 9bcad4a9b505188a6c4bbb684a42062f36eb60cc | <ide><path>.github/ISSUE_TEMPLATE/1_Bug_report.md
<ide> ---
<ide> name: "🐛 Bug Report"
<del>about: 'Report a general framework issue. Please first check if your Laravel version is still supported: https://laravel.com/docs/5.8/releases#support-policy'
<add>about: 'Report a general framework issue. Please first check if your Laravel version is still supported: https://laravel.com/docs/releases#support-policy'
<ide>
<ide> ---
<ide>
<ide><path>.github/PULL_REQUEST_TEMPLATE.md
<ide> <!--
<del>Please only send in a PR to branches which are currently supported: https://laravel.com/docs/5.8/releases#support-policy
<add>Please only send in a PR to branches which are currently supported: https://laravel.com/docs/releases#support-policy
<ide>
<del>If you are unsure to which branch you want to send a PR please read: https://laravel.com/docs/5.8/contributions#which-branch
<add>If you are unsure to which branch you want to send a PR please read: https://laravel.com/docs/contributions#which-branch
<ide>
<ide> Pull Requests without a descriptive title, thorough description, or tests will be closed.
<ide> | 2 |
Go | Go | add warnings about missing blkio cgroup support | d378625554dc5d568d754b635c1d0fb8dae3c4bf | <ide><path>daemon/info_unix.go
<ide> func (daemon *Daemon) fillPlatformInfo(v *types.Info, sysInfo *sysinfo.SysInfo)
<ide> if v.CgroupVersion == "2" {
<ide> v.Warnings = append(v.Warnings, "WARNING: Support for cgroup v2 is experimental")
<ide> }
<add> // TODO add fields for these options in types.Info
<add> if !sysInfo.BlkioWeight {
<add> v.Warnings = append(v.Warnings, "WARNING: No blkio weight support")
<add> }
<add> if !sysInfo.BlkioWeightDevice {
<add> v.Warnings = append(v.Warnings, "WARNING: No blkio weight_device support")
<add> }
<add> if !sysInfo.BlkioReadBpsDevice {
<add> v.Warnings = append(v.Warnings, "WARNING: No blkio throttle.read_bps_device support")
<add> }
<add> if !sysInfo.BlkioWriteBpsDevice {
<add> v.Warnings = append(v.Warnings, "WARNING: No blkio throttle.write_bps_device support")
<add> }
<add> if !sysInfo.BlkioReadIOpsDevice {
<add> v.Warnings = append(v.Warnings, "WARNING: No blkio throttle.read_iops_device support")
<add> }
<add> if !sysInfo.BlkioWriteIOpsDevice {
<add> v.Warnings = append(v.Warnings, "WARNING: No blkio throttle.write_iops_device support")
<add> }
<ide> }
<ide> if !v.IPv4Forwarding {
<ide> v.Warnings = append(v.Warnings, "WARNING: IPv4 forwarding is disabled") | 1 |
Javascript | Javascript | improve compatibility of legacy api | 4cf931db1736a73717f4e6b9f11c3450de8606c6 | <ide><path>lib/http2.js
<ide> function Client(port, host) {
<ide> port = port || 80;
<ide> this.host = host;
<ide> this.port = port;
<add> this.agent = new Agent({ host: host, port: port, maxSockets: 1 });
<ide> }
<ide> util.inherits(Client, EventEmitter);
<ide> Client.prototype.request = function(method, path, headers) {
<ide> Client.prototype.request = function(method, path, headers) {
<ide> options.method = method;
<ide> options.path = path;
<ide> options.headers = headers;
<add> options.agent = self.agent;
<ide> var c = new ClientRequest(options);
<ide> c.on('error', function(e) {
<ide> self.emit('error', e);
<ide><path>test/simple/test-http-legacy.js
<add>// Copyright Joyent, Inc. and other Node contributors.
<add>//
<add>// Permission is hereby granted, free of charge, to any person obtaining a
<add>// copy of this software and associated documentation files (the
<add>// "Software"), to deal in the Software without restriction, including
<add>// without limitation the rights to use, copy, modify, merge, publish,
<add>// distribute, sublicense, and/or sell copies of the Software, and to permit
<add>// persons to whom the Software is furnished to do so, subject to the
<add>// following conditions:
<add>//
<add>// The above copyright notice and this permission notice shall be included
<add>// in all copies or substantial portions of the Software.
<add>//
<add>// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
<add>// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
<add>// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
<add>// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
<add>// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
<add>// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
<add>// USE OR OTHER DEALINGS IN THE SOFTWARE.
<add>
<add>var common = require('../common');
<add>var assert = require('assert');
<add>var http = require('http');
<add>var url = require('url');
<add>
<add>function p(x) {
<add> common.error(common.inspect(x));
<add>}
<add>
<add>var responses_sent = 0;
<add>var responses_recvd = 0;
<add>var body0 = '';
<add>var body1 = '';
<add>
<add>var server = http.createServer(function(req, res) {
<add> if (responses_sent == 0) {
<add> assert.equal('GET', req.method);
<add> assert.equal('/hello', url.parse(req.url).pathname);
<add>
<add> console.dir(req.headers);
<add> assert.equal(true, 'accept' in req.headers);
<add> assert.equal('*/*', req.headers['accept']);
<add>
<add> assert.equal(true, 'foo' in req.headers);
<add> assert.equal('bar', req.headers['foo']);
<add> }
<add>
<add> if (responses_sent == 1) {
<add> assert.equal('POST', req.method);
<add> assert.equal('/world', url.parse(req.url).pathname);
<add> this.close();
<add> }
<add>
<add> req.on('end', function() {
<add> res.writeHead(200, {'Content-Type': 'text/plain'});
<add> res.write('The path was ' + url.parse(req.url).pathname);
<add> res.end();
<add> responses_sent += 1;
<add> });
<add>
<add> //assert.equal('127.0.0.1', res.connection.remoteAddress);
<add>});
<add>
<add>server.listen(common.PORT, function() {
<add> var client = http.createClient(common.PORT);
<add> var req = client.request('/hello', {'Accept': '*/*', 'Foo': 'bar'});
<add> setTimeout(function() {
<add> req.end();
<add> }, 100);
<add> req.on('response', function(res) {
<add> assert.equal(200, res.statusCode);
<add> responses_recvd += 1;
<add> res.setEncoding('utf8');
<add> res.on('data', function(chunk) { body0 += chunk; });
<add> common.debug('Got /hello response');
<add> });
<add>
<add> setTimeout(function() {
<add> var req = client.request('POST', '/world');
<add> req.end();
<add> req.on('response', function(res) {
<add> assert.equal(200, res.statusCode);
<add> responses_recvd += 1;
<add> res.setEncoding('utf8');
<add> res.on('data', function(chunk) { body1 += chunk; });
<add> common.debug('Got /world response');
<add> });
<add> }, 1);
<add>});
<add>
<add>process.on('exit', function() {
<add> common.debug('responses_recvd: ' + responses_recvd);
<add> assert.equal(2, responses_recvd);
<add>
<add> common.debug('responses_sent: ' + responses_sent);
<add> assert.equal(2, responses_sent);
<add>
<add> assert.equal('The path was /hello', body0);
<add> assert.equal('The path was /world', body1);
<add>}); | 2 |
Python | Python | parse all options when detached | ed4f50ed8f404d30be2cbdb709ffbf199ce210ed | <ide><path>celery/bin/worker.py
<ide> def run_from_argv(self, prog_name, argv=None, command=None):
<ide> # parse options before detaching so errors can be handled.
<ide> options, args = self.prepare_args(
<ide> *self.parse_options(prog_name, argv, command))
<del> self.maybe_detach([command] + argv)
<add> self.maybe_detach([command] + sys.argv[1:])
<ide> return self(*args, **options)
<ide>
<ide> def maybe_detach(self, argv, dopts=['-D', '--detach']): | 1 |
Javascript | Javascript | use native isarray, endswith | 6e59852456636d16cc58b1afa562f6d91ce0c60a | <ide><path>src/config.js
<ide> class Config {
<ide> deepClone (object) {
<ide> if (object instanceof Color) {
<ide> return object.clone()
<del> } else if (_.isArray(object)) {
<add> } else if (Array.isArray(object)) {
<ide> return object.map(value => this.deepClone(value))
<ide> } else if (isPlainObject(object)) {
<ide> return _.mapObject(object, (key, value) => [key, this.deepClone(value)])
<ide> Config.addSchemaEnforcers({
<ide> }
<ide> })
<ide>
<del>let isPlainObject = value => _.isObject(value) && !_.isArray(value) && !_.isFunction(value) && !_.isString(value) && !(value instanceof Color)
<add>let isPlainObject = value => _.isObject(value) && !Array.isArray(value) && !_.isFunction(value) && !_.isString(value) && !(value instanceof Color)
<ide>
<ide> let sortObject = value => {
<ide> if (!isPlainObject(value)) { return value }
<ide><path>src/decoration.js
<del>const _ = require('underscore-plus')
<ide> const {Emitter} = require('event-kit')
<ide>
<ide> let idCounter = 0
<ide> class Decoration {
<ide> // 'line-number' is a 'gutter', but a 'gutter' is not a 'line-number'.
<ide> static isType (decorationProperties, type) {
<ide> // 'line-number' is a special case of 'gutter'.
<del> if (_.isArray(decorationProperties.type)) {
<add> if (Array.isArray(decorationProperties.type)) {
<ide> if (decorationProperties.type.includes(type)) {
<ide> return true
<ide> }
<ide><path>src/notification.js
<ide> class Notification {
<ide> throw new Error(`Notification must be created with string message: ${this.message}`)
<ide> }
<ide>
<del> if (!_.isObject(this.options) || _.isArray(this.options)) {
<add> if (!_.isObject(this.options) || Array.isArray(this.options)) {
<ide> throw new Error(`Notification must be created with an options object: ${this.options}`)
<ide> }
<ide> }
<ide><path>src/theme-manager.js
<ide> class ThemeManager {
<ide>
<ide> warnForNonExistentThemes () {
<ide> let themeNames = this.config.get('core.themes') || []
<del> if (!_.isArray(themeNames)) { themeNames = [themeNames] }
<add> if (!Array.isArray(themeNames)) { themeNames = [themeNames] }
<ide> for (let themeName of themeNames) {
<ide> if (!themeName || (typeof themeName !== 'string') || !this.packageManager.resolvePackagePath(themeName)) {
<ide> console.warn(`Enabled theme '${themeName}' is not installed.`)
<ide> class ThemeManager {
<ide> // Returns an array of theme names in the order that they should be activated.
<ide> getEnabledThemeNames () {
<ide> let themeNames = this.config.get('core.themes') || []
<del> if (!_.isArray(themeNames)) { themeNames = [themeNames] }
<add> if (!Array.isArray(themeNames)) { themeNames = [themeNames] }
<ide> themeNames = themeNames.filter((themeName) =>
<ide> (typeof themeName === 'string') && this.packageManager.resolvePackagePath(themeName)
<ide> )
<ide> class ThemeManager {
<ide> if (themeNames.length === 0) {
<ide> themeNames = ['one-dark-syntax', 'one-dark-ui']
<ide> } else if (themeNames.length === 1) {
<del> if (_.endsWith(themeNames[0], '-ui')) {
<add> if (themeNames[0].endsWith('-ui')) {
<ide> themeNames.unshift('one-dark-syntax')
<ide> } else {
<ide> themeNames.push('one-dark-ui') | 4 |
Text | Text | use azure pipelines badge | 462439ea1d3140b2b6a6adc5531dc3dd71d4b96c | <ide><path>README.md
<ide> Second, read the [Troubleshooting Checklist](https://docs.brew.sh/Troubleshootin
<ide> **If you don't read these it will take us far longer to help you with your problem.**
<ide>
<ide> ## Contributing
<del>[](https://travis-ci.org/Homebrew/brew)
<add>[](https://dev.azure.com/Homebrew/Homebrew/_build/latest?definitionId=1)
<ide> [](https://codecov.io/gh/Homebrew/brew)
<ide>
<ide> We'd love you to contribute to Homebrew. First, please read our [Contribution Guide](CONTRIBUTING.md) and [Code of Conduct](CODE_OF_CONDUCT.md#code-of-conduct). | 1 |
Javascript | Javascript | add nzaom app | 538307d179d98e38e263cadfc3655e536b7bdfab | <ide><path>website/src/react-native/showcase.js
<ide> var apps = [
<ide> author: 'Melih Mucuk',
<ide> },
<ide> {
<del> name:'天才段子手',
<del> icon:'http://pp.myapp.com/ma_icon/0/icon_12236104_1451810987/96',
<add> name: '天才段子手',
<add> icon: 'http://pp.myapp.com/ma_icon/0/icon_12236104_1451810987/96',
<ide> linkAppStore: 'https://itunes.apple.com/us/app/tian-cai-duan-zi-shou-shen/id992312701?l=zh&ls=1&mt=8',
<ide> linkPlayStore: 'https://play.google.com/store/apps/details?id=com.geniusJokeWriter.app',
<del> author:'Ran Zhao&Ji Zhao'
<add> author: 'Ran Zhao&Ji Zhao'
<add> },
<add> {
<add> name: '你造么',
<add> icon: 'http://7xk1ez.com2.z0.glb.qiniucdn.com/logo-mobile-0114logo_welcom.png',
<add> link: 'https://itunes.apple.com/us/app/ni-zao-me/id1025294933?l=zh&ls=1&mt=8',
<add> author: 'Scott Chen(@NZAOM)'
<ide> }
<ide> ];
<ide> | 1 |
Javascript | Javascript | make sure http pipelining does not emit a warning | 31fe3b215f175176d6474439f932bb5e7a12b573 | <ide><path>test/parallel/test-http-many-ended-pipelines.js
<ide> // USE OR OTHER DEALINGS IN THE SOFTWARE.
<ide>
<ide> 'use strict';
<del>require('../common');
<add>const common = require('../common');
<ide>
<ide> // No warnings should happen!
<ide> const trace = console.trace;
<ide> server.listen(0, function() {
<ide> client.end();
<ide> client.pipe(process.stdout);
<ide> });
<add>
<add>process.on('warning', common.mustNotCall()); | 1 |
Python | Python | fix some errors for distributed lm_finetuning | 60a1bdcdacc4ec3d2ca6dad16e61b8ad8022285e | <ide><path>examples/lm_finetuning/simple_lm_finetuning.py
<ide> def main():
<ide>
<ide> if os.path.exists(args.output_dir) and os.listdir(args.output_dir):
<ide> raise ValueError("Output directory ({}) already exists and is not empty.".format(args.output_dir))
<del> if not os.path.exists(args.output_dir):
<add> if not os.path.exists(args.output_dir) and torch.distributed.get_rank() == 0:
<ide> os.makedirs(args.output_dir)
<ide>
<ide> tokenizer = BertTokenizer.from_pretrained(args.bert_model, do_lower_case=args.do_lower_case)
<ide> def main():
<ide> global_step += 1
<ide>
<ide> # Save a trained model
<del> logger.info("** ** * Saving fine - tuned model ** ** * ")
<ide> model_to_save = model.module if hasattr(model, 'module') else model # Only save the model it-self
<ide> output_model_file = os.path.join(args.output_dir, WEIGHTS_NAME)
<ide> output_config_file = os.path.join(args.output_dir, CONFIG_NAME)
<del> if args.do_train:
<add> if args.do_train and torch.distributed.get_rank() == 0:
<add> logger.info("** ** * Saving fine - tuned model ** ** * ")
<ide> torch.save(model_to_save.state_dict(), output_model_file)
<ide> model_to_save.config.to_json_file(output_config_file)
<ide> tokenizer.save_vocabulary(args.output_dir) | 1 |
Mixed | Javascript | introduce `socket#connecting` property | cee4c25c9281d106f80b20ba7854bf9003f9357a | <ide><path>doc/api/net.md
<ide> The `connectListener` parameter will be added as a listener for the
<ide> As [`socket.connect(options\[, connectListener\])`][`socket.connect(options, connectListener)`],
<ide> with options either as either `{port: port, host: host}` or `{path: path}`.
<ide>
<add>### socket.connecting
<add>
<add>If `true` - [`socket.connect(options\[, connectListener\])`][] was called and
<add>haven't yet finished. Will be set to `false` before emitting `connect` event
<add>and/or calling [`socket.connect(options\[, connectListener\])`][]'s callback.
<add>
<ide> ### socket.destroy()
<ide>
<ide> Ensures that no more I/O activity happens on this socket. Only necessary in
<ide><path>lib/_tls_legacy.js
<ide> CryptoStream.prototype._done = function() {
<ide> // readyState is deprecated. Don't use it.
<ide> Object.defineProperty(CryptoStream.prototype, 'readyState', {
<ide> get: function() {
<del> if (this._connecting) {
<add> if (this.connecting) {
<ide> return 'opening';
<ide> } else if (this.readable && this.writable) {
<ide> return 'open';
<ide><path>lib/_tls_wrap.js
<ide> function TLSSocket(socket, options) {
<ide>
<ide> this._init(socket, wrap);
<ide>
<del> // Make sure to setup all required properties like: `_connecting` before
<add> // Make sure to setup all required properties like: `connecting` before
<ide> // starting the flow of the data
<ide> this.readable = true;
<ide> this.writable = true;
<ide> TLSSocket.prototype._init = function(socket, wrap) {
<ide> this._parent = socket;
<ide>
<ide> // To prevent assertion in afterConnect() and properly kick off readStart
<del> this._connecting = socket._connecting || !socket._handle;
<add> this.connecting = socket.connecting || !socket._handle;
<ide> socket.once('connect', function() {
<del> self._connecting = false;
<add> self.connecting = false;
<ide> self.emit('connect');
<ide> });
<ide> }
<ide> TLSSocket.prototype._init = function(socket, wrap) {
<ide> });
<ide> } else {
<ide> assert(!socket);
<del> this._connecting = true;
<add> this.connecting = true;
<ide> }
<ide> };
<ide>
<ide> TLSSocket.prototype._finishInit = function() {
<ide> };
<ide>
<ide> TLSSocket.prototype._start = function() {
<del> if (this._connecting) {
<add> if (this.connecting) {
<ide> this.once('connect', function() {
<ide> this._start();
<ide> });
<ide><path>lib/net.js
<ide> const BYTES_READ = Symbol('bytesRead');
<ide> function Socket(options) {
<ide> if (!(this instanceof Socket)) return new Socket(options);
<ide>
<del> this._connecting = false;
<add> this.connecting = false;
<ide> this._hadError = false;
<ide> this._handle = null;
<ide> this._parent = null;
<ide> Socket.prototype._unrefTimer = function unrefTimer() {
<ide> // so that only the writable side will be cleaned up.
<ide> function onSocketFinish() {
<ide> // If still connecting - defer handling 'finish' until 'connect' will happen
<del> if (this._connecting) {
<add> if (this.connecting) {
<ide> debug('osF: not yet connected');
<ide> return this.once('connect', onSocketFinish);
<ide> }
<ide> Socket.prototype.address = function() {
<ide> };
<ide>
<ide>
<add>Object.defineProperty(Socket.prototype, '_connecting', {
<add> get: function() {
<add> return this.connecting;
<add> }
<add>});
<add>
<add>
<ide> Object.defineProperty(Socket.prototype, 'readyState', {
<ide> get: function() {
<del> if (this._connecting) {
<add> if (this.connecting) {
<ide> return 'opening';
<ide> } else if (this.readable && this.writable) {
<ide> return 'open';
<ide> Object.defineProperty(Socket.prototype, 'bufferSize', {
<ide> Socket.prototype._read = function(n) {
<ide> debug('_read');
<ide>
<del> if (this._connecting || !this._handle) {
<add> if (this.connecting || !this._handle) {
<ide> debug('_read wait for connection');
<ide> this.once('connect', () => this._read(n));
<ide> } else if (!this._handle.reading) {
<ide> function maybeDestroy(socket) {
<ide> if (!socket.readable &&
<ide> !socket.writable &&
<ide> !socket.destroyed &&
<del> !socket._connecting &&
<add> !socket.connecting &&
<ide> !socket._writableState.length) {
<ide> socket.destroy();
<ide> }
<ide> Socket.prototype._destroy = function(exception, cb) {
<ide> return;
<ide> }
<ide>
<del> this._connecting = false;
<add> this.connecting = false;
<ide>
<ide> this.readable = this.writable = false;
<ide>
<ide> Socket.prototype._writeGeneric = function(writev, data, encoding, cb) {
<ide> // If we are still connecting, then buffer this for later.
<ide> // The Writable logic will buffer up any more writes while
<ide> // waiting for this one to be done.
<del> if (this._connecting) {
<add> if (this.connecting) {
<ide> this._pendingData = data;
<ide> this._pendingEncoding = encoding;
<ide> this.once('connect', function() {
<ide> function connect(self, address, port, addressType, localAddress, localPort) {
<ide> // TODO return promise from Socket.prototype.connect which
<ide> // wraps _connectReq.
<ide>
<del> assert.ok(self._connecting);
<add> assert.ok(self.connecting);
<ide>
<ide> var err;
<ide>
<ide> Socket.prototype.connect = function(options, cb) {
<ide>
<ide> this._unrefTimer();
<ide>
<del> this._connecting = true;
<add> this.connecting = true;
<ide> this.writable = true;
<ide>
<ide> if (pipe) {
<ide> function lookupAndConnect(self, options) {
<ide> var addressType = exports.isIP(host);
<ide> if (addressType) {
<ide> process.nextTick(function() {
<del> if (self._connecting)
<add> if (self.connecting)
<ide> connect(self, host, port, addressType, localAddress, localPort);
<ide> });
<ide> return;
<ide> function lookupAndConnect(self, options) {
<ide> // It's possible we were destroyed while looking this up.
<ide> // XXX it would be great if we could cancel the promise returned by
<ide> // the look up.
<del> if (!self._connecting) return;
<add> if (!self.connecting) return;
<ide>
<ide> if (err) {
<ide> // net.createConnection() creates a net.Socket object and
<ide> function afterConnect(status, handle, req, readable, writable) {
<ide>
<ide> debug('afterConnect');
<ide>
<del> assert.ok(self._connecting);
<del> self._connecting = false;
<add> assert.ok(self.connecting);
<add> self.connecting = false;
<ide> self._sockname = null;
<ide>
<ide> if (status == 0) {
<ide> function afterConnect(status, handle, req, readable, writable) {
<ide> self.read(0);
<ide>
<ide> } else {
<del> self._connecting = false;
<add> self.connecting = false;
<ide> var details;
<ide> if (req.localAddress && req.localPort) {
<ide> details = req.localAddress + ':' + req.localPort;
<ide><path>test/parallel/test-net-connect-buffer.js
<ide> tcp.listen(common.PORT, function() {
<ide> connectHappened = true;
<ide> });
<ide>
<del> console.log('_connecting = ' + socket._connecting);
<add> console.log('connecting = ' + socket.connecting);
<ide>
<ide> assert.equal('opening', socket.readyState);
<ide>
<ide><path>test/parallel/test-net-socket-connecting.js
<add>'use strict';
<add>const common = require('../common');
<add>const assert = require('assert');
<add>const net = require('net');
<add>
<add>const server = net.createServer((conn) => {
<add> conn.end();
<add> server.close();
<add>}).listen(common.PORT, () => {
<add> const client = net.connect(common.PORT, () => {
<add> assert.strictEqual(client.connecting, false);
<add>
<add> // Legacy getter
<add> assert.strictEqual(client._connecting, false);
<add> client.end();
<add> });
<add> assert.strictEqual(client.connecting, true);
<add>
<add> // Legacy getter
<add> assert.strictEqual(client._connecting, true);
<add>}); | 6 |
Javascript | Javascript | improve async useeffect warning | 9d77a317bf5bde7e6edd3c8cd0ebb00feb447223 | <ide><path>packages/react-reconciler/src/ReactFiberCommitWork.js
<ide> function commitHookEffectList(
<ide> } else if (typeof destroy.then === 'function') {
<ide> addendum =
<ide> '\n\nIt looks like you wrote useEffect(async () => ...) or returned a Promise. ' +
<del> 'Instead, you may write an async function separately ' +
<del> 'and then call it from inside the effect:\n\n' +
<del> 'async function fetchComment(commentId) {\n' +
<del> ' // You can await here\n' +
<del> '}\n\n' +
<add> 'Instead, write the async function inside your effect ' +
<add> 'and call it immediately:\n\n' +
<ide> 'useEffect(() => {\n' +
<del> ' fetchComment(commentId);\n' +
<del> '}, [commentId]);\n\n' +
<del> 'In the future, React will provide a more idiomatic solution for data fetching ' +
<del> "that doesn't involve writing effects manually.";
<add> ' async function fetchData() {\n' +
<add> ' // You can await here\n' +
<add> ' const response = await MyAPI.getData(someId);\n' +
<add> ' // ...\n' +
<add> ' }\n' +
<add> ' fetchData();\n' +
<add> '}, [someId]);\n\n' +
<add> 'Learn more about data fetching with Hooks: https://fb.me/react-hooks-data-fetching';
<ide> } else {
<ide> addendum = ' You returned: ' + destroy;
<ide> }
<ide> warningWithoutStack(
<ide> false,
<del> 'An Effect function must not return anything besides a function, ' +
<add> 'An effect function must not return anything besides a function, ' +
<ide> 'which is used for clean-up.%s%s',
<ide> addendum,
<ide> getStackByFiberInDevAndProd(finishedWork),
<ide><path>packages/react-reconciler/src/__tests__/ReactHooks-test.internal.js
<ide> describe('ReactHooks', () => {
<ide>
<ide> const root1 = ReactTestRenderer.create(null);
<ide> expect(() => root1.update(<App return={17} />)).toWarnDev([
<del> 'Warning: An Effect function must not return anything besides a ' +
<add> 'Warning: An effect function must not return anything besides a ' +
<ide> 'function, which is used for clean-up. You returned: 17',
<ide> ]);
<ide>
<ide> const root2 = ReactTestRenderer.create(null);
<ide> expect(() => root2.update(<App return={null} />)).toWarnDev([
<del> 'Warning: An Effect function must not return anything besides a ' +
<add> 'Warning: An effect function must not return anything besides a ' +
<ide> 'function, which is used for clean-up. You returned null. If your ' +
<ide> 'effect does not require clean up, return undefined (or nothing).',
<ide> ]);
<ide>
<ide> const root3 = ReactTestRenderer.create(null);
<ide> expect(() => root3.update(<App return={Promise.resolve()} />)).toWarnDev([
<del> 'Warning: An Effect function must not return anything besides a ' +
<add> 'Warning: An effect function must not return anything besides a ' +
<ide> 'function, which is used for clean-up.\n\n' +
<ide> 'It looks like you wrote useEffect(async () => ...) or returned a Promise.',
<ide> ]); | 2 |
Python | Python | fix typo in trainer_tf.py | 3caba8d35f8713d6dba67e0b1b4145867c302625 | <ide><path>src/transformers/trainer_tf.py
<ide> def train(self) -> None:
<ide>
<ide> if (
<ide> self.args.eval_steps > 0
<del> and self.args.evaluate_strategy == EvaluationStrategy.STEPS
<add> and self.args.evaluation_strategy == EvaluationStrategy.STEPS
<ide> and self.global_step % self.args.eval_steps == 0
<ide> ):
<ide> self.evaluate() | 1 |
Text | Text | add link to contributing.md | 1495861a3df9fd1853e2069aec012a80b85d0b9c | <ide><path>README.md
<ide> Contributions go far beyond pull requests and commits. Although we love giving y
<ide> * [Blogging, speaking about, or creating tutorials](https://github.com/webpack-contrib/awesome-webpack) about one of webpack's many features.
<ide> * Helping others in our webpack [gitter channel](https://gitter.im/webpack/webpack).
<ide>
<add>To get started have a look at our [documentation on contributing](https://github.com/webpack/webpack/blob/master/CONTRIBUTING.md).
<add>
<ide> If you are worried or don't know where to start, you can **always** reach out to [Sean Larkin (@TheLarkInn) on Twitter](https://twitter.com/thelarkinn) or simply submit an issue and a maintainer can help give you guidance!
<ide>
<ide> We have also started a series on our [Medium Publication](https://medium.com/webpack) called [The Contributor's Guide to webpack](https://medium.com/webpack/contributors-guide/home). We welcome you to read it and post any questions or responses if you still need help. | 1 |
Javascript | Javascript | normalize scroll wheel | 98f84c1b26a1d0506859b3aff3bf937ceb69478a | <ide><path>examples/js/controls/EditorControls.js
<ide> THREE.EditorControls = function ( object, domElement ) {
<ide> this.enabled = true;
<ide> this.center = new THREE.Vector3();
<ide> this.panSpeed = 0.001;
<del> this.zoomSpeed = 0.001;
<add> this.zoomSpeed = 0.1;
<ide> this.rotationSpeed = 0.005;
<ide>
<ide> // internals
<ide> THREE.EditorControls = function ( object, domElement ) {
<ide>
<ide> event.preventDefault();
<ide>
<del> // if ( scope.enabled === false ) return;
<del>
<del> scope.zoom( new THREE.Vector3( 0, 0, event.deltaY ) );
<add> // Normalize deltaY due to https://bugzilla.mozilla.org/show_bug.cgi?id=1392460
<add> scope.zoom( new THREE.Vector3( 0, 0, event.deltaY > 0 ? 1 : - 1 ) );
<ide>
<ide> }
<ide> | 1 |
Javascript | Javascript | enforce strict mode for test-domain-crypto | d4eafd0c114b6765983c5524759656f335675835 | <ide><path>test/parallel/test-domain-crypto.js
<del>/* eslint-disable strict, required-modules */
<add>/* eslint-disable required-modules */
<add>'use strict';
<add>
<ide> try {
<ide> var crypto = require('crypto');
<ide> } catch (e) { | 1 |
Go | Go | add lock to protext devices map | 70826e8b3fee27b971852aad89053507c6866d3e | <ide><path>runtime/graphdriver/devmapper/deviceset.go
<ide> type DevInfo struct {
<ide> }
<ide>
<ide> type MetaData struct {
<del> Devices map[string]*DevInfo `json:devices`
<add> Devices map[string]*DevInfo `json:devices`
<add> devicesLock sync.Mutex `json:"-"` // Protects all read/writes to Devices map
<ide> }
<ide>
<ide> type DeviceSet struct {
<ide> func (devices *DeviceSet) allocateTransactionId() uint64 {
<ide> }
<ide>
<ide> func (devices *DeviceSet) saveMetadata() error {
<add> devices.devicesLock.Lock()
<ide> jsonData, err := json.Marshal(devices.MetaData)
<add> devices.devicesLock.Unlock()
<ide> if err != nil {
<ide> return fmt.Errorf("Error encoding metadata to json: %s", err)
<ide> }
<ide> func (devices *DeviceSet) saveMetadata() error {
<ide> }
<ide>
<ide> func (devices *DeviceSet) lookupDevice(hash string) (*DevInfo, error) {
<add> devices.devicesLock.Lock()
<add> defer devices.devicesLock.Unlock()
<ide> info := devices.Devices[hash]
<ide> if info == nil {
<ide> return nil, fmt.Errorf("Unknown device %s", hash)
<ide> func (devices *DeviceSet) registerDevice(id int, hash string, size uint64) (*Dev
<ide> devices: devices,
<ide> }
<ide>
<add> devices.devicesLock.Lock()
<ide> devices.Devices[hash] = info
<add> devices.devicesLock.Unlock()
<add>
<ide> if err := devices.saveMetadata(); err != nil {
<ide> // Try to remove unused device
<add> devices.devicesLock.Lock()
<ide> delete(devices.Devices, hash)
<add> devices.devicesLock.Unlock()
<ide> return nil, err
<ide> }
<ide>
<ide> func (devices *DeviceSet) deleteDevice(info *DevInfo) error {
<ide> }
<ide>
<ide> devices.allocateTransactionId()
<add> devices.devicesLock.Lock()
<ide> delete(devices.Devices, info.Hash)
<add> devices.devicesLock.Unlock()
<ide>
<ide> if err := devices.saveMetadata(); err != nil {
<add> devices.devicesLock.Lock()
<ide> devices.Devices[info.Hash] = info
<add> devices.devicesLock.Unlock()
<ide> utils.Debugf("Error saving meta data: %s\n", err)
<ide> return err
<ide> }
<ide> func (devices *DeviceSet) Shutdown() error {
<ide> utils.Debugf("[devmapper] Shutting down DeviceSet: %s", devices.root)
<ide> defer utils.Debugf("[deviceset %s] shutdown END", devices.devicePrefix)
<ide>
<add> var devs []*DevInfo
<add>
<add> devices.devicesLock.Lock()
<ide> for _, info := range devices.Devices {
<add> devs = append(devs, info)
<add> }
<add> devices.devicesLock.Unlock()
<add>
<add> for _, info := range devs {
<ide> info.lock.Lock()
<ide> if info.mountCount > 0 {
<ide> // We use MNT_DETACH here in case it is still busy in some running
<ide> func (devices *DeviceSet) List() []string {
<ide> devices.Lock()
<ide> defer devices.Unlock()
<ide>
<add> devices.devicesLock.Lock()
<ide> ids := make([]string, len(devices.Devices))
<ide> i := 0
<ide> for k := range devices.Devices {
<ide> ids[i] = k
<ide> i++
<ide> }
<add> devices.devicesLock.Unlock()
<add>
<ide> return ids
<ide> }
<ide> | 1 |
Javascript | Javascript | fix process.ci typo | be85544b89cd88add5e1158812c16f4ca6c39b3a | <ide><path>scripts/tasks/eslint.js
<ide> const runESLint = require('../eslint');
<ide>
<ide> console.log('Linting all files...');
<del>if (!process.CI) {
<add>// https://circleci.com/docs/2.0/env-vars/#circleci-environment-variable-descriptions
<add>if (!process.env.CI) {
<ide> console.log('Hint: run `yarn linc` to only lint changed files.');
<ide> }
<ide> | 1 |
PHP | PHP | prepare response from router | f3ef1653f6f82e2af9c2682a7584d932b974fadd | <ide><path>src/Illuminate/Routing/Router.php
<ide> public function dispatch(Request $request)
<ide> $response = $this->dispatchToRoute($request);
<ide> }
<ide>
<del> $response = $this->prepareResponse($response);
<add> $response = $this->prepareResponse($request, $response);
<ide>
<ide> // Once this route has run and the response has been prepared, we will run the
<ide> // after filter to do any last work on the response or for this application
<ide> public function dispatchToRoute(Request $request)
<ide> $response = $route->run($request);
<ide> }
<ide>
<del> $response = $this->prepareResponse($response);
<add> $response = $this->prepareResponse($request, $response);
<ide>
<ide> // After we have a prepared response from the route or filter we will call to
<ide> // the "after" filters to do any last minute processing on this request or
<ide> public function callRouteFilter($filter, $parameters, $route, $request, $respons
<ide> /**
<ide> * Create a response instance from the given value.
<ide> *
<add> * @param \Symfony\Component\HttpFoundation\Request $request
<ide> * @param mixed $response
<ide> * @return \Illuminate\Http\Response
<ide> */
<del> protected function prepareResponse($response)
<add> protected function prepareResponse($request, $response)
<ide> {
<ide> if ( ! $response instanceof SymfonyResponse)
<ide> {
<ide> $response = new Response($response);
<ide> }
<ide>
<del> return $response;
<add> return $response->prepare($request);
<ide> }
<ide>
<ide> /** | 1 |
Java | Java | introduce @enabledif support for junit jupiter | 634d1c03a3d4b55b44c23c0b240a786331f12659 | <ide><path>spring-test/src/main/java/org/springframework/test/context/junit/jupiter/AbstractExpressionEvaluatingCondition.java
<add>/*
<add> * Copyright 2002-2016 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.test.context.junit.jupiter;
<add>
<add>import java.lang.annotation.Annotation;
<add>import java.lang.reflect.AnnotatedElement;
<add>import java.util.Optional;
<add>import java.util.function.Function;
<add>
<add>import org.apache.commons.logging.Log;
<add>import org.apache.commons.logging.LogFactory;
<add>
<add>import org.junit.jupiter.api.extension.ConditionEvaluationResult;
<add>import org.junit.jupiter.api.extension.ContainerExecutionCondition;
<add>import org.junit.jupiter.api.extension.ExtensionContext;
<add>import org.junit.jupiter.api.extension.TestExecutionCondition;
<add>
<add>import org.springframework.beans.factory.config.BeanExpressionContext;
<add>import org.springframework.beans.factory.config.BeanExpressionResolver;
<add>import org.springframework.beans.factory.config.ConfigurableBeanFactory;
<add>import org.springframework.context.ApplicationContext;
<add>import org.springframework.context.ConfigurableApplicationContext;
<add>import org.springframework.core.annotation.AnnotatedElementUtils;
<add>import org.springframework.util.Assert;
<add>import org.springframework.util.StringUtils;
<add>
<add>/**
<add> * Abstract base class for implementations of {@link ContainerExecutionCondition}
<add> * and {@link TestExecutionCondition} that evaluate expressions configured via
<add> * annotations to determine if a container or test is enabled.
<add> *
<add> * <p>Expressions can be any of the following.
<add> *
<add> * <ul>
<add> * <li>Spring Expression Language (SpEL) expression — for example:
<add> * <pre style="code">#{systemProperties['os.name'].toLowerCase().contains('mac')}</pre>
<add> * <li>Placeholder for a property available in the Spring
<add> * {@link org.springframework.core.env.Environment Environment} — for example:
<add> * <pre style="code">${smoke.tests.enabled}</pre>
<add> * <li>Text literal — for example:
<add> * <pre style="code">true</pre>
<add> * </ul>
<add> *
<add> * @author Sam Brannen
<add> * @author Tadaya Tsuyukubo
<add> * @since 5.0
<add> * @see EnabledIf
<add> * @see DisabledIf
<add> */
<add>abstract class AbstractExpressionEvaluatingCondition implements ContainerExecutionCondition, TestExecutionCondition {
<add>
<add> private static final Log logger = LogFactory.getLog(AbstractExpressionEvaluatingCondition.class);
<add>
<add>
<add> /**
<add> * Evaluate the expression configured via the supplied annotation type on
<add> * the {@link AnnotatedElement} for the supplied {@link ExtensionContext}.
<add> *
<add> * @param annotationType the type of annotation to process
<add> * @param expressionExtractor a function that extracts the expression from
<add> * the annotation
<add> * @param reasonExtractor a function that extracts the reason from the
<add> * annotation
<add> * @param enabledOnTrue indicates whether the returned {@code ConditionEvaluationResult}
<add> * should be {@link ConditionEvaluationResult#enabled enabled} if the expression
<add> * evaluates to {@code true}
<add> * @param context the {@code ExtensionContext}
<add> * @return {@link ConditionEvaluationResult#enabled enabled} if the container
<add> * or test should be enabled; otherwise {@link ConditionEvaluationResult#disabled disabled}
<add> */
<add> protected <A extends Annotation> ConditionEvaluationResult evaluateAnnotation(Class<A> annotationType,
<add> Function<A, String> expressionExtractor, Function<A, String> reasonExtractor, boolean enabledOnTrue,
<add> ExtensionContext context) {
<add>
<add> AnnotatedElement element = context.getElement().get();
<add> Optional<A> annotation = findMergedAnnotation(element, annotationType);
<add>
<add> if (!annotation.isPresent()) {
<add> String reason = String.format("%s is enabled since @%s is not present", element,
<add> annotationType.getSimpleName());
<add> if (logger.isDebugEnabled()) {
<add> logger.debug(reason);
<add> }
<add> return ConditionEvaluationResult.enabled(reason);
<add> }
<add>
<add> // @formatter:off
<add> String expression = annotation.map(expressionExtractor).map(String::trim).filter(StringUtils::hasLength)
<add> .orElseThrow(() -> new IllegalStateException(String.format(
<add> "The expression in @%s on [%s] must not be blank", annotationType.getSimpleName(), element)));
<add> // @formatter:on
<add>
<add> boolean result = evaluateExpression(expression, annotationType, context);
<add>
<add> if (result) {
<add> String adjective = (enabledOnTrue ? "enabled" : "disabled");
<add> String reason = annotation.map(reasonExtractor).filter(StringUtils::hasText).orElseGet(
<add> () -> String.format("%s is %s because @%s(\"%s\") evaluated to true", element, adjective,
<add> annotationType.getSimpleName(), expression));
<add> if (logger.isInfoEnabled()) {
<add> logger.info(reason);
<add> }
<add> return (enabledOnTrue ? ConditionEvaluationResult.enabled(reason)
<add> : ConditionEvaluationResult.disabled(reason));
<add> }
<add> else {
<add> String adjective = (enabledOnTrue ? "disabled" : "enabled");
<add> String reason = String.format("%s is %s because @%s(\"%s\") did not evaluate to true",
<add> element, adjective, annotationType.getSimpleName(), expression);
<add> if (logger.isDebugEnabled()) {
<add> logger.debug(reason);
<add> }
<add> return (enabledOnTrue ? ConditionEvaluationResult.disabled(reason)
<add> : ConditionEvaluationResult.enabled(reason));
<add> }
<add> }
<add>
<add> private <A extends Annotation> boolean evaluateExpression(String expression, Class<A> annotationType,
<add> ExtensionContext extensionContext) {
<add>
<add> ApplicationContext applicationContext = SpringExtension.getApplicationContext(extensionContext);
<add>
<add> if (!(applicationContext instanceof ConfigurableApplicationContext)) {
<add> if (logger.isWarnEnabled()) {
<add> String contextType = (applicationContext != null ? applicationContext.getClass().getName() : "null");
<add> logger.warn(String.format("@%s(\"%s\") could not be evaluated on [%s] since the test " +
<add> "ApplicationContext [%s] is not a ConfigurableApplicationContext",
<add> annotationType.getSimpleName(), expression, extensionContext.getElement(), contextType));
<add> }
<add> return false;
<add> }
<add>
<add> ConfigurableBeanFactory configurableBeanFactory = ((ConfigurableApplicationContext) applicationContext).getBeanFactory();
<add> BeanExpressionResolver expressionResolver = configurableBeanFactory.getBeanExpressionResolver();
<add> BeanExpressionContext beanExpressionContext = new BeanExpressionContext(configurableBeanFactory, null);
<add>
<add> Object result = expressionResolver.evaluate(configurableBeanFactory.resolveEmbeddedValue(expression),
<add> beanExpressionContext);
<add>
<add> Assert.state((result instanceof Boolean || result instanceof String),
<add> () -> String.format("@%s(\"%s\") must evaluate to a String or a Boolean, not %s",
<add> annotationType.getSimpleName(), expression, (result != null ? result.getClass().getName() : "null")));
<add>
<add> return (result instanceof Boolean && ((Boolean) result).booleanValue())
<add> || (result instanceof String && Boolean.parseBoolean((String) result));
<add> }
<add>
<add> private static <A extends Annotation> Optional<A> findMergedAnnotation(AnnotatedElement element,
<add> Class<A> annotationType) {
<add> return Optional.ofNullable(AnnotatedElementUtils.findMergedAnnotation(element, annotationType));
<add> }
<add>
<add>}
<ide><path>spring-test/src/main/java/org/springframework/test/context/junit/jupiter/DisabledIf.java
<ide> * @author Tadaya Tsuyukubo
<ide> * @since 5.0
<ide> * @see SpringExtension
<add> * @see EnabledIf
<ide> * @see org.junit.jupiter.api.Disabled
<ide> */
<ide> @Target({ ElementType.TYPE, ElementType.METHOD })
<ide><path>spring-test/src/main/java/org/springframework/test/context/junit/jupiter/DisabledIfCondition.java
<ide>
<ide> package org.springframework.test.context.junit.jupiter;
<ide>
<del>import java.lang.annotation.Annotation;
<del>import java.lang.reflect.AnnotatedElement;
<del>import java.util.Optional;
<del>
<del>import org.apache.commons.logging.Log;
<del>import org.apache.commons.logging.LogFactory;
<del>
<ide> import org.junit.jupiter.api.extension.ConditionEvaluationResult;
<ide> import org.junit.jupiter.api.extension.ContainerExecutionCondition;
<ide> import org.junit.jupiter.api.extension.ContainerExtensionContext;
<ide> import org.junit.jupiter.api.extension.ExtensionContext;
<ide> import org.junit.jupiter.api.extension.TestExecutionCondition;
<ide> import org.junit.jupiter.api.extension.TestExtensionContext;
<ide>
<del>import org.springframework.beans.factory.config.BeanExpressionContext;
<del>import org.springframework.beans.factory.config.BeanExpressionResolver;
<del>import org.springframework.beans.factory.config.ConfigurableBeanFactory;
<del>import org.springframework.context.ApplicationContext;
<del>import org.springframework.context.ConfigurableApplicationContext;
<del>import org.springframework.core.annotation.AnnotatedElementUtils;
<del>import org.springframework.util.Assert;
<del>import org.springframework.util.StringUtils;
<del>
<ide> /**
<ide> * {@code DisabledIfCondition} is a composite {@link ContainerExecutionCondition}
<ide> * and {@link TestExecutionCondition} that supports the {@link DisabledIf @DisabledIf}
<ide> * annotation when using the <em>Spring TestContext Framework</em> in conjunction
<ide> * with JUnit 5's <em>Jupiter</em> programming model.
<ide> *
<del> * <p>Any attempt to use {@code DisabledIfCondition} without the presence of
<del> * {@link DisabledIf @DisabledIf} will result in an {@link IllegalStateException}.
<add> * <p>Any attempt to use the {@code DisabledIfCondition} without the presence of
<add> * {@link DisabledIf @DisabledIf} will result in an <em>enabled</em>
<add> * {@link ConditionEvaluationResult}.
<ide> *
<ide> * @author Sam Brannen
<ide> * @author Tadaya Tsuyukubo
<ide> * @since 5.0
<del> * @see org.springframework.test.context.junit.jupiter.DisabledIf
<del> * @see org.springframework.test.context.junit.jupiter.SpringExtension
<add> * @see DisabledIf
<add> * @see EnabledIf
<add> * @see SpringExtension
<ide> */
<del>public class DisabledIfCondition implements ContainerExecutionCondition, TestExecutionCondition {
<del>
<del> private static final Log logger = LogFactory.getLog(DisabledIfCondition.class);
<del>
<add>public class DisabledIfCondition extends AbstractExpressionEvaluatingCondition {
<ide>
<ide> /**
<ide> * Containers are disabled if {@code @DisabledIf} is present on the test class
<ide> public ConditionEvaluationResult evaluate(TestExtensionContext context) {
<ide> return evaluateDisabledIf(context);
<ide> }
<ide>
<del> private ConditionEvaluationResult evaluateDisabledIf(ExtensionContext extensionContext) {
<del> AnnotatedElement element = extensionContext.getElement().get();
<del> Optional<DisabledIf> disabledIf = findMergedAnnotation(element, DisabledIf.class);
<del> Assert.state(disabledIf.isPresent(), () -> "@DisabledIf must be present on " + element);
<del>
<del> // @formatter:off
<del> String expression = disabledIf.map(DisabledIf::expression).map(String::trim).filter(StringUtils::hasLength)
<del> .orElseThrow(() -> new IllegalStateException(String.format(
<del> "The expression in @DisabledIf on [%s] must not be blank", element)));
<del> // @formatter:on
<del>
<del> if (isDisabled(expression, extensionContext)) {
<del> String reason = disabledIf.map(DisabledIf::reason).filter(StringUtils::hasText).orElseGet(
<del> () -> String.format("%s is disabled because @DisabledIf(\"%s\") evaluated to true", element,
<del> expression));
<del> logger.info(reason);
<del> return ConditionEvaluationResult.disabled(reason);
<del> }
<del> else {
<del> String reason = String.format("%s is enabled because @DisabledIf(\"%s\") did not evaluate to true",
<del> element, expression);
<del> logger.debug(reason);
<del> return ConditionEvaluationResult.enabled(reason);
<del> }
<del> }
<del>
<del> private boolean isDisabled(String expression, ExtensionContext extensionContext) {
<del> ApplicationContext applicationContext = SpringExtension.getApplicationContext(extensionContext);
<del>
<del> if (!(applicationContext instanceof ConfigurableApplicationContext)) {
<del> if (logger.isWarnEnabled()) {
<del> String contextType = (applicationContext != null ? applicationContext.getClass().getName() : "null");
<del> logger.warn(String.format("@DisabledIf(\"%s\") could not be evaluated on [%s] since the test " +
<del> "ApplicationContext [%s] is not a ConfigurableApplicationContext",
<del> expression, extensionContext.getElement(), contextType));
<del> }
<del> return false;
<del> }
<del>
<del> ConfigurableBeanFactory configurableBeanFactory = ((ConfigurableApplicationContext) applicationContext).getBeanFactory();
<del> BeanExpressionResolver expressionResolver = configurableBeanFactory.getBeanExpressionResolver();
<del> BeanExpressionContext beanExpressionContext = new BeanExpressionContext(configurableBeanFactory, null);
<del>
<del> Object result = expressionResolver.evaluate(configurableBeanFactory.resolveEmbeddedValue(expression),
<del> beanExpressionContext);
<del>
<del> Assert.state((result instanceof Boolean || result instanceof String), () ->
<del> String.format("@DisabledIf(\"%s\") must evaluate to a String or a Boolean, not %s", expression,
<del> (result != null ? result.getClass().getName() : "null")));
<del>
<del> boolean disabled = (result instanceof Boolean && ((Boolean) result).booleanValue()) ||
<del> (result instanceof String && Boolean.parseBoolean((String) result));
<del>
<del> return disabled;
<del> }
<del>
<del> private static <A extends Annotation> Optional<A> findMergedAnnotation(AnnotatedElement element,
<del> Class<A> annotationType) {
<del> return Optional.ofNullable(AnnotatedElementUtils.findMergedAnnotation(element, annotationType));
<add> private ConditionEvaluationResult evaluateDisabledIf(ExtensionContext context) {
<add> return evaluateAnnotation(DisabledIf.class, DisabledIf::expression, DisabledIf::reason, false, context);
<ide> }
<ide>
<ide> }
<ide><path>spring-test/src/main/java/org/springframework/test/context/junit/jupiter/EnabledIf.java
<add>/*
<add> * Copyright 2002-2016 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.test.context.junit.jupiter;
<add>
<add>import java.lang.annotation.Documented;
<add>import java.lang.annotation.ElementType;
<add>import java.lang.annotation.Retention;
<add>import java.lang.annotation.RetentionPolicy;
<add>import java.lang.annotation.Target;
<add>
<add>import org.junit.jupiter.api.extension.ExtendWith;
<add>
<add>import org.springframework.core.annotation.AliasFor;
<add>
<add>/**
<add> * {@code @EnabledIf} is used to signal that the annotated test class or test
<add> * method is <em>enabled</em> and should be executed if the supplied
<add> * {@link #expression} evaluates to {@code true}.
<add> *
<add> * <p>When applied at the class level, all test methods within that class
<add> * are automatically enabled by default as well.
<add> *
<add> * <p>For basic examples, see the Javadoc for {@link #expression}.
<add> *
<add> * <p>This annotation may be used as a <em>meta-annotation</em> to create
<add> * custom <em>composed annotations</em>. For example, a custom
<add> * {@code @EnabledOnMac} annotation can be created as follows.
<add> *
<add> * <pre style="code">
<add> * {@literal @}Target({ ElementType.TYPE, ElementType.METHOD })
<add> * {@literal @}Retention(RetentionPolicy.RUNTIME)
<add> * {@literal @}EnabledIf(
<add> * expression = "#{systemProperties['os.name'].toLowerCase().contains('mac')}",
<add> * reason = "Enabled on Mac OS"
<add> * )
<add> * public {@literal @}interface EnabledOnMac {}
<add> * </pre>
<add> *
<add> * @author Sam Brannen
<add> * @since 5.0
<add> * @see SpringExtension
<add> * @see DisabledIf
<add> * @see org.junit.jupiter.api.Disabled
<add> */
<add>@Target({ ElementType.TYPE, ElementType.METHOD })
<add>@Retention(RetentionPolicy.RUNTIME)
<add>@Documented
<add>@ExtendWith(EnabledIfCondition.class)
<add>public @interface EnabledIf {
<add>
<add> /**
<add> * Alias for {@link #expression}; only intended to be used if an
<add> * explicit {@link #reason} is not provided.
<add> *
<add> * @see #expression
<add> */
<add> @AliasFor("expression")
<add> String value() default "";
<add>
<add> /**
<add> * The expression that will be evaluated to determine if the annotated test
<add> * class or test method is <em>enabled</em>.
<add> *
<add> * <p>If the expression evaluates to {@link Boolean#TRUE} or a {@link String}
<add> * equal to {@code "true"} (ignoring case), the test will be enabled.
<add> *
<add> * <p>Expressions can be any of the following.
<add> *
<add> * <ul>
<add> * <li>Spring Expression Language (SpEL) expression — for example:
<add> * <pre style="code">@EnabledIf("#{systemProperties['os.name'].toLowerCase().contains('mac')}")</pre>
<add> * <li>Placeholder for a property available in the Spring
<add> * {@link org.springframework.core.env.Environment Environment} — for example:
<add> * <pre style="code">@EnabledIf("${smoke.tests.enabled}")</pre>
<add> * <li>Text literal — for example:
<add> * <pre style="code">@EnabledIf("true")</pre>
<add> * </ul>
<add> *
<add> * <p>Note, however, that a <em>text literal</em> which is not the result of
<add> * dynamic resolution of a property placeholder is of zero practical value
<add> * since {@code @EnabledIf("false")} is equivalent to {@code @Disabled}
<add> * and {@code @EnabledIf("true")} is logically meaningless.
<add> *
<add> * @see #reason
<add> * @see #value
<add> */
<add> @AliasFor("value")
<add> String expression() default "";
<add>
<add> /**
<add> * The reason this test is enabled.
<add> *
<add> * @see #expression
<add> */
<add> String reason() default "";
<add>
<add>}
<ide><path>spring-test/src/main/java/org/springframework/test/context/junit/jupiter/EnabledIfCondition.java
<add>/*
<add> * Copyright 2002-2016 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.test.context.junit.jupiter;
<add>
<add>import org.junit.jupiter.api.extension.ConditionEvaluationResult;
<add>import org.junit.jupiter.api.extension.ContainerExecutionCondition;
<add>import org.junit.jupiter.api.extension.ContainerExtensionContext;
<add>import org.junit.jupiter.api.extension.ExtensionContext;
<add>import org.junit.jupiter.api.extension.TestExecutionCondition;
<add>import org.junit.jupiter.api.extension.TestExtensionContext;
<add>
<add>/**
<add> * {@code EnabledIfCondition} is a composite {@link ContainerExecutionCondition}
<add> * and {@link TestExecutionCondition} that supports the {@link EnabledIf @EnabledIf}
<add> * annotation when using the <em>Spring TestContext Framework</em> in conjunction
<add> * with JUnit 5's <em>Jupiter</em> programming model.
<add> *
<add> * <p>Any attempt to use the {@code EnabledIfCondition} without the presence of
<add> * {@link EnabledIf @EnabledIf} will result in an <em>enabled</em>
<add> * {@link ConditionEvaluationResult}.
<add> *
<add> * @author Sam Brannen
<add> * @since 5.0
<add> * @see EnabledIf
<add> * @see DisabledIf
<add> * @see SpringExtension
<add> */
<add>public class EnabledIfCondition extends AbstractExpressionEvaluatingCondition {
<add>
<add> /**
<add> * Containers are enabled if {@code @EnabledIf} is present on the test class
<add> * and the configured expression evaluates to {@code true}.
<add> */
<add> @Override
<add> public ConditionEvaluationResult evaluate(ContainerExtensionContext context) {
<add> return evaluateEnabledIf(context);
<add> }
<add>
<add> /**
<add> * Tests are enabled if {@code @EnabledIf} is present on the test method
<add> * and the configured expression evaluates to {@code true}.
<add> */
<add> @Override
<add> public ConditionEvaluationResult evaluate(TestExtensionContext context) {
<add> return evaluateEnabledIf(context);
<add> }
<add>
<add> private ConditionEvaluationResult evaluateEnabledIf(ExtensionContext context) {
<add> return evaluateAnnotation(EnabledIf.class, EnabledIf::expression, EnabledIf::reason, true, context);
<add> }
<add>
<add>}
<ide><path>spring-test/src/test/java/org/springframework/test/context/junit/jupiter/DisabledIfConditionTestCase.java
<ide> import static org.hamcrest.CoreMatchers.endsWith;
<ide> import static org.hamcrest.CoreMatchers.equalTo;
<ide> import static org.hamcrest.CoreMatchers.is;
<del>import static org.hamcrest.CoreMatchers.startsWith;
<ide> import static org.hamcrest.MatcherAssert.assertThat;
<ide> import static org.junit.jupiter.api.Assertions.assertAll;
<ide> import static org.junit.jupiter.api.Assertions.assertFalse;
<ide> class DisabledIfConditionTestCase {
<ide>
<ide> @Test
<ide> void missingDisabledIf() {
<del> IllegalStateException exception = expectThrows(IllegalStateException.class,
<del> () -> condition.evaluate(buildExtensionContext("missingDisabledIf")));
<del>
<del> assertThat(exception.getMessage(), startsWith("@DisabledIf must be present"));
<add> assertResult(condition.evaluate(buildExtensionContext("missingDisabledIf")), false,
<add> endsWith("missingDisabledIf() is enabled since @DisabledIf is not present"));
<ide> }
<ide>
<ide> @Test
<ide><path>spring-test/src/test/java/org/springframework/test/context/junit/jupiter/DisabledIfTestCase.java
<ide> class DisabledIfOnMethodTestCase {
<ide>
<ide> @Test
<ide> @DisabledIf("true")
<del> void disabledByStringTrue() {
<add> void disabledIfWithStringTrue() {
<ide> fail("This test must be disabled");
<ide> }
<ide>
<ide> @Test
<ide> @DisabledIf(" true ")
<del> void disabledByStringTrueWithSurroundingWhitespace() {
<add> void disabledIfWithStringTrueWithSurroundingWhitespace() {
<ide> fail("This test must be disabled");
<ide> }
<ide>
<ide> @Test
<ide> @DisabledIf("TrUe")
<del> void disabledByStringTrueIgnoreCase() {
<add> void disabledIfWithStringTrueIgnoreCase() {
<ide> fail("This test must be disabled");
<ide> }
<ide>
<ide> @Test
<ide> @DisabledIf("${foo}")
<del> void disabledByPropertyPlaceholder() {
<add> void disabledIfWithPropertyPlaceholder() {
<ide> fail("This test must be disabled");
<ide> }
<ide>
<ide> @Test
<ide> @DisabledIf("\t${foo} ")
<del> void disabledByPropertyPlaceholderWithSurroundingWhitespace() {
<add> void disabledIfWithPropertyPlaceholderWithSurroundingWhitespace() {
<ide> fail("This test must be disabled");
<ide> }
<ide>
<ide> @Test
<del> @DisabledIf("#{T(java.lang.Boolean).TRUE}")
<del> void disabledBySpelBoolean() {
<add> @DisabledIf("#{T(Boolean).TRUE}")
<add> void disabledIfWithSpelBoolean() {
<ide> fail("This test must be disabled");
<ide> }
<ide>
<ide> @Test
<del> @DisabledIf(" #{T(java.lang.Boolean).TRUE} ")
<del> void disabledBySpelBooleanWithSurroundingWhitespace() {
<add> @DisabledIf(" #{T(Boolean).TRUE} ")
<add> void disabledIfWithSpelBooleanWithSurroundingWhitespace() {
<ide> fail("This test must be disabled");
<ide> }
<ide>
<ide> @Test
<ide> @DisabledIf("#{'tr' + 'ue'}")
<del> void disabledBySpelStringConcatenation() {
<add> void disabledIfWithSpelStringConcatenation() {
<ide> fail("This test must be disabled");
<ide> }
<ide>
<ide> @Test
<ide> @DisabledIf("#{6 * 7 == 42}")
<del> void disabledBySpelMathematicalComparison() {
<add> void disabledIfWithSpelArithmeticComparison() {
<ide> fail("This test must be disabled");
<ide> }
<ide>
<ide> @Test
<ide> @DisabledOnMac
<del> void disabledBySpelOsCheckInCustomComposedAnnotation() {
<add> void disabledIfWithSpelOsCheckInCustomComposedAnnotation() {
<ide> assertFalse(System.getProperty("os.name").contains("Mac"), "This test must be disabled on Mac OS");
<ide> }
<ide>
<ide> @Test
<ide> @DisabledIf("#{@booleanTrueBean}")
<del> void disabledBySpelBooleanTrueBean() {
<add> void disabledIfWithSpelBooleanTrueBean() {
<ide> fail("This test must be disabled");
<ide> }
<ide>
<ide> @Test
<ide> @DisabledIf("#{@stringTrueBean}")
<del> void disabledBySpelStringTrueBean() {
<add> void disabledIfWithSpelStringTrueBean() {
<ide> fail("This test must be disabled");
<ide> }
<ide>
<ide> void foo() {
<ide> fail("This test must be disabled");
<ide> }
<ide>
<del> // Even though method level condition is not disabling test, class level condition
<del> // should take precedence
<ide> @Test
<ide> @DisabledIf("false")
<ide> void bar() {
<del> fail("This test must be disabled");
<add> fail("This test must be disabled due to class-level condition");
<ide> }
<ide>
<ide> }
<ide><path>spring-test/src/test/java/org/springframework/test/context/junit/jupiter/EnabledIfTestCase.java
<add>/*
<add> * Copyright 2002-2016 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.test.context.junit.jupiter;
<add>
<add>import org.junit.jupiter.api.Nested;
<add>import org.junit.jupiter.api.Test;
<add>import org.springframework.context.annotation.Bean;
<add>import org.springframework.context.annotation.Configuration;
<add>import org.springframework.test.context.TestPropertySource;
<add>
<add>import static org.junit.jupiter.api.Assertions.assertFalse;
<add>import static org.junit.jupiter.api.Assertions.assertTrue;
<add>import static org.junit.jupiter.api.Assertions.fail;
<add>
<add>/**
<add> * Integration tests which verify support for {@link EnabledIf @EnabledIf}
<add> * in conjunction with the {@link SpringExtension} in a JUnit 5 (Jupiter)
<add> * environment.
<add> *
<add> * @author Tadaya Tsuyukubo
<add> * @author Sam Brannen
<add> * @since 5.0
<add> * @see EnabledIfConditionTestCase
<add> * @see EnabledIf
<add> * @see SpringExtension
<add> */
<add>class EnabledIfTestCase {
<add>
<add> @SpringJUnitConfig(Config.class)
<add> @TestPropertySource(properties = "foo = false")
<add> @Nested
<add> class EnabledIfOnMethodTestCase {
<add>
<add> @Test
<add> @EnabledIf("false")
<add> void enabledIfWithStringFalse() {
<add> fail("This test must be disabled");
<add> }
<add>
<add> @Test
<add> @EnabledIf(" false ")
<add> void enabledIfWithStringFalseWithSurroundingWhitespace() {
<add> fail("This test must be disabled");
<add> }
<add>
<add> @Test
<add> @EnabledIf("FaLsE")
<add> void enabledIfWithStringFalseIgnoreCase() {
<add> fail("This test must be disabled");
<add> }
<add>
<add> @Test
<add> @EnabledIf("${foo}")
<add> void enabledIfWithPropertyPlaceholder() {
<add> fail("This test must be disabled");
<add> }
<add>
<add> @Test
<add> @EnabledIf("\t${foo} ")
<add> void enabledIfWithPropertyPlaceholderWithSurroundingWhitespace() {
<add> fail("This test must be disabled");
<add> }
<add>
<add> @Test
<add> @EnabledIf("#{T(Boolean).FALSE}")
<add> void enabledIfWithSpelBoolean() {
<add> fail("This test must be disabled");
<add> }
<add>
<add> @Test
<add> @EnabledIf(" #{T(Boolean).FALSE} ")
<add> void enabledIfWithSpelBooleanWithSurroundingWhitespace() {
<add> fail("This test must be disabled");
<add> }
<add>
<add> @Test
<add> @EnabledIf("#{'fal' + 'se'}")
<add> void enabledIfWithSpelStringConcatenation() {
<add> fail("This test must be disabled");
<add> }
<add>
<add> @Test
<add> @EnabledIf("#{1 + 2 == 4}")
<add> void enabledIfWithSpelArithmeticComparison() {
<add> fail("This test must be disabled");
<add> }
<add>
<add> @Test
<add> @EnabledOnMac
<add> void enabledIfWithSpelOsCheckInCustomComposedAnnotation() {
<add> String os = System.getProperty("os.name").toLowerCase();
<add> assertTrue(os.contains("mac"), "This test must be enabled on Mac OS");
<add> assertFalse(os.contains("win"), "This test must be disabled on Windows");
<add> }
<add>
<add> @Test
<add> @EnabledIf("#{@booleanFalseBean}")
<add> void enabledIfWithSpelBooleanFalseBean() {
<add> fail("This test must be disabled");
<add> }
<add>
<add> @Test
<add> @EnabledIf("#{@stringFalseBean}")
<add> void enabledIfWithSpelStringFalseBean() {
<add> fail("This test must be disabled");
<add> }
<add> }
<add>
<add> @SpringJUnitConfig(Config.class)
<add> @Nested
<add> @EnabledIf("false")
<add> class EnabledIfOnClassTestCase {
<add>
<add> @Test
<add> void foo() {
<add> fail("This test must be disabled");
<add> }
<add>
<add> @Test
<add> @EnabledIf("true")
<add> void bar() {
<add> fail("This test must be disabled due to class-level condition");
<add> }
<add> }
<add>
<add> @Configuration
<add> static class Config {
<add>
<add> @Bean
<add> Boolean booleanFalseBean() {
<add> return Boolean.FALSE;
<add> }
<add>
<add> @Bean
<add> String stringFalseBean() {
<add> return "false";
<add> }
<add> }
<add>
<add>}
<ide><path>spring-test/src/test/java/org/springframework/test/context/junit/jupiter/EnabledOnMac.java
<add>/*
<add> * Copyright 2002-2016 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.test.context.junit.jupiter;
<add>
<add>import java.lang.annotation.Documented;
<add>import java.lang.annotation.ElementType;
<add>import java.lang.annotation.Retention;
<add>import java.lang.annotation.RetentionPolicy;
<add>import java.lang.annotation.Target;
<add>
<add>/**
<add> * Demo <em>composed annotation</em> for {@link EnabledIf @EnabledIf} that
<add> * enables a test class or test method if the current operating system is
<add> * Mac OS.
<add> *
<add> * @author Sam Brannen
<add> * @since 5.0
<add> */
<add>@Target({ ElementType.TYPE, ElementType.METHOD })
<add>@Retention(RetentionPolicy.RUNTIME)
<add>@Documented
<add>@EnabledIf(expression = "#{systemProperties['os.name'].toLowerCase().contains('mac')}", reason = "Enabled on Mac OS")
<add>public @interface EnabledOnMac {
<add>} | 9 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.