content_type stringclasses 8 values | main_lang stringclasses 7 values | message stringlengths 1 50 | sha stringlengths 40 40 | patch stringlengths 52 962k | file_count int64 1 300 |
|---|---|---|---|---|---|
Javascript | Javascript | update punycode to 2.1.1 | ab10bfe376b17f3f3567605148ef6fdcc5caef7c | <ide><path>lib/punycode.js
<ide> const delimiter = '-'; // '\x2D'
<ide>
<ide> /** Regular expressions */
<ide> const regexPunycode = /^xn--/;
<del>const regexNonASCII = /[^\x20-\x7E]/; // unprintable ASCII chars + non-ASCII chars
<add>const regexNonASCII = /[^\0-\x7E]/; // non-ASCII chars
<ide> const regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators
<ide>
<ide> /** Error messages */
<ide> const decode = function(input) {
<ide> basic = 0;
<ide> }
<ide>
<del> for (var j = 0; j < basic; ++j) {
<add> for (let j = 0; j < basic; ++j) {
<ide> // if it's not a basic code point
<ide> if (input.charCodeAt(j) >= 0x80) {
<ide> error('not-basic');
<ide> const decode = function(input) {
<ide> // Main decoding loop: start just after the last delimiter if any basic code
<ide> // points were copied; start at the beginning otherwise.
<ide>
<del> for (var index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
<add> for (let index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
<ide>
<ide> // `index` is the index of the next character to be consumed.
<ide> // Decode a generalized variable-length integer into `delta`,
<ide> // which gets added to `i`. The overflow checking is easier
<ide> // if we increase `i` as we go, then subtract off its starting
<ide> // value at the end to obtain `delta`.
<ide> let oldi = i;
<del> for (var w = 1, k = base; /* no condition */; k += base) {
<add> for (let w = 1, k = base; /* no condition */; k += base) {
<ide>
<ide> if (index >= inputLength) {
<ide> error('invalid-input');
<ide> const encode = function(input) {
<ide> if (currentValue == n) {
<ide> // Represent delta as a generalized variable-length integer.
<ide> let q = delta;
<del> for (var k = base; /* no condition */; k += base) {
<add> for (let k = base; /* no condition */; k += base) {
<ide> const t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
<ide> if (q < t) {
<ide> break;
<ide> const punycode = {
<ide> * @memberOf punycode
<ide> * @type String
<ide> */
<del> 'version': '2.0.0',
<add> 'version': '2.1.0',
<ide> /**
<ide> * An object of methods to convert from JavaScript's internal character
<ide> * representation (UCS-2) to Unicode code points, and back. | 1 |
Javascript | Javascript | allow key pressing when triggering browser event | 26e8ab3693eb0ad388247ae5c35cd52eaa709b0c | <ide><path>src/scenario/Scenario.js
<ide> function callerFile(offset) {
<ide> * Triggers a browser event. Attempts to choose the right event if one is
<ide> * not specified.
<ide> *
<del> * @param {Object} Either a wrapped jQuery/jqLite node or a DOMElement
<del> * @param {string} Optional event type.
<add> * @param {Object} element Either a wrapped jQuery/jqLite node or a DOMElement
<add> * @param {string} type Optional event type.
<add> * @param {Array.<string>=} keys Optional list of pressed keys
<add> * (valid values: 'alt', 'meta', 'shift', 'ctrl')
<ide> */
<del>function browserTrigger(element, type) {
<add>function browserTrigger(element, type, keys) {
<ide> if (element && !element.nodeName) element = element[0];
<ide> if (!element) return;
<ide> if (!type) {
<ide> function browserTrigger(element, type) {
<ide> element = element.parentNode;
<ide> type = 'change';
<ide> }
<add>
<add> keys = keys || [];
<add> function pressed(key) {
<add> return indexOf(keys, key) !== -1;
<add> }
<add>
<ide> if (msie < 9) {
<ide> switch(element.type) {
<ide> case 'radio':
<ide> function browserTrigger(element, type) {
<ide> // forcing the browser to compute the element position (by reading its CSS)
<ide> // puts the element in consistent state.
<ide> element.style.posLeft;
<add>
<add> // TODO(vojta): create event objects with pressed keys to get it working on IE<9
<ide> var ret = element.fireEvent('on' + type);
<ide> if (lowercase(element.type) == 'submit') {
<ide> while(element) {
<ide> function browserTrigger(element, type) {
<ide> return originalPreventDefault.apply(evnt, arguments);
<ide> };
<ide>
<del> evnt.initMouseEvent(type, true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, element);
<add> evnt.initMouseEvent(type, true, true, window, 0, 0, 0, 0, 0, pressed('ctrl'), pressed('alt'),
<add> pressed('shift'), pressed('meta'), 0, element);
<ide>
<ide> element.dispatchEvent(evnt);
<ide> finalProcessDefault = !(appWindow.angular['ff-684208-preventDefault'] || !fakeProcessDefault) | 1 |
Javascript | Javascript | replace loop with padstart | 9d768504d25a2b2899a8d1826794ca24be7e65df | <ide><path>tools/license2rtf.js
<ide> function RtfGenerator() {
<ide> };
<ide>
<ide> function toHex(number, length) {
<del> var hex = (~~number).toString(16);
<del> while (hex.length < length)
<del> hex = `0${hex}`;
<del> return hex;
<add> return (~~number).toString(16).padStart(length, '0');
<ide> }
<ide>
<ide> function rtfEscape(string) { | 1 |
Java | Java | use pathcontainer in web.reactive.function.server | 2ccbc55ffdffc08d8f64f0b195b38e602cca7ce1 | <ide><path>spring-test/src/main/java/org/springframework/mock/web/reactive/function/server/MockServerRequest.java
<ide> import java.net.InetSocketAddress;
<ide> import java.net.URI;
<ide> import java.nio.charset.Charset;
<add>import java.nio.charset.StandardCharsets;
<ide> import java.security.Principal;
<ide> import java.util.Arrays;
<ide> import java.util.Collections;
<ide> import org.springframework.http.HttpMethod;
<ide> import org.springframework.http.HttpRange;
<ide> import org.springframework.http.MediaType;
<add>import org.springframework.http.server.reactive.PathContainer;
<add>import org.springframework.http.server.reactive.RequestPath;
<ide> import org.springframework.http.server.reactive.ServerHttpRequest;
<ide> import org.springframework.lang.Nullable;
<ide> import org.springframework.util.Assert;
<ide> public class MockServerRequest implements ServerRequest {
<ide>
<ide> private final URI uri;
<ide>
<add> private final RequestPath pathContainer;
<add>
<ide> private final MockHeaders headers;
<ide>
<ide> private final MultiValueMap<String, HttpCookie> cookies;
<ide> public class MockServerRequest implements ServerRequest {
<ide> private Principal principal;
<ide>
<ide>
<del> private MockServerRequest(HttpMethod method, URI uri, MockHeaders headers,
<add> private MockServerRequest(HttpMethod method, URI uri, String contextPath, MockHeaders headers,
<ide> MultiValueMap<String, HttpCookie> cookies, @Nullable Object body,
<ide> Map<String, Object> attributes, MultiValueMap<String, String> queryParams,
<ide> Map<String, String> pathVariables, @Nullable WebSession session, @Nullable Principal principal) {
<ide>
<ide> this.method = method;
<ide> this.uri = uri;
<add> this.pathContainer = RequestPath.create(uri, contextPath, StandardCharsets.UTF_8);
<ide> this.headers = headers;
<ide> this.cookies = cookies;
<ide> this.body = body;
<ide> public URI uri() {
<ide> return this.uri;
<ide> }
<ide>
<add> @Override
<add> public PathContainer pathContainer() {
<add> return this.pathContainer;
<add> }
<add>
<ide> @Override
<ide> public Headers headers() {
<ide> return this.headers;
<ide> public interface Builder {
<ide>
<ide> Builder uri(URI uri);
<ide>
<add> Builder contextPath(String contextPath);
<add>
<ide> Builder header(String key, String value);
<ide>
<ide> Builder headers(HttpHeaders headers);
<ide> private static class BuilderImpl implements Builder {
<ide>
<ide> private URI uri = URI.create("http://localhost");
<ide>
<add> private String contextPath = "";
<add>
<ide> private MockHeaders headers = new MockHeaders(new HttpHeaders());
<ide>
<ide> private MultiValueMap<String, HttpCookie> cookies = new LinkedMultiValueMap<>();
<ide> public Builder uri(URI uri) {
<ide> return this;
<ide> }
<ide>
<add> @Override
<add> public Builder contextPath(String contextPath) {
<add> Assert.notNull(contextPath, "'contextPath' must not be null");
<add> this.contextPath = contextPath;
<add> return this;
<add>
<add> }
<add>
<ide> @Override
<ide> public Builder cookie(HttpCookie... cookies) {
<ide> Arrays.stream(cookies).forEach(cookie -> this.cookies.add(cookie.getName(), cookie));
<ide> public Builder session(Principal principal) {
<ide> @Override
<ide> public MockServerRequest body(Object body) {
<ide> this.body = body;
<del> return new MockServerRequest(this.method, this.uri, this.headers, this.cookies,
<del> this.body, this.attributes, this.queryParams, this.pathVariables, this.session,
<del> this.principal);
<add> return new MockServerRequest(this.method, this.uri, this.contextPath, this.headers,
<add> this.cookies, this.body, this.attributes, this.queryParams, this.pathVariables,
<add> this.session, this.principal);
<ide> }
<ide>
<ide> @Override
<ide> public MockServerRequest build() {
<del> return new MockServerRequest(this.method, this.uri, this.headers, this.cookies, null,
<del> this.attributes, this.queryParams, this.pathVariables, this.session,
<del> this.principal);
<add> return new MockServerRequest(this.method, this.uri, this.contextPath, this.headers,
<add> this.cookies, null, this.attributes, this.queryParams, this.pathVariables,
<add> this.session, this.principal);
<ide> }
<ide> }
<ide>
<ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/RequestPath.java
<ide> */
<ide> package org.springframework.http.server.reactive;
<ide>
<add>import java.net.URI;
<add>import java.nio.charset.Charset;
<add>
<ide> /**
<ide> * Represents the complete path for a request.
<ide> *
<ide> public interface RequestPath extends PathContainer {
<ide> */
<ide> PathContainer pathWithinApplication();
<ide>
<add> /**
<add> * Create a new {@code RequestPath} with the given parameters.
<add> */
<add> static RequestPath create(URI uri, String contextPath, Charset charset) {
<add> return new DefaultRequestPath(uri, contextPath, charset);
<add> }
<add>
<ide> }
<ide><path>spring-web/src/main/java/org/springframework/web/util/pattern/PathPattern.java
<ide> public static class PathRemainingMatchInfo {
<ide> /**
<ide> * Return the part of a path that was not matched by a pattern.
<ide> */
<del> public String getPathRemaining() {
<del> return this.pathRemaining.value();
<add> public PathContainer getPathRemaining() {
<add> return this.pathRemaining;
<ide> }
<ide>
<ide> /**
<ide><path>spring-web/src/test/java/org/springframework/web/util/pattern/PathPatternMatcherTests.java
<ide> import org.springframework.web.util.pattern.PathPattern.PathRemainingMatchInfo;
<ide>
<ide> import static org.hamcrest.CoreMatchers.containsString;
<del>import static org.junit.Assert.assertEquals;
<del>import static org.junit.Assert.assertFalse;
<del>import static org.junit.Assert.assertNotNull;
<del>import static org.junit.Assert.assertNull;
<del>import static org.junit.Assert.assertThat;
<del>import static org.junit.Assert.assertTrue;
<del>import static org.junit.Assert.fail;
<add>import static org.junit.Assert.*;
<ide>
<ide> /**
<ide> * Exercise matching of {@link PathPattern} objects.
<ide> public void optionalTrailingSeparators() {
<ide> @Test
<ide> public void pathRemainderBasicCases_spr15336() {
<ide> // Cover all PathElement kinds
<del> assertEquals("/bar", getPathRemaining("/foo","/foo/bar").getPathRemaining());
<del> assertEquals("/", getPathRemaining("/foo","/foo/").getPathRemaining());
<del> assertEquals("/bar",getPathRemaining("/foo*","/foo/bar").getPathRemaining());
<del> assertEquals("/bar", getPathRemaining("/*","/foo/bar").getPathRemaining());
<del> assertEquals("/bar", getPathRemaining("/{foo}","/foo/bar").getPathRemaining());
<add> assertEquals("/bar", getPathRemaining("/foo","/foo/bar").getPathRemaining().value());
<add> assertEquals("/", getPathRemaining("/foo","/foo/").getPathRemaining().value());
<add> assertEquals("/bar",getPathRemaining("/foo*","/foo/bar").getPathRemaining().value());
<add> assertEquals("/bar", getPathRemaining("/*","/foo/bar").getPathRemaining().value());
<add> assertEquals("/bar", getPathRemaining("/{foo}","/foo/bar").getPathRemaining().value());
<ide> assertNull(getPathRemaining("/foo","/bar/baz"));
<del> assertEquals("",getPathRemaining("/**","/foo/bar").getPathRemaining());
<del> assertEquals("",getPathRemaining("/{*bar}","/foo/bar").getPathRemaining());
<del> assertEquals("/bar",getPathRemaining("/a?b/d?e","/aab/dde/bar").getPathRemaining());
<del> assertEquals("/bar",getPathRemaining("/{abc}abc","/xyzabc/bar").getPathRemaining());
<del> assertEquals("/bar",getPathRemaining("/*y*","/xyzxyz/bar").getPathRemaining());
<del> assertEquals("",getPathRemaining("/","/").getPathRemaining());
<del> assertEquals("a",getPathRemaining("/","/a").getPathRemaining());
<del> assertEquals("a/",getPathRemaining("/","/a/").getPathRemaining());
<del> assertEquals("/bar",getPathRemaining("/a{abc}","/a/bar").getPathRemaining());
<del> assertEquals("/bar", getPathRemaining("/foo//","/foo///bar").getPathRemaining());
<add> assertEquals("",getPathRemaining("/**","/foo/bar").getPathRemaining().value());
<add> assertEquals("",getPathRemaining("/{*bar}","/foo/bar").getPathRemaining().value());
<add> assertEquals("/bar",getPathRemaining("/a?b/d?e","/aab/dde/bar").getPathRemaining().value());
<add> assertEquals("/bar",getPathRemaining("/{abc}abc","/xyzabc/bar").getPathRemaining().value());
<add> assertEquals("/bar",getPathRemaining("/*y*","/xyzxyz/bar").getPathRemaining().value());
<add> assertEquals("",getPathRemaining("/","/").getPathRemaining().value());
<add> assertEquals("a",getPathRemaining("/","/a").getPathRemaining().value());
<add> assertEquals("a/",getPathRemaining("/","/a/").getPathRemaining().value());
<add> assertEquals("/bar",getPathRemaining("/a{abc}","/a/bar").getPathRemaining().value());
<add> assertEquals("/bar", getPathRemaining("/foo//","/foo///bar").getPathRemaining().value());
<ide> }
<ide>
<ide> @Test
<ide> public void pathRemainingCornerCases_spr15336() {
<ide> // With a /** on the end have to check if there is any more data post
<ide> // 'the match' it starts with a separator
<ide> assertNull(parse("/resource/**").getPathRemaining(toPathContainer("/resourceX")));
<del> assertEquals("",parse("/resource/**").getPathRemaining(toPathContainer("/resource")).getPathRemaining());
<add> assertEquals("",parse("/resource/**").getPathRemaining(toPathContainer("/resource")).getPathRemaining().value());
<ide>
<ide> // Similar to above for the capture-the-rest variant
<ide> assertNull(parse("/resource/{*foo}").getPathRemaining(toPathContainer("/resourceX")));
<del> assertEquals("",parse("/resource/{*foo}").getPathRemaining(toPathContainer("/resource")).getPathRemaining());
<add> assertEquals("",parse("/resource/{*foo}").getPathRemaining(toPathContainer("/resource")).getPathRemaining().value());
<ide>
<ide> PathPattern.PathRemainingMatchInfo pri = parse("/aaa/{bbb}/c?d/e*f/*/g").getPathRemaining(toPathContainer("/aaa/b/ccd/ef/x/g/i"));
<ide> assertNotNull(pri);
<del> assertEquals("/i",pri.getPathRemaining());
<add> assertEquals("/i",pri.getPathRemaining().value());
<ide> assertEquals("b",pri.getUriVariables().get("bbb"));
<ide>
<ide> pri = parse("/aaa/{bbb}/c?d/e*f/*/g/").getPathRemaining(toPathContainer("/aaa/b/ccd/ef/x/g/i"));
<ide> assertNotNull(pri);
<del> assertEquals("i",pri.getPathRemaining());
<add> assertEquals("i",pri.getPathRemaining().value());
<ide> assertEquals("b",pri.getUriVariables().get("bbb"));
<ide>
<ide> pri = parse("/{aaa}_{bbb}/e*f/{x}/g").getPathRemaining(toPathContainer("/aa_bb/ef/x/g/i"));
<ide> assertNotNull(pri);
<del> assertEquals("/i",pri.getPathRemaining());
<add> assertEquals("/i",pri.getPathRemaining().value());
<ide> assertEquals("aa",pri.getUriVariables().get("aaa"));
<ide> assertEquals("bb",pri.getUriVariables().get("bbb"));
<ide> assertEquals("x",pri.getUriVariables().get("x"));
<ide>
<ide> assertNull(parse("/a/b").getPathRemaining(toPathContainer("")));
<del> assertEquals("/a/b",parse("").getPathRemaining(toPathContainer("/a/b")).getPathRemaining());
<del> assertEquals("",parse("").getPathRemaining(toPathContainer("")).getPathRemaining());
<add> assertEquals("/a/b",parse("").getPathRemaining(toPathContainer("/a/b")).getPathRemaining().value());
<add> assertEquals("",parse("").getPathRemaining(toPathContainer("")).getPathRemaining().value());
<ide> }
<ide>
<ide> @Test
<ide> public void pathRemainingEnhancements_spr15419() {
<ide> // It would be nice to partially match a path and get any bound variables in one step
<ide> pp = parse("/{this}/{one}/{here}");
<ide> pri = getPathRemaining(pp, "/foo/bar/goo/boo");
<del> assertEquals("/boo",pri.getPathRemaining());
<add> assertEquals("/boo",pri.getPathRemaining().value());
<ide> assertEquals("foo",pri.getUriVariables().get("this"));
<ide> assertEquals("bar",pri.getUriVariables().get("one"));
<ide> assertEquals("goo",pri.getUriVariables().get("here"));
<ide>
<ide> pp = parse("/aaa/{foo}");
<ide> pri = getPathRemaining(pp, "/aaa/bbb");
<del> assertEquals("",pri.getPathRemaining());
<add> assertEquals("",pri.getPathRemaining().value());
<ide> assertEquals("bbb",pri.getUriVariables().get("foo"));
<ide>
<ide> pp = parse("/aaa/bbb");
<ide> pri = getPathRemaining(pp, "/aaa/bbb");
<del> assertEquals("",pri.getPathRemaining());
<add> assertEquals("",pri.getPathRemaining().value());
<ide> assertEquals(0,pri.getUriVariables().size());
<ide>
<ide> pp = parse("/*/{foo}/b*");
<ide> pri = getPathRemaining(pp, "/foo");
<ide> assertNull(pri);
<ide> pri = getPathRemaining(pp, "/abc/def/bhi");
<del> assertEquals("",pri.getPathRemaining());
<add> assertEquals("",pri.getPathRemaining().value());
<ide> assertEquals("def",pri.getUriVariables().get("foo"));
<ide>
<ide> pri = getPathRemaining(pp, "/abc/def/bhi/jkl");
<del> assertEquals("/jkl",pri.getPathRemaining());
<add> assertEquals("/jkl",pri.getPathRemaining().value());
<ide> assertEquals("def",pri.getUriVariables().get("foo"));
<ide> }
<ide>
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/server/DefaultServerRequest.java
<ide> import org.springframework.http.HttpRange;
<ide> import org.springframework.http.MediaType;
<ide> import org.springframework.http.codec.HttpMessageReader;
<add>import org.springframework.http.server.reactive.PathContainer;
<ide> import org.springframework.http.server.reactive.ServerHttpRequest;
<ide> import org.springframework.http.server.reactive.ServerHttpResponse;
<ide> import org.springframework.util.Assert;
<ide> public URI uri() {
<ide> return request().getURI();
<ide> }
<ide>
<add> @Override
<add> public PathContainer pathContainer() {
<add> return request().getPath();
<add> }
<add>
<ide> @Override
<ide> public Headers headers() {
<ide> return this.headers;
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/server/RequestPredicates.java
<ide>
<ide> import java.net.URI;
<ide> import java.security.Principal;
<add>import java.util.ArrayList;
<ide> import java.util.Arrays;
<ide> import java.util.Collections;
<ide> import java.util.HashSet;
<ide> import org.springframework.http.HttpCookie;
<ide> import org.springframework.http.HttpMethod;
<ide> import org.springframework.http.MediaType;
<add>import org.springframework.http.server.reactive.PathContainer;
<ide> import org.springframework.http.server.reactive.ServerHttpRequest;
<ide> import org.springframework.lang.Nullable;
<ide> import org.springframework.util.Assert;
<ide> public PathPatternPredicate(PathPattern pattern) {
<ide>
<ide> @Override
<ide> public boolean test(ServerRequest request) {
<del> String path = request.path();
<del> boolean match = this.pattern.matches(path);
<del> traceMatch("Pattern", this.pattern.getPatternString(), path, match);
<add> boolean match = this.pattern.matches(request.pathContainer());
<add> traceMatch("Pattern", this.pattern.getPatternString(), request.path(), match);
<ide> if (match) {
<ide> mergeTemplateVariables(request, this.pattern.matchAndExtract(request.path()).getUriVariables());
<ide> return true;
<ide> public boolean test(ServerRequest request) {
<ide>
<ide> @Override
<ide> public Optional<ServerRequest> nest(ServerRequest request) {
<del> return Optional.ofNullable(this.pattern.getPathRemaining(request.path()))
<add> return Optional.ofNullable(this.pattern.getPathRemaining(request.pathContainer()))
<ide> .map(info -> {
<ide> mergeTemplateVariables(request, info.getUriVariables());
<del> String path = info.getPathRemaining();
<del> if (!path.startsWith("/")) {
<del> path = "/" + path;
<del> }
<del> return new SubPathServerRequestWrapper(request, path);
<add> return new SubPathServerRequestWrapper(request, info);
<ide> });
<ide> }
<ide>
<ide> private static class SubPathServerRequestWrapper implements ServerRequest {
<ide>
<ide> private final ServerRequest request;
<ide>
<del> private final String subPath;
<add> private final PathContainer subPathContainer;
<ide>
<ide>
<del> public SubPathServerRequestWrapper(ServerRequest request, String subPath) {
<add> public SubPathServerRequestWrapper(ServerRequest request, PathPattern.PathRemainingMatchInfo info) {
<ide> this.request = request;
<del> this.subPath = subPath;
<add> this.subPathContainer = new SubPathContainer(info.getPathRemaining());
<ide> }
<ide>
<ide> @Override
<ide> public URI uri() {
<ide>
<ide> @Override
<ide> public String path() {
<del> return this.subPath;
<add> return this.subPathContainer.value();
<add> }
<add>
<add> @Override
<add> public PathContainer pathContainer() {
<add> return this.subPathContainer;
<ide> }
<ide>
<ide> @Override
<ide> public Mono<? extends Principal> principal() {
<ide> public String toString() {
<ide> return method() + " " + path();
<ide> }
<add>
<add> private static class SubPathContainer implements PathContainer {
<add>
<add> private static final PathContainer.Separator SEPARATOR = () -> "/";
<add>
<add>
<add> private final String value;
<add>
<add> private final List<Element> elements;
<add>
<add> public SubPathContainer(PathContainer original) {
<add> this.value = prefixWithSlash(original.value());
<add> this.elements = prependWithSeparator(original.elements());
<add> }
<add>
<add> private static String prefixWithSlash(String path) {
<add> if (!path.startsWith("/")) {
<add> path = "/" + path;
<add> }
<add> return path;
<add> }
<add>
<add> private static List<Element> prependWithSeparator(List<Element> elements) {
<add> List<Element> result = new ArrayList<>(elements);
<add> if (!(result.get(0) instanceof Separator)) {
<add> result.add(0, SEPARATOR);
<add> }
<add> return Collections.unmodifiableList(result);
<add> }
<add>
<add>
<add> @Override
<add> public String value() {
<add> return this.value;
<add> }
<add>
<add> @Override
<add> public List<Element> elements() {
<add> return this.elements;
<add> }
<add> }
<ide> }
<ide>
<ide> }
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/server/ServerRequest.java
<ide> import java.net.InetSocketAddress;
<ide> import java.net.URI;
<ide> import java.nio.charset.Charset;
<add>import java.nio.charset.StandardCharsets;
<ide> import java.security.Principal;
<ide> import java.util.List;
<ide> import java.util.Locale;
<ide> import org.springframework.http.MediaType;
<ide> import org.springframework.http.codec.HttpMessageReader;
<ide> import org.springframework.http.codec.json.Jackson2CodecSupport;
<add>import org.springframework.http.server.reactive.PathContainer;
<ide> import org.springframework.http.server.reactive.ServerHttpRequest;
<ide> import org.springframework.lang.Nullable;
<ide> import org.springframework.util.MultiValueMap;
<ide> default String path() {
<ide> return uri().getRawPath();
<ide> }
<ide>
<add> /**
<add> * Return the request path as {@code PathContainer}.
<add> */
<add> default PathContainer pathContainer() {
<add> return PathContainer.parse(path(), StandardCharsets.UTF_8);
<add> }
<add>
<ide> /**
<ide> * Return the headers of this request.
<ide> */
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/server/support/ServerRequestWrapper.java
<ide> import org.springframework.http.HttpMethod;
<ide> import org.springframework.http.HttpRange;
<ide> import org.springframework.http.MediaType;
<add>import org.springframework.http.server.reactive.PathContainer;
<ide> import org.springframework.http.server.reactive.ServerHttpRequest;
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.util.MultiValueMap;
<ide> public String path() {
<ide> return this.delegate.path();
<ide> }
<ide>
<add> @Override
<add> public PathContainer pathContainer() {
<add> return this.delegate.pathContainer();
<add> }
<add>
<ide> @Override
<ide> public Headers headers() {
<ide> return this.delegate.headers();
<ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/function/server/MockServerRequest.java
<ide> import java.net.InetSocketAddress;
<ide> import java.net.URI;
<ide> import java.nio.charset.Charset;
<add>import java.nio.charset.StandardCharsets;
<ide> import java.security.Principal;
<ide> import java.util.Arrays;
<ide> import java.util.Collections;
<ide> import org.springframework.http.HttpMethod;
<ide> import org.springframework.http.HttpRange;
<ide> import org.springframework.http.MediaType;
<add>import org.springframework.http.server.reactive.PathContainer;
<add>import org.springframework.http.server.reactive.RequestPath;
<ide> import org.springframework.http.server.reactive.ServerHttpRequest;
<ide> import org.springframework.lang.Nullable;
<ide> import org.springframework.util.Assert;
<ide>
<ide> /**
<ide> * Mock implementation of {@link ServerRequest}.
<add> *
<ide> * @author Arjen Poutsma
<ide> * @since 5.0
<ide> */
<ide> public class MockServerRequest implements ServerRequest {
<ide>
<ide> private final URI uri;
<ide>
<add> private final RequestPath pathContainer;
<add>
<ide> private final MockHeaders headers;
<ide>
<ide> private final MultiValueMap<String, HttpCookie> cookies;
<ide> public class MockServerRequest implements ServerRequest {
<ide> @Nullable
<ide> private Principal principal;
<ide>
<del> private MockServerRequest(HttpMethod method, URI uri,
<del> MockHeaders headers, MultiValueMap<String, HttpCookie> cookies, @Nullable Object body,
<add>
<add> private MockServerRequest(HttpMethod method, URI uri, String contextPath, MockHeaders headers,
<add> MultiValueMap<String, HttpCookie> cookies, @Nullable Object body,
<ide> Map<String, Object> attributes, MultiValueMap<String, String> queryParams,
<ide> Map<String, String> pathVariables, @Nullable WebSession session, @Nullable Principal principal) {
<ide>
<ide> this.method = method;
<ide> this.uri = uri;
<add> this.pathContainer = RequestPath.create(uri, contextPath, StandardCharsets.UTF_8);
<ide> this.headers = headers;
<ide> this.cookies = cookies;
<ide> this.body = body;
<ide> public URI uri() {
<ide> return this.uri;
<ide> }
<ide>
<add> @Override
<add> public PathContainer pathContainer() {
<add> return this.pathContainer;
<add> }
<add>
<ide> @Override
<ide> public Headers headers() {
<ide> return this.headers;
<ide> public MultiValueMap<String, HttpCookie> cookies() {
<ide>
<ide> @Override
<ide> @SuppressWarnings("unchecked")
<del> public <S> S body(BodyExtractor<S, ? super ServerHttpRequest> extractor){
<add> public <S> S body(BodyExtractor<S, ? super ServerHttpRequest> extractor) {
<ide> Assert.state(this.body != null, "No body");
<ide> return (S) this.body;
<ide> }
<ide> public interface Builder {
<ide>
<ide> Builder uri(URI uri);
<ide>
<add> Builder contextPath(String contextPath);
<add>
<ide> Builder header(String key, String value);
<ide>
<ide> Builder headers(HttpHeaders headers);
<ide> private static class BuilderImpl implements Builder {
<ide>
<ide> private URI uri = URI.create("http://localhost");
<ide>
<add> private String contextPath = "";
<add>
<ide> private MockHeaders headers = new MockHeaders(new HttpHeaders());
<ide>
<ide> private MultiValueMap<String, HttpCookie> cookies = new LinkedMultiValueMap<>();
<ide> public Builder uri(URI uri) {
<ide> }
<ide>
<ide> @Override
<del> public Builder header(String key, String value) {
<del> Assert.notNull(key, "'key' must not be null");
<del> Assert.notNull(value, "'value' must not be null");
<del> this.headers.header(key, value);
<add> public Builder contextPath(String contextPath) {
<add> Assert.notNull(contextPath, "'contextPath' must not be null");
<add> this.contextPath = contextPath;
<ide> return this;
<del> }
<ide>
<del> @Override
<del> public Builder headers(HttpHeaders headers) {
<del> Assert.notNull(headers, "'headers' must not be null");
<del> this.headers = new MockHeaders(headers);
<del> return this;
<ide> }
<ide>
<ide> @Override
<ide> public Builder cookies(MultiValueMap<String, HttpCookie> cookies) {
<ide> return this;
<ide> }
<ide>
<add> @Override
<add> public Builder header(String key, String value) {
<add> Assert.notNull(key, "'key' must not be null");
<add> Assert.notNull(value, "'value' must not be null");
<add> this.headers.header(key, value);
<add> return this;
<add> }
<add>
<add> @Override
<add> public Builder headers(HttpHeaders headers) {
<add> Assert.notNull(headers, "'headers' must not be null");
<add> this.headers = new MockHeaders(headers);
<add> return this;
<add> }
<add>
<ide> @Override
<ide> public Builder attribute(String name, Object value) {
<ide> Assert.notNull(name, "'name' must not be null");
<ide> public Builder session(Principal principal) {
<ide> @Override
<ide> public MockServerRequest body(Object body) {
<ide> this.body = body;
<del> return new MockServerRequest(this.method, this.uri, this.headers, this.cookies,
<del> this.body, this.attributes, this.queryParams, this.pathVariables, this.session,
<del> this.principal);
<add> return new MockServerRequest(this.method, this.uri, this.contextPath, this.headers,
<add> this.cookies, this.body, this.attributes, this.queryParams, this.pathVariables,
<add> this.session, this.principal);
<ide> }
<ide>
<ide> @Override
<ide> public MockServerRequest build() {
<del> return new MockServerRequest(this.method, this.uri, this.headers, this.cookies, null,
<del> this.attributes, this.queryParams, this.pathVariables, this.session,
<del> this.principal);
<add> return new MockServerRequest(this.method, this.uri, this.contextPath, this.headers,
<add> this.cookies, null, this.attributes, this.queryParams, this.pathVariables,
<add> this.session, this.principal);
<ide> }
<ide> }
<ide> | 9 |
Javascript | Javascript | prevent navigation if already on the url | 4bd7bedf48c0c1ebb62f6bd8c85e8ea00f94502b | <ide><path>src/ng/location.js
<ide> function $LocationProvider(){
<ide> rewrittenUrl = $location.$$rewrite(absHref);
<ide>
<ide> if (absHref && !elm.attr('target') && rewrittenUrl) {
<del> // update location manually
<del> $location.$$parse(rewrittenUrl);
<del> $rootScope.$apply();
<ide> event.preventDefault();
<del> // hack to work around FF6 bug 684208 when scenario runner clicks on links
<del> window.angular['ff-684208-preventDefault'] = true;
<add> if (rewrittenUrl != initialUrl) {
<add> // update location manually
<add> $location.$$parse(rewrittenUrl);
<add> $rootScope.$apply();
<add> // hack to work around FF6 bug 684208 when scenario runner clicks on links
<add> window.angular['ff-684208-preventDefault'] = true;
<add> }
<ide> }
<ide> });
<ide>
<ide><path>test/ng/locationSpec.js
<ide> describe('$location', function() {
<ide> });
<ide>
<ide>
<add> it('should do nothing if already on the same URL', function() {
<add> configureService('/base/', true, true);
<add> inject(
<add> initBrowser(),
<add> initLocation(),
<add> function($browser) {
<add> browserTrigger(link, 'click');
<add> expectNoRewrite($browser, 'http://host.com/base/');
<add> }
<add> );
<add> });
<add>
<add>
<ide> it('should rewrite abs link to new url when history enabled on new browser', function() {
<ide> configureService('/base/link?a#b', true, true);
<ide> inject( | 2 |
Text | Text | remove references to doac in docs | a6b6b6ce5536ad4987d0f243466b820c3dea4798 | <ide><path>docs/api-guide/authentication.md
<ide> For details on configuration and usage see the Django REST framework OAuth docum
<ide>
<ide> HTTP digest authentication is a widely implemented scheme that was intended to replace HTTP basic authentication, and which provides a simple encrypted authentication mechanism. [Juan Riaza][juanriaza] maintains the [djangorestframework-digestauth][djangorestframework-digestauth] package which provides HTTP digest authentication support for REST framework.
<ide>
<del>## Django OAuth2 Consumer
<del>
<del>The [Django OAuth2 Consumer][doac] library from [Rediker Software][rediker] is another package that provides [OAuth 2.0 support for REST framework][doac-rest-framework]. The package includes token scoping permissions on tokens, which allows finer-grained access to your API.
<del>
<ide> ## JSON Web Token Authentication
<ide>
<ide> JSON Web Token is a fairly new standard which can be used for token-based authentication. Unlike the built-in TokenAuthentication scheme, JWT Authentication doesn't need to use a database to validate a token. [Blimp][blimp] maintains the [djangorestframework-jwt][djangorestframework-jwt] package which provides a JWT Authentication class as well as a mechanism for clients to obtain a JWT given the username and password. An alternative package for JWT authentication is [djangorestframework-simplejwt][djangorestframework-simplejwt] which provides different features as well as a pluggable token blacklist app.
<ide> HTTP Signature (currently a [IETF draft][http-signature-ietf-draft]) provides a
<ide> [django-oauth-toolkit]: https://github.com/evonove/django-oauth-toolkit
<ide> [evonove]: https://github.com/evonove/
<ide> [oauthlib]: https://github.com/idan/oauthlib
<del>[doac]: https://github.com/Rediker-Software/doac
<del>[rediker]: https://github.com/Rediker-Software
<del>[doac-rest-framework]: https://github.com/Rediker-Software/doac/blob/master/docs/integrations.md#
<ide> [blimp]: https://github.com/GetBlimp
<ide> [djangorestframework-jwt]: https://github.com/GetBlimp/django-rest-framework-jwt
<ide> [djangorestframework-simplejwt]: https://github.com/davesque/django-rest-framework-simplejwt
<ide><path>docs/topics/third-party-packages.md
<ide> To submit new content, [open an issue][drf-create-issue] or [create a pull reque
<ide>
<ide> * [djangorestframework-digestauth][djangorestframework-digestauth] - Provides Digest Access Authentication support.
<ide> * [django-oauth-toolkit][django-oauth-toolkit] - Provides OAuth 2.0 support.
<del>* [doac][doac] - Provides OAuth 2.0 support.
<ide> * [djangorestframework-jwt][djangorestframework-jwt] - Provides JSON Web Token Authentication support.
<ide> * [djangorestframework-simplejwt][djangorestframework-simplejwt] - An alternative package that provides JSON Web Token Authentication support.
<ide> * [hawkrest][hawkrest] - Provides Hawk HTTP Authorization.
<ide> To submit new content, [open an issue][drf-create-issue] or [create a pull reque
<ide> [discussion-group]: https://groups.google.com/forum/#!forum/django-rest-framework
<ide> [djangorestframework-digestauth]: https://github.com/juanriaza/django-rest-framework-digestauth
<ide> [django-oauth-toolkit]: https://github.com/evonove/django-oauth-toolkit
<del>[doac]: https://github.com/Rediker-Software/doac
<ide> [djangorestframework-jwt]: https://github.com/GetBlimp/django-rest-framework-jwt
<ide> [djangorestframework-simplejwt]: https://github.com/davesque/django-rest-framework-simplejwt
<ide> [hawkrest]: https://github.com/kumar303/hawkrest | 2 |
PHP | PHP | apply fixes from styleci | e3d6e82c095d29ef85bfd41e4f28f25093bf49b2 | <ide><path>tests/Auth/AuthDatabaseUserProviderTest.php
<ide> public function testRetrieveByCredentialsWithMultiplyPasswordsReturnsNull()
<ide> $provider = new DatabaseUserProvider($conn, $hasher, 'foo');
<ide> $user = $provider->retrieveByCredentials([
<ide> 'password' => 'dayle',
<del> 'password2' => 'night'
<add> 'password2' => 'night',
<ide> ]);
<ide>
<ide> $this->assertNull($user);
<ide><path>tests/Auth/AuthEloquentUserProviderTest.php
<ide> public function testRetrieveByCredentialsWithMultiplyPasswordsReturnsNull()
<ide> $provider = $this->getProviderMock();
<ide> $user = $provider->retrieveByCredentials([
<ide> 'password' => 'dayle',
<del> 'password2' => 'night'
<add> 'password2' => 'night',
<ide> ]);
<ide>
<ide> $this->assertNull($user); | 2 |
Python | Python | add test case for zone with no nodes | f5d6440c7e2b78cc9b62f58967fa58b1480113af | <ide><path>libcloud/test/compute/test_gce.py
<ide> def test_list_nodes(self):
<ide> nodes = self.driver.list_nodes()
<ide> nodes_all = self.driver.list_nodes(ex_zone='all')
<ide> nodes_uc1a = self.driver.list_nodes(ex_zone='us-central1-a')
<add> nodes_uc1b = self.driver.list_nodes(ex_zone='us-central1-b')
<ide> self.assertEqual(len(nodes), 1)
<ide> self.assertEqual(len(nodes_all), 8)
<ide> self.assertEqual(len(nodes_uc1a), 1)
<add> self.assertEqual(len(nodes_uc1b), 0)
<ide> self.assertEqual(nodes[0].name, 'node-name')
<ide> self.assertEqual(nodes_uc1a[0].name, 'node-name')
<ide> self.assertEqual(nodes_uc1a[0].extra['cpuPlatform'], 'Intel Skylake')
<ide> def _zones_europe_west1_a_instances(self, method, url, body, headers):
<ide> body = self.fixtures.load('zones_europe-west1-a_instances.json')
<ide> return (httplib.OK, body, self.json_hdr, httplib.responses[httplib.OK])
<ide>
<add> def _zones_us_central1_b_instances(self, method, url, body, headers):
<add> if method == 'GET':
<add> body = '{}'
<add> return (httplib.OK, body, self.json_hdr, httplib.responses[httplib.OK])
<add>
<ide> def _zones_europe_west1_a_diskTypes_pd_standard(self, method, url, body,
<ide> headers):
<ide> body = self.fixtures.load( | 1 |
Javascript | Javascript | improve jqlite docs | d769b8b8f0fba81b35e441249e31e7e209d40580 | <ide><path>src/jqLite.js
<ide> *
<ide> * @description
<ide> * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
<del> * `angular.element` can be either an alias for [jQuery](http://api.jquery.com/jQuery/) function, if
<del> * jQuery is available, or a function that wraps the element or string in Angular's jQuery lite
<del> * implementation (commonly referred to as jqLite).
<ide> *
<del> * Real jQuery always takes precedence over jqLite, provided it was loaded before `DOMContentLoaded`
<del> * event fired.
<add> * If jQuery is available, `angular.element` is an alias for the
<add> * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element`
<add> * delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite."
<ide> *
<del> * jqLite is a tiny, API-compatible subset of jQuery that allows
<del> * Angular to manipulate the DOM. jqLite implements only the most commonly needed functionality
<del> * within a very small footprint, so only a subset of the jQuery API - methods, arguments and
<del> * invocation styles - are supported.
<add> * <div class="alert alert-success">jqLite is a tiny, API-compatible subset of jQuery that allows
<add> * Angular to manipulate the DOM in a cross-browser compatible way. **jqLite** implements only the most
<add> * commonly needed functionality with the goal of having a very small footprint.</div>
<ide> *
<del> * Note: All element references in Angular are always wrapped with jQuery or jqLite; they are never
<del> * raw DOM references.
<add> * To use jQuery, simply load it before `DOMContentLoaded` event fired.
<add> *
<add> * <div class="alert">**Note:** all element references in Angular are always wrapped with jQuery or
<add> * jqLite; they are never raw DOM references.</div>
<ide> *
<ide> * ## Angular's jqLite
<del> * Angular's lite version of jQuery provides only the following jQuery methods:
<add> * jqLite provides only the following jQuery methods:
<ide> *
<del> * - [addClass()](http://api.jquery.com/addClass/)
<del> * - [after()](http://api.jquery.com/after/)
<del> * - [append()](http://api.jquery.com/append/)
<del> * - [attr()](http://api.jquery.com/attr/)
<del> * - [bind()](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
<del> * - [children()](http://api.jquery.com/children/) - Does not support selectors
<del> * - [clone()](http://api.jquery.com/clone/)
<del> * - [contents()](http://api.jquery.com/contents/)
<del> * - [css()](http://api.jquery.com/css/)
<del> * - [data()](http://api.jquery.com/data/)
<del> * - [eq()](http://api.jquery.com/eq/)
<del> * - [find()](http://api.jquery.com/find/) - Limited to lookups by tag name
<del> * - [hasClass()](http://api.jquery.com/hasClass/)
<del> * - [html()](http://api.jquery.com/html/)
<del> * - [next()](http://api.jquery.com/next/) - Does not support selectors
<del> * - [on()](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
<del> * - [off()](http://api.jquery.com/off/) - Does not support namespaces or selectors
<del> * - [parent()](http://api.jquery.com/parent/) - Does not support selectors
<del> * - [prepend()](http://api.jquery.com/prepend/)
<del> * - [prop()](http://api.jquery.com/prop/)
<del> * - [ready()](http://api.jquery.com/ready/)
<del> * - [remove()](http://api.jquery.com/remove/)
<del> * - [removeAttr()](http://api.jquery.com/removeAttr/)
<del> * - [removeClass()](http://api.jquery.com/removeClass/)
<del> * - [removeData()](http://api.jquery.com/removeData/)
<del> * - [replaceWith()](http://api.jquery.com/replaceWith/)
<del> * - [text()](http://api.jquery.com/text/)
<del> * - [toggleClass()](http://api.jquery.com/toggleClass/)
<del> * - [triggerHandler()](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers.
<del> * - [unbind()](http://api.jquery.com/off/) - Does not support namespaces
<del> * - [val()](http://api.jquery.com/val/)
<del> * - [wrap()](http://api.jquery.com/wrap/)
<add> * - [`addClass()`](http://api.jquery.com/addClass/)
<add> * - [`after()`](http://api.jquery.com/after/)
<add> * - [`append()`](http://api.jquery.com/append/)
<add> * - [`attr()`](http://api.jquery.com/attr/)
<add> * - [`bind()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
<add> * - [`children()`](http://api.jquery.com/children/) - Does not support selectors
<add> * - [`clone()`](http://api.jquery.com/clone/)
<add> * - [`contents()`](http://api.jquery.com/contents/)
<add> * - [`css()`](http://api.jquery.com/css/)
<add> * - [`data()`](http://api.jquery.com/data/)
<add> * - [`eq()`](http://api.jquery.com/eq/)
<add> * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name
<add> * - [`hasClass()`](http://api.jquery.com/hasClass/)
<add> * - [`html()`](http://api.jquery.com/html/)
<add> * - [`next()`](http://api.jquery.com/next/) - Does not support selectors
<add> * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
<add> * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces or selectors
<add> * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors
<add> * - [`prepend()`](http://api.jquery.com/prepend/)
<add> * - [`prop()`](http://api.jquery.com/prop/)
<add> * - [`ready()`](http://api.jquery.com/ready/)
<add> * - [`remove()`](http://api.jquery.com/remove/)
<add> * - [`removeAttr()`](http://api.jquery.com/removeAttr/)
<add> * - [`removeClass()`](http://api.jquery.com/removeClass/)
<add> * - [`removeData()`](http://api.jquery.com/removeData/)
<add> * - [`replaceWith()`](http://api.jquery.com/replaceWith/)
<add> * - [`text()`](http://api.jquery.com/text/)
<add> * - [`toggleClass()`](http://api.jquery.com/toggleClass/)
<add> * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers.
<add> * - [`unbind()`](http://api.jquery.com/off/) - Does not support namespaces
<add> * - [`val()`](http://api.jquery.com/val/)
<add> * - [`wrap()`](http://api.jquery.com/wrap/)
<ide> *
<ide> * ## jQuery/jqLite Extras
<ide> * Angular also provides the following additional methods and events to both jQuery and jqLite:
<ide> * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event
<ide> * on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM
<ide> * element before it is removed.
<add> *
<ide> * ### Methods
<ide> * - `controller(name)` - retrieves the controller of the current element or its parent. By default
<ide> * retrieves controller associated with the `ngController` directive. If `name` is provided as | 1 |
Ruby | Ruby | remove bottle hooks | 8bbe9b744f627f1b3741b4b667e64ed797e6323a | <ide><path>Library/Homebrew/formula_installer.rb
<ide> require "formula_cellar_checks"
<ide> require "install_renamed"
<ide> require "cmd/postinstall"
<del>require "hooks/bottles"
<ide> require "debrew"
<ide> require "sandbox"
<ide> require "emoji"
<ide> def build_bottle?
<ide> end
<ide>
<ide> def pour_bottle?(install_bottle_options = { warn: false })
<del> return true if Homebrew::Hooks::Bottles.formula_has_bottle?(formula)
<del>
<ide> return false if @pour_failed
<ide>
<ide> return false if !formula.bottled? && !formula.local_bottle_path
<ide> def post_install
<ide> end
<ide>
<ide> def pour
<del> if Homebrew::Hooks::Bottles.formula_has_bottle?(formula)
<del> return if Homebrew::Hooks::Bottles.pour_formula_bottle(formula)
<del> end
<del>
<ide> if (bottle_path = formula.local_bottle_path)
<ide> downloader = LocalBottleDownloadStrategy.new(bottle_path)
<ide> else
<ide><path>Library/Homebrew/hooks/bottles.rb
<del># Boxen (and perhaps others) want to override our bottling infrastructure so
<del># they can avoid declaring checksums in formulae files.
<del># Instead of periodically breaking their monkeypatches let's add some hooks that
<del># we can query to allow their own behaviour.
<del>
<del># PLEASE DO NOT EVER RENAME THIS CLASS OR ADD/REMOVE METHOD ARGUMENTS!
<del>module Homebrew
<del> module Hooks
<del> module Bottles
<del> def self.setup_formula_has_bottle(&block)
<del> @has_bottle = block
<del> true
<del> end
<del>
<del> def self.setup_pour_formula_bottle(&block)
<del> @pour_bottle = block
<del> true
<del> end
<del>
<del> def self.formula_has_bottle?(formula)
<del> return false unless @has_bottle
<del> @has_bottle.call formula
<del> end
<del>
<del> def self.pour_formula_bottle(formula)
<del> return false unless @pour_bottle
<del> @pour_bottle.call formula
<del> end
<del>
<del> def self.reset_hooks
<del> @has_bottle = @pour_bottle = nil
<del> end
<del> end
<del> end
<del>end
<ide><path>Library/Homebrew/test/bottle_hooks_spec.rb
<del>require "formula_installer"
<del>require "hooks/bottles"
<del>
<del>describe Homebrew::Hooks::Bottles do
<del> alias_matcher :pour_bottle, :be_pour_bottle
<del>
<del> subject { FormulaInstaller.new formula }
<del>
<del> let(:formula) do
<del> double(
<del> bottled?: false,
<del> local_bottle_path: nil,
<del> bottle_disabled?: false,
<del> some_random_method: true,
<del> keg_only?: false,
<del> )
<del> end
<del>
<del> after(:each) do
<del> described_class.reset_hooks
<del> end
<del>
<del> describe "#setup_formula_has_bottle" do
<del> context "given a block which evaluates to true" do
<del> before(:each) do
<del> described_class.setup_formula_has_bottle(&:some_random_method)
<del> end
<del>
<del> it { is_expected.to pour_bottle }
<del> end
<del>
<del> context "given a block which evaluates to false" do
<del> before(:each) do
<del> described_class.setup_formula_has_bottle { |f| !f.some_random_method }
<del> end
<del>
<del> it { is_expected.not_to pour_bottle }
<del> end
<del> end
<del>
<del> describe "#setup_pour_formula_bottle" do
<del> before(:each) do
<del> described_class.setup_formula_has_bottle { true }
<del> described_class.setup_pour_formula_bottle(&:some_random_method)
<del> end
<del>
<del> it "does not raise an error" do
<del> expect { subject.pour }.not_to raise_error
<del> end
<del> end
<del>end | 3 |
Ruby | Ruby | expand #preprocess_url tests more | 5a007a4ec6eed7df2c255e1175ff918fa1f1b00e | <ide><path>Library/Homebrew/test/livecheck/livecheck_spec.rb
<ide> describe "::preprocess_url" do
<ide> let(:github_git_url_with_extension) { "https://github.com/Homebrew/brew.git" }
<ide>
<add> it "returns the unmodified URL for an unparseable URL" do
<add> # Modeled after the `head` URL in the `ncp` formula
<add> expect(livecheck.preprocess_url(":something:cvs:@cvs.brew.sh:/cvs"))
<add> .to eq(":something:cvs:@cvs.brew.sh:/cvs")
<add> end
<add>
<ide> it "returns the unmodified URL for a GitHub URL ending in .git" do
<ide> expect(livecheck.preprocess_url(github_git_url_with_extension))
<ide> .to eq(github_git_url_with_extension)
<ide> expect(livecheck.preprocess_url("https://lolg.it/Homebrew/brew/archive/brew-1.0.0.tar.gz"))
<ide> .to eq("https://lolg.it/Homebrew/brew.git")
<ide> end
<add>
<add> it "returns the Git repository URL for a sourcehut archive URL" do
<add> expect(livecheck.preprocess_url("https://git.sr.ht/~Homebrew/brew/archive/1.0.0.tar.gz"))
<add> .to eq("https://git.sr.ht/~Homebrew/brew")
<add> end
<ide> end
<ide> end | 1 |
Java | Java | bind implementation of merge | 723d9352170bacef29a7f722f42345c248efc3ae | <ide><path>rxjava-core/src/main/java/rx/Observable.java
<ide> import rx.operators.OperationJoinPatterns;
<ide> import rx.operators.OperatorMap;
<ide> import rx.operators.OperationMaterialize;
<del>import rx.operators.OperationMerge;
<add>import rx.operators.OperatorMerge;
<ide> import rx.operators.OperationMergeDelayError;
<ide> import rx.operators.OperationMinMax;
<ide> import rx.operators.OperationMulticast;
<ide> public final static <T> Observable<T> merge(Iterable<? extends Observable<? exte
<ide> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229099.aspx">MSDN: Observable.Merge</a>
<ide> */
<ide> public final static <T> Observable<T> merge(Observable<? extends Observable<? extends T>> source) {
<del> return create(OperationMerge.merge(source));
<add> return source.bind(new OperatorMerge()); // any idea how to get these generics working?!
<ide> }
<ide>
<ide> /**
<ide> public final static <T> Observable<T> merge(Observable<? extends Observable<? ex
<ide> * @see <a href="http://msdn.microsoft.com/en-us/library/hh211914.aspx">MSDN: Observable.Merge</a>
<ide> */
<ide> public final static <T> Observable<T> merge(Observable<? extends Observable<? extends T>> source, int maxConcurrent) {
<del> return create(OperationMerge.merge(source, maxConcurrent));
<add> return source.bind(new OperatorMerge(maxConcurrent)); // any idea how to get these generics working?!
<ide> }
<ide>
<ide> /**
<ide><path>rxjava-core/src/main/java/rx/operators/OperationMerge.java
<del>/**
<del> * Copyright 2014 Netflix, Inc.
<del> *
<del> * Licensed under the Apache License, Version 2.0 (the "License");
<del> * you may not use this file except in compliance with the License.
<del> * You may obtain a copy of the License at
<del> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<del> *
<del> * Unless required by applicable law or agreed to in writing, software
<del> * distributed under the License is distributed on an "AS IS" BASIS,
<del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<del> * See the License for the specific language governing permissions and
<del> * limitations under the License.
<del> */
<del>package rx.operators;
<del>
<del>import java.util.LinkedList;
<del>
<del>import rx.Observable;
<del>import rx.Observable.OnSubscribeFunc;
<del>import rx.Observer;
<del>import rx.Subscription;
<del>import rx.subscriptions.CompositeSubscription;
<del>
<del>/**
<del> * Flattens a list of Observables into one Observable sequence, without any transformation.
<del> * <p>
<del> * <img width="640" src="https://github.com/Netflix/RxJava/wiki/images/rx-operators/merge.png">
<del> * <p>
<del> * You can combine the items emitted by multiple Observables so that they act like a single
<del> * Observable, by using the merge operation.
<del> */
<del>public final class OperationMerge {
<del>
<del> /**
<del> * Flattens the observable sequences from the list of Observables into one observable sequence without any transformation.
<del> *
<del> * @param o
<del> * An observable sequence of elements to project.
<del> * @return An observable sequence whose elements are the result of flattening the output from the list of Observables.
<del> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229099(v=vs.103).aspx">Observable.Merge(TSource) Method (IObservable(TSource)[])</a>
<del> */
<del> public static <T> OnSubscribeFunc<T> merge(final Observable<? extends Observable<? extends T>> o) {
<del> return merge(o, Integer.MAX_VALUE);
<del> }
<del>
<del> public static <T> OnSubscribeFunc<T> merge(final Observable<? extends Observable<? extends T>> o, final int maxConcurrent) {
<del> if (maxConcurrent <= 0) {
<del> throw new IllegalArgumentException("maxConcurrent must be positive");
<del> }
<del> return new OnSubscribeFunc<T>() {
<del>
<del> @Override
<del> public Subscription onSubscribe(Observer<? super T> observer) {
<del> return new MergeObservable<T>(o, maxConcurrent).onSubscribe(observer);
<del> }
<del> };
<del> }
<del>
<del> /**
<del> * This class is NOT thread-safe if invoked and referenced multiple times. In other words, don't subscribe to it multiple times from different threads.
<del> * <p>
<del> * It IS thread-safe from within it while receiving onNext events from multiple threads.
<del> * <p>
<del> * This should all be fine as long as it's kept as a private class and a new instance created from static factory method above.
<del> * <p>
<del> * Note how the take() factory method above protects us from a single instance being exposed with the Observable wrapper handling the subscribe flow.
<del> *
<del> * @param <T>
<del> */
<del> private static final class MergeObservable<T> implements OnSubscribeFunc<T> {
<del> private final Observable<? extends Observable<? extends T>> sequences;
<del> private final CompositeSubscription ourSubscription = new CompositeSubscription();
<del> private volatile boolean parentCompleted = false;
<del> private final LinkedList<Observable<? extends T>> pendingObservables = new LinkedList<Observable<? extends T>>();
<del> private volatile int activeObservableCount = 0;
<del> private final int maxConcurrent;
<del> /**
<del> * Protect both pendingObservables and activeObservableCount from concurrent accesses.
<del> */
<del> private final Object gate = new Object();
<del>
<del> private MergeObservable(Observable<? extends Observable<? extends T>> sequences, int maxConcurrent) {
<del> this.sequences = sequences;
<del> this.maxConcurrent = maxConcurrent;
<del> }
<del>
<del> public Subscription onSubscribe(Observer<? super T> actualObserver) {
<del>
<del> /**
<del> * We must synchronize a merge because we subscribe to multiple sequences in parallel that will each be emitting.
<del> * <p>
<del> * The calls from each sequence must be serialized.
<del> * <p>
<del> * Bug report: https://github.com/Netflix/RxJava/issues/200
<del> */
<del> SafeObservableSubscription subscription = new SafeObservableSubscription(ourSubscription);
<del> SynchronizedObserver<T> synchronizedObserver = new SynchronizedObserver<T>(
<del> new SafeObserver<T>(subscription, actualObserver), // Create a SafeObserver as SynchronizedObserver does not automatically unsubscribe
<del> subscription);
<del>
<del> /**
<del> * Subscribe to the parent Observable to get to the children Observables
<del> */
<del> ourSubscription.add(sequences.subscribe(new ParentObserver(synchronizedObserver)));
<del>
<del> return subscription;
<del> }
<del>
<del> /**
<del> * Subscribe to the top level Observable to receive the sequence of Observable<T> children.
<del> *
<del> * @param <T>
<del> */
<del> private class ParentObserver implements Observer<Observable<? extends T>> {
<del> private final SynchronizedObserver<T> synchronizedObserver;
<del>
<del> public ParentObserver(SynchronizedObserver<T> synchronizedObserver) {
<del> this.synchronizedObserver = synchronizedObserver;
<del> }
<del>
<del> @Override
<del> public void onCompleted() {
<del> parentCompleted = true;
<del> if (ourSubscription.isUnsubscribed()) {
<del> return;
<del> }
<del> // this *can* occur before the children are done, so if it does we won't send onCompleted
<del> // but will let the child worry about it
<del> // if however this completes and there are no children processing, then we will send onCompleted
<del> if (isStopped()) {
<del> synchronizedObserver.onCompleted();
<del> }
<del> }
<del>
<del> @Override
<del> public void onError(Throwable e) {
<del> synchronizedObserver.onError(e);
<del> }
<del>
<del> @Override
<del> public void onNext(Observable<? extends T> childObservable) {
<del> if (ourSubscription.isUnsubscribed()) {
<del> // we won't act on any further items
<del> return;
<del> }
<del>
<del> if (childObservable == null) {
<del> throw new IllegalArgumentException("Observable<T> can not be null.");
<del> }
<del>
<del> Observable<? extends T> observable = null;
<del> synchronized (gate) {
<del> if (activeObservableCount >= maxConcurrent) {
<del> pendingObservables.add(childObservable);
<del> }
<del> else {
<del> observable = childObservable;
<del> activeObservableCount++;
<del> }
<del> }
<del> if (observable != null) {
<del> ourSubscription.add(observable.subscribe(new ChildObserver(
<del> synchronizedObserver)));
<del> }
<del> }
<del> }
<del>
<del> /**
<del> * Subscribe to each child Observable<T> and forward their sequence of data to the actualObserver
<del> *
<del> */
<del> private class ChildObserver implements Observer<T> {
<del>
<del> private final SynchronizedObserver<T> synchronizedObserver;
<del>
<del> public ChildObserver(SynchronizedObserver<T> synchronizedObserver) {
<del> this.synchronizedObserver = synchronizedObserver;
<del> }
<del>
<del> @Override
<del> public void onCompleted() {
<del> if (ourSubscription.isUnsubscribed()) {
<del> return;
<del> }
<del>
<del> Observable<? extends T> childObservable = null;
<del> // Try to fetch a pending observable
<del> synchronized (gate) {
<del> childObservable = pendingObservables.poll();
<del> if (childObservable == null) {
<del> // There is no pending observable, decrease activeObservableCount.
<del> activeObservableCount--;
<del> }
<del> else {
<del> // Fetch an observable successfully.
<del> // We will subscribe(this) at once. So don't change activeObservableCount.
<del> }
<del> }
<del> if (childObservable != null) {
<del> ourSubscription.add(childObservable.subscribe(this));
<del> } else {
<del> // No pending observable. Need to check if it's necessary to emit an onCompleted
<del> if (isStopped()) {
<del> synchronizedObserver.onCompleted();
<del> }
<del> }
<del> }
<del>
<del> @Override
<del> public void onError(Throwable e) {
<del> synchronizedObserver.onError(e);
<del> }
<del>
<del> @Override
<del> public void onNext(T args) {
<del> synchronizedObserver.onNext(args);
<del> }
<del>
<del> }
<del>
<del> private boolean isStopped() {
<del> synchronized (gate) {
<del> return parentCompleted && activeObservableCount == 0
<del> && pendingObservables.size() == 0;
<del> }
<del> }
<del> }
<del>}
<ide><path>rxjava-core/src/main/java/rx/operators/OperationMergeDelayError.java
<ide> import rx.util.CompositeException;
<ide>
<ide> /**
<del> * This behaves like {@link OperationMerge} except that if any of the merged Observables notify of
<add> * This behaves like {@link OperatorMerge} except that if any of the merged Observables notify of
<ide> * an error via <code>onError</code>, mergeDelayError will refrain from propagating that error
<ide> * notification until all of the merged Observables have finished emitting items.
<ide> * <p>
<ide><path>rxjava-core/src/main/java/rx/operators/OperatorMerge.java
<add>/**
<add> * Copyright 2014 Netflix, Inc.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>package rx.operators;
<add>
<add>import java.util.concurrent.ConcurrentLinkedQueue;
<add>import java.util.concurrent.atomic.AtomicInteger;
<add>
<add>import rx.Observable;
<add>import rx.Observable.OperatorSubscription;
<add>import rx.Observer;
<add>import rx.util.functions.Func0;
<add>import rx.util.functions.Func2;
<add>
<add>/**
<add> * Flattens a list of Observables into one Observable sequence, without any transformation.
<add> * <p>
<add> * <img width="640" src="https://github.com/Netflix/RxJava/wiki/images/rx-operators/merge.png">
<add> * <p>
<add> * You can combine the items emitted by multiple Observables so that they act like a single
<add> * Observable, by using the merge operation.
<add> */
<add>public final class OperatorMerge<T> implements Func2<Observer<? super T>, OperatorSubscription, Observer<? extends Observable<? extends T>>> {
<add> private final int maxConcurrent;
<add>
<add> public OperatorMerge() {
<add> maxConcurrent = Integer.MAX_VALUE;
<add> }
<add>
<add> public OperatorMerge(int maxConcurrent) {
<add> if (maxConcurrent <= 0) {
<add> throw new IllegalArgumentException("maxConcurrent must be positive");
<add> }
<add> this.maxConcurrent = maxConcurrent;
<add> }
<add>
<add> @Override
<add> public Observer<? extends Observable<? extends T>> call(Observer<? super T> _o, final OperatorSubscription os) {
<add>
<add> final AtomicInteger completionCounter = new AtomicInteger(1);
<add> final AtomicInteger concurrentCounter = new AtomicInteger(1);
<add> // Concurrent* since we'll be accessing them from the inner Observers which can be on other threads
<add> final ConcurrentLinkedQueue<Observable<? extends T>> pending = new ConcurrentLinkedQueue<Observable<? extends T>>();
<add>
<add> final Observer<T> o = new SynchronizedObserver<T>(_o);
<add> return new Observer<Observable<? extends T>>() {
<add>
<add> @Override
<add> public void onCompleted() {
<add> complete();
<add> }
<add>
<add> @Override
<add> public void onError(Throwable e) {
<add> o.onError(e);
<add> }
<add>
<add> @Override
<add> public void onNext(Observable<? extends T> innerObservable) {
<add> // track so we send onComplete only when all have finished
<add> completionCounter.incrementAndGet();
<add> // check concurrency
<add> if (concurrentCounter.incrementAndGet() > maxConcurrent) {
<add> pending.add(innerObservable);
<add> concurrentCounter.decrementAndGet();
<add> } else {
<add> // we are able to proceed
<add> innerObservable.subscribe(new InnerObserver(), subscriptionFunc);
<add> }
<add> }
<add>
<add> private void complete() {
<add> if (completionCounter.decrementAndGet() == 0) {
<add> o.onCompleted();
<add> return;
<add> } else {
<add> // not all are completed and some may still need to run
<add> concurrentCounter.decrementAndGet();
<add> }
<add>
<add> // do work-stealing on whatever thread we're on and subscribe to pending observables
<add> if (concurrentCounter.incrementAndGet() > maxConcurrent) {
<add> // still not space to run
<add> concurrentCounter.decrementAndGet();
<add> } else {
<add> // we can run
<add> Observable<? extends T> outstandingObservable = pending.poll();
<add> if (outstandingObservable != null) {
<add> outstandingObservable.subscribe(new InnerObserver(), subscriptionFunc);
<add> }
<add> }
<add> }
<add>
<add> final class InnerObserver implements Observer<T> {
<add>
<add> @Override
<add> public void onCompleted() {
<add> complete();
<add> }
<add>
<add> @Override
<add> public void onError(Throwable e) {
<add> o.onError(e);
<add> }
<add>
<add> @Override
<add> public void onNext(T a) {
<add> o.onNext(a);
<add> }
<add>
<add> };
<add>
<add> Func0<OperatorSubscription> subscriptionFunc = new Func0<OperatorSubscription>() {
<add>
<add> @Override
<add> public OperatorSubscription call() {
<add> OperatorSubscription innerSubscription = new OperatorSubscription();
<add> os.add(innerSubscription);
<add> return innerSubscription;
<add> }
<add>
<add> };
<add>
<add> };
<add>
<add> }
<add>
<add>}
<ide><path>rxjava-core/src/perf/java/rx/operators/OperatorFromIterablePerformance.java
<ide> public void call() {
<ide>
<ide> }
<ide>
<add> /**
<add> * Single Observable from an Iterable with REPETITIONS items.
<add> *
<add> * Run: 10 - 210,730,391 ops/sec
<add> * Run: 11 - 137,608,366 ops/sec
<add> * Run: 12 - 204,114,957 ops/sec
<add> * Run: 13 - 217,561,569 ops/sec
<add> * Run: 14 - 185,061,810 ops/sec
<add> *
<add> * For comparison, if we don't check for isUnsubscribed then we get this:
<add> *
<add> * Run: 10 - 243,546,030 ops/sec
<add> * Run: 11 - 149,102,403 ops/sec
<add> * Run: 12 - 250,325,423 ops/sec
<add> * Run: 13 - 249,289,524 ops/sec
<add> * Run: 14 - 266,965,668 ops/sec
<add> *
<add> * @return
<add> */
<add> public long timeRepetitionsEmission() {
<add> LongSumObserver o = new LongSumObserver();
<add> Observable.from(ITERABLE_OF_REPETITIONS).subscribe(o);
<add> return o.sum;
<add> }
<add>
<ide> /**
<ide> * Observable.from(Iterable)
<ide> *
<ide> public long timeTenLongs() {
<ide> return o.sum;
<ide> }
<ide>
<del> /**
<del> * Single Observable from an Iterable with REPETITIONS items.
<del> *
<del> * Run: 10 - 210,730,391 ops/sec
<del> * Run: 11 - 137,608,366 ops/sec
<del> * Run: 12 - 204,114,957 ops/sec
<del> * Run: 13 - 217,561,569 ops/sec
<del> * Run: 14 - 185,061,810 ops/sec
<del> *
<del> * For comparison, if we don't check for isUnsubscribed then we get this:
<del> *
<del> * Run: 10 - 243,546,030 ops/sec
<del> * Run: 11 - 149,102,403 ops/sec
<del> * Run: 12 - 250,325,423 ops/sec
<del> * Run: 13 - 249,289,524 ops/sec
<del> * Run: 14 - 266,965,668 ops/sec
<del> *
<del> * @return
<del> */
<del> public long timeRepetitionsEmission() {
<del>
<del> Iterable<Long> i = new Iterable<Long>() {
<del>
<del> @Override
<del> public Iterator<Long> iterator() {
<del> return new Iterator<Long>() {
<del> long count = 0;
<del>
<del> @Override
<del> public boolean hasNext() {
<del> return count <= REPETITIONS;
<del> }
<del>
<del> @Override
<del> public Long next() {
<del> return count++;
<del> }
<del>
<del> @Override
<del> public void remove() {
<del> // do nothing
<del> }
<del>
<del> };
<del> };
<del> };
<del>
<del> LongSumObserver o = new LongSumObserver();
<del> Observable.from(i).subscribe(o);
<del> return o.sum;
<del> }
<del>
<ide> }
<ide><path>rxjava-core/src/perf/java/rx/operators/OperatorMergePerformance.java
<ide> import rx.Observable;
<ide> import rx.perf.AbstractPerformanceTester;
<ide> import rx.perf.IntegerSumObserver;
<add>import rx.perf.LongSumObserver;
<ide> import rx.util.functions.Action0;
<ide>
<ide> public class OperatorMergePerformance extends AbstractPerformanceTester {
<ide> public static void main(String args[]) {
<ide>
<ide> @Override
<ide> public void call() {
<add> spt.timeRepetitionsEmission();
<ide> // spt.timeMergeAandBwithSingleItems();
<del> spt.timeMergeAandBwith100Items();
<add> // spt.timeMergeAandBwith100Items();
<ide> }
<ide> });
<ide> } catch (Exception e) {
<ide> public void call() {
<ide>
<ide> }
<ide>
<add> /**
<add> * Run: 10 - 44,561,691 ops/sec
<add> * Run: 11 - 44,038,119 ops/sec
<add> * Run: 12 - 44,032,689 ops/sec
<add> * Run: 13 - 43,390,724 ops/sec
<add> * Run: 14 - 44,088,600 ops/sec
<add> */
<add> public long timeRepetitionsEmission() {
<add>
<add> Observable<Long> sA = Observable.from(ITERABLE_OF_REPETITIONS);
<add> Observable<Long> sB = Observable.from(ITERABLE_OF_REPETITIONS);
<add> Observable<Long> s = Observable.merge(sA, sB);
<add>
<add> LongSumObserver o = new LongSumObserver();
<add> s.subscribe(o);
<add> return o.sum;
<add> }
<add>
<ide> /**
<ide> * Observable.merge(from(1), from(1))
<ide> *
<add> * -- Old pre-bind
<add> *
<ide> * Run: 10 - 2,308,617 ops/sec
<ide> * Run: 11 - 2,309,602 ops/sec
<ide> * Run: 12 - 2,318,590 ops/sec
<ide> * Run: 13 - 2,270,100 ops/sec
<ide> * Run: 14 - 2,312,006 ops/sec
<ide> *
<add> * -- new post-bind create
<add> *
<add> * Run: 10 - 1,983,888 ops/sec
<add> * Run: 11 - 1,963,829 ops/sec
<add> * Run: 12 - 1,952,321 ops/sec
<add> * Run: 13 - 1,936,031 ops/sec
<add> * Run: 14 - 1,862,887 ops/sec
<add> *
<add> * -- new merge operator
<add> *
<add> * Run: 10 - 2,630,464 ops/sec
<add> * Run: 11 - 2,627,986 ops/sec
<add> * Run: 12 - 2,628,281 ops/sec
<add> * Run: 13 - 2,617,781 ops/sec
<add> * Run: 14 - 2,625,995 ops/sec
<add> *
<ide> */
<ide> public long timeMergeAandBwithSingleItems() {
<ide>
<ide> public long timeMergeAandBwithSingleItems() {
<ide> /**
<ide> * Observable.merge(range(0, 100), range(100, 200))
<ide> *
<add> * -- Old pre-bind
<add> *
<ide> * Run: 10 - 340,049 ops/sec
<ide> * Run: 11 - 339,059 ops/sec
<ide> * Run: 12 - 348,899 ops/sec
<ide> * Run: 13 - 350,953 ops/sec
<ide> * Run: 14 - 352,228 ops/sec
<add> *
<add> * -- new post-bind create
<add> *
<add> * Run: 0 - 236,536 ops/sec
<add> * Run: 1 - 254,272 ops/sec
<add> *
<add> * -- new merge operator
<add> *
<add> * Run: 0 - 266,204 ops/sec
<add> * Run: 1 - 290,318 ops/sec
<add> * Run: 2 - 285,908 ops/sec
<add> * Run: 3 - 289,695 ops/sec
<add> * Run: 4 - 281,689 ops/sec
<add> * Run: 5 - 290,375 ops/sec
<add> * Run: 6 - 287,271 ops/sec
<ide> */
<ide> public long timeMergeAandBwith100Items() {
<ide>
<ide><path>rxjava-core/src/perf/java/rx/perf/AbstractPerformanceTester.java
<ide> package rx.perf;
<ide>
<add>import java.util.Iterator;
<add>
<ide> import rx.util.functions.Action0;
<ide>
<ide> public abstract class AbstractPerformanceTester {
<ide> public long baseline() {
<ide> return o.sum;
<ide> }
<ide>
<add> public static Iterable<Long> ITERABLE_OF_REPETITIONS = new Iterable<Long>() {
<add>
<add> @Override
<add> public Iterator<Long> iterator() {
<add> return new Iterator<Long>() {
<add> long count = 0;
<add>
<add> @Override
<add> public boolean hasNext() {
<add> return count <= REPETITIONS;
<add> }
<add>
<add> @Override
<add> public Long next() {
<add> return count++;
<add> }
<add>
<add> @Override
<add> public void remove() {
<add> // do nothing
<add> }
<add>
<add> };
<add> };
<add> };
<add>
<ide> }
<add><path>rxjava-core/src/test/java/rx/operators/OperatorMergeTest.java
<del><path>rxjava-core/src/test/java/rx/operators/OperationMergeTest.java
<ide> import static org.junit.Assert.*;
<ide> import static org.mockito.Matchers.*;
<ide> import static org.mockito.Mockito.*;
<del>import static rx.operators.OperationMerge.*;
<add>import static rx.operators.OperatorMerge.*;
<ide>
<ide> import java.util.ArrayList;
<ide> import java.util.Arrays;
<ide> import rx.util.functions.Action0;
<ide> import rx.util.functions.Action1;
<ide>
<del>public class OperationMergeTest {
<add>public class OperatorMergeTest {
<ide>
<ide> @Mock
<ide> Observer<String> stringObserver;
<ide> public void testMergeList() {
<ide> verify(stringObserver, times(2)).onNext("hello");
<ide> }
<ide>
<del> @Test
<del> public void testUnSubscribe() {
<del> TestObservable tA = new TestObservable();
<del> TestObservable tB = new TestObservable();
<del>
<del> Observable<String> m = Observable.merge(Observable.create(tA), Observable.create(tB));
<del> Subscription s = m.subscribe(stringObserver);
<del>
<del> tA.sendOnNext("Aone");
<del> tB.sendOnNext("Bone");
<del> s.unsubscribe();
<del> tA.sendOnNext("Atwo");
<del> tB.sendOnNext("Btwo");
<del> tA.sendOnCompleted();
<del> tB.sendOnCompleted();
<del>
<del> verify(stringObserver, never()).onError(any(Throwable.class));
<del> verify(stringObserver, times(1)).onNext("Aone");
<del> verify(stringObserver, times(1)).onNext("Bone");
<del> assertTrue(tA.unsubscribed);
<del> assertTrue(tB.unsubscribed);
<del> verify(stringObserver, never()).onNext("Atwo");
<del> verify(stringObserver, never()).onNext("Btwo");
<del> verify(stringObserver, never()).onCompleted();
<del> }
<del>
<ide> @Test
<ide> public void testUnSubscribeObservableOfObservables() throws InterruptedException {
<ide>
<ide> public void run() {
<ide> });
<ide>
<ide> final AtomicInteger count = new AtomicInteger();
<del> Observable.create(merge(source)).take(6).toBlockingObservable().forEach(new Action1<Long>() {
<add> Observable.merge(source).take(6).toBlockingObservable().forEach(new Action1<Long>() {
<ide>
<ide> @Override
<ide> public void call(Long v) { | 8 |
Go | Go | support custom paths for secrets | 67d282a5c95ca1d25cd4e9c688e89191f662d448 | <ide><path>container/container.go
<ide> func (container *Container) InitializeStdio(iop libcontainerd.IOPipe) error {
<ide>
<ide> return nil
<ide> }
<add>
<add>// SecretMountPath returns the path of the secret mount for the container
<add>func (container *Container) SecretMountPath() string {
<add> return filepath.Join(container.Root, "secrets")
<add>}
<add>
<add>func (container *Container) getLocalSecretPath(r *swarmtypes.SecretReference) string {
<add> return filepath.Join(container.SecretMountPath(), filepath.Base(r.File.Name))
<add>}
<add>
<add>func getSecretTargetPath(r *swarmtypes.SecretReference) string {
<add> if filepath.IsAbs(r.File.Name) {
<add> return r.File.Name
<add> }
<add>
<add> return filepath.Join(containerSecretMountPath, r.File.Name)
<add>}
<ide><path>container/container_notlinux.go
<ide> func detachMounted(path string) error {
<ide> return unix.Unmount(path, 0)
<ide> }
<ide>
<del>// SecretMount returns the mount for the secret path
<del>func (container *Container) SecretMount() *Mount {
<add>// SecretMounts returns the mounts for the secret path
<add>func (container *Container) SecretMounts() []Mount {
<ide> return nil
<ide> }
<ide>
<ide><path>container/container_unit_test.go
<ide> package container
<ide>
<ide> import (
<add> "path/filepath"
<ide> "testing"
<ide>
<ide> "github.com/docker/docker/api/types/container"
<add> swarmtypes "github.com/docker/docker/api/types/swarm"
<ide> "github.com/docker/docker/pkg/signal"
<ide> )
<ide>
<ide> func TestContainerStopTimeout(t *testing.T) {
<ide> t.Fatalf("Expected 15, got %v", s)
<ide> }
<ide> }
<add>
<add>func TestContainerSecretReferenceDestTarget(t *testing.T) {
<add> ref := &swarmtypes.SecretReference{
<add> File: &swarmtypes.SecretReferenceFileTarget{
<add> Name: "app",
<add> },
<add> }
<add>
<add> d := getSecretTargetPath(ref)
<add> expected := filepath.Join(containerSecretMountPath, "app")
<add> if d != expected {
<add> t.Fatalf("expected secret dest %q; received %q", expected, d)
<add> }
<add>}
<ide><path>container/container_unix.go
<ide> func (container *Container) NetworkMounts() []Mount {
<ide> return mounts
<ide> }
<ide>
<del>// SecretMountPath returns the path of the secret mount for the container
<del>func (container *Container) SecretMountPath() string {
<del> return filepath.Join(container.Root, "secrets")
<del>}
<del>
<ide> // CopyImagePathContent copies files in destination to the volume.
<ide> func (container *Container) CopyImagePathContent(v volume.Volume, destination string) error {
<ide> rootfs, err := symlink.FollowSymlinkInScope(filepath.Join(container.BaseFS, destination), container.BaseFS)
<ide> func (container *Container) IpcMounts() []Mount {
<ide> return mounts
<ide> }
<ide>
<del>// SecretMount returns the mount for the secret path
<del>func (container *Container) SecretMount() *Mount {
<del> if len(container.SecretReferences) > 0 {
<del> return &Mount{
<del> Source: container.SecretMountPath(),
<del> Destination: containerSecretMountPath,
<add>// SecretMounts returns the mount for the secret path
<add>func (container *Container) SecretMounts() []Mount {
<add> var mounts []Mount
<add> for _, r := range container.SecretReferences {
<add> // secrets are created in the SecretMountPath at a single level
<add> // i.e. /var/run/secrets/foo
<add> srcPath := container.getLocalSecretPath(r)
<add> mounts = append(mounts, Mount{
<add> Source: srcPath,
<add> Destination: getSecretTargetPath(r),
<ide> Writable: false,
<del> }
<add> })
<ide> }
<ide>
<del> return nil
<add> return mounts
<ide> }
<ide>
<ide> // UnmountSecrets unmounts the local tmpfs for secrets
<ide><path>container/container_windows.go
<ide> import (
<ide> containertypes "github.com/docker/docker/api/types/container"
<ide> )
<ide>
<add>const (
<add> containerSecretMountPath = `C:\ProgramData\Docker\secrets`
<add>)
<add>
<ide> // Container holds fields specific to the Windows implementation. See
<ide> // CommonContainer for standard fields common to all containers.
<ide> type Container struct {
<ide> func (container *Container) IpcMounts() []Mount {
<ide> return nil
<ide> }
<ide>
<del>// SecretMount returns the mount for the secret path
<del>func (container *Container) SecretMount() *Mount {
<add>// SecretMounts returns the mount for the secret path
<add>func (container *Container) SecretMounts() []Mount {
<ide> return nil
<ide> }
<ide>
<ide><path>daemon/container_operations_unix.go
<ide> func (daemon *Daemon) setupSecretDir(c *container.Container) (setupErr error) {
<ide> return fmt.Errorf("secret target type is not a file target")
<ide> }
<ide>
<del> targetPath := filepath.Clean(s.File.Name)
<del> // ensure that the target is a filename only; no paths allowed
<del> if targetPath != filepath.Base(targetPath) {
<del> return fmt.Errorf("error creating secret: secret must not be a path")
<del> }
<del>
<del> fPath := filepath.Join(localMountPath, targetPath)
<add> // secrets are created in the SecretMountPath at a single level
<add> // i.e. /var/run/secrets/foo
<add> fPath := filepath.Join(localMountPath, filepath.Base(s.File.Name))
<ide> if err := idtools.MkdirAllAs(filepath.Dir(fPath), 0700, rootUID, rootGID); err != nil {
<ide> return errors.Wrap(err, "error creating secret mount path")
<ide> }
<ide><path>daemon/oci_linux.go
<ide> func (daemon *Daemon) createSpec(c *container.Container) (*specs.Spec, error) {
<ide> }
<ide> ms = append(ms, tmpfsMounts...)
<ide>
<del> if m := c.SecretMount(); m != nil {
<del> ms = append(ms, *m)
<add> if m := c.SecretMounts(); m != nil {
<add> ms = append(ms, m...)
<ide> }
<ide>
<ide> sort.Sort(mounts(ms))
<ide><path>integration-cli/docker_cli_service_create_test.go
<ide> func (s *DockerSwarmSuite) TestServiceCreateWithSecretSimple(c *check.C) {
<ide> c.Assert(refs[0].File.Name, checker.Equals, testName)
<ide> c.Assert(refs[0].File.UID, checker.Equals, "0")
<ide> c.Assert(refs[0].File.GID, checker.Equals, "0")
<del>}
<del>
<del>func (s *DockerSwarmSuite) TestServiceCreateWithSecretSourceTarget(c *check.C) {
<del> d := s.AddDaemon(c, true, true)
<ide>
<del> serviceName := "test-service-secret"
<del> testName := "test_secret"
<del> id := d.CreateSecret(c, swarm.SecretSpec{
<del> Annotations: swarm.Annotations{
<del> Name: testName,
<del> },
<del> Data: []byte("TESTINGDATA"),
<del> })
<del> c.Assert(id, checker.Not(checker.Equals), "", check.Commentf("secrets: %s", id))
<del> testTarget := "testing"
<del>
<del> out, err := d.Cmd("service", "create", "--name", serviceName, "--secret", fmt.Sprintf("source=%s,target=%s", testName, testTarget), "busybox", "top")
<add> out, err = d.Cmd("service", "rm", serviceName)
<ide> c.Assert(err, checker.IsNil, check.Commentf(out))
<add> d.DeleteSecret(c, testName)
<add>}
<ide>
<del> out, err = d.Cmd("service", "inspect", "--format", "{{ json .Spec.TaskTemplate.ContainerSpec.Secrets }}", serviceName)
<del> c.Assert(err, checker.IsNil)
<del>
<del> var refs []swarm.SecretReference
<del> c.Assert(json.Unmarshal([]byte(out), &refs), checker.IsNil)
<del> c.Assert(refs, checker.HasLen, 1)
<add>func (s *DockerSwarmSuite) TestServiceCreateWithSecretSourceTargetPaths(c *check.C) {
<add> d := s.AddDaemon(c, true, true)
<ide>
<del> c.Assert(refs[0].SecretName, checker.Equals, testName)
<del> c.Assert(refs[0].File, checker.Not(checker.IsNil))
<del> c.Assert(refs[0].File.Name, checker.Equals, testTarget)
<add> testPaths := map[string]string{
<add> "app": "/etc/secret",
<add> "test_secret": "test_secret",
<add> }
<add> for testName, testTarget := range testPaths {
<add> serviceName := "svc-" + testName
<add> id := d.CreateSecret(c, swarm.SecretSpec{
<add> Annotations: swarm.Annotations{
<add> Name: testName,
<add> },
<add> Data: []byte("TESTINGDATA"),
<add> })
<add> c.Assert(id, checker.Not(checker.Equals), "", check.Commentf("secrets: %s", id))
<add>
<add> out, err := d.Cmd("service", "create", "--name", serviceName, "--secret", fmt.Sprintf("source=%s,target=%s", testName, testTarget), "busybox", "top")
<add> c.Assert(err, checker.IsNil, check.Commentf(out))
<add>
<add> out, err = d.Cmd("service", "inspect", "--format", "{{ json .Spec.TaskTemplate.ContainerSpec.Secrets }}", serviceName)
<add> c.Assert(err, checker.IsNil)
<add>
<add> var refs []swarm.SecretReference
<add> c.Assert(json.Unmarshal([]byte(out), &refs), checker.IsNil)
<add> c.Assert(refs, checker.HasLen, 1)
<add>
<add> c.Assert(refs[0].SecretName, checker.Equals, testName)
<add> c.Assert(refs[0].File, checker.Not(checker.IsNil))
<add> c.Assert(refs[0].File.Name, checker.Equals, testTarget)
<add>
<add> out, err = d.Cmd("service", "rm", serviceName)
<add> c.Assert(err, checker.IsNil, check.Commentf(out))
<add>
<add> d.DeleteSecret(c, testName)
<add> }
<ide> }
<ide>
<ide> func (s *DockerSwarmSuite) TestServiceCreateMountTmpfs(c *check.C) {
<ide><path>opts/secret.go
<ide> import (
<ide> "encoding/csv"
<ide> "fmt"
<ide> "os"
<del> "path/filepath"
<ide> "strconv"
<ide> "strings"
<ide>
<ide> func (o *SecretOpt) Set(value string) error {
<ide> case "source", "src":
<ide> options.SecretName = value
<ide> case "target":
<del> tDir, _ := filepath.Split(value)
<del> if tDir != "" {
<del> return fmt.Errorf("target must not be a path")
<del> }
<ide> options.File.Name = value
<ide> case "uid":
<ide> options.File.UID = value | 9 |
PHP | PHP | replace redis to contracts interface | ae450475b44d145f5b72fe884d26e250607b37a4 | <ide><path>src/Illuminate/Cache/RedisStore.php
<ide> namespace Illuminate\Cache;
<ide>
<ide> use Illuminate\Contracts\Cache\Store;
<del>use Illuminate\Redis\Database as Redis;
<add>use Illuminate\Contracts\Redis\Database as Redis;
<ide>
<ide> class RedisStore extends TaggableStore implements Store
<ide> { | 1 |
Ruby | Ruby | avoid extra string objects in the inner join case | 890eaf4784fb6b4ee9e1a8f167f6a9b28525722e | <ide><path>lib/arel/visitors/to_sql.rb
<ide> def visit_Arel_Nodes_OuterJoin o
<ide> end
<ide>
<ide> def visit_Arel_Nodes_InnerJoin o
<del> "INNER JOIN #{visit o.left} #{visit o.right if o.right}"
<add> s = "INNER JOIN #{visit o.left}"
<add> if o.right
<add> s << SPACE
<add> s << visit(o.right)
<add> end
<add> s
<ide> end
<ide>
<ide> def visit_Arel_Nodes_On o | 1 |
Ruby | Ruby | fix empty gem rbis for non-vendored dependencies | 14c2afe1d84af5657a3af0f85e194aa619f94661 | <ide><path>Library/Homebrew/sorbet/tapioca/require.rb
<ide> # typed: strict
<ide> # frozen_string_literal: true
<ide>
<del># Add your extra requires here
<add># This should not be made a constant or Tapioca will think it is part of a gem.
<add>dependency_require_map = {
<add> "activesupport" => "active_support",
<add> "ruby-macho" => "macho",
<add>}.freeze
<add>
<add>Bundler.definition.locked_gems.specs.each do |spec|
<add> name = spec.name
<add>
<add> # sorbet(-static) gem contains executables rather than a library
<add> next if name == "sorbet"
<add> next if name == "sorbet-static"
<add>
<add> name = dependency_require_map[name] if dependency_require_map.key?(name)
<add>
<add> require name
<add>rescue LoadError
<add> raise unless name.include?("-")
<add>
<add> name = name.tr("-", "/")
<add> require name
<add>end | 1 |
Javascript | Javascript | add test for node.async_hooks tracing in workers | 908e114750989d42797a917938529a9b2ebed13e | <ide><path>test/parallel/test-trace-events-async-hooks-worker.js
<add>'use strict';
<add>
<add>const common = require('../common');
<add>if (!process.binding('config').hasTracing)
<add> common.skip('missing trace events');
<add>
<add>const assert = require('assert');
<add>const cp = require('child_process');
<add>const fs = require('fs');
<add>const path = require('path');
<add>const util = require('util');
<add>
<add>const code =
<add> 'setTimeout(() => { for (var i = 0; i < 100000; i++) { "test" + i } }, 1)';
<add>const worker = `const { Worker } = require('worker_threads');
<add> const worker = new Worker('${code}',
<add> { eval: true, stdout: true, stderr: true });
<add> worker.stdout.on('data',
<add> (chunk) => console.log('worker', chunk.toString()));
<add> worker.stderr.on('data',
<add> (chunk) => console.error('worker', chunk.toString()));`;
<add>
<add>const tmpdir = require('../common/tmpdir');
<add>const filename = path.join(tmpdir.path, 'node_trace.1.log');
<add>
<add>tmpdir.refresh();
<add>const proc = cp.spawnSync(
<add> process.execPath,
<add> [ '--trace-event-categories', 'node.async_hooks', '-e', worker ],
<add> {
<add> cwd: tmpdir.path,
<add> env: Object.assign({}, process.env, {
<add> 'NODE_DEBUG_NATIVE': 'tracing',
<add> 'NODE_DEBUG': 'tracing'
<add> })
<add> });
<add>
<add>console.log(proc.signal);
<add>console.log(proc.stderr.toString());
<add>assert.strictEqual(proc.status, 0);
<add>
<add>assert(fs.existsSync(filename));
<add>const data = fs.readFileSync(filename, 'utf-8');
<add>const traces = JSON.parse(data).traceEvents;
<add>assert(traces.length > 0);
<add>// V8 trace events should be generated.
<add>assert(!traces.some((trace) => {
<add> if (trace.pid !== proc.pid)
<add> return false;
<add> if (trace.cat !== 'v8')
<add> return false;
<add> if (trace.name !== 'V8.ScriptCompiler')
<add> return false;
<add> return true;
<add>}));
<add>
<add>// C++ async_hooks trace events should be generated.
<add>assert(traces.some((trace) => {
<add> if (trace.pid !== proc.pid)
<add> return false;
<add> if (trace.cat !== 'node,node.async_hooks')
<add> return false;
<add> return true;
<add>}));
<add>
<add>// JavaScript async_hooks trace events should be generated.
<add>assert(traces.some((trace) => {
<add> if (trace.pid !== proc.pid)
<add> return false;
<add> if (trace.cat !== 'node,node.async_hooks')
<add> return false;
<add> if (trace.name !== 'Timeout')
<add> return false;
<add> return true;
<add>}));
<add>
<add>// Check args in init events
<add>const initEvents = traces.filter((trace) => {
<add> return (trace.ph === 'b' && !trace.name.includes('_CALLBACK'));
<add>});
<add>
<add>for (const trace of initEvents) {
<add> if (trace.name === 'MESSAGEPORT' &&
<add> trace.args.data.executionAsyncId === 0 &&
<add> trace.args.data.triggerAsyncId === 0) {
<add> continue;
<add> }
<add> if (trace.args.data.executionAsyncId > 0 &&
<add> trace.args.data.triggerAsyncId > 0) {
<add> continue;
<add> }
<add> assert.fail('Unexpected initEvent: ',
<add> util.inspect(trace, { depth: Infinity }));
<add>} | 1 |
Python | Python | move max_length to nlp.make_doc() | e931d3f72be04dfc0eb34831555ae2f66a90310e | <ide><path>spacy/language.py
<ide> def __call__(self, text, disable=[], component_cfg=None):
<ide>
<ide> DOCS: https://spacy.io/api/language#call
<ide> """
<del> if len(text) > self.max_length:
<del> raise ValueError(
<del> Errors.E088.format(length=len(text), max_length=self.max_length)
<del> )
<ide> doc = self.make_doc(text)
<ide> if component_cfg is None:
<ide> component_cfg = {}
<ide> def disable_pipes(self, *names):
<ide> return DisabledPipes(self, *names)
<ide>
<ide> def make_doc(self, text):
<add> if len(text) > self.max_length:
<add> raise ValueError(
<add> Errors.E088.format(length=len(text), max_length=self.max_length)
<add> )
<ide> return self.tokenizer(text)
<ide>
<ide> def _format_docs_and_golds(self, docs, golds): | 1 |
Ruby | Ruby | add initial support for xcode 11.0 | 2a5aee0a0b98f40d6936d124c67cc3ec33d6ee03 | <ide><path>Library/Homebrew/os/mac.rb
<ide> def full_version=(version)
<ide>
<ide> def latest_sdk_version
<ide> # TODO: bump version when new Xcode macOS SDK is released
<del> Version.new "10.14"
<add> Version.new "10.15"
<ide> end
<ide>
<ide> def latest_stable_version
<ide> def preferred_arch
<ide> "10.1" => { clang: "10.0", clang_build: 1000 },
<ide> "10.2" => { clang: "10.0", clang_build: 1001 },
<ide> "10.2.1" => { clang: "10.0", clang_build: 1001 },
<add> "11.0" => { clang: "11.0", clang_build: 1100 },
<ide> }.freeze
<ide>
<ide> def compilers_standard?
<ide><path>Library/Homebrew/os/mac/xcode.rb
<ide> def latest_version
<ide> when "10.12" then "9.2"
<ide> when "10.13" then "10.1"
<ide> when "10.14" then "10.2.1"
<add> when "10.15" then "11.0"
<ide> else
<ide> raise "macOS '#{MacOS.version}' is invalid" unless OS::Mac.prerelease?
<ide>
<ide> # Default to newest known version of Xcode for unreleased macOS versions.
<del> "10.2.1"
<add> "11.0"
<ide> end
<ide> end
<ide>
<ide> def minimum_version
<ide> case MacOS.version
<add> when "10.15" then "11.0"
<ide> when "10.14" then "10.2"
<ide> when "10.13" then "9.0"
<ide> when "10.12" then "8.0"
<ide> def detect_version_from_clang_version
<ide> when 90 then "9.2"
<ide> when 91 then "9.4"
<ide> when 100 then "10.2.1"
<del> else "10.2.1"
<add> when 110 then "11.0"
<add> else "11.0"
<ide> end
<ide> end
<ide>
<ide> def latest_version
<ide> # on the older supported platform for that Xcode release, i.e there's no
<ide> # CLT package for 10.11 that contains the Clang version from Xcode 8.
<ide> case MacOS.version
<add> when "10.15" then "1100.0.20.17"
<ide> when "10.14" then "1001.0.46.4"
<ide> when "10.13" then "1000.10.44.2"
<ide> when "10.12" then "900.0.39.2"
<ide> def latest_version
<ide>
<ide> def minimum_version
<ide> case MacOS.version
<add> when "10.15" then "11.0.0"
<ide> when "10.14" then "10.0.0"
<ide> when "10.13" then "9.0.0"
<ide> when "10.12" then "8.0.0" | 2 |
Ruby | Ruby | allow comparison on model objects - closes | bc743dc1ce4657be0c377edaab69f8e9ca0e350b | <ide><path>activerecord/lib/active_record/base.rb
<ide> def frozen?
<ide> @attributes.frozen?
<ide> end
<ide>
<add> # Allows sort on objects
<add> def <=>(other_object)
<add> self.to_key <=> other_object.to_key
<add> end
<add>
<ide> # Backport dup from 1.9 so that initialize_dup() gets called
<ide> unless Object.respond_to?(:initialize_dup)
<ide> def dup # :nodoc:
<ide><path>activerecord/test/cases/base_test.rb
<ide> def test_equality_of_destroyed_records
<ide> def test_hashing
<ide> assert_equal [ Topic.find(1) ], [ Topic.find(2).topic ] & [ Topic.find(1) ]
<ide> end
<add>
<add> def test_comparison
<add> topic_1 = Topic.create!
<add> topic_2 = Topic.create!
<add>
<add> assert_equal [topic_2, topic_1].sort, [topic_1, topic_2]
<add> end
<ide>
<ide> def test_readonly_attributes
<ide> assert_equal Set.new([ 'title' , 'comments_count' ]), ReadonlyTitlePost.readonly_attributes | 2 |
Javascript | Javascript | restore jquery push behavior in .find | 4d3050b3d80dc58cdcca0ce7bfdd780e50b0483f | <ide><path>src/traversing/findFilter.js
<ide> jQuery.filter = function( expr, elems, not ) {
<ide>
<ide> jQuery.fn.extend( {
<ide> find: function( selector ) {
<del> var i,
<add> var i, ret,
<ide> len = this.length,
<del> ret = [],
<ide> self = this;
<ide>
<ide> if ( typeof selector !== "string" ) {
<ide> jQuery.fn.extend( {
<ide> } ) );
<ide> }
<ide>
<add> ret = this.pushStack( [] );
<add>
<ide> for ( i = 0; i < len; i++ ) {
<ide> jQuery.find( selector, self[ i ], ret );
<ide> }
<ide>
<del> return this.pushStack( len > 1 ? jQuery.uniqueSort( ret ) : ret );
<add> return len > 1 ? jQuery.uniqueSort( ret ) : ret;
<ide> },
<ide> filter: function( selector ) {
<ide> return this.pushStack( winnow( this, selector || [], false ) ); | 1 |
Python | Python | add extra logging | ceab9a3f2ec25d422a8e6acd9c3f9a84591f2541 | <ide><path>airflow/contrib/auth/backends/kerberos_auth.py
<ide> def login(self, request):
<ide>
<ide> session = settings.Session()
<ide> user = session.query(models.User).filter(
<del> models.User.username == DEFAULT_USERNAME).first()
<add> models.User.username == username).first()
<ide>
<ide> if not user:
<ide> user = models.User(
<del> username=DEFAULT_USERNAME,
<del> is_superuser=True)
<add> username=username,
<add> is_superuser=False)
<ide>
<ide> session.merge(user)
<ide> session.commit()
<ide><path>airflow/contrib/auth/backends/ldap_auth.py
<ide> from airflow import models
<ide> from airflow import configuration
<ide>
<add>import logging
<add>
<ide> DEFAULT_USERNAME = 'airflow'
<ide>
<ide> login_manager = flask_login.LoginManager()
<ide> login_manager.login_view = 'airflow.login' # Calls login() bellow
<ide> login_manager.login_message = None
<ide>
<add>LOG = logging.getLogger(__name__)
<add>
<ide>
<ide> class AuthenticationError(Exception):
<ide> pass
<ide> def get_ldap_connection(dn=None, password=None):
<ide> conn = Connection(server, dn, password)
<ide>
<ide> if not conn.bind():
<add> LOG.error("Cannot bind to ldap server: %s ", conn.last_error)
<ide> raise AuthenticationError("Username or password incorrect")
<ide>
<ide> return conn
<ide> def try_login(username, password):
<ide>
<ide> # todo: use list or result?
<ide> if not res:
<add> LOG.info("Cannot find user %s", username)
<ide> raise AuthenticationError("Invalid username or password")
<ide>
<ide> entry = conn.response[0]
<ide> def try_login(username, password):
<ide> conn = get_ldap_connection(entry['dn'], password)
<ide>
<ide> if not conn:
<add> LOG.info("Password incorrect for user %s", username)
<ide> raise AuthenticationError("Invalid username or password")
<ide>
<ide> def is_active(self):
<ide> def login(self, request):
<ide>
<ide> try:
<ide> LdapUser.try_login(username, password)
<add> LOG.info("User %s successfully authenticated", username)
<ide>
<ide> session = settings.Session()
<ide> user = session.query(models.User).filter(
<del> models.User.username == DEFAULT_USERNAME).first()
<add> models.User.username == username).first()
<ide>
<ide> if not user:
<ide> user = models.User(
<del> username=DEFAULT_USERNAME,
<del> is_superuser=True)
<add> username=username,
<add> is_superuser=False)
<ide>
<ide> session.merge(user)
<ide> session.commit() | 2 |
Javascript | Javascript | fix minor issue | 202bbb3422e0884db972df6d022dec11393f7e99 | <ide><path>src/extras/core/Font.js
<ide> Object.assign( Font.prototype, {
<ide>
<ide> function createPaths( text, size, divisions, data ) {
<ide>
<del> var chars = String( text ).split( '' );
<add> var chars = Array.from ? Array.from( text ) : String( text ).split( '' ); // see #13988
<ide> var scale = size / data.resolution;
<ide> var line_height = ( data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness ) * scale;
<ide> | 1 |
Javascript | Javascript | add test for a unref'ed timer leak | 6f72d87c274f28021ba3bf7056d8faa18e75b4f1 | <ide><path>test/parallel/test-timers-unref-leak.js
<add>var assert = require('assert');
<add>
<add>var called = 0;
<add>var closed = 0;
<add>
<add>var timeout = setTimeout(function() {
<add> called++;
<add>}, 10);
<add>timeout.unref();
<add>
<add>// Wrap `close` method to check if the handle was closed
<add>var close = timeout._handle.close;
<add>timeout._handle.close = function() {
<add> closed++;
<add> return close.apply(this, arguments);
<add>};
<add>
<add>// Just to keep process alive and let previous timer's handle die
<add>setTimeout(function() {
<add>}, 50);
<add>
<add>process.on('exit', function() {
<add> assert.equal(called, 1);
<add> assert.equal(closed, 1);
<add>}); | 1 |
Ruby | Ruby | allow add_to_transaction with null transaction | 95254e4f129cedd4048c63e2f068227d5f80864d | <ide><path>activerecord/lib/active_record/connection_adapters/abstract/transaction.rb
<ide> def set_state(state)
<ide>
<ide> class NullTransaction #:nodoc:
<ide> def initialize; end
<add> def state; end
<ide> def closed?; true; end
<ide> def open?; false; end
<ide> def joinable?; false; end
<ide><path>activerecord/test/cases/transactions_test.rb
<ide> def transaction_with_return
<ide> end
<ide> end
<ide>
<add> def test_add_to_null_transaction
<add> topic = Topic.new
<add> topic.add_to_transaction
<add> end
<add>
<ide> def test_successful_with_return
<ide> committed = false
<ide> | 2 |
Java | Java | increase randomness in socketutils | d5944c4e398a288ff416a51ab35871024d612804 | <ide><path>spring-core/src/main/java/org/springframework/util/SocketUtils.java
<ide> import java.net.DatagramSocket;
<ide> import java.net.InetAddress;
<ide> import java.net.ServerSocket;
<del>import java.util.Random;
<add>import java.security.SecureRandom;
<ide> import java.util.SortedSet;
<ide> import java.util.TreeSet;
<ide> import javax.net.ServerSocketFactory;
<ide> public class SocketUtils {
<ide> public static final int PORT_RANGE_MAX = 65535;
<ide>
<ide>
<del> private static final Random random = new Random(System.currentTimeMillis());
<del>
<del>
<ide> /**
<ide> * Although {@code SocketUtils} consists solely of static utility methods,
<ide> * this constructor is intentionally {@code public}.
<ide> protected boolean isPortAvailable(int port) {
<ide> */
<ide> private int findRandomPort(int minPort, int maxPort) {
<ide> int portRange = maxPort - minPort;
<del> return minPort + random.nextInt(portRange);
<add> return minPort + new SecureRandom().nextInt(portRange);
<ide> }
<ide>
<ide> /** | 1 |
Ruby | Ruby | fix collectionproxy documentation markup | ab2e2a9d2b772cf4aef4d9f4f2d506a03c205035 | <ide><path>activerecord/lib/active_record/associations/collection_proxy.rb
<ide> class CollectionProxy < Relation
<ide> ##
<ide> # :method: first
<ide> # Returns the first record, or the first +n+ records, from the collection.
<del> # If the collection is empty, the first form returns nil, and the second
<add> # If the collection is empty, the first form returns +nil+, and the second
<ide> # form returns an empty array.
<ide> #
<ide> # class Person < ActiveRecord::Base
<ide> class CollectionProxy < Relation
<ide> ##
<ide> # :method: last
<ide> # Returns the last record, or the last +n+ records, from the collection.
<del> # If the collection is empty, the first form returns nil, and the second
<add> # If the collection is empty, the first form returns +nil+, and the second
<ide> # form returns an empty array.
<ide> #
<ide> # class Person < ActiveRecord::Base
<ide> class CollectionProxy < Relation
<ide>
<ide> ##
<ide> # :method: empty?
<del> # Returns true if the collection is empty.
<add> # Returns +true+ if the collection is empty.
<ide> #
<ide> # class Person < ActiveRecord::Base
<ide> # has_many :pets
<ide> class CollectionProxy < Relation
<ide>
<ide> ##
<ide> # :method: any?
<del> # Returns true if the collection is not empty.
<add> # Returns +true+ if the collection is not empty.
<ide> #
<ide> # class Person < ActiveRecord::Base
<ide> # has_many :pets
<ide> class CollectionProxy < Relation
<ide> ##
<ide> # :method: many?
<ide> # Returns true if the collection has more than one record.
<del> # Equivalent to +collection.size > 1+.
<add> # Equivalent to <tt>collection.size > 1</tt>.
<ide> #
<ide> # class Person < ActiveRecord::Base
<ide> # has_many :pets
<ide> class CollectionProxy < Relation
<ide>
<ide> ##
<ide> # :method: include?
<del> # Returns true if the given object is present in the collection.
<add> # Returns +true+ if the given object is present in the collection.
<ide> #
<ide> # class Person < ActiveRecord::Base
<ide> # has_many :pets
<ide> def <<(*records)
<ide> #
<ide> # Pet.find(1) # => #<Pet id: 1, name: "Snoop", group: "dogs", person_id: nil>
<ide> #
<del> # If they are associated with +dependent: :destroy+ option, it deletes
<add> # If they are associated with <tt>dependent: :destroy</tt> option, it deletes
<ide> # them directly from the database.
<ide> #
<ide> # class Person < ActiveRecord::Base
<ide> def clear
<ide> end
<ide>
<ide> # Reloads the collection from the database. Returns +self+.
<del> # Equivalent to +collection(true)+.
<add> # Equivalent to <tt>collection(true)</tt>.
<ide> #
<ide> # class Person < ActiveRecord::Base
<ide> # has_many :pets | 1 |
Ruby | Ruby | reduce number of comparisons and array allocations | 155fd955ac380c7877785f1b74b61ad86fd40772 | <ide><path>activerecord/lib/active_record/associations/join_dependency.rb
<ide> def instantiate(result_set)
<ide> records = result_set.map { |row_hash|
<ide> primary_id = type_caster.type_cast row_hash[primary_key]
<ide> parent = parents[primary_id] ||= join_base.instantiate(row_hash)
<del> construct(parent, assoc, join_associations, row_hash, result_set)
<add> construct(parent, assoc, row_hash, result_set)
<ide> parent
<ide> }.uniq
<ide>
<ide> def build_join_association(reflection, parent, join_type)
<ide> Node.new part
<ide> end
<ide>
<del> def construct(parent, nodes, join_parts, row, rs)
<add> def construct(parent, nodes, row, rs)
<ide> nodes.sort_by { |k| k.name.to_s }.each do |node|
<ide> association_name = node.name
<ide> assoc = node.children
<del> association = construct_scalar(parent, association_name, join_parts, row, rs)
<del> construct(association, assoc, join_parts, row, rs) if association
<add> association = construct_scalar(parent, association_name, row, rs, nodes)
<add> construct(association, assoc, row, rs) if association
<ide> end
<ide> end
<ide>
<del> def construct_scalar(parent, associations, join_parts, row, rs)
<add> def construct_scalar(parent, associations, row, rs, nodes)
<ide> name = associations.to_s
<ide>
<del> join_part = join_parts.detect { |j|
<del> j.reflection.name.to_s == name &&
<del> j.parent_table_name == parent.class.table_name
<add> node = nodes.detect { |j|
<add> j.name.to_s == name &&
<add> j.join_part.parent_table_name == parent.class.table_name
<ide> }
<ide>
<del> raise(ConfigurationError, "No such association") unless join_part
<add> raise(ConfigurationError, "No such association") unless node
<ide>
<del> join_parts.delete(join_part)
<del> construct_association(parent, join_part, row, rs)
<add> construct_association(parent, node.join_part, row, rs)
<ide> end
<ide>
<ide> def construct_association(record, join_part, row, rs) | 1 |
Text | Text | fix minor details and wording | fdabdf5d53de866dbcf7435c48d5a9af978d8aa5 | <ide><path>docs/rfcs/002-atom-nightly-releases.md
<ide> Today, a bleeding-edge user must manually pull Atom's `master` branch and compil
<ide>
<ide> A user who wants to use the latest improvements to Atom each day can go to atom.io, download the Atom Nightly release, and install it on their machine. This release can be installed alongside Atom Stable and Atom Beta.
<ide>
<del>Each night when there are new commits to Atom's `master` branch, a scheduled CI build creates a new Atom Nightly release with packages for Windows, macOS, and Linux. These packages are automatically uploaded to a new GitHub release on the `atom/atom-nightly` repository using a nightly version based off of the current `dev` version in `master` (e.g. v1.29.0-dev.1 or v1.29.0-dev.20180601).
<add>Each night when there are new commits to Atom's `master` branch, a scheduled CI build creates a new Atom Nightly release with packages for Windows, macOS, and Linux. These packages are automatically uploaded to a new GitHub release on the `atom/atom-nightly-releases` repository using a monotonically-increasing nightly version based off of the version in `master` (e.g. `v1.29.0-nightly1`).
<ide>
<del>Every 6 hours, an Atom Nightly release installed on Windows or macOS checks for a new update by consulting Electron's [update.electronjs.org](update-electron) service. If a new update is available, it is downloaded in the background and the user is notified to restart Atom once it's complete. This update flow is the same as what users experience in Atom Stable or Beta releases but occurs more frequently.
<add>Every 4 hours, an Atom Nightly release installed on Windows or macOS checks for a new update by consulting Electron's [update.electronjs.org](update-electron) service. If a new update is available, it is downloaded in the background and the user is notified to restart Atom once it's complete. This update flow is the same as what users experience in Atom Stable or Beta releases but updates occur more frequently.
<ide>
<del>Linux users must manually download nightly releases for now as there isn't an easy way to automatically install new updates across the various Linux distrubutions. We may consider providing updatable [AppImage](http://appimage.org/) packages in the future; this will be proposed in a separate RFC.
<add>Linux users must manually download nightly releases for now as there isn't an easy way to automatically install new updates across the various Linux distributions. We may consider providing updatable [AppImage](http://appimage.org/) packages in the future; this will be proposed in a separate RFC.
<ide>
<ide> ## Drawbacks
<ide>
<ide> The impact of not taking this approach is that we continue to have to wait 1-2 m
<ide> - Atom Reactor
<ide> - Atom Dev - Currently the name of dev builds but it might make sense to leave that for "normal" builds from `master`
<ide>
<add>According to a [Twitter poll](https://twitter.com/daviwil/status/1006545552987701248) with about 1,600 responses, 50% of the voters chose "Atom Nightly". The final name will be determined before launch.
<add>
<ide> - **Will Electron's new autoUpdate service work for all Atom releases?**
<ide>
<ide> One outcome of this effort is to use the new [update.electronjs.org](update-electron) service for Atom's update checks so that we can deprecate on our own custom update service. Building the Nightly channel on this service will allow us to evaluate it to see if it meets the needs of the Stable and Beta channels.
<ide>
<del>[update-elctron]: https://github.com/electron/update.electronjs.org
<add>[update-electron]: https://github.com/electron/update.electronjs.org | 1 |
Javascript | Javascript | change items unknown style | e270ae9f010db42290c2df733383cfb7dcfcd697 | <ide><path>lib/util.js
<ide> function formatValue(ctx, value, recurseTimes, ln) {
<ide> if (ctx.showHidden) {
<ide> formatter = formatWeakSet;
<ide> } else {
<del> extra = '[items unknown]';
<add> extra = '<items unknown>';
<ide> }
<ide> } else if (isWeakMap(value)) {
<ide> braces[0] = `${getPrefix(constructor, tag)}{`;
<ide> if (ctx.showHidden) {
<ide> formatter = formatWeakMap;
<ide> } else {
<del> extra = '[items unknown]';
<add> extra = '<items unknown>';
<ide> }
<ide> } else if (types.isModuleNamespaceObject(value)) {
<ide> braces[0] = `[${tag}] {`;
<ide><path>test/parallel/test-util-inspect.js
<ide> util.inspect(process);
<ide> assert.strictEqual(out, expect);
<ide>
<ide> out = util.inspect(weakMap);
<del> expect = 'WeakMap { [items unknown] }';
<add> expect = 'WeakMap { <items unknown> }';
<ide> assert.strictEqual(out, expect);
<ide>
<ide> out = util.inspect(weakMap, { maxArrayLength: 0, showHidden: true });
<ide> util.inspect(process);
<ide> assert.strictEqual(out, expect);
<ide>
<ide> out = util.inspect(weakSet);
<del> expect = 'WeakSet { [items unknown] }';
<add> expect = 'WeakSet { <items unknown> }';
<ide> assert.strictEqual(out, expect);
<ide>
<ide> out = util.inspect(weakSet, { maxArrayLength: -2, showHidden: true }); | 2 |
PHP | PHP | batch insert correction | 78c3357578dc83984f82bb88d0c15d23311f3d28 | <ide><path>src/Illuminate/Database/Query/Grammars/Grammar.php
<ide> public function compileInsert(Builder $query, array $values)
<ide>
<ide> $columns = $this->columnize(array_keys(reset($values)));
<ide>
<del> // We need to build a list of parameter place-holders of values that are bound
<del> // to the query. Each insert should have the exact same amount of parameter
<del> // bindings so we can just go off the first list of values in this array.
<del> $parameters = $this->parameterize(reset($values));
<add> $value = array();
<ide>
<del> $value = array_fill(0, count($values), "($parameters)");
<add> foreach($values as $record)
<add> {
<add> $value[] = '('.$this->parameterize($record).')';
<add> }
<ide>
<ide> $parameters = implode(', ', $value);
<ide>
<ide><path>tests/Database/DatabaseQueryBuilderTest.php
<ide> public function testInsertMethodRespectsRawBindings()
<ide> }
<ide>
<ide>
<add> public function testMultipleInsertsWithExpressionValues()
<add> {
<add> $builder = $this->getBuilder();
<add> $builder->getConnection()->shouldReceive('insert')->once()->with('insert into "users" ("email") values (UPPER(\'Foo\')), (LOWER(\'Foo\'))', array())->andReturn(true);
<add> $result = $builder->from('users')->insert(array(array('email' => new Raw("UPPER('Foo')")), array('email' => new Raw("LOWER('Foo')"))));
<add> $this->assertTrue($result);
<add> }
<add>
<add>
<ide> public function testUpdateMethod()
<ide> {
<ide> $builder = $this->getBuilder(); | 2 |
Javascript | Javascript | pluralize dom element | d506b8a9df467f4d182f4a40333df7566c552015 | <ide><path>src/ng/compile.js
<ide> *
<ide> * ### Transclusion
<ide> *
<del> * Transclusion is the process of extracting a collection of DOM element from one part of the DOM and
<add> * Transclusion is the process of extracting a collection of DOM elements from one part of the DOM and
<ide> * copying them to another part of the DOM, while maintaining their connection to the original AngularJS
<ide> * scope from where they were taken.
<ide> * | 1 |
Javascript | Javascript | fix tests from to use jasmine 2 | a49b7a2dfb57852264eb83a7510490d19268089c | <ide><path>src/isomorphic/classic/class/__tests__/ReactClassMixin-test.js
<ide> describe('ReactClass-mixin', function() {
<ide> },
<ide> });
<ide>
<del> expect(console.error.argsForCall.length).toBe(1);
<del> expect(console.error.argsForCall[0][0]).toBe(
<add> expect(console.error.calls.count()).toBe(1);
<add> expect(console.error.calls.argsFor(0)[0]).toBe(
<ide> 'Warning: ReactClass: You\'re attempting to include a mixin that is ' +
<ide> 'either null or not an object. Check the mixins included by the ' +
<ide> 'component, as well as any mixins they include themselves. ' +
<ide> describe('ReactClass-mixin', function() {
<ide> },
<ide> });
<ide>
<del> expect(console.error.argsForCall.length).toBe(1);
<del> expect(console.error.argsForCall[0][0]).toBe(
<add> expect(console.error.calls.count()).toBe(1);
<add> expect(console.error.calls.argsFor(0)[0]).toBe(
<ide> 'Warning: ReactClass: You\'re attempting to include a mixin that is ' +
<ide> 'either null or not an object. Check the mixins included by the ' +
<ide> 'component, as well as any mixins they include themselves. ' +
<ide> describe('ReactClass-mixin', function() {
<ide> },
<ide> });
<ide>
<del> expect(console.error.argsForCall.length).toBe(1);
<del> expect(console.error.argsForCall[0][0]).toBe(
<add> expect(console.error.calls.count()).toBe(1);
<add> expect(console.error.calls.argsFor(0)[0]).toBe(
<ide> 'Warning: ReactClass: You\'re attempting to include a mixin that is ' +
<ide> 'either null or not an object. Check the mixins included by the ' +
<ide> 'component, as well as any mixins they include themselves. ' +
<ide> describe('ReactClass-mixin', function() {
<ide> },
<ide> });
<ide>
<del> expect(console.error.argsForCall.length).toBe(1);
<del> expect(console.error.argsForCall[0][0]).toBe(
<add> expect(console.error.calls.count()).toBe(1);
<add> expect(console.error.calls.argsFor(0)[0]).toBe(
<ide> 'Warning: ReactClass: You\'re attempting to include a mixin that is ' +
<ide> 'either null or not an object. Check the mixins included by the ' +
<ide> 'component, as well as any mixins they include themselves. ' + | 1 |
Python | Python | fix typo in docstring for readonlyfield | b209fe04fc5720fe7d13c8ff9abadfe09df9f146 | <ide><path>rest_framework/fields.py
<ide> class ReadOnlyField(Field):
<ide>
<ide> For example, the following would call `get_expiry_date()` on the object:
<ide>
<del> class ExampleSerializer(self):
<add> class ExampleSerializer(Serializer):
<ide> expiry_date = ReadOnlyField(source='get_expiry_date')
<ide> """
<ide> | 1 |
Python | Python | fix conv layers loading for model_from_config | ed4acfae40e15c9598fb07e8bf67f63b98fea6d6 | <ide><path>keras/utils/layer_utils.py
<ide> from ..layers.advanced_activations import LeakyReLU, PReLU
<ide> from ..layers.core import Dense, Merge, Dropout, Activation, Reshape, Flatten, RepeatVector, Layer
<ide> from ..layers.core import ActivityRegularization, TimeDistributedDense, AutoEncoder, MaxoutDense
<add>from ..layers.convolutional import Convolution1D, Convolution2D, MaxPooling1D, MaxPooling2D, ZeroPadding2D
<ide> from ..layers.embeddings import Embedding, WordContextProduct
<ide> from ..layers.noise import GaussianNoise, GaussianDropout
<ide> from ..layers.normalization import BatchNormalization | 1 |
Mixed | Ruby | fix date_select option overwriting html classes | 60ed9d62826678006f0c8abde25ee779b1740c3a | <ide><path>actionview/CHANGELOG.md
<add>* `date_select` helper with option `with_css_classes: true` does not overwrite other classes.
<add>
<add> *Izumi Wong-Horiuchi*
<add>
<ide> * `number_to_percentage` does not crash with `Float::NAN` or `Float::INFINITY`
<ide> as input.
<ide>
<ide><path>actionview/lib/action_view/helpers/date_helper.rb
<ide> def build_select(type, select_options_as_html)
<ide> :name => input_name_from_type(type)
<ide> }.merge!(@html_options)
<ide> select_options[:disabled] = 'disabled' if @options[:disabled]
<del> select_options[:class] = type if @options[:with_css_classes]
<add> select_options[:class] = [select_options[:class], type].compact.join(' ') if @options[:with_css_classes]
<ide>
<ide> select_html = "\n"
<ide> select_html << content_tag(:option, '', :value => '') + "\n" if @options[:include_blank]
<ide><path>actionview/test/template/date_helper_test.rb
<ide> def test_select_date_with_css_classes_option
<ide> assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), {:start_year => 2003, :end_year => 2005, :prefix => "date[first]", :with_css_classes => true})
<ide> end
<ide>
<add> def test_select_date_with_css_classes_option_and_html_class_option
<add> expected = %(<select id="date_first_year" name="date[first][year]" class="datetime optional year">\n)
<add> expected << %(<option value="2003" selected="selected">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n)
<add> expected << "</select>\n"
<add>
<add> expected << %(<select id="date_first_month" name="date[first][month]" class="datetime optional month">\n)
<add> expected << %(<option value="1">January</option>\n<option value="2">February</option>\n<option value="3">March</option>\n<option value="4">April</option>\n<option value="5">May</option>\n<option value="6">June</option>\n<option value="7">July</option>\n<option value="8" selected="selected">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n)
<add> expected << "</select>\n"
<add>
<add> expected << %(<select id="date_first_day" name="date[first][day]" class="datetime optional day">\n)
<add> expected << %(<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16" selected="selected">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n)
<add> expected << "</select>\n"
<add>
<add> assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), {:start_year => 2003, :end_year => 2005, :prefix => "date[first]", :with_css_classes => true}, { class: 'datetime optional' })
<add> end
<add>
<ide> def test_select_datetime
<ide> expected = %(<select id="date_first_year" name="date[first][year]">\n)
<ide> expected << %(<option value="2003" selected="selected">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n) | 3 |
Text | Text | add space after dot | 8d099567132eba326bbbd956ea430905d6e85219 | <ide><path>guide/english/javascript/es6/for-of/index.md
<ide> for (const fruit of fruits)
<ide> The above snippet is going to return us the items in the array above.
<ide>
<ide> ## for-of loop in knowing index
<del>What if we want to know the index of each item too.In that case we can iterate over fruits.entries() which gives us the ArrayIterator.
<add>What if we want to know the index of each item too. In that case we can iterate over fruits.entries() which gives us the ArrayIterator.
<ide>
<ide> ```javascript
<ide> for (const fruit of fruits.entries()) | 1 |
PHP | PHP | add actingas() tests. | 80ef2d0ea836b15c7a45e611d17e9bc24d4bd235 | <ide><path>tests/Integration/Foundation/Testing/Concerns/InteractsWithAuthenticationTest.php
<add><?php
<add>
<add>namespace Illuminate\Tests\Integration\Foundation\Testing\Concerns;
<add>
<add>use Illuminate\Http\Request;
<add>use Orchestra\Testbench\TestCase;
<add>use Illuminate\Support\Facades\Auth;
<add>use Illuminate\Support\Facades\Route;
<add>use Illuminate\Support\Facades\Schema;
<add>use Illuminate\Auth\EloquentUserProvider;
<add>use Illuminate\Foundation\Auth\User as Authenticatable;
<add>
<add>class InteractsWithAuthenticationTest extends TestCase
<add>{
<add> protected function getEnvironmentSetUp($app)
<add> {
<add> $app['config']->set('auth.providers.users.model', AuthenticationTestUser::class);
<add>
<add> $app['config']->set('database.default', 'testbench');
<add> $app['config']->set('database.connections.testbench', [
<add> 'driver' => 'sqlite',
<add> 'database' => ':memory:',
<add> 'prefix' => '',
<add> ]);
<add> }
<add>
<add> public function setUp()
<add> {
<add> parent::setUp();
<add>
<add> Schema::create('users', function ($table) {
<add> $table->increments('id');
<add> $table->string('email');
<add> $table->string('username');
<add> $table->string('password');
<add> $table->string('remember_token')->default(null)->nullable();
<add> $table->tinyInteger('is_active')->default(0);
<add> });
<add>
<add> AuthenticationTestUser::create([
<add> 'username' => 'taylorotwell',
<add> 'email' => 'taylorotwell@laravel.com',
<add> 'password' => bcrypt('password'),
<add> 'is_active' => true,
<add> ]);
<add> }
<add>
<add> public function test_acting_as_is_properly_handled_for_session_auth()
<add> {
<add> Route::get('me', function (Request $request) {
<add> return 'Hello '.$request->user()->username;
<add> })->middleware(['auth']);
<add>
<add> $user = AuthenticationTestUser::where('username', '=', 'taylorotwell')->first();
<add>
<add> $this->actingAs($user)
<add> ->get('/me')
<add> ->assertSuccessful()
<add> ->assertSeeText('Hello taylorotwell');
<add> }
<add>
<add> public function test_acting_as_is_properly_handled_for_auth_via_request()
<add> {
<add> Route::get('me', function (Request $request) {
<add> return 'Hello '.$request->user()->username;
<add> })->middleware(['auth:api']);
<add>
<add> Auth::viaRequest('basic', function ($request) {
<add> return $request->user();
<add> });
<add>
<add> $user = AuthenticationTestUser::where('username', '=', 'taylorotwell')->first();
<add>
<add> $this->actingAs($user, 'api')
<add> ->get('/me')
<add> ->assertSuccessful()
<add> ->assertSeeText('Hello taylorotwell');
<add> }
<add>}
<add>
<add>class AuthenticationTestUser extends Authenticatable
<add>{
<add> public $table = 'users';
<add> public $timestamps = false;
<add>
<add> /**
<add> * The attributes that are mass assignable.
<add> *
<add> * @var array
<add> */
<add> protected $guarded = ['id'];
<add>
<add> /**
<add> * The attributes that should be hidden for arrays.
<add> *
<add> * @var array
<add> */
<add> protected $hidden = [
<add> 'password', 'remember_token',
<add> ];
<add>} | 1 |
Ruby | Ruby | fix formula path usage in brew-gist-logs | 84251bd44fbdc722a36c41891ed2b15b3406afbe | <ide><path>Library/Contributions/cmd/brew-gist-logs.rb
<ide> def initialize response
<ide> end
<ide>
<ide> def repo_name f
<del> dir = (f.path.symlink? ? f.path.realpath.dirname : HOMEBREW_REPOSITORY)
<add> dir = f.path.dirname
<ide> url = dir.cd { `git config --get remote.origin.url` }
<ide> unless url =~ %r{github.com(?:/|:)([\w\d]+)/([\-\w\d]+)}
<ide> raise 'Unable to determine formula repository.' | 1 |
Python | Python | update benchmark codes to match current set | 57d222ff3d422b3c4a454fa66a037c4b478c9524 | <ide><path>benchmarks/benchmarks/bench_random.py
<ide> def time_permutation_int(self):
<ide>
<ide> class RNG(Benchmark):
<ide> param_names = ['rng']
<del> params = ['PCG64', 'MT19937', 'Philox', 'numpy']
<add> params = ['PCG64', 'MT19937', 'Philox', 'SFC64', 'numpy']
<ide>
<ide> def setup(self, bitgen):
<ide> if bitgen == 'numpy':
<ide> class Bounded(Benchmark):
<ide> u32 = np.uint32
<ide> u64 = np.uint64
<ide> param_names = ['rng', 'dt_max']
<del> params = [['PCG64', 'MT19937', 'Philox', 'numpy'],
<add> params = [['PCG64', 'MT19937', 'Philox', 'SFC64', 'numpy'],
<ide> [[u8, 95],
<ide> [u8, 64], # Worst case for legacy
<ide> [u8, 127], # Best case for legacy
<ide><path>doc/source/reference/random/performance.py
<ide> import pandas as pd
<ide>
<ide> import numpy as np
<del>from numpy.random import MT19937, ThreeFry, PCG64, Philox
<add>from numpy.random import MT19937, PCG64, Philox, SFC64
<ide>
<del>PRNGS = [MT19937, PCG64, Philox, ThreeFry]
<add>PRNGS = [MT19937, PCG64, Philox, SFC64]
<ide>
<ide> funcs = OrderedDict()
<ide> integers = 'integers(0, 2**{bits},size=1000000, dtype="uint{bits}")' | 2 |
Go | Go | fix typo in pullimage | 3f17844b6ec3edb981653ca237d085909d5be671 | <ide><path>server.go
<ide> func (srv *Server) pullImage(r *registry.Registry, out io.Writer, imgID, endpoin
<ide> if err != nil {
<ide> return err
<ide> }
<del> out.Write(sf.FormatProgress(utils.TruncateID(imgID), "Pulling", "dependend layers"))
<add> out.Write(sf.FormatProgress(utils.TruncateID(imgID), "Pulling", "dependent layers"))
<ide> // FIXME: Try to stream the images?
<ide> // FIXME: Launch the getRemoteImage() in goroutines
<ide>
<ide> func (srv *Server) pullImage(r *registry.Registry, out io.Writer, imgID, endpoin
<ide> out.Write(sf.FormatProgress(utils.TruncateID(id), "Pulling", "metadata"))
<ide> imgJSON, imgSize, err := r.GetRemoteImageJSON(id, endpoint, token)
<ide> if err != nil {
<del> out.Write(sf.FormatProgress(utils.TruncateID(id), "Error", "pulling dependend layers"))
<add> out.Write(sf.FormatProgress(utils.TruncateID(id), "Error", "pulling dependent layers"))
<ide> // FIXME: Keep going in case of error?
<ide> return err
<ide> }
<ide> img, err := NewImgJSON(imgJSON)
<ide> if err != nil {
<del> out.Write(sf.FormatProgress(utils.TruncateID(id), "Error", "pulling dependend layers"))
<add> out.Write(sf.FormatProgress(utils.TruncateID(id), "Error", "pulling dependent layers"))
<ide> return fmt.Errorf("Failed to parse json: %s", err)
<ide> }
<ide>
<ide> // Get the layer
<ide> out.Write(sf.FormatProgress(utils.TruncateID(id), "Pulling", "fs layer"))
<ide> layer, err := r.GetRemoteImageLayer(img.ID, endpoint, token)
<ide> if err != nil {
<del> out.Write(sf.FormatProgress(utils.TruncateID(id), "Error", "pulling dependend layers"))
<add> out.Write(sf.FormatProgress(utils.TruncateID(id), "Error", "pulling dependent layers"))
<ide> return err
<ide> }
<ide> defer layer.Close()
<ide> if err := srv.runtime.graph.Register(imgJSON, utils.ProgressReader(layer, imgSize, out, sf.FormatProgress(utils.TruncateID(id), "Downloading", "%8v/%v (%v)"), sf, false), img); err != nil {
<del> out.Write(sf.FormatProgress(utils.TruncateID(id), "Error", "downloading dependend layers"))
<add> out.Write(sf.FormatProgress(utils.TruncateID(id), "Error", "downloading dependent layers"))
<ide> return err
<ide> }
<ide> } | 1 |
Text | Text | update rails 5 release notes with syntax fixes | b96e5ea2e158d5f19406a4b25f7a5b5945c5cb2f | <ide><path>guides/source/5_0_release_notes.md
<ide> It also changes the behavior of values passed to `ActiveRecord::Base.where`, whi
<ide> without having to rely on implementation details or monkey patching.
<ide>
<ide> Some things that you can achieve with this:
<add>
<ide> * The type detected by Active Record can be overridden.
<ide> * A default can also be provided.
<ide> * Attributes do not need to be backed by a database column.
<ide> model.attributes #=> {field_without_db_column: [1, 2, 3]}
<ide> **Creating Custom Types:**
<ide>
<ide> You can define your own custom types, as long as they respond
<del>to the methods defined on the value type. The method +deserialize+ or
<del>+cast+ will be called on your type object, with raw input from the
<add>to the methods defined on the value type. The method `deserialize` or
<add>`cast` will be called on your type object, with raw input from the
<ide> database or from your controllers. This is useful, for example, when doing custom conversion,
<ide> like Money data.
<ide>
<ide> **Querying:**
<ide>
<ide> When `ActiveRecord::Base.where` is called, it will
<ide> use the type defined by the model class to convert the value to SQL,
<del>calling +serialize+ on your type object.
<add>calling `serialize` on your type object.
<ide>
<ide> This gives the objects ability to specify, how to convert values when performing SQL queries.
<ide> | 1 |
Javascript | Javascript | use useragentdata in favour of useragent | 2d96c9d78023d75115152f9f520ea51dcf94c958 | <ide><path>src/js/tech/html5.js
<ide> class Html5 extends Tech {
<ide> // Our goal should be to get the custom controls on mobile solid everywhere
<ide> // so we can remove this all together. Right now this will block custom
<ide> // controls on touch enabled laptops like the Chrome Pixel
<del> if ((browser.TOUCH_ENABLED || browser.IS_IPHONE ||
<del> browser.IS_NATIVE_ANDROID) && options.nativeControlsForTouch === true) {
<add> if ((browser.TOUCH_ENABLED || browser.IS_IPHONE) && options.nativeControlsForTouch === true) {
<ide> this.setControls(true);
<ide> }
<ide>
<ide> class Html5 extends Tech {
<ide> */
<ide> supportsFullScreen() {
<ide> if (typeof this.el_.webkitEnterFullScreen === 'function') {
<del> const userAgent = window.navigator && window.navigator.userAgent || '';
<del>
<del> // Seems to be broken in Chromium/Chrome && Safari in Leopard
<del> if ((/Android/).test(userAgent) || !(/Chrome|Mac OS X 10.5/).test(userAgent)) {
<add> // Still needed?
<add> if (browser.IS_ANDROID) {
<ide> return true;
<ide> }
<ide> }
<ide> Html5.prototype.featuresTimeupdateEvents = true;
<ide> */
<ide> Html5.prototype.featuresVideoFrameCallback = !!(Html5.TEST_VID && Html5.TEST_VID.requestVideoFrameCallback);
<ide>
<del>// HTML5 Feature detection and Device Fixes --------------------------------- //
<del>let canPlayType;
<del>
<del>Html5.patchCanPlayType = function() {
<del>
<del> // Android 4.0 and above can play HLS to some extent but it reports being unable to do so
<del> // Firefox and Chrome report correctly
<del> if (browser.ANDROID_VERSION >= 4.0 && !browser.IS_FIREFOX && !browser.IS_CHROME) {
<del> canPlayType = Html5.TEST_VID && Html5.TEST_VID.constructor.prototype.canPlayType;
<del> Html5.TEST_VID.constructor.prototype.canPlayType = function(type) {
<del> const mpegurlRE = /^application\/(?:x-|vnd\.apple\.)mpegurl/i;
<del>
<del> if (type && mpegurlRE.test(type)) {
<del> return 'maybe';
<del> }
<del> return canPlayType.call(this, type);
<del> };
<del> }
<del>};
<del>
<del>Html5.unpatchCanPlayType = function() {
<del> const r = Html5.TEST_VID.constructor.prototype.canPlayType;
<del>
<del> if (canPlayType) {
<del> Html5.TEST_VID.constructor.prototype.canPlayType = canPlayType;
<del> }
<del> return r;
<del>};
<del>
<del>// by default, patch the media element
<del>Html5.patchCanPlayType();
<del>
<ide> Html5.disposeMediaElement = function(el) {
<ide> if (!el) {
<ide> return;
<ide><path>src/js/utils/browser.js
<ide> import * as Dom from './dom';
<ide> import window from 'global/window';
<ide>
<del>const USER_AGENT = window.navigator && window.navigator.userAgent || '';
<del>const webkitVersionMap = (/AppleWebKit\/([\d.]+)/i).exec(USER_AGENT);
<del>const appleWebkitVersion = webkitVersionMap ? parseFloat(webkitVersionMap.pop()) : null;
<del>
<ide> /**
<ide> * Whether or not this device is an iPod.
<ide> *
<ide> * @static
<del> * @const
<ide> * @type {Boolean}
<ide> */
<del>export const IS_IPOD = (/iPod/i).test(USER_AGENT);
<add>export let IS_IPOD = false;
<ide>
<ide> /**
<ide> * The detected iOS version - or `null`.
<ide> *
<ide> * @static
<del> * @const
<ide> * @type {string|null}
<ide> */
<del>export const IOS_VERSION = (function() {
<del> const match = USER_AGENT.match(/OS (\d+)_/i);
<del>
<del> if (match && match[1]) {
<del> return match[1];
<del> }
<del> return null;
<del>}());
<add>export let IOS_VERSION = null;
<ide>
<ide> /**
<ide> * Whether or not this is an Android device.
<ide> *
<ide> * @static
<del> * @const
<ide> * @type {Boolean}
<ide> */
<del>export const IS_ANDROID = (/Android/i).test(USER_AGENT);
<add>export let IS_ANDROID = false;
<ide>
<ide> /**
<del> * The detected Android version - or `null`.
<add> * The detected Android version - or `null` if not Android or indeterminable.
<ide> *
<ide> * @static
<del> * @const
<ide> * @type {number|string|null}
<ide> */
<del>export const ANDROID_VERSION = (function() {
<del> // This matches Android Major.Minor.Patch versions
<del> // ANDROID_VERSION is Major.Minor as a Number, if Minor isn't available, then only Major is returned
<del> const match = USER_AGENT.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);
<del>
<del> if (!match) {
<del> return null;
<del> }
<del>
<del> const major = match[1] && parseFloat(match[1]);
<del> const minor = match[2] && parseFloat(match[2]);
<del>
<del> if (major && minor) {
<del> return parseFloat(match[1] + '.' + match[2]);
<del> } else if (major) {
<del> return major;
<del> }
<del> return null;
<del>}());
<add>export let ANDROID_VERSION;
<ide>
<ide> /**
<del> * Whether or not this is a native Android browser.
<add> * Whether or not this is Mozilla Firefox.
<ide> *
<ide> * @static
<del> * @const
<ide> * @type {Boolean}
<ide> */
<del>export const IS_NATIVE_ANDROID = IS_ANDROID && ANDROID_VERSION < 5 && appleWebkitVersion < 537;
<add>export let IS_FIREFOX = false;
<ide>
<ide> /**
<del> * Whether or not this is Mozilla Firefox.
<add> * Whether or not this is Microsoft Edge.
<ide> *
<ide> * @static
<del> * @const
<ide> * @type {Boolean}
<ide> */
<del>export const IS_FIREFOX = (/Firefox/i).test(USER_AGENT);
<add>export let IS_EDGE = false;
<ide>
<ide> /**
<del> * Whether or not this is Microsoft Edge.
<add> * Whether or not this is any Chromium Browser
<ide> *
<ide> * @static
<del> * @const
<ide> * @type {Boolean}
<ide> */
<del>export const IS_EDGE = (/Edg/i).test(USER_AGENT);
<add>export let IS_CHROMIUM = false;
<ide>
<ide> /**
<del> * Whether or not this is Google Chrome.
<add> * Whether or not this is any Chromium browser that is not Edge.
<ide> *
<ide> * This will also be `true` for Chrome on iOS, which will have different support
<ide> * as it is actually Safari under the hood.
<ide> *
<add> * Depreacted, as the behaviour to not match Edge was to prevent Legacy Edge's UA matching.
<add> * IS_CHROMIUM should be used instead.
<add> * "Chromium but not Edge" could be explicitly tested with IS_CHROMIUM && !IS_EDGE
<add> *
<ide> * @static
<del> * @const
<add> * @deprecated
<ide> * @type {Boolean}
<ide> */
<del>export const IS_CHROME = !IS_EDGE && ((/Chrome/i).test(USER_AGENT) || (/CriOS/i).test(USER_AGENT));
<add>export let IS_CHROME = false;
<ide>
<ide> /**
<del> * The detected Google Chrome version - or `null`.
<add> * The detected Chromium version - or `null`.
<ide> *
<ide> * @static
<del> * @const
<ide> * @type {number|null}
<ide> */
<del>export const CHROME_VERSION = (function() {
<del> const match = USER_AGENT.match(/(Chrome|CriOS)\/(\d+)/);
<add>export let CHROMIUM_VERSION = null;
<ide>
<del> if (match && match[2]) {
<del> return parseFloat(match[2]);
<del> }
<del> return null;
<del>}());
<add>/**
<add> * The detected Google Chrome version - or `null`.
<add> * This has always been the _Chromium_ version, i.e. would return on Chromium Edge.
<add> * Depreacted, use CHROMIUM_VERSION instead.
<add> *
<add> * @static
<add> * @deprecated
<add> * @type {number|null}
<add> */
<add>export let CHROME_VERSION = null;
<ide>
<ide> /**
<ide> * The detected Internet Explorer version - or `null`.
<ide> *
<ide> * @static
<del> * @const
<add> * @deprecated
<ide> * @type {number|null}
<ide> */
<del>export const IE_VERSION = (function() {
<del> const result = (/MSIE\s(\d+)\.\d/).exec(USER_AGENT);
<del> let version = result && parseFloat(result[1]);
<del>
<del> if (!version && (/Trident\/7.0/i).test(USER_AGENT) && (/rv:11.0/).test(USER_AGENT)) {
<del> // IE 11 has a different user agent string than other IE versions
<del> version = 11.0;
<del> }
<del>
<del> return version;
<del>}());
<add>export let IE_VERSION = null;
<ide>
<ide> /**
<ide> * Whether or not this is desktop Safari.
<ide> *
<ide> * @static
<del> * @const
<ide> * @type {Boolean}
<ide> */
<del>export const IS_SAFARI = (/Safari/i).test(USER_AGENT) && !IS_CHROME && !IS_ANDROID && !IS_EDGE;
<add>export let IS_SAFARI = false;
<ide>
<ide> /**
<ide> * Whether or not this is a Windows machine.
<ide> *
<ide> * @static
<del> * @const
<ide> * @type {Boolean}
<ide> */
<del>export const IS_WINDOWS = (/Windows/i).test(USER_AGENT);
<add>export let IS_WINDOWS = false;
<ide>
<ide> /**
<del> * Whether or not this device is touch-enabled.
<add> * Whether or not this device is an iPad.
<ide> *
<ide> * @static
<del> * @const
<ide> * @type {Boolean}
<ide> */
<del>export const TOUCH_ENABLED = Boolean(Dom.isReal() && (
<del> 'ontouchstart' in window ||
<del> window.navigator.maxTouchPoints ||
<del> window.DocumentTouch && window.document instanceof window.DocumentTouch));
<add>export let IS_IPAD = false;
<ide>
<ide> /**
<del> * Whether or not this device is an iPad.
<add> * Whether or not this device is an iPhone.
<ide> *
<ide> * @static
<del> * @const
<ide> * @type {Boolean}
<ide> */
<del>export const IS_IPAD = (/iPad/i).test(USER_AGENT) ||
<del> (IS_SAFARI && TOUCH_ENABLED && !(/iPhone/i).test(USER_AGENT));
<add>// The Facebook app's UIWebView identifies as both an iPhone and iPad, so
<add>// to identify iPhones, we need to exclude iPads.
<add>// http://artsy.github.io/blog/2012/10/18/the-perils-of-ios-user-agent-sniffing/
<add>export let IS_IPHONE = false;
<ide>
<ide> /**
<del> * Whether or not this device is an iPhone.
<add> * Whether or not this device is touch-enabled.
<ide> *
<ide> * @static
<ide> * @const
<ide> * @type {Boolean}
<ide> */
<del>// The Facebook app's UIWebView identifies as both an iPhone and iPad, so
<del>// to identify iPhones, we need to exclude iPads.
<del>// http://artsy.github.io/blog/2012/10/18/the-perils-of-ios-user-agent-sniffing/
<del>export const IS_IPHONE = (/iPhone/i).test(USER_AGENT) && !IS_IPAD;
<add>export const TOUCH_ENABLED = Boolean(Dom.isReal() && (
<add> 'ontouchstart' in window ||
<add> window.navigator.maxTouchPoints ||
<add> window.DocumentTouch && window.document instanceof window.DocumentTouch));
<add>
<add>const UAD = window.navigator && window.navigator.userAgentData;
<add>
<add>if (UAD) {
<add> // If userAgentData is present, use it instead of userAgent to avoid warnings
<add> // Currently only implemented on Chromium
<add> // userAgentData does not expose Android version, so ANDROID_VERSION remains `null`
<add>
<add> IS_ANDROID = UAD.platform === 'Android';
<add> IS_EDGE = Boolean(UAD.brands.find(b => b.brand === 'Microsoft Edge'));
<add> IS_CHROMIUM = Boolean(UAD.brands.find(b => b.brand === 'Chromium'));
<add> IS_CHROME = !IS_EDGE && IS_CHROMIUM;
<add> CHROMIUM_VERSION = CHROME_VERSION = (UAD.brands.find(b => b.brand === 'Chromium') || {}).version || null;
<add> IS_WINDOWS = UAD.platform === 'Windows';
<add>}
<add>
<add>// If the broser is not Chromium, either userAgentData is not present which could be an old Chromium browser,
<add>// or it's a browser that has added userAgentData since that we don't have tests for yet. In either case,
<add>// the checks need to be made agiainst the regular userAgent string.
<add>if (!IS_CHROMIUM) {
<add> const USER_AGENT = window.navigator && window.navigator.userAgent || '';
<add>
<add> IS_IPOD = (/iPod/i).test(USER_AGENT);
<add>
<add> IOS_VERSION = (function() {
<add> const match = USER_AGENT.match(/OS (\d+)_/i);
<add>
<add> if (match && match[1]) {
<add> return match[1];
<add> }
<add> return null;
<add> }());
<add>
<add> IS_ANDROID = (/Android/i).test(USER_AGENT);
<add>
<add> ANDROID_VERSION = (function() {
<add> // This matches Android Major.Minor.Patch versions
<add> // ANDROID_VERSION is Major.Minor as a Number, if Minor isn't available, then only Major is returned
<add> const match = USER_AGENT.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);
<add>
<add> if (!match) {
<add> return null;
<add> }
<add>
<add> const major = match[1] && parseFloat(match[1]);
<add> const minor = match[2] && parseFloat(match[2]);
<add>
<add> if (major && minor) {
<add> return parseFloat(match[1] + '.' + match[2]);
<add> } else if (major) {
<add> return major;
<add> }
<add> return null;
<add> }());
<add>
<add> IS_FIREFOX = (/Firefox/i).test(USER_AGENT);
<add>
<add> IS_EDGE = (/Edg/i).test(USER_AGENT);
<add>
<add> IS_CHROMIUM = ((/Chrome/i).test(USER_AGENT) || (/CriOS/i).test(USER_AGENT));
<add>
<add> IS_CHROME = !IS_EDGE && IS_CHROMIUM;
<add>
<add> CHROMIUM_VERSION = CHROME_VERSION = (function() {
<add> const match = USER_AGENT.match(/(Chrome|CriOS)\/(\d+)/);
<add>
<add> if (match && match[2]) {
<add> return parseFloat(match[2]);
<add> }
<add> return null;
<add> }());
<add>
<add> IE_VERSION = (function() {
<add> const result = (/MSIE\s(\d+)\.\d/).exec(USER_AGENT);
<add> let version = result && parseFloat(result[1]);
<add>
<add> if (!version && (/Trident\/7.0/i).test(USER_AGENT) && (/rv:11.0/).test(USER_AGENT)) {
<add> // IE 11 has a different user agent string than other IE versions
<add> version = 11.0;
<add> }
<add>
<add> return version;
<add> }());
<add>
<add> IS_SAFARI = (/Safari/i).test(USER_AGENT) && !IS_CHROME && !IS_ANDROID && !IS_EDGE;
<add>
<add> IS_WINDOWS = (/Windows/i).test(USER_AGENT);
<add>
<add> IS_IPAD = (/iPad/i).test(USER_AGENT) ||
<add> (IS_SAFARI && TOUCH_ENABLED && !(/iPhone/i).test(USER_AGENT));
<add>
<add> IS_IPHONE = (/iPhone/i).test(USER_AGENT) && !IS_IPAD;
<add>}
<ide>
<ide> /**
<ide> * Whether or not this is an iOS device.
<ide><path>test/unit/tech/html5.test.js
<ide> QUnit.test('should remove the controls attribute when recreating the element', f
<ide> assert.ok(player.tagAttributes.controls, 'tag attribute is still present');
<ide> });
<ide>
<del>QUnit.test('patchCanPlayType patches canplaytype with our function, conditionally', function(assert) {
<del> // the patch runs automatically so we need to first unpatch
<del> Html5.unpatchCanPlayType();
<del>
<del> const oldAV = browser.ANDROID_VERSION;
<del> const oldIsFirefox = browser.IS_FIREFOX;
<del> const oldIsChrome = browser.IS_CHROME;
<del> const video = document.createElement('video');
<del> const canPlayType = Html5.TEST_VID.constructor.prototype.canPlayType;
<del>
<del> browser.stub_ANDROID_VERSION(4.0);
<del> browser.stub_IS_FIREFOX(false);
<del> browser.stub_IS_CHROME(false);
<del> Html5.patchCanPlayType();
<del>
<del> assert.notStrictEqual(
<del> video.canPlayType,
<del> canPlayType,
<del> 'original canPlayType and patched canPlayType should not be equal'
<del> );
<del>
<del> const patchedCanPlayType = video.canPlayType;
<del> const unpatchedCanPlayType = Html5.unpatchCanPlayType();
<del>
<del> assert.strictEqual(
<del> canPlayType,
<del> Html5.TEST_VID.constructor.prototype.canPlayType,
<del> 'original canPlayType and unpatched canPlayType should be equal'
<del> );
<del> assert.strictEqual(
<del> patchedCanPlayType,
<del> unpatchedCanPlayType,
<del> 'patched canPlayType and function returned from unpatch are equal'
<del> );
<del>
<del> browser.stub_ANDROID_VERSION(oldAV);
<del> browser.stub_IS_FIREFOX(oldIsFirefox);
<del> browser.stub_IS_CHROME(oldIsChrome);
<del> Html5.unpatchCanPlayType();
<del>});
<del>
<del>QUnit.test('patchCanPlayType doesn\'t patch canplaytype with our function in Chrome for Android', function(assert) {
<del> // the patch runs automatically so we need to first unpatch
<del> Html5.unpatchCanPlayType();
<del>
<del> const oldAV = browser.ANDROID_VERSION;
<del> const oldIsChrome = browser.IS_CHROME;
<del> const oldIsFirefox = browser.IS_FIREFOX;
<del> const video = document.createElement('video');
<del> const canPlayType = Html5.TEST_VID.constructor.prototype.canPlayType;
<del>
<del> browser.stub_ANDROID_VERSION(4.0);
<del> browser.stub_IS_CHROME(true);
<del> browser.stub_IS_FIREFOX(false);
<del> Html5.patchCanPlayType();
<del>
<del> assert.strictEqual(
<del> video.canPlayType,
<del> canPlayType,
<del> 'original canPlayType and patched canPlayType should be equal'
<del> );
<del>
<del> browser.stub_ANDROID_VERSION(oldAV);
<del> browser.stub_IS_CHROME(oldIsChrome);
<del> browser.stub_IS_FIREFOX(oldIsFirefox);
<del> Html5.unpatchCanPlayType();
<del>});
<del>
<del>QUnit.test('patchCanPlayType doesn\'t patch canplaytype with our function in Firefox for Android', function(assert) {
<del> // the patch runs automatically so we need to first unpatch
<del> Html5.unpatchCanPlayType();
<del>
<del> const oldAV = browser.ANDROID_VERSION;
<del> const oldIsFirefox = browser.IS_FIREFOX;
<del> const oldIsChrome = browser.IS_CHROME;
<del> const video = document.createElement('video');
<del> const canPlayType = Html5.TEST_VID.constructor.prototype.canPlayType;
<del>
<del> browser.stub_ANDROID_VERSION(4.0);
<del> browser.stub_IS_FIREFOX(true);
<del> browser.stub_IS_CHROME(false);
<del> Html5.patchCanPlayType();
<del>
<del> assert.strictEqual(
<del> video.canPlayType,
<del> canPlayType,
<del> 'original canPlayType and patched canPlayType should be equal'
<del> );
<del>
<del> browser.stub_ANDROID_VERSION(oldAV);
<del> browser.stub_IS_FIREFOX(oldIsFirefox);
<del> browser.stub_IS_CHROME(oldIsChrome);
<del> Html5.unpatchCanPlayType();
<del>});
<del>
<del>QUnit.test('should return maybe for HLS urls on Android 4.0 or above when not Chrome or Firefox', function(assert) {
<del> const oldAV = browser.ANDROID_VERSION;
<del> const oldIsFirefox = browser.IS_FIREFOX;
<del> const oldIsChrome = browser.IS_CHROME;
<del> const video = document.createElement('video');
<del>
<del> browser.stub_ANDROID_VERSION(4.0);
<del> browser.stub_IS_FIREFOX(false);
<del> browser.stub_IS_CHROME(false);
<del> Html5.patchCanPlayType();
<del>
<del> assert.strictEqual(
<del> video.canPlayType('application/x-mpegurl'),
<del> 'maybe',
<del> 'android version 4.0 or above should be a maybe for x-mpegurl'
<del> );
<del> assert.strictEqual(
<del> video.canPlayType('application/x-mpegURL'),
<del> 'maybe',
<del> 'android version 4.0 or above should be a maybe for x-mpegURL'
<del> );
<del> assert.strictEqual(
<del> video.canPlayType('application/vnd.apple.mpegurl'),
<del> 'maybe',
<del> 'android version 4.0 or above should be a ' +
<del> 'maybe for vnd.apple.mpegurl'
<del> );
<del> assert.strictEqual(
<del> video.canPlayType('application/vnd.apple.mpegURL'),
<del> 'maybe',
<del> 'android version 4.0 or above should be a ' +
<del> 'maybe for vnd.apple.mpegurl'
<del> );
<del>
<del> browser.stub_ANDROID_VERSION(oldAV);
<del> browser.stub_IS_FIREFOX(oldIsFirefox);
<del> browser.stub_IS_CHROME(oldIsChrome);
<del> Html5.unpatchCanPlayType();
<del>});
<del>
<ide> QUnit.test('error events may not set the errors property', function(assert) {
<ide> assert.equal(tech.error(), undefined, 'no tech-level error');
<ide> tech.trigger('error'); | 3 |
PHP | PHP | use a regex to test for placeholders | ed358f0fc258e1498c0763b5d047068552454b04 | <ide><path>src/Database/QueryCompiler.php
<ide> public function compile(Query $query, ValueBinder $generator)
<ide> if ($query->valueBinder() !== $generator) {
<ide> foreach ($query->valueBinder()->bindings() as $binding) {
<ide> $placeholder = ':' . $binding['placeholder'];
<del> if (strpos($sql, $placeholder) !== false) {
<add> if (preg_match('/' . $placeholder . '(?:\W|$)/', $sql) > 0) {
<ide> $generator->bind($placeholder, $binding['value'], $binding['type']);
<ide> }
<ide> } | 1 |
Python | Python | fix flags to force_v2_in_keras_compile | d09994b26ac8592765be45dc8a8444ead55eb32b | <ide><path>official/resnet/keras/keras_imagenet_benchmark.py
<ide> def benchmark_1_gpu_no_dist_strat_run_eagerly(self):
<ide> FLAGS.batch_size = 64
<ide> self._run_and_report_benchmark()
<ide>
<del> def benchmark_1_gpu_force_dist_strat_run_eagerly(self):
<del> """No dist strat but forced ds tf.compile path and force eager."""
<add> def benchmark_1_gpu_no_dist_strat_force_v2_run_eagerly(self):
<add> """Forced v2 execution in tf.compile path and force eager."""
<ide> self._setup()
<ide>
<ide> FLAGS.num_gpus = 1
<ide> def benchmark_1_gpu_force_dist_strat_run_eagerly(self):
<ide> FLAGS.model_dir = self._get_model_dir(
<ide> 'benchmark_1_gpu_force_dist_strat_run_eagerly')
<ide> FLAGS.batch_size = 64
<del> FLAGS.force_run_distributed = True
<add> FLAGS.force_v2_in_keras_compile = True
<ide> self._run_and_report_benchmark()
<ide>
<del> def benchmark_1_gpu_force_dist_strat(self):
<del> """No dist strat but forced ds tf.compile path."""
<add> def benchmark_1_gpu_no_dist_strat_force_v2(self):
<add> """No dist strat but forced v2 execution tf.compile path."""
<ide> self._setup()
<ide>
<ide> FLAGS.num_gpus = 1
<ide> def benchmark_1_gpu_force_dist_strat(self):
<ide> FLAGS.model_dir = self._get_model_dir(
<ide> 'benchmark_1_gpu_force_dist_strat')
<ide> FLAGS.batch_size = 128
<del> FLAGS.force_run_distributed = True
<add> FLAGS.force_v2_in_keras_compile = True
<ide> self._run_and_report_benchmark()
<ide>
<ide> def benchmark_1_gpu_no_dist_strat_run_eagerly_fp16(self): | 1 |
Java | Java | reduce byte[] allocations in stompencoder | 95ef9c25c2f68b25e430922aad091dd985cf2a6f | <ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/StompEncoder.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>
<ide> package org.springframework.messaging.simp.stomp;
<ide>
<del>import java.io.ByteArrayOutputStream;
<del>import java.io.DataOutputStream;
<del>import java.io.IOException;
<ide> import java.nio.charset.StandardCharsets;
<ide> import java.util.Collections;
<ide> import java.util.LinkedHashMap;
<add>import java.util.LinkedList;
<ide> import java.util.List;
<ide> import java.util.Map;
<ide> import java.util.Map.Entry;
<ide> */
<ide> public class StompEncoder {
<ide>
<del> private static final byte LF = '\n';
<add> private static final Byte LINE_FEED_BYTE = '\n';
<ide>
<del> private static final byte COLON = ':';
<add> private static final Byte COLON_BYTE = ':';
<ide>
<ide> private static final Log logger = SimpLogging.forLogName(StompEncoder.class);
<ide>
<ide> public byte[] encode(Map<String, Object> headers, byte[] payload) {
<ide> Assert.notNull(headers, "'headers' is required");
<ide> Assert.notNull(payload, "'payload' is required");
<ide>
<del> try {
<del> ByteArrayOutputStream baos = new ByteArrayOutputStream(128 + payload.length);
<del> DataOutputStream output = new DataOutputStream(baos);
<del>
<del> if (SimpMessageType.HEARTBEAT.equals(SimpMessageHeaderAccessor.getMessageType(headers))) {
<del> logger.trace("Encoding heartbeat");
<del> output.write(StompDecoder.HEARTBEAT_PAYLOAD);
<del> }
<del>
<del> else {
<del> StompCommand command = StompHeaderAccessor.getCommand(headers);
<del> if (command == null) {
<del> throw new IllegalStateException("Missing STOMP command: " + headers);
<del> }
<del>
<del> output.write(command.toString().getBytes(StandardCharsets.UTF_8));
<del> output.write(LF);
<del> writeHeaders(command, headers, payload, output);
<del> output.write(LF);
<del> writeBody(payload, output);
<del> output.write((byte) 0);
<del> }
<del>
<del> return baos.toByteArray();
<add> if (SimpMessageType.HEARTBEAT.equals(SimpMessageHeaderAccessor.getMessageType(headers))) {
<add> logger.trace("Encoding heartbeat");
<add> return StompDecoder.HEARTBEAT_PAYLOAD;
<ide> }
<del> catch (IOException ex) {
<del> throw new StompConversionException("Failed to encode STOMP frame, headers=" + headers, ex);
<add>
<add> StompCommand command = StompHeaderAccessor.getCommand(headers);
<add> if (command == null) {
<add> throw new IllegalStateException("Missing STOMP command: " + headers);
<ide> }
<add>
<add> Result result = new DefaultResult();
<add> result.add(command.toString().getBytes(StandardCharsets.UTF_8));
<add> result.add(LINE_FEED_BYTE);
<add> writeHeaders(command, headers, payload, result);
<add> result.add(LINE_FEED_BYTE);
<add> result.add(payload);
<add> result.add((byte) 0);
<add> return result.toByteArray();
<ide> }
<ide>
<del> private void writeHeaders(StompCommand command, Map<String, Object> headers, byte[] payload,
<del> DataOutputStream output) throws IOException {
<add> private void writeHeaders(
<add> StompCommand command, Map<String, Object> headers, byte[] payload, Result result) {
<ide>
<ide> @SuppressWarnings("unchecked")
<ide> Map<String,List<String>> nativeHeaders =
<ide> private void writeHeaders(StompCommand command, Map<String, Object> headers, byt
<ide>
<ide> byte[] encodedKey = encodeHeaderKey(entry.getKey(), shouldEscape);
<ide> for (String value : values) {
<del> output.write(encodedKey);
<del> output.write(COLON);
<del> output.write(encodeHeaderValue(value, shouldEscape));
<del> output.write(LF);
<add> result.add(encodedKey);
<add> result.add(COLON_BYTE);
<add> result.add(encodeHeaderValue(value, shouldEscape));
<add> result.add(LINE_FEED_BYTE);
<ide> }
<ide> }
<ide>
<ide> if (command.requiresContentLength()) {
<ide> int contentLength = payload.length;
<del> output.write("content-length:".getBytes(StandardCharsets.UTF_8));
<del> output.write(Integer.toString(contentLength).getBytes(StandardCharsets.UTF_8));
<del> output.write(LF);
<add> result.add("content-length:".getBytes(StandardCharsets.UTF_8));
<add> result.add(Integer.toString(contentLength).getBytes(StandardCharsets.UTF_8));
<add> result.add(LINE_FEED_BYTE);
<ide> }
<ide> }
<ide>
<ide> private StringBuilder getStringBuilder(@Nullable StringBuilder sb, String inStri
<ide> return sb;
<ide> }
<ide>
<del> private void writeBody(byte[] payload, DataOutputStream output) throws IOException {
<del> output.write(payload);
<add>
<add> /**
<add> * Accumulates byte content and returns an aggregated byte[] at the end.
<add> */
<add> private interface Result {
<add>
<add> void add(byte[] bytes);
<add>
<add> void add(byte b);
<add>
<add> byte[] toByteArray();
<add>
<add> }
<add>
<add> @SuppressWarnings("serial")
<add> private static class DefaultResult extends LinkedList<Object> implements Result {
<add>
<add> private int size;
<add>
<add>
<add> public void add(byte[] bytes) {
<add> this.size += bytes.length;
<add> super.add(bytes);
<add> }
<add>
<add> public void add(byte b) {
<add> this.size++;
<add> super.add(b);
<add> }
<add>
<add> public byte[] toByteArray() {
<add> byte[] result = new byte[this.size];
<add> int position = 0;
<add> for (Object o : this) {
<add> if (o instanceof byte[]) {
<add> byte[] src = (byte[]) o;
<add> System.arraycopy(src, 0, result, position, src.length);
<add> position += src.length;
<add> }
<add> else {
<add> result[position++] = (Byte) o;
<add> }
<add> }
<add> return result;
<add> }
<ide> }
<ide>
<ide> } | 1 |
PHP | PHP | remove validationerrors properties | 91ff33629d5f55ed018085c23322af1198852b57 | <ide><path>src/Controller/Controller.php
<ide> class Controller implements EventListener {
<ide> */
<ide> public $methods = array();
<ide>
<del>/**
<del> * Holds any validation errors produced by the last call of the validateErrors() method/
<del> *
<del> * @var array
<del> */
<del> public $validationErrors = null;
<del>
<ide> /**
<ide> * Instance of the Cake\Event\EventManager this controller is using
<ide> * to dispatch inner events.
<ide><path>src/View/View.php
<ide> class View {
<ide> */
<ide> public $cacheAction = false;
<ide>
<del>/**
<del> * Holds current errors for the model validation.
<del> *
<del> * @var array
<del> */
<del> public $validationErrors = array();
<del>
<ide> /**
<ide> * True when the view has been rendered.
<ide> *
<ide><path>tests/TestCase/Utility/DebuggerTest.php
<ide> public function testExportVar() {
<ide> subDir => null
<ide> theme => null
<ide> cacheAction => false
<del> validationErrors => []
<ide> hasRendered => false
<ide> uuids => []
<ide> request => object(Cake\Network\Request) {} | 3 |
Python | Python | fix slow ci by pinning resampy | 9bd3968509010378c32009ed632f96fd69d1f3b8 | <ide><path>setup.py
<ide> "ray[tune]",
<ide> "regex!=2019.12.17",
<ide> "requests",
<add> "resampy<0.3.1",
<ide> "rjieba",
<ide> "rouge-score",
<ide> "sacrebleu>=1.4.12,<2.0.0",
<ide> def run(self):
<ide> extras["integrations"] = extras["optuna"] + extras["ray"] + extras["sigopt"]
<ide>
<ide> extras["serving"] = deps_list("pydantic", "uvicorn", "fastapi", "starlette")
<del>extras["audio"] = deps_list("librosa", "pyctcdecode", "phonemizer")
<add>extras["audio"] = deps_list("librosa", "pyctcdecode", "phonemizer", "resampy") # resampy can be removed once unpinned.
<ide> # `pip install ".[speech]"` is deprecated and `pip install ".[torch-speech]"` should be used instead
<ide> extras["speech"] = deps_list("torchaudio") + extras["audio"]
<ide> extras["torch-speech"] = deps_list("torchaudio") + extras["audio"]
<ide><path>src/transformers/dependency_versions_table.py
<ide> "ray[tune]": "ray[tune]",
<ide> "regex": "regex!=2019.12.17",
<ide> "requests": "requests",
<add> "resampy": "resampy<0.3.1",
<ide> "rjieba": "rjieba",
<ide> "rouge-score": "rouge-score",
<ide> "sacrebleu": "sacrebleu>=1.4.12,<2.0.0", | 2 |
Text | Text | make building with ninja more discoverable | d5e94fa7121c9d424588f0e1a388f8c72c784622 | <ide><path>BUILDING.md
<ide> $ ./configure
<ide> $ make -j4
<ide> ```
<ide>
<add>We can speed up the builds by using [Ninja](https://ninja-build.org/). For more
<add>information, see
<add>[Building Node.js with Ninja](doc/contributing/building-node-with-ninja.md).
<add>
<ide> The `-j4` option will cause `make` to run 4 simultaneous compilation jobs which
<ide> may reduce build time. For more information, see the
<ide> [GNU Make Documentation](https://www.gnu.org/software/make/manual/html_node/Parallel.html).
<ide><path>doc/contributing/pull-requests.md
<ide> test suite. To run the tests (including code linting) on Unix / macOS:
<ide> ./configure && make -j4 test
<ide> ```
<ide>
<add>We can speed up the builds by using [Ninja](https://ninja-build.org/). For more
<add>information, see
<add>[Building Node.js with Ninja](building-node-with-ninja.md).
<add>
<ide> And on Windows:
<ide>
<ide> ```text | 2 |
Text | Text | fix v2.0.2 entry in changelog.md | c7fb91dc1310f9454d4aa8091bcc6d305322a72f | <ide><path>CHANGELOG.md
<ide> # io.js ChangeLog
<ide>
<del>## 2015-05-15, Version 2.0.1, @Fishrock123
<add>## 2015-05-15, Version 2.0.2, @Fishrock123
<ide>
<ide> ### Notable changes
<ide> | 1 |
Ruby | Ruby | add debug information for empty bom error | c32415529532369c6fffdd34c95da1ee21546f87 | <ide><path>Library/Homebrew/unpack_strategy/dmg.rb
<ide> def extract_to_dir(unpack_dir, basename:, verbose:)
<ide> Tempfile.open(["", ".bom"]) do |bomfile|
<ide> bomfile.close
<ide>
<add> bom = path.bom
<add>
<ide> Tempfile.open(["", ".list"]) do |filelist|
<del> filelist.puts(path.bom)
<add> filelist.puts(bom)
<ide> filelist.close
<ide>
<ide> system_command! "mkbom",
<ide> args: ["-s", "-i", filelist.path, "--", bomfile.path],
<ide> verbose: verbose
<ide> end
<ide>
<del> system_command! "ditto",
<del> args: ["--bom", bomfile.path, "--", path, unpack_dir],
<del> verbose: verbose
<add> result = system_command! "ditto",
<add> args: ["--bom", bomfile.path, "--", path, unpack_dir],
<add> verbose: verbose
<add>
<add> odebug "BOM contents:", bom
<add> if result.stderr.include?("contains no files, nothing copied")
<add> odebug "Directory contents:", Pathname.glob(path/"**/*", File::FNM_DOTMATCH).map(&:to_s).join("\n")
<add> end
<ide>
<ide> FileUtils.chmod "u+w", Pathname.glob(unpack_dir/"**/*", File::FNM_DOTMATCH).reject(&:symlink?)
<ide> end | 1 |
Javascript | Javascript | enhance test-case to verify correct behaviour | c2fb4b6986c13e6484f646ad732c1470d2c353db | <ide><path>test/ngResource/resourceSpec.js
<ide> describe("resource", function() {
<ide> var cc = CreditCard.get({id: 123});
<ide> $httpBackend.flush();
<ide>
<add> cc.$myProp = 'still here';
<add>
<ide> expect(cc.$promise).toBeDefined();
<ide> expect(cc.$resolved).toBe(true);
<ide>
<ide> var json = JSON.parse(angular.toJson(cc));
<ide> expect(json.$promise).not.toBeDefined();
<ide> expect(json.$resolved).not.toBeDefined();
<del> expect(json).toEqual({id: 123, number: '9876'});
<add> expect(json).toEqual({id: 123, number: '9876', $myProp: 'still here'});
<ide> });
<ide>
<ide> describe('promise api', function() { | 1 |
Text | Text | remove irrelevant question from faq | 72d3d724a3a0c6bc46981efd0dad8f7f61121a47 | <ide><path>README.md
<ide> as a static resource in your Xcode project. Then set the `jsCodeLocation` in
<ide> `AppDelegate.m` to point to that file and deploy to your device like you would
<ide> any other app.
<ide>
<del>##### Q. What's up with this private repo? Why aren't you just open sourcing it now?
<del>A. We want input from the React community before we open the floodgates so we
<del>can incorporate your feedback, and we also have a bunch more features we want to
<del>add to make a more complete offering before we open source.
<del>
<ide> ##### Q. Do you have to ship a JS runtime with your apps?
<ide> A. No, we just use the JavaScriptCore public API that is part of iOS 7 and
<ide> later. | 1 |
Mixed | Ruby | add db to the list of default annotation folders | 553b563749517114323b4e8742509227e0daab67 | <ide><path>railties/CHANGELOG.md
<ide> ## Rails 4.0.0 (unreleased) ##
<ide>
<add>* Add `db` to list of folders included by `rake notes` and `rake notes:custom`. *Antonio Cangiano*
<add>
<ide> * Engines with a dummy app include the rake tasks of dependencies in the app namespace.
<ide> Fix #8229
<ide>
<ide><path>railties/lib/rails/source_annotation_extractor.rb
<ide> class SourceAnnotationExtractor
<ide> class Annotation < Struct.new(:line, :tag, :text)
<ide> def self.directories
<del> @@directories ||= %w(app config lib script test) + (ENV['SOURCE_ANNOTATION_DIRECTORIES'] || '').split(',')
<add> @@directories ||= %w(app config db lib script test) + (ENV['SOURCE_ANNOTATION_DIRECTORIES'] || '').split(',')
<ide> end
<ide>
<ide> # Returns a representation of the annotation that looks like this:
<ide><path>railties/test/application/rake/notes_test.rb
<ide> def teardown
<ide> test 'notes finds notes in default directories' do
<ide> app_file "app/controllers/some_controller.rb", "# TODO: note in app directory"
<ide> app_file "config/initializers/some_initializer.rb", "# TODO: note in config directory"
<add> app_file "db/some_seeds.rb", "# TODO: note in db directory"
<ide> app_file "lib/some_file.rb", "# TODO: note in lib directory"
<ide> app_file "script/run_something.rb", "# TODO: note in script directory"
<ide> app_file "test/some_test.rb", 1000.times.map { "" }.join("\n") << "# TODO: note in test directory"
<ide> def teardown
<ide>
<ide> assert_match(/note in app directory/, output)
<ide> assert_match(/note in config directory/, output)
<add> assert_match(/note in db directory/, output)
<ide> assert_match(/note in lib directory/, output)
<ide> assert_match(/note in script directory/, output)
<ide> assert_match(/note in test directory/, output)
<ide> def teardown
<ide> test 'notes finds notes in custom directories' do
<ide> app_file "app/controllers/some_controller.rb", "# TODO: note in app directory"
<ide> app_file "config/initializers/some_initializer.rb", "# TODO: note in config directory"
<add> app_file "db/some_seeds.rb", "# TODO: note in db directory"
<ide> app_file "lib/some_file.rb", "# TODO: note in lib directory"
<ide> app_file "script/run_something.rb", "# TODO: note in script directory"
<ide> app_file "test/some_test.rb", 1000.times.map { "" }.join("\n") << "# TODO: note in test directory"
<ide> def teardown
<ide>
<ide> assert_match(/note in app directory/, output)
<ide> assert_match(/note in config directory/, output)
<add> assert_match(/note in db directory/, output)
<ide> assert_match(/note in lib directory/, output)
<ide> assert_match(/note in script directory/, output)
<ide> assert_match(/note in test directory/, output) | 3 |
Text | Text | fix typos for docker separate build image | 863f638b5344d0c34aea9f688a095b6c2ccc9a5e | <ide><path>guide/english/docker/separate-build-image/index.md
<ide> title: Separate Build Image
<ide> ---
<ide> ## Overview
<ide>
<del>Making lightweight docker images is key to having a fast development/deployment pipeline. For compiled code, building the binary inside a docker container has the benefit of being a repeatable and standardised build process. However, this can create a very large images which can become an issue down the line.
<add>Making lightweight Docker images is key to having a fast development/deployment pipeline. For compiled code, building the binary inside a Docker container has the benefit of being a repeatable and standardised build process. However, this can create a very large images which can become an issue down the line.
<ide>
<ide> ## Our code
<ide>
<del>In this example, we will use a simple webserver writen in [Go](https://golang.org/). The following code is just a simple hello world webserver listening on port `8080`.
<add>In this example, we will use a simple webserver written in [Go](https://golang.org/). The following code is just a simple hello world webserver listening on port `8080`.
<ide>
<ide> ```go
<ide> package main
<ide> EXPOSE 8080
<ide> CMD [ "myserver" ]
<ide> ```
<ide>
<del>Building from this dockerfile results in a final image size of only 6.55MB! That's over **100 times smaller** than our first attempt, making it 100 times faster to pull the image down from a registry!
<add>Building from this Dockerfile results in a final image size of only 6.55MB! That's over **100 times smaller** than our first attempt, making it 100 times faster to pull the image down from a registry!
<ide>
<ide> ### Bonus benefit
<ide>
<del>Not only do we now have a tiny docker image for our application, we also only have to worry about the security of our application as there is no other software running inside the container.
<ide>\ No newline at end of file
<add>Not only do we now have a tiny Docker image for our application, we also only have to worry about the security of our application as there is no other software running inside the container. | 1 |
Javascript | Javascript | reduce benchmark test run time | 85893afb0594d7de479ade90ac309e138e63f8d7 | <ide><path>test/sequential/test-benchmark-buffer.js
<ide> runBenchmark('buffers',
<ide> 'encoding=utf8',
<ide> 'endian=BE',
<ide> 'len=2',
<add> 'millions=0.000001',
<ide> 'method=',
<ide> 'n=1',
<ide> 'noAssert=true', | 1 |
Ruby | Ruby | allow association as 1st uniqueness validation arg | 3b5fbafab014325bdd42a7cae867ee5c92bc3298 | <ide><path>activerecord/lib/active_record/validations/uniqueness.rb
<ide> def find_finder_class_for(record) #:nodoc:
<ide> end
<ide>
<ide> def build_relation(klass, table, attribute, value) #:nodoc:
<del> column = klass.columns_hash[attribute.to_s]
<add> reflection = klass.reflect_on_association(attribute)
<add> column = nil
<add> if(reflection)
<add> column = klass.columns_hash[reflection.foreign_key]
<add> attribute = reflection.foreign_key
<add> value = value.attributes[reflection.primary_key_column.name]
<add> else
<add> column = klass.columns_hash[attribute.to_s]
<add> end
<ide> value = column.limit ? value.to_s[0, column.limit] : value.to_s if !value.nil? && column.text?
<ide>
<ide> if !options[:case_sensitive] && value && column.text?
<ide><path>activerecord/test/cases/validations/uniqueness_validation_test.rb
<ide> def test_validate_uniqueness_with_object_scope
<ide> assert !r2.valid?, "Saving r2 first time"
<ide> end
<ide>
<add> def test_validate_uniqueness_with_object_arg
<add> Reply.validates_uniqueness_of(:topic)
<add>
<add> t = Topic.create("title" => "I'm unique!")
<add>
<add> r1 = t.replies.create "title" => "r1", "content" => "hello world"
<add> assert r1.valid?, "Saving r1"
<add>
<add> r2 = t.replies.create "title" => "r2", "content" => "hello world"
<add> assert !r2.valid?, "Saving r2 first time"
<add> end
<add>
<ide> def test_validate_uniqueness_scoped_to_defining_class
<ide> t = Topic.create("title" => "What, me worry?")
<ide> | 2 |
Text | Text | add docs for fasttest | d5533cfb6d2c5581c5ea7e2dc33d96cdc4d0f076 | <ide><path>README.md
<ide> We use grunt to automate many tasks. Run `grunt -h` to see a mostly complete lis
<ide> grunt test
<ide> # Build and run tests in your browser
<ide> grunt test --debug
<add># For speed, you can use fasttest and add --filter to only run one test
<add>grunt fasttest --filter=ReactIdentity
<ide> # Lint the code with JSHint
<ide> grunt lint
<ide> # Wipe out build directory | 1 |
Text | Text | create nirantk.md [ci skip] | a5d92a30357a729c442d9be432fae48b06601a7e | <ide><path>.github/contributors/NirantK.md
<add># spaCy contributor agreement
<add>
<add>This spaCy Contributor Agreement (**"SCA"**) is based on the
<add>[Oracle Contributor Agreement](http://www.oracle.com/technetwork/oca-405177.pdf).
<add>The SCA applies to any contribution that you make to any product or project
<add>managed by us (the **"project"**), and sets out the intellectual property rights
<add>you grant to us in the contributed materials. The term **"us"** shall mean
<add>[ExplosionAI GmbH](https://explosion.ai/legal). The term
<add>**"you"** shall mean the person or entity identified below.
<add>
<add>If you agree to be bound by these terms, fill in the information requested
<add>below and include the filled-in version with your first pull request, under the
<add>folder [`.github/contributors/`](/.github/contributors/). The name of the file
<add>should be your GitHub username, with the extension `.md`. For example, the user
<add>example_user would create the file `.github/contributors/example_user.md`.
<add>
<add>Read this agreement carefully before signing. These terms and conditions
<add>constitute a binding legal agreement.
<add>
<add>## Contributor Agreement
<add>
<add>1. The term "contribution" or "contributed materials" means any source code,
<add>object code, patch, tool, sample, graphic, specification, manual,
<add>documentation, or any other material posted or submitted by you to the project.
<add>
<add>2. With respect to any worldwide copyrights, or copyright applications and
<add>registrations, in your contribution:
<add>
<add> * you hereby assign to us joint ownership, and to the extent that such
<add> assignment is or becomes invalid, ineffective or unenforceable, you hereby
<add> grant to us a perpetual, irrevocable, non-exclusive, worldwide, no-charge,
<add> royalty-free, unrestricted license to exercise all rights under those
<add> copyrights. This includes, at our option, the right to sublicense these same
<add> rights to third parties through multiple levels of sublicensees or other
<add> licensing arrangements;
<add>
<add> * you agree that each of us can do all things in relation to your
<add> contribution as if each of us were the sole owners, and if one of us makes
<add> a derivative work of your contribution, the one who makes the derivative
<add> work (or has it made will be the sole owner of that derivative work;
<add>
<add> * you agree that you will not assert any moral rights in your contribution
<add> against us, our licensees or transferees;
<add>
<add> * you agree that we may register a copyright in your contribution and
<add> exercise all ownership rights associated with it; and
<add>
<add> * you agree that neither of us has any duty to consult with, obtain the
<add> consent of, pay or render an accounting to the other for any use or
<add> distribution of your contribution.
<add>
<add>3. With respect to any patents you own, or that you can license without payment
<add>to any third party, you hereby grant to us a perpetual, irrevocable,
<add>non-exclusive, worldwide, no-charge, royalty-free license to:
<add>
<add> * make, have made, use, sell, offer to sell, import, and otherwise transfer
<add> your contribution in whole or in part, alone or in combination with or
<add> included in any product, work or materials arising out of the project to
<add> which your contribution was submitted, and
<add>
<add> * at our option, to sublicense these same rights to third parties through
<add> multiple levels of sublicensees or other licensing arrangements.
<add>
<add>4. Except as set out above, you keep all right, title, and interest in your
<add>contribution. The rights that you grant to us under these terms are effective
<add>on the date you first submitted a contribution to us, even if your submission
<add>took place before the date you sign these terms.
<add>
<add>5. You covenant, represent, warrant and agree that:
<add>
<add> * Each contribution that you submit is and shall be an original work of
<add> authorship and you can legally grant the rights set out in this SCA;
<add>
<add> * to the best of your knowledge, each contribution will not violate any
<add> third party's copyrights, trademarks, patents, or other intellectual
<add> property rights; and
<add>
<add> * each contribution shall be in compliance with U.S. export control laws and
<add> other applicable export and import laws. You agree to notify us if you
<add> become aware of any circumstance which would make any of the foregoing
<add> representations inaccurate in any respect. We may publicly disclose your
<add> participation in the project, including the fact that you have signed the SCA.
<add>
<add>6. This SCA is governed by the laws of the State of California and applicable
<add>U.S. Federal law. Any choice of law rules will not apply.
<add>
<add>7. Please place an “x” on one of the applicable statement below. Please do NOT
<add>mark both statements:
<add>
<add> * [x] I am signing on behalf of myself as an individual and no other person
<add> or entity, including my employer, has or will have rights with respect to my
<add> contributions.
<add>
<add> * [ ] I am signing on behalf of my employer or a legal entity and I have the
<add> actual authority to contractually bind that entity.
<add>
<add>## Contributor Details
<add>
<add>| Field | Entry |
<add>|------------------------------- | -------------------- |
<add>| Name | Nirant Kasliwal |
<add>| Company name (if applicable) | |
<add>| Title or role (if applicable) | |
<add>| Date | |
<add>| GitHub username | NirantK |
<add>| Website (optional) | https://nirantk.com | | 1 |
Go | Go | swap cat by top to prevent 2 warnings | 0e021ed470a1014bb924ad7067d85540f8f1e71a | <ide><path>api_test.go
<ide> func TestPostContainersRestart(t *testing.T) {
<ide> container, err := runtime.Create(
<ide> &Config{
<ide> Image: GetTestImage(runtime).ID,
<del> Cmd: []string{"/bin/cat"},
<add> Cmd: []string{"/bin/top"},
<ide> OpenStdin: true,
<ide> },
<ide> )
<ide> func TestPostContainersStop(t *testing.T) {
<ide> container, err := runtime.Create(
<ide> &Config{
<ide> Image: GetTestImage(runtime).ID,
<del> Cmd: []string{"/bin/cat"},
<add> Cmd: []string{"/bin/top"},
<ide> OpenStdin: true,
<ide> },
<ide> ) | 1 |
Mixed | Javascript | use a default message in assert | 3cd7977a425d4ef6d2e9b6d535763bc5633789bf | <ide><path>doc/api/assert.md
<ide> parameter is an instance of an [`Error`][] then it will be thrown instead of the
<ide> added: v0.1.21
<ide> changes:
<ide> - version: REPLACEME
<del> pr-url: https://github.com/nodejs/node/pull/17581
<del> description: assert.ok() will throw a `ERR_MISSING_ARGS` error.
<del> Use assert.fail() instead.
<add> pr-url: https://github.com/nodejs/node/pull/REPLACEME
<add> description: assert.ok() (no arguments) will now use a predefined error msg.
<ide> -->
<ide> * `value` {any}
<ide> * `message` {any}
<ide> property set equal to the value of the `message` parameter. If the `message`
<ide> parameter is `undefined`, a default error message is assigned. If the `message`
<ide> parameter is an instance of an [`Error`][] then it will be thrown instead of the
<ide> `AssertionError`.
<add>If no arguments are passed in at all `message` will be set to the string:
<add>"No value argument passed to assert.ok".
<ide>
<ide> Be aware that in the `repl` the error message will be different to the one
<ide> thrown in a file! See below for further details.
<ide> assert.ok(true);
<ide> assert.ok(1);
<ide> // OK
<ide>
<add>assert.ok();
<add>// throws:
<add>// "AssertionError: No value argument passed to `assert.ok`.
<add>
<ide> assert.ok(false, 'it\'s false');
<ide> // throws "AssertionError: it's false"
<ide>
<ide><path>lib/assert.js
<ide> function getBuffer(fd, assertLine) {
<ide> function innerOk(args, fn) {
<ide> var [value, message] = args;
<ide>
<del> if (args.length === 0)
<del> throw new TypeError('ERR_MISSING_ARGS', 'value');
<del>
<ide> if (!value) {
<del> if (message == null) {
<add> if (args.length === 0) {
<add> message = 'No value argument passed to `assert.ok()`';
<add> } else if (message == null) {
<ide> // Use the call as error message if possible.
<ide> // This does not work with e.g. the repl.
<ide> const err = new Error();
<ide><path>test/parallel/test-assert.js
<ide> common.expectsError(
<ide> assert.equal(assert.notDeepEqual, assert.notDeepStrictEqual);
<ide> assert.equal(Object.keys(assert).length, Object.keys(a).length);
<ide> assert(7);
<del> common.expectsError(
<del> () => assert(),
<add> assert.throws(
<add> () => assert(...[]),
<ide> {
<del> code: 'ERR_MISSING_ARGS',
<del> type: TypeError
<add> message: 'No value argument passed to `assert.ok()`',
<add> name: 'AssertionError [ERR_ASSERTION]'
<ide> }
<ide> );
<del> common.expectsError(
<add> assert.throws(
<ide> () => a(),
<ide> {
<del> code: 'ERR_MISSING_ARGS',
<del> type: TypeError
<add> message: 'No value argument passed to `assert.ok()`',
<add> name: 'AssertionError [ERR_ASSERTION]'
<ide> }
<ide> );
<ide> | 3 |
Javascript | Javascript | add test case for preloading buildmanifest | 39e00a3f2f87fa2c1ee6d858dc49120842fb9a5b | <ide><path>test/integration/dynamic-routing/test/index.test.js
<ide> function runTests(dev) {
<ide> expect(res.status).toBe(400)
<ide> })
<ide>
<add> it('should preload buildManifest for auto-export dynamic pages', async () => {
<add> const html = await renderViaHTTP(appPort, '/on-mount/hello')
<add> const $ = cheerio.load(html)
<add> let found = 0
<add>
<add> for (const el of Array.from($('link[rel="preload"]'))) {
<add> const { href } = el.attribs
<add> if (
<add> href.includes('_buildManifest.js') ||
<add> href.includes('_buildManifest.module.js')
<add> ) {
<add> found++
<add> }
<add> }
<add> expect(found).toBe(dev ? 2 : 1)
<add> })
<add>
<add> it('should not preload buildManifest for non-auto export dynamic pages', async () => {
<add> const html = await renderViaHTTP(appPort, '/hello')
<add> const $ = cheerio.load(html)
<add> let found = 0
<add>
<add> for (const el of Array.from($('link[rel="preload"]'))) {
<add> const { href } = el.attribs
<add> if (
<add> href.includes('_buildManifest.js') ||
<add> href.includes('_buildManifest.module.js')
<add> ) {
<add> found++
<add> }
<add> }
<add> expect(found).toBe(0)
<add> })
<add>
<ide> if (dev) {
<ide> it('should resolve dynamic route href for page added later', async () => {
<ide> const browser = await webdriver(appPort, '/') | 1 |
Ruby | Ruby | disallow unstable specs for versioned formulae | a185f3272edf96fc6e65eaf236a61d067270c966 | <ide><path>Library/Homebrew/dev-cmd/audit.rb
<ide> def audit_specs
<ide> end
<ide> end
<ide>
<del> if @new_formula && formula.head
<del> new_formula_problem "Formulae should not have a HEAD spec"
<add> if formula.head || formula.devel
<add> unstable_spec_message = "Formulae should not have an unstable spec"
<add> if @new_formula
<add> new_formula_problem unstable_spec_message
<add> elsif formula.versioned_formula?
<add> versioned_unstable_spec = %w[
<add> bash-completion@2
<add> imagemagick@6
<add> openssl@1.1
<add> python@2
<add> ]
<add> problem unstable_spec_message unless versioned_unstable_spec.include?(formula.name)
<add> end
<ide> end
<ide>
<ide> throttled = %w[ | 1 |
Javascript | Javascript | fix typos and make minor layout improvements | d28ae2126e0c9e24f534aff4f13c9a92c842e5f1 | <ide><path>src/ng/directive/validators.js
<ide> * @description
<ide> *
<ide> * ngRequired adds the required {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
<del> * It is most often used for [@link input `input`} and {@link select `select`} controls, but can also be
<add> * It is most often used for {@link input `input`} and {@link select `select`} controls, but can also be
<ide> * applied to custom controls.
<ide> *
<ide> * The directive sets the `required` attribute on the element if the Angular expression inside
<ide> * </div>
<ide> * </file>
<ide> * <file name="protractor.js" type="protractor">
<del> * var required = element(by.binding('form.input.$error.required'));
<del> * var model = element(by.binding('model'));
<del> *
<del> * it('should set the required error', function() {
<del> * expect(required.getText()).toContain('true');
<del> *
<del> * element(by.id('input')).sendKeys('123');
<del> * expect(required.getText()).not.toContain('true');
<del> * expect(model.getText()).toContain('123');
<del> * });
<add> var required = element(by.binding('form.input.$error.required'));
<add> var model = element(by.binding('model'));
<add> var input = element(by.id('input'));
<add>
<add> it('should set the required error', function() {
<add> expect(required.getText()).toContain('true');
<add>
<add> input.sendKeys('123');
<add> expect(required.getText()).not.toContain('true');
<add> expect(model.getText()).toContain('123');
<add> });
<ide> * </file>
<ide> * </example>
<ide> */
<ide> var requiredDirective = function() {
<ide> * @description
<ide> *
<ide> * ngPattern adds the pattern {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
<del> * It is most often used for text-based [@link input `input`} controls, but can also be applied to custom text-based controls.
<add> * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls.
<ide> *
<del> * The validator sets the `pattern` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
<del> * does not match a RegExp which is obtained by evaluating the Angular expression given in the
<del> * `ngPattern` attribute value:
<del> * * If the expression evaluates to a RegExp object, then this is used directly.
<del> * * If the expression evaluates to a string, then it will be converted to a RegExp after wrapping it
<del> * in `^` and `$` characters. For instance, `"abc"` will be converted to `new RegExp('^abc$')`.
<add> * The validator sets the `pattern` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
<add> * does not match a RegExp which is obtained by evaluating the Angular expression given in the
<add> * `ngPattern` attribute value:
<add> * * If the expression evaluates to a RegExp object, then this is used directly.
<add> * * If the expression evaluates to a string, then it will be converted to a RegExp after wrapping it
<add> * in `^` and `$` characters. For instance, `"abc"` will be converted to `new RegExp('^abc$')`.
<ide> *
<ide> * <div class="alert alert-info">
<ide> * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
<ide> var requiredDirective = function() {
<ide> * <div class="alert alert-info">
<ide> * **Note:** This directive is also added when the plain `pattern` attribute is used, with two
<ide> * differences:
<del> * 1. `ngPattern` does not set the `pattern` attribute and therefore not HTML5 constraint validation
<del> * is available.
<del> * 2. The `ngPattern` attribute must be an expression, while the `pattern` value must be interpolated
<add> * <ol>
<add> * <li>
<add> * `ngPattern` does not set the `pattern` attribute and therefore HTML5 constraint validation is
<add> * not available.
<add> * </li>
<add> * <li>
<add> * The `ngPattern` attribute must be an expression, while the `pattern` value must be
<add> * interpolated.
<add> * </li>
<add> * </ol>
<ide> * </div>
<ide> *
<ide> * @example
<ide> var requiredDirective = function() {
<ide> * </div>
<ide> * </file>
<ide> * <file name="protractor.js" type="protractor">
<del> var model = element(by.binding('model'));
<del> var input = element(by.id('input'));
<add> var model = element(by.binding('model'));
<add> var input = element(by.id('input'));
<ide>
<del> it('should validate the input with the default pattern', function() {
<del> input.sendKeys('aaa');
<del> expect(model.getText()).not.toContain('aaa');
<add> it('should validate the input with the default pattern', function() {
<add> input.sendKeys('aaa');
<add> expect(model.getText()).not.toContain('aaa');
<ide>
<del> input.clear().then(function() {
<del> input.sendKeys('123');
<del> expect(model.getText()).toContain('123');
<del> });
<del> });
<add> input.clear().then(function() {
<add> input.sendKeys('123');
<add> expect(model.getText()).toContain('123');
<add> });
<add> });
<ide> * </file>
<ide> * </example>
<ide> */
<ide> var patternDirective = function() {
<ide> * @description
<ide> *
<ide> * ngMaxlength adds the maxlength {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
<del> * It is most often used for text-based [@link input `input`} controls, but can also be applied to custom text-based controls.
<add> * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls.
<ide> *
<del> * The validator sets the `maxlength` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
<del> * is longer than the integer obtained by evaluating the Angular expression given in the
<del> * `ngMaxlength` attribute value.
<add> * The validator sets the `maxlength` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
<add> * is longer than the integer obtained by evaluating the Angular expression given in the
<add> * `ngMaxlength` attribute value.
<ide> *
<ide> * <div class="alert alert-info">
<ide> * **Note:** This directive is also added when the plain `maxlength` attribute is used, with two
<ide> * differences:
<del> * 1. `ngMaxlength` does not set the `maxlength` attribute and therefore not HTML5 constraint validation
<del> * is available.
<del> * 2. The `ngMaxlength` attribute must be an expression, while the `maxlength` value must be interpolated
<add> * <ol>
<add> * <li>
<add> * `ngMaxlength` does not set the `maxlength` attribute and therefore HTML5 constraint
<add> * validation is not available.
<add> * </li>
<add> * <li>
<add> * The `ngMaxlength` attribute must be an expression, while the `maxlength` value must be
<add> * interpolated.
<add> * </li>
<add> * </ol>
<ide> * </div>
<ide> *
<ide> * @example
<ide> var patternDirective = function() {
<ide> * </div>
<ide> * </file>
<ide> * <file name="protractor.js" type="protractor">
<del> * var model = element(by.binding('model'));
<add> var model = element(by.binding('model'));
<ide> var input = element(by.id('input'));
<ide>
<ide> it('should validate the input with the default maxlength', function() {
<ide> var maxlengthDirective = function() {
<ide> * @description
<ide> *
<ide> * ngMinlength adds the minlength {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
<del> * It is most often used for text-based [@link input `input`} controls, but can also be applied to custom text-based controls.
<add> * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls.
<ide> *
<del> * The validator sets the `minlength` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
<del> * is shorter than the integer obtained by evaluating the Angular expression given in the
<del> * `ngMinlength` attribute value.
<add> * The validator sets the `minlength` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
<add> * is shorter than the integer obtained by evaluating the Angular expression given in the
<add> * `ngMinlength` attribute value.
<ide> *
<ide> * <div class="alert alert-info">
<ide> * **Note:** This directive is also added when the plain `minlength` attribute is used, with two
<ide> * differences:
<del> * 1. `ngMinlength` does not set the `minlength` attribute and therefore not HTML5 constraint validation
<del> * is available.
<del> * 2. The `ngMinlength` value must be an expression, while the `minlength` value must be interpolated
<add> * <ol>
<add> * <li>
<add> * `ngMinlength` does not set the `minlength` attribute and therefore HTML5 constraint
<add> * validation is not available.
<add> * </li>
<add> * <li>
<add> * The `ngMinlength` value must be an expression, while the `minlength` value must be
<add> * interpolated.
<add> * </li>
<add> * </ol>
<ide> * </div>
<ide> *
<ide> * @example
<ide> var maxlengthDirective = function() {
<ide> * </div>
<ide> * </file>
<ide> * <file name="protractor.js" type="protractor">
<del> * var model = element(by.binding('model'));
<del> *
<del> * it('should validate the input with the default minlength', function() {
<del> * element(by.id('input')).sendKeys('ab');
<del> * expect(model.getText()).not.toContain('ab');
<del> *
<del> * element(by.id('input')).sendKeys('abc');
<del> * expect(model.getText()).toContain('abc');
<del> * });
<add> var model = element(by.binding('model'));
<add> var input = element(by.id('input'));
<add>
<add> it('should validate the input with the default minlength', function() {
<add> input.sendKeys('ab');
<add> expect(model.getText()).not.toContain('ab');
<add>
<add> input.sendKeys('abc');
<add> expect(model.getText()).toContain('abc');
<add> });
<ide> * </file>
<ide> * </example>
<ide> */ | 1 |
Ruby | Ruby | add failing spec for `dependencyorder` cop | fdb2406b2044d74fb28ea7844b0987c8fb9feb20 | <ide><path>Library/Homebrew/test/rubocops/dependency_order_cop_spec.rb
<ide> class Foo < Formula
<ide> RUBY
<ide> end
<ide>
<add> it "supports requirement constants" do
<add> expect_offense(<<~RUBY)
<add> class Foo < Formula
<add> homepage "http://example.com"
<add> url "http://example.com/foo-1.0.tgz"
<add> depends_on FooRequirement
<add> depends_on "bar"
<add> ^^^^^^^^^^^^^^^^ dependency "bar" (line 5) should be put before dependency "FooRequirement" (line 4)
<add> end
<add> RUBY
<add> end
<add>
<ide> it "wrong conditional depends_on order" do
<ide> expect_offense(<<~RUBY)
<ide> class Foo < Formula | 1 |
Text | Text | commit suggestions from pr review | 989adad03995109f0b5daeaaf8fe92d9fd98d302 | <ide><path>branding/logo/logoguidelines.md
<ide> These guidelines are meant to help keep the NumPy logo consistent and recognizab
<ide> The primary logo is the horizontal option (logomark and text next to each other) and the secondary logo is the stacked version (logomark over text). I’ve also provided the logomark on its own (meaning it doesn’t have text). When in doubt, it’s preferable to use primary or secondary options over the logomark alone.
<ide>
<ide> ## Color
<del>The full color options are a combo of Maximum Blue/rgb(77, 171, 207) and Han Blue/rgb(77, 119, 207), while light options are White/rgb(255, 255, 255) and dark options are Gunmetal/rgb(1, 50, 67).
<add>The full color options are a combo of two shades of blue, rgb(77, 171, 207) and rgb(77, 119, 207), while light options are rgb(255, 255, 255) and dark options are rgb(1, 50, 67).
<ide>
<ide> Whenever possible, use the full color logos. One color logos (light or dark) are to be used when full color will not have enough contrast, usually when logos must be on colored backgrounds.
<ide> | 1 |
Javascript | Javascript | remove test for missing feature | d7e5392139347c756e338b3bd104dc1a44b15e11 | <ide><path>packager/react-packager/src/DependencyResolver/DependencyGraph/__tests__/DependencyGraph-test.js
<ide> describe('DependencyGraph', function() {
<ide> });
<ide> });
<ide>
<del> //TODO(davidaurelio) Make this actually worked. The test only passed because
<del> // the mocked cache didn't cache. In reality, it didn't work. I tried it.
<del> xpit('updates package.json', function() {
<del> var root = '/root';
<del> var filesystem = fs.__setMockFilesystem({
<del> 'root': {
<del> 'index.js': [
<del> '/**',
<del> ' * @providesModule index',
<del> ' */',
<del> 'require("aPackage")',
<del> ].join('\n'),
<del> 'aPackage': {
<del> 'package.json': JSON.stringify({
<del> name: 'aPackage',
<del> main: 'main.js',
<del> }),
<del> 'main.js': 'main',
<del> },
<del> },
<del> });
<del>
<del> var dgraph = new DependencyGraph({
<del> ...defaults,
<del> roots: [root],
<del> });
<del> return getOrderedDependenciesAsJSON(dgraph, '/root/index.js').then(function() {
<del> filesystem.root['index.js'] = filesystem.root['index.js'].replace(/aPackage/, 'bPackage');
<del> triggerFileChange('change', 'index.js', root, mockStat);
<del>
<del> filesystem.root.aPackage['package.json'] = JSON.stringify({
<del> name: 'bPackage',
<del> main: 'main.js',
<del> });
<del> triggerFileChange('change', 'package.json', '/root/aPackage', mockStat);
<del>
<del> return getOrderedDependenciesAsJSON(dgraph, '/root/index.js').then(function(deps) {
<del> expect(deps)
<del> .toEqual([
<del> {
<del> id: 'index',
<del> path: '/root/index.js',
<del> dependencies: ['bPackage'],
<del> isAsset: false,
<del> isAsset_DEPRECATED: false,
<del> isJSON: false,
<del> isPolyfill: false,
<del> resolution: undefined,
<del> resolveDependency: undefined,
<del> },
<del> {
<del> id: 'bPackage/main.js',
<del> path: '/root/aPackage/main.js',
<del> dependencies: [],
<del> isAsset: false,
<del> isAsset_DEPRECATED: false,
<del> isJSON: false,
<del> isPolyfill: false,
<del> resolution: undefined,
<del> resolveDependency: undefined,
<del> },
<del> ]);
<del> });
<del> });
<del> });
<del>
<ide> pit('changes to browser field', function() {
<ide> var root = '/root';
<ide> var filesystem = fs.__setMockFilesystem({ | 1 |
PHP | PHP | add option to disable local xml file parsing | 2cde19f24c3679e8162e3abbce73818a8b0c02a0 | <ide><path>src/Controller/Component/RequestHandlerComponent.php
<ide> public function startup(Event $event)
<ide> public function convertXml($xml)
<ide> {
<ide> try {
<del> $xml = Xml::build($xml);
<add> $xml = Xml::build($xml, ['readFile' => false]);
<ide> if (isset($xml->data)) {
<ide> return Xml::toArray($xml->data);
<ide> }
<ide><path>src/Utility/Xml.php
<ide> class Xml
<ide> * - `return` Can be 'simplexml' to return object of SimpleXMLElement or 'domdocument' to return DOMDocument.
<ide> * - `loadEntities` Defaults to false. Set to true to enable loading of `<!ENTITY` definitions. This
<ide> * is disabled by default for security reasons.
<add> * - `readFile` Set to false to disable file reading. This is important to disable when
<add> * putting user data into Xml::build(). If enabled local files will be read if they exist.
<add> * Defaults to true for backwards compatibility reasons.
<ide> * - If using array as input, you can pass `options` from Xml::fromArray.
<ide> *
<ide> * @param string|array $input XML string, a path to a file, a URL or an array
<ide> public static function build($input, array $options = [])
<ide> $defaults = [
<ide> 'return' => 'simplexml',
<ide> 'loadEntities' => false,
<add> 'readFile' => true
<ide> ];
<ide> $options += $defaults;
<ide>
<ide> public static function build($input, array $options = [])
<ide> return static::_loadXml($input, $options);
<ide> }
<ide>
<del> if (file_exists($input)) {
<add> if ($options['readFile'] && file_exists($input)) {
<ide> return static::_loadXml(file_get_contents($input), $options);
<ide> }
<ide>
<ide><path>tests/TestCase/Controller/Component/RequestHandlerComponentTest.php
<ide> public function testStartupProcessData()
<ide> $this->assertEquals(['valid' => true], $this->Controller->request->data);
<ide> }
<ide>
<add> /**
<add> * Test that file handles are ignored as XML data.
<add> *
<add> * @return void
<add> * @triggers Controller.startup $this->Controller
<add> */
<add> public function testStartupIgnoreFileAsXml()
<add> {
<add> $this->Controller->request = $this->getMock('Cake\Network\Request', ['_readInput']);
<add> $this->Controller->request->expects($this->any())
<add> ->method('_readInput')
<add> ->will($this->returnValue('/dev/random'));
<add>
<add> $this->Controller->request->env('REQUEST_METHOD', 'POST');
<add> $this->Controller->request->env('CONTENT_TYPE', 'application/xml');
<add>
<add> $event = new Event('Controller.startup', $this->Controller);
<add> $this->RequestHandler->startup($event);
<add> $this->assertEquals([], $this->Controller->request->data);
<add> }
<add>
<ide> /**
<ide> * Test mapping a new type and having startup process it.
<ide> *
<ide><path>tests/TestCase/Utility/XmlTest.php
<ide> public function testBuild()
<ide> $this->assertNotRegExp('/encoding/', $obj->saveXML());
<ide> }
<ide>
<add> /**
<add> * Test that the readFile option disables local file parsing.
<add> *
<add> * @expectedException \Cake\Utility\Exception\XmlException
<add> * @return void
<add> */
<add> public function testBuildFromFileWhenDisabled()
<add> {
<add> $xml = CORE_TESTS . 'Fixture/sample.xml';
<add> $obj = Xml::build($xml, ['readFile' => false]);
<add> }
<add>
<ide> /**
<ide> * Test build() with a Collection instance.
<ide> * | 4 |
Text | Text | add some notes about now deployment | ac31f1636ee15daad983d6d801a1e35764c7fe79 | <ide><path>UPGRADING.md
<ide> # Migrating from v8 to v9
<ide>
<add>## Preamble
<add>
<add>#### Production Deployment on ZEIT Now v2
<add>
<add>If you previously configured `routes` in your `now.json` file for dynamic routes, these rules can be removed when leveraging Next.js 9's new [Dynamic Routing feature](https://github.com/zeit/next.js#dynamic-routing).
<add>
<add>Next.js 9's dynamic routes are **automatically configured on [Now](https://zeit.co/now)** and do not require any `now.json` customization.
<add>
<add>You can read more about [Dynamic Routing here](https://github.com/zeit/next.js#dynamic-routing).
<add>
<ide> ## Breaking Changes
<ide>
<ide> #### `@zeit/next-typescript` is no longer necessary
<ide> module.exports = {
<ide> Pages in `./pages/api/` are now considered [API Routes](https://nextjs.org/blog/next-9#api-routes).
<ide> Pages in this directory will no longer contain a client-side bundle.
<ide>
<del>
<ide> ## Deprecated Features
<ide>
<ide> #### `next/dynamic` has deprecated loading multiple modules at once
<ide><path>packages/next/README.md
<ide> For example, `/post/abc?pid=bcd` will have the `query` object: `{ pid: 'abc' }`.
<ide> > After hydration, Next.js will trigger an update to your application to provide the route parameters in the `query` object.
<ide> > If your application cannot tolerate this behavior, you can opt-out of static optimization by capturing the query parameter in `getInitialProps`.
<ide>
<add>> **Note**: If deploying to [ZEIT Now](https://zeit.co/now) dynamic routes will work out-of-the-box.
<add>> You do not need to configure custom routes in a `now.json` file.
<add>>
<add>> If you are new to ZEIT Now, you can learn how to deploy a Next.js app to it in the [_Deploying a Next.js App_ Learn section](https://nextjs.org/learn/basics/deploying-a-nextjs-app).
<add>
<ide> ### Populating `<head>`
<ide>
<ide> <details>
<ide> next build
<ide> next start
<ide> ```
<ide>
<del>To deploy Next.js with [ZEIT Now](https://zeit.co/now) see the [ZEIT Guide for Deploying Next.js with Now](https://zeit.co/guides/deploying-nextjs-with-now/).
<add>To deploy Next.js with [ZEIT Now](https://zeit.co/now) see the [ZEIT Guide for Deploying Next.js](https://zeit.co/guides/deploying-nextjs-with-now/) or the [Next.js Learn section about deploying on ZEIT Now](https://nextjs.org/learn/basics/deploying-a-nextjs-app/deploying-to-zeit-now).
<ide>
<ide> Next.js can be deployed to other hosting solutions too. Please have a look at the ['Deployment'](https://github.com/zeit/next.js/wiki/Deployment) section of the wiki.
<ide> | 2 |
Javascript | Javascript | refine handling of illegal tokens | de0aa23ad71e63c90be947f79b547f7c303ce7b8 | <ide><path>lib/repl.js
<ide> REPLServer.prototype.convertToContext = function(cmd) {
<ide> return cmd;
<ide> };
<ide>
<add>function bailOnIllegalToken(parser) {
<add> return parser._literal === null &&
<add> !parser.blockComment &&
<add> !parser.regExpLiteral;
<add>}
<ide>
<ide> // If the error is that we've unexpectedly ended the input,
<ide> // then let the user try to recover by adding more input.
<ide> function isRecoverableError(e, self) {
<ide> return true;
<ide> }
<ide>
<del> return message.startsWith('Unexpected end of input') ||
<del> message.startsWith('Unexpected token') ||
<del> message.startsWith('missing ) after argument list');
<add> if (message.startsWith('Unexpected end of input') ||
<add> message.startsWith('missing ) after argument list'))
<add> return true;
<add>
<add> if (message.startsWith('Unexpected token')) {
<add> if (message.includes('ILLEGAL') && bailOnIllegalToken(self.lineParser))
<add> return false;
<add> else
<add> return true;
<add> }
<ide> }
<ide> return false;
<ide> }
<ide><path>test/parallel/test-repl.js
<ide> function error_test() {
<ide> 'undefined\n' + prompt_unix },
<ide> { client: client_unix, send: '{ var x = 4; }',
<ide> expect: 'undefined\n' + prompt_unix },
<add> // Illegal token is not recoverable outside string literal, RegExp literal,
<add> // or block comment. https://github.com/nodejs/node/issues/3611
<add> { client: client_unix, send: 'a = 3.5e',
<add> expect: /^SyntaxError: Unexpected token ILLEGAL/ },
<ide> ]);
<ide> }
<ide> | 2 |
Text | Text | change mac os x to macos | 7a5d07c7fbd43f3645d7f707fd6a98f2a251bdbd | <ide><path>BUILDING.md
<ide> Depending on host platform, the selection of toolchains may vary.
<ide>
<ide> ## Building Node.js on supported platforms
<ide>
<del>### Unix / OS X
<add>### Unix / macOS
<ide>
<ide> Prerequisites:
<ide>
<ide> Prerequisites:
<ide> * Python 2.6 or 2.7
<ide> * GNU Make 3.81 or newer
<ide>
<del>On OS X, you will also need:
<add>On macOS, you will also need:
<ide> * [Xcode](https://developer.apple.com/xcode/download/)
<ide> - You also need to install the `Command Line Tools` via Xcode. You can find
<ide> this under the menu `Xcode -> Preferences -> Downloads`
<ide> With the `--download=all`, this may download ICU if you don't have an
<ide> ICU in `deps/icu`. (The embedded `small-icu` included in the default
<ide> Node.js source does not include all locales.)
<ide>
<del>##### Unix / OS X:
<add>##### Unix / macOS:
<ide>
<ide> ```console
<ide> $ ./configure --with-intl=full-icu --download=all
<ide> $ ./configure --with-intl=full-icu --download=all
<ide> The `Intl` object will not be available, nor some other APIs such as
<ide> `String.normalize`.
<ide>
<del>##### Unix / OS X:
<add>##### Unix / macOS:
<ide>
<ide> ```console
<ide> $ ./configure --without-intl
<ide> $ ./configure --without-intl
<ide> > .\vcbuild without-intl
<ide> ```
<ide>
<del>#### Use existing installed ICU (Unix / OS X only):
<add>#### Use existing installed ICU (Unix / macOS only):
<ide>
<ide> ```console
<ide> $ pkg-config --modversion icu-i18n && ./configure --with-intl=system-icu
<ide> You can find other ICU releases at
<ide> Download the file named something like `icu4c-**##.#**-src.tgz` (or
<ide> `.zip`).
<ide>
<del>##### Unix / OS X
<add>##### Unix / macOS
<ide>
<ide> From an already-unpacked ICU:
<ide> ```console
<ide><path>CONTRIBUTING.md
<ide> Bug fixes and features **should come with tests**. Add your tests in the
<ide> project, see this [guide](./doc/guides/writing-tests.md). Looking at other tests
<ide> to see how they should be structured can also help.
<ide>
<del>To run the tests on Unix / OS X:
<add>To run the tests on Unix / macOS:
<ide>
<ide> ```text
<ide> $ ./configure && make -j4 test
<ide><path>doc/STYLE_GUIDE.md
<ide> * When documenting APIs, note the version the API was introduced in at
<ide> the end of the section. If an API has been deprecated, also note the first
<ide> version that the API appeared deprecated in.
<del>* When using dashes, use emdashes ("—", Ctrl+Alt+"-" on OSX) surrounded by
<add>* When using dashes, use emdashes ("—", Ctrl+Alt+"-" on macOS) surrounded by
<ide> spaces, per the New York Times usage.
<ide> * Including assets:
<ide> * If you wish to add an illustration or full program, add it to the
<ide><path>doc/api/child_process.md
<ide> when the child process terminates.
<ide>
<ide> The importance of the distinction between [`child_process.exec()`][] and
<ide> [`child_process.execFile()`][] can vary based on platform. On Unix-type operating
<del>systems (Unix, Linux, OSX) [`child_process.execFile()`][] can be more efficient
<add>systems (Unix, Linux, macOS) [`child_process.execFile()`][] can be more efficient
<ide> because it does not spawn a shell. On Windows, however, `.bat` and `.cmd`
<ide> files are not executable on their own without a terminal, and therefore cannot
<ide> be launched using [`child_process.execFile()`][]. When running on Windows, `.bat`
<ide> child.on('error', (err) => {
<ide> });
<ide> ```
<ide>
<del>*Note: Certain platforms (OS X, Linux) will use the value of `argv[0]` for the
<add>*Note: Certain platforms (macOS, Linux) will use the value of `argv[0]` for the
<ide> process title while others (Windows, SunOS) will use `command`.*
<ide>
<ide> *Note: Node.js currently overwrites `argv[0]` with `process.execPath` on
<ide><path>doc/api/documentation.md
<ide> like `fs.open()`, will document that. The docs link to the corresponding man
<ide> pages (short for manual pages) which describe how the syscalls work.
<ide>
<ide> **Caveat:** some syscalls, like lchown(2), are BSD-specific. That means, for
<del>example, that `fs.lchown()` only works on Mac OS X and other BSD-derived systems,
<add>example, that `fs.lchown()` only works on macOS and other BSD-derived systems,
<ide> and is not available on Linux.
<ide>
<ide> Most Unix syscalls have Windows equivalents, but behavior may differ on Windows
<del>relative to Linux and OS X. For an example of the subtle ways in which it's
<add>relative to Linux and macOS. For an example of the subtle ways in which it's
<ide> sometimes impossible to replace Unix syscall semantics on Windows, see [Node
<ide> issue 4760](https://github.com/nodejs/node/issues/4760).
<ide>
<ide><path>doc/api/errors.md
<ide> found [here][online].
<ide> [file descriptors][] allowable on the system has been reached, and
<ide> requests for another descriptor cannot be fulfilled until at least one
<ide> has been closed. This is encountered when opening many files at once in
<del> parallel, especially on systems (in particular, OS X) where there is a low
<add> parallel, especially on systems (in particular, macOS) where there is a low
<ide> file descriptor limit for processes. To remedy a low limit, run
<ide> `ulimit -n 2048` in the same shell that will run the Node.js process.
<ide>
<ide><path>doc/api/fs.md
<ide> changes:
<ide> Asynchronous lchmod(2). No arguments other than a possible exception
<ide> are given to the completion callback.
<ide>
<del>Only available on Mac OS X.
<add>Only available on macOS.
<ide>
<ide> ## fs.lchmodSync(path, mode)
<ide> <!-- YAML
<ide> The kernel ignores the position argument and always appends the data to
<ide> the end of the file.
<ide>
<ide> _Note: The behavior of `fs.open()` is platform specific for some flags. As such,
<del>opening a directory on OS X and Linux with the `'a+'` flag - see example below -
<add>opening a directory on macOS and Linux with the `'a+'` flag - see example below -
<ide> will return an error. In contrast, on Windows and FreeBSD, a file descriptor
<ide> will be returned._
<ide>
<ide> ```js
<del>// OS X and Linux
<add>// macOS and Linux
<ide> fs.open('<directory>', 'a+', (err, fd) => {
<ide> // => [Error: EISDIR: illegal operation on a directory, open <directory>]
<ide> });
<ide> Also note the listener callback is attached to the `'change'` event fired by
<ide> The `fs.watch` API is not 100% consistent across platforms, and is
<ide> unavailable in some situations.
<ide>
<del>The recursive option is only supported on OS X and Windows.
<add>The recursive option is only supported on macOS and Windows.
<ide>
<ide> #### Availability
<ide>
<ide> to be notified of filesystem changes.
<ide>
<ide> * On Linux systems, this uses [`inotify`]
<ide> * On BSD systems, this uses [`kqueue`]
<del>* On OS X, this uses [`kqueue`] for files and [`FSEvents`] for directories.
<add>* On macOS, this uses [`kqueue`] for files and [`FSEvents`] for directories.
<ide> * On SunOS systems (including Solaris and SmartOS), this uses [`event ports`].
<ide> * On Windows systems, this feature depends on [`ReadDirectoryChangesW`].
<ide> * On Aix systems, this feature depends on [`AHAFS`], which must be enabled.
<ide> less reliable.
<ide>
<ide> <!--type=misc-->
<ide>
<del>On Linux and OS X systems, `fs.watch()` resolves the path to an [inode][] and
<add>On Linux and macOS systems, `fs.watch()` resolves the path to an [inode][] and
<ide> watches the inode. If the watched path is deleted and recreated, it is assigned
<ide> a new inode. The watch will emit an event for the delete but will continue
<ide> watching the *original* inode. Events for the new inode will not be emitted.
<ide> In AIX, save and close of a file being watched causes two notifications -
<ide> one for adding new content, and one for truncation. Moreover, save and
<ide> close operations on some platforms cause inode changes that force watch
<ide> operations to become invalid and ineffective. AIX retains inode for the
<del>lifetime of a file, that way though this is different from Linux / OS X,
<add>lifetime of a file, that way though this is different from Linux / macOS,
<ide> this improves the usability of file watching. This is expected behavior.
<ide>
<ide> #### Filename Argument
<ide><path>doc/api/net.md
<ide> sockets on other operating systems.
<ide> On UNIX, the local domain is also known as the UNIX domain. The path is a
<ide> filesystem path name. It gets truncated to `sizeof(sockaddr_un.sun_path) - 1`,
<ide> which varies on different operating system between 91 and 107 bytes.
<del>The typical values are 107 on Linux and 103 on OS X. The path is
<add>The typical values are 107 on Linux and 103 on macOS. The path is
<ide> subject to the same naming conventions and permissions checks as would be done
<ide> on file creation. It will be visible in the filesystem, and will *persist until
<ide> unlinked*.
<ide><path>doc/api/os.md
<ide> added: v0.3.3
<ide> * Returns: {string}
<ide>
<ide> The `os.type()` method returns a string identifying the operating system name
<del>as returned by uname(3). For example `'Linux'` on Linux, `'Darwin'` on OS X and
<add>as returned by uname(3). For example `'Linux'` on Linux, `'Darwin'` on macOS and
<ide> `'Windows_NT'` on Windows.
<ide>
<ide> Please see https://en.wikipedia.org/wiki/Uname#Examples for additional
<ide><path>doc/api/process.md
<ide> the current value of `ps`.
<ide>
<ide> *Note*: When a new value is assigned, different platforms will impose different
<ide> maximum length restrictions on the title. Usually such restrictions are quite
<del>limited. For instance, on Linux and OS X, `process.title` is limited to the size
<add>limited. For instance, on Linux and macOS, `process.title` is limited to the size
<ide> of the binary name plus the length of the command line arguments because setting
<ide> the `process.title` overwrites the `argv` memory of the process. Node.js v0.8
<ide> allowed for longer process title strings by also overwriting the `environ`
<ide><path>test/README.md
<ide> Platform check for Linux on PowerPC.
<ide> ### isOSX
<ide> * return [<Boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
<ide>
<del>Platform check for OS X.
<add>Platform check for macOS.
<ide>
<ide> ### isSunOS
<ide> * return [<Boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) | 11 |
PHP | PHP | apply fixes from styleci | 20faf9fc0dc9302eec46a62aa477a700edddae36 | <ide><path>tests/Broadcasting/BroadcasterTest.php
<ide> use Illuminate\Http\Request;
<ide> use Mockery as m;
<ide> use PHPUnit\Framework\TestCase;
<del>use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
<ide> use Symfony\Component\HttpKernel\Exception\HttpException;
<ide>
<ide> class BroadcasterTest extends TestCase | 1 |
Javascript | Javascript | add regression test for --debug-brk -e 0 | 810cc05116b39963b25c87fd17be32a6bb867eb0 | <ide><path>test/parallel/test-debug-brk.js
<add>'use strict';
<add>
<add>const common = require('../common');
<add>const assert = require('assert');
<add>const spawnSync = require('child_process').spawnSync;
<add>
<add>const args = [`--debug-brk=${common.PORT}`, `-e`, `0`];
<add>const proc = spawnSync(process.execPath, args, {encoding: 'utf8'});
<add>assert(/Debugger listening on/.test(proc.stderr)); | 1 |
Text | Text | fix typo line 60 | 64a385662b6f23953831b5c32d2475921c10733b | <ide><path>guide/english/algorithms/flood-fill/index.md
<ide> void flood_fill(int pos_x, int pos_y, int target_color, int color)
<ide>
<ide> As seen above, my starting point is (4,4). After calling the function for the start coordinates **x = 4** and **y = 4**,
<ide> I can start checking if there is no wall or color on the spot. If that is valid i mark the spot with one **"color"**
<del>and start checking the other adiacent squares.
<add>and start checking the other adjacent squares.
<ide>
<ide> Going south we will get to point (5,4) and the function runs again.
<ide> | 1 |
Javascript | Javascript | fix conflict between makeglobal prs | fffe2f3e715c754a9ce2ff2276894ed680aa443d | <ide><path>moment.js
<ide> }
<ide> return local_moment.apply(null, arguments);
<ide> };
<del> extend(this.moment, local_moment);
<add> extend(global.moment, local_moment);
<ide> } else {
<ide> global['moment'] = moment;
<ide> } | 1 |
Go | Go | fix panic on --label-add | 85bc3194aa12c19a5bd755666d1e9617dc1bb322 | <ide><path>api/client/service/update.go
<ide> func updatePlacement(flags *pflag.FlagSet, placement *swarm.Placement) {
<ide>
<ide> func updateLabels(flags *pflag.FlagSet, field *map[string]string) {
<ide> if flags.Changed(flagLabelAdd) {
<del> if field == nil {
<add> if *field == nil {
<ide> *field = map[string]string{}
<ide> }
<ide>
<ide> func updateLabels(flags *pflag.FlagSet, field *map[string]string) {
<ide> }
<ide> }
<ide>
<del> if field != nil && flags.Changed(flagLabelRemove) {
<add> if *field != nil && flags.Changed(flagLabelRemove) {
<ide> toRemove := flags.Lookup(flagLabelRemove).Value.(*opts.ListOpts).GetAll()
<ide> for _, label := range toRemove {
<ide> delete(*field, label)
<ide><path>integration-cli/daemon_swarm.go
<ide> func (d *SwarmDaemon) getService(c *check.C, id string) *swarm.Service {
<ide> c.Assert(status, checker.Equals, http.StatusOK, check.Commentf("output: %q", string(out)))
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(json.Unmarshal(out, &service), checker.IsNil)
<del> c.Assert(service.ID, checker.Equals, id)
<ide> return &service
<ide> }
<ide>
<ide><path>integration-cli/docker_cli_service_update_test.go
<ide> func (s *DockerSwarmSuite) TestServiceUpdatePort(c *check.C) {
<ide> }
<ide> c.Assert(portConfig, checker.DeepEquals, expected)
<ide> }
<add>
<add>func (s *DockerSwarmSuite) TestServiceUpdateLabel(c *check.C) {
<add> d := s.AddDaemon(c, true, true)
<add> out, err := d.Cmd("service", "create", "--name=test", "busybox", "top")
<add> c.Assert(err, checker.IsNil, check.Commentf(out))
<add> service := d.getService(c, "test")
<add> c.Assert(service.Spec.Labels, checker.HasLen, 0)
<add>
<add> // add label to empty set
<add> out, err = d.Cmd("service", "update", "test", "--label-add", "foo=bar")
<add> c.Assert(err, checker.IsNil, check.Commentf(out))
<add> service = d.getService(c, "test")
<add> c.Assert(service.Spec.Labels, checker.HasLen, 1)
<add> c.Assert(service.Spec.Labels["foo"], checker.Equals, "bar")
<add>
<add> // add label to non-empty set
<add> out, err = d.Cmd("service", "update", "test", "--label-add", "foo2=bar")
<add> c.Assert(err, checker.IsNil, check.Commentf(out))
<add> service = d.getService(c, "test")
<add> c.Assert(service.Spec.Labels, checker.HasLen, 2)
<add> c.Assert(service.Spec.Labels["foo2"], checker.Equals, "bar")
<add>
<add> out, err = d.Cmd("service", "update", "test", "--label-rm", "foo2")
<add> c.Assert(err, checker.IsNil, check.Commentf(out))
<add> service = d.getService(c, "test")
<add> c.Assert(service.Spec.Labels, checker.HasLen, 1)
<add> c.Assert(service.Spec.Labels["foo2"], checker.Equals, "")
<add>
<add> out, err = d.Cmd("service", "update", "test", "--label-rm", "foo")
<add> c.Assert(err, checker.IsNil, check.Commentf(out))
<add> service = d.getService(c, "test")
<add> c.Assert(service.Spec.Labels, checker.HasLen, 0)
<add> c.Assert(service.Spec.Labels["foo"], checker.Equals, "")
<add>
<add> // now make sure we can add again
<add> out, err = d.Cmd("service", "update", "test", "--label-add", "foo=bar")
<add> c.Assert(err, checker.IsNil, check.Commentf(out))
<add> service = d.getService(c, "test")
<add> c.Assert(service.Spec.Labels, checker.HasLen, 1)
<add> c.Assert(service.Spec.Labels["foo"], checker.Equals, "bar")
<add>} | 3 |
Go | Go | add testsandboxinfoequal in sandbox_test.go | 3da12c72198a99a7cd4b37ce54bdbdcf98bb5df9 | <ide><path>libnetwork/sandbox/sandbox_test.go
<ide> func TestInterfaceEqual(t *testing.T) {
<ide> }
<ide> }
<ide>
<add>func TestSandboxInfoEqual(t *testing.T) {
<add> si1 := &Info{Interfaces: getInterfaceList(), Gateway: net.ParseIP("192.168.1.254"), GatewayIPv6: net.ParseIP("2001:2345::abcd:8889")}
<add> si2 := &Info{Interfaces: getInterfaceList(), Gateway: net.ParseIP("172.18.255.254"), GatewayIPv6: net.ParseIP("2001:2345::abcd:8888")}
<add>
<add> if !si1.Equal(si1) {
<add> t.Fatalf("Info.Equal() returned false negative")
<add> }
<add>
<add> if si1.Equal(si2) {
<add> t.Fatalf("Info.Equal() returned false positive")
<add> }
<add>
<add> if si1.Equal(si2) != si2.Equal(si1) {
<add> t.Fatalf("Info.Equal() failed commutative check")
<add> }
<add>}
<add>
<ide> func TestInterfaceCopy(t *testing.T) {
<ide> for _, iface := range getInterfaceList() {
<ide> cp := iface.GetCopy() | 1 |
PHP | PHP | initialize array in sqlitegrammar.php | b5c0e040b406696b137f681c1defd25ea0e2a89a | <ide><path>src/Illuminate/Database/Schema/Grammars/SQLiteGrammar.php
<ide> public function compileAdd(Blueprint $blueprint, Fluent $command)
<ide>
<ide> $columns = $this->prefixArray('add column', $this->getColumns($blueprint));
<ide>
<add> $statements = array();
<add>
<ide> foreach ($columns as $column)
<ide> {
<ide> $statements[] = 'alter table '.$table.' '.$column; | 1 |
Text | Text | add log with function call to challenge | 5ffcd0f28484d3c700ccf62d4e213069a73af95c | <ide><path>curriculum/challenges/english/02-javascript-algorithms-and-data-structures/basic-data-structures/iterate-through-the-keys-of-an-object-with-a-for...in-statement.md
<ide> const usersObj3 = {
<ide> ## --seed-contents--
<ide>
<ide> ```js
<add>const users = {
<add> Alan: {
<add> online: false
<add> },
<add> Jeff: {
<add> online: true
<add> },
<add> Sarah: {
<add> online: false
<add> }
<add>}
<add>
<ide> function countOnline(usersObj) {
<ide> // Only change code below this line
<ide>
<ide> // Only change code above this line
<ide> }
<add>
<add>console.log(countOnline(users));
<ide> ```
<ide>
<ide> # --solutions-- | 1 |
Ruby | Ruby | complete all the standard severity levels | 0373afba17406bc513e6d6b6e8ab5b1b8f2bff30 | <ide><path>lib/action_cable/connection/tagged_logger_proxy.rb
<ide> def initialize(logger, tags:)
<ide> @tags = tags.flatten
<ide> end
<ide>
<del> def info(message)
<del> log :info, message
<del> end
<del>
<del> def error(message)
<del> log :error, message
<del> end
<del>
<ide> def add_tags(*tags)
<ide> @tags += tags.flatten
<ide> @tags = @tags.uniq
<ide> end
<ide>
<add> %i( debug info warn error fatal unknown ).each do |severity|
<add> define_method(severity) do |message|
<add> log severity, message
<add> end
<add> end
<add>
<ide> protected
<ide> def log(type, message)
<ide> @logger.tagged(*@tags) { @logger.send type, message } | 1 |
Ruby | Ruby | inline this method | a78b9063892aeb4e5084edcfc7ed873587997abc | <ide><path>Library/Homebrew/cleaner.rb
<ide> def prune
<ide> end
<ide> end
<ide>
<del> # Set permissions for executables and non-executables
<del> def clean_file_permissions path
<del> perms = if path.mach_o_executable? || path.text_executable?
<del> 0555
<del> else
<del> 0444
<del> end
<del> if ARGV.debug?
<del> old_perms = path.stat.mode & 0777
<del> if perms != old_perms
<del> puts "Fixing #{path} permissions from #{old_perms.to_s(8)} to #{perms.to_s(8)}"
<del> end
<del> end
<del> path.chmod perms
<del> end
<del>
<del> # Removes .la files and fixes file permissions for a directory tree, keeping
<del> # existing files and permissions if instructed to by the formula
<add> # Clean a single folder (non-recursively)
<ide> def clean_dir d
<ide> d.find do |path|
<ide> path.extend(ObserverPathnameExtension)
<ide> def clean_dir d
<ide> elsif path.extname == '.la'
<ide> path.unlink
<ide> else
<del> clean_file_permissions(path)
<add> # Set permissions for executables and non-executables
<add> perms = if path.mach_o_executable? || path.text_executable?
<add> 0555
<add> else
<add> 0444
<add> end
<add> if ARGV.debug?
<add> old_perms = path.stat.mode & 0777
<add> if perms != old_perms
<add> puts "Fixing #{path} permissions from #{old_perms.to_s(8)} to #{perms.to_s(8)}"
<add> end
<add> end
<add> path.chmod perms
<ide> end
<ide> end
<ide> end | 1 |
Ruby | Ruby | reduce conditionals in url_for | 9df60693d77813b362fb528fc62381ac8f1eec12 | <ide><path>actionpack/lib/action_dispatch/routing/route_set.rb
<ide> def url_for(options)
<ide> options = default_url_options.merge(options || {})
<ide>
<ide> user, password = extract_authentication(options)
<del> recall = options.delete(:_recall)
<add> recall = options.delete(:_recall) { {} }
<ide>
<ide> original_script_name = options.delete(:original_script_name).presence
<ide> script_name = options.delete(:script_name).presence || _generate_prefix(options)
<ide> def url_for(options)
<ide> RESERVED_OPTIONS.each { |ro| path_options.delete ro }
<ide> path_options = yield(path_options) if block_given?
<ide>
<del> path, params = generate(path_options, recall || {})
<del> params.merge!(options[:params] || {})
<add> path, params = generate(path_options, recall)
<add>
<add> if options.key? :params
<add> params.merge! options[:params]
<add> end
<ide>
<ide> ActionDispatch::Http::URL.url_for(options.merge!({
<ide> :path => path, | 1 |
Javascript | Javascript | add flag to be silent in runner | e4383c0170832368564bd39ddc5dba6e104eb1b2 | <ide><path>benchmark/common.js
<ide> var assert = require('assert');
<ide> var path = require('path');
<add>var silent = +process.env.NODE_BENCH_SILENT;
<ide>
<ide> exports.PORT = process.env.PORT || 12346;
<ide>
<ide> Benchmark.prototype.end = function(operations) {
<ide>
<ide> Benchmark.prototype.report = function(value) {
<ide> var heading = this.getHeading();
<del> console.log('%s: %s', heading, value.toPrecision(5));
<add> if (!silent)
<add> console.log('%s: %s', heading, value.toPrecision(5));
<ide> process.exit(0);
<ide> };
<ide> | 1 |
PHP | PHP | fix empty datetime inputs | 46ea01353fab948fd0a116239cc291b59f364f9e | <ide><path>src/View/Widget/DateTimeWidget.php
<ide> protected function _deconstructDate($value, $options)
<ide> ];
<ide> $validDate = false;
<ide> foreach ($dateArray as $key => $dateValue) {
<del> if (isset($value[$key])) {
<del> $dateArray[$key] = str_pad($value[$key], 2, '0', STR_PAD_LEFT);
<add> $exists = isset($value[$key]);
<add> if ($exists) {
<ide> $validDate = true;
<ide> }
<add> if ($exists && $value[$key] !== '') {
<add> $dateArray[$key] = str_pad($value[$key], 2, '0', STR_PAD_LEFT);
<add> }
<ide> }
<ide> if ($validDate) {
<del> if (empty($dateArray['second'])) {
<add> if (!isset($dateArray['second'])) {
<ide> $dateArray['second'] = 0;
<ide> }
<ide> if (isset($value['meridian'])) {
<ide><path>tests/TestCase/View/Widget/DateTimeWidgetTest.php
<ide> public function testRenderSelectedInvalid($selected)
<ide> );
<ide> }
<ide>
<add> /**
<add> * test rendering empty selected.
<add> *
<add> * @return void
<add> */
<add> public function testRenderSelectedEmpty()
<add> {
<add> $result = $this->DateTime->render([
<add> 'val' => '',
<add> 'year' => ['empty' => true],
<add> 'month' => ['empty' => true],
<add> 'day' => ['empty' => true],
<add> 'hour' => ['empty' => true],
<add> 'minute' => ['empty' => true],
<add> ], $this->context);
<add> $this->assertContains('<option value="" selected="selected"></option>', $result);
<add> $this->assertNotRegExp('/value="\d+" selected="selected"/', $result);
<add>
<add> $result = $this->DateTime->render([
<add> 'val' => ['year' => '', 'month' => '', 'day' => '', 'hour' => '', 'minute' => ''],
<add> 'year' => ['empty' => true],
<add> 'month' => ['empty' => true],
<add> 'day' => ['empty' => true],
<add> 'hour' => ['empty' => true],
<add> 'minute' => ['empty' => true],
<add> ], $this->context);
<add> $this->assertContains('<option value="" selected="selected"></option>', $result);
<add> $this->assertNotRegExp('/value="\d+" selected="selected"/', $result);
<add> }
<add>
<ide> /**
<ide> * Data provider for testing various acceptable selected values.
<ide> * | 2 |
Javascript | Javascript | fix error type | cc6abc6e84b96fd5f1c4123066eba93ddb637e60 | <ide><path>lib/internal/url.js
<ide> class URL {
<ide> constructor(input, base) {
<ide> // toUSVString is not needed.
<ide> input = `${input}`;
<del> if (base !== undefined &&
<del> (!base[searchParams] || !base[searchParams][searchParams])) {
<add> if (base !== undefined) {
<ide> base = new URL(base);
<ide> }
<ide> parse(this, input, base);
<ide><path>test/parallel/test-whatwg-url-parsing.js
<ide> const failureTests = tests.filter((test) => test.failure).concat([
<ide> { input: null },
<ide> { input: new Date() },
<ide> { input: new RegExp() },
<add> { input: 'test', base: null },
<add> { input: 'http://nodejs.org', base: null },
<ide> { input: () => {} }
<ide> ]);
<ide> | 2 |
Ruby | Ruby | improve existing tests for livecheck dsl | 47d07b2f1baaa2a999c64b768d66ba2f7a80b892 | <ide><path>Library/Homebrew/test/livecheck_spec.rb
<ide> require "livecheck"
<ide>
<ide> describe Livecheck do
<add> HOMEPAGE_URL = "https://example.com/"
<add> STABLE_URL = "https://example.com/example-1.2.3.tar.gz"
<add> HEAD_URL = "https://example.com/example.git"
<add>
<ide> let(:f) do
<ide> formula do
<del> url "https://brew.sh/test-0.1.tbz"
<add> homepage HOMEPAGE_URL
<add> url STABLE_URL
<add> head HEAD_URL
<ide> end
<ide> end
<ide> let(:livecheckable) { described_class.new(f) }
<ide>
<ide> describe "#regex" do
<del> it "returns nil if unset" do
<add> it "returns nil if not set" do
<ide> expect(livecheckable.regex).to be nil
<ide> end
<ide>
<del> it "returns the Regex if set" do
<add> it "returns the Regexp if set" do
<ide> livecheckable.regex(/foo/)
<ide> expect(livecheckable.regex).to eq(/foo/)
<ide> end
<ide> end
<ide>
<ide> describe "#skip" do
<del> it "sets the instance variable skip to true and skip_msg to nil when the argument is not present" do
<del> livecheckable.skip
<add> it "sets @skip to true when no argument is provided" do
<add> expect(livecheckable.skip).to be true
<ide> expect(livecheckable.instance_variable_get(:@skip)).to be true
<ide> expect(livecheckable.instance_variable_get(:@skip_msg)).to be nil
<ide> end
<ide>
<del> it "sets the instance variable skip to true and skip_msg to the argument when present" do
<del> livecheckable.skip("foo")
<add> it "sets @skip to true and @skip_msg to the provided String" do
<add> expect(livecheckable.skip("foo")).to be true
<ide> expect(livecheckable.instance_variable_get(:@skip)).to be true
<ide> expect(livecheckable.instance_variable_get(:@skip_msg)).to eq("foo")
<ide> end
<ide> end
<ide>
<ide> describe "#skip?" do
<del> it "returns the value of the instance variable skip" do
<add> it "returns the value of @skip" do
<ide> expect(livecheckable.skip?).to be false
<add>
<ide> livecheckable.skip
<ide> expect(livecheckable.skip?).to be true
<ide> end
<ide> end
<ide>
<ide> describe "#url" do
<del> it "returns nil if unset" do
<add> it "returns nil if not set" do
<ide> expect(livecheckable.url).to be nil
<ide> end
<ide>
<ide> it "returns the URL if set" do
<ide> livecheckable.url("foo")
<ide> expect(livecheckable.url).to eq("foo")
<ide>
<add> livecheckable.url(:homepage)
<add> expect(livecheckable.url).to eq(HOMEPAGE_URL)
<add>
<add> livecheckable.url(:stable)
<add> expect(livecheckable.url).to eq(STABLE_URL)
<add>
<add> livecheckable.url(:head)
<add> expect(livecheckable.url).to eq(HEAD_URL)
<add> end
<add>
<ide> it "raises a TypeError if the argument isn't a String or Symbol" do
<ide> expect {
<ide> livecheckable.url(/foo/) | 1 |
Python | Python | treat internal errors as failure | e0d865c56cb43827db85f7418d02fbfb746d7f7b | <ide><path>celery/app/trace.py
<ide> def trace_task(task, uuid, args, kwargs, request=None, **opts):
<ide> return task.__trace__(uuid, args, kwargs, request)
<ide> except Exception as exc:
<ide> _signal_internal_error(task, uuid, args, kwargs, request, exc)
<del> return trace_ok_t(report_internal_error(task, exc), None, 0.0, None)
<add> return trace_ok_t(report_internal_error(task, exc), TraceInfo(FAILURE, exc), 0.0, None)
<ide>
<ide>
<ide> def _signal_internal_error(task, uuid, args, kwargs, request, exc):
<ide><path>celery/worker/request.py
<ide> def execute(self, loglevel=None, logfile=None):
<ide> 'logfile': logfile,
<ide> 'is_eager': False,
<ide> }, **embed or {})
<del> retval = trace_task(self.task, self.id, self._args, self._kwargs, request,
<del> hostname=self._hostname, loader=self._app.loader,
<del> app=self._app)[0]
<del> self.acknowledge()
<add>
<add> retval, I, _, _ = trace_task(self.task, self.id, self._args, self._kwargs, request,
<add> hostname=self._hostname, loader=self._app.loader,
<add> app=self._app)
<add>
<add> if I:
<add> self.reject(requeue=False)
<add> else:
<add> self.acknowledge()
<ide> return retval
<ide>
<ide> def maybe_expire(self):
<ide><path>t/unit/tasks/test_trace.py
<ide> from __future__ import absolute_import, unicode_literals
<ide>
<ide> import pytest
<add>from billiard.einfo import ExceptionInfo
<ide> from case import Mock, patch
<ide> from kombu.exceptions import EncodeError
<ide>
<ide> trace_task,
<ide> traceback_clear,
<ide> )
<add>from celery.backends.base import BaseDictBackend
<ide>
<ide> from celery.exceptions import Ignore, Reject, Retry
<ide>
<ide> def add(x, y):
<ide> with pytest.raises(MemoryError):
<ide> self.trace(add, (2, 2), {}, eager=False)
<ide>
<add> def test_when_backend_raises_exception(self):
<add> @self.app.task(shared=False)
<add> def add(x, y):
<add> return x + y
<add>
<add> add.backend = Mock(name='backend')
<add> add.backend.mark_as_done.side_effect = Exception()
<add> add.backend.mark_as_failure.side_effect = Exception("failed mark_as_failure")
<add>
<add> with pytest.raises(Exception):
<add> self.trace(add, (2, 2), {}, eager=False)
<add>
<ide> def test_traceback_clear(self):
<ide> import inspect
<ide> import sys
<ide> def xtask():
<ide> assert send.call_count
<ide> assert xtask.__trace__ is tracer
<ide>
<add> def test_backend_error_should_report_failure(self):
<add> """check internal error is reported as failure.
<add>
<add> In case of backend error, an exception may bubble up from trace and be
<add> caught by trace_task.
<add> """
<add>
<add> @self.app.task(shared=False)
<add> def xtask():
<add> pass
<add>
<add> xtask.backend = BaseDictBackend(app=self.app)
<add> xtask.backend.mark_as_done = Mock()
<add> xtask.backend.mark_as_done.side_effect = Exception()
<add> xtask.backend.mark_as_failure = Mock()
<add> xtask.backend.mark_as_failure.side_effect = Exception()
<add>
<add> ret, info, _, _ = trace_task(xtask, 'uuid', (), {}, app=self.app)
<add> assert info is not None
<add> assert isinstance(ret, ExceptionInfo)
<add>
<ide>
<ide> class test_TraceInfo(TraceCase):
<ide> class TI(TraceInfo):
<ide><path>t/unit/worker/test_request.py
<ide> from celery.app.trace import (TraceInfo, _trace_task_ret, build_tracer,
<ide> mro_lookup, reset_worker_optimizations,
<ide> setup_worker_optimizations, trace_task)
<add>from celery.backends.base import BaseDictBackend
<ide> from celery.exceptions import (Ignore, InvalidTaskError, Reject, Retry,
<ide> TaskRevokedError, Terminated, WorkerLostError)
<ide> from celery.five import monotonic
<ide> def test_execute(self):
<ide> assert meta['status'] == states.SUCCESS
<ide> assert meta['result'] == 256
<ide>
<add> def test_execute_backend_error_acks_late(self):
<add> """direct call to execute should reject task in case of internal failure."""
<add> tid = uuid()
<add> self.mytask.acks_late = True
<add> job = self.xRequest(id=tid, args=[4], kwargs={})
<add> job._on_reject = Mock()
<add> job._on_ack = Mock()
<add> self.mytask.backend = BaseDictBackend(app=self.app)
<add> self.mytask.backend.mark_as_done = Mock()
<add> self.mytask.backend.mark_as_done.side_effect = Exception()
<add> self.mytask.backend.mark_as_failure = Mock()
<add> self.mytask.backend.mark_as_failure.side_effect = Exception()
<add>
<add> job.execute()
<add>
<add> assert job.acknowledged
<add> job._on_reject.assert_called_once()
<add> job._on_ack.assert_not_called()
<add>
<ide> def test_execute_success_no_kwargs(self):
<ide>
<ide> @self.app.task # traverses coverage for decorator without parens | 4 |
Text | Text | add next_locale cookie note to docs | 782537dd2d265d718c5e2e3a5e51dd418df0f366 | <ide><path>docs/advanced-features/i18n-routing.md
<ide> export default function IndexPage(props) {
<ide> }
<ide> ```
<ide>
<add>## Leveraging the NEXT_LOCALE cookie
<add>
<add>Next.js supports overriding the accept-language header with a `NEXT_LOCALE=the-locale` cookie. This cookie can be set using a language switcher and then when a user comes back to the site it will leverage the locale specified in the cookie.
<add>
<add>For example, if a user prefers the locale `fr` but a `NEXT_LOCALE=en` cookie is set the `en` locale will be used instead until the cookie is removed or expired.
<add>
<ide> ## Search Engine Optimization
<ide>
<ide> Since Next.js knows what language the user is visiting it will automatically add the `lang` attribute to the `<html>` tag. | 1 |
Python | Python | add tap output to the test runner | 14ed1732cee8d1e721977eb2673b88995ef46608 | <ide><path>tools/test.py
<ide> def HasRun(self, output):
<ide> sys.stdout.flush()
<ide>
<ide>
<add>class TapProgressIndicator(SimpleProgressIndicator):
<add>
<add> def Starting(self):
<add> print '1..%i' % len(self.cases)
<add> self._done = 0
<add>
<add> def AboutToRun(self, case):
<add> pass
<add>
<add> def HasRun(self, output):
<add> self._done += 1
<add> command = basename(output.command[1])
<add> if output.UnexpectedOutput():
<add> print 'not ok %i - %s' % (self._done, command)
<add> for l in output.output.stderr.split(os.linesep):
<add> print '#' + l
<add> for l in output.output.stdout.split(os.linesep):
<add> print '#' + l
<add> else:
<add> print 'ok %i - %s' % (self._done, command)
<add>
<add> def Done(self):
<add> pass
<add>
<add>
<ide> class CompactProgressIndicator(ProgressIndicator):
<ide>
<ide> def __init__(self, cases, templates):
<ide> def ClearLine(self, last_line_length):
<ide> 'verbose': VerboseProgressIndicator,
<ide> 'dots': DotsProgressIndicator,
<ide> 'color': ColorProgressIndicator,
<add> 'tap': TapProgressIndicator,
<ide> 'mono': MonochromeProgressIndicator
<ide> }
<ide>
<ide> def BuildOptions():
<ide> result.add_option("-S", dest="scons_flags", help="Flag to pass through to scons",
<ide> default=[], action="append")
<ide> result.add_option("-p", "--progress",
<del> help="The style of progress indicator (verbose, dots, color, mono)",
<add> help="The style of progress indicator (verbose, dots, color, mono, tap)",
<ide> choices=PROGRESS_INDICATORS.keys(), default="mono")
<ide> result.add_option("--no-build", help="Don't build requirements",
<ide> default=True, action="store_true") | 1 |
Java | Java | refine names in web.server and polish javadoc | 381855aaf315adfd44e22797bbf14f07d08155d9 | <ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/DispatcherHandler.java
<ide> import org.springframework.core.annotation.AnnotationAwareOrderComparator;
<ide> import org.springframework.http.server.reactive.ServerHttpRequest;
<ide> import org.springframework.web.server.WebHandler;
<del>import org.springframework.web.server.WebServerExchange;
<add>import org.springframework.web.server.ServerWebExchange;
<ide>
<ide> /**
<ide> * Central dispatcher for HTTP request handlers/controllers. Dispatches to registered
<ide> protected void initStrategies(ApplicationContext context) {
<ide>
<ide>
<ide> @Override
<del> public Mono<Void> handle(WebServerExchange exchange) {
<add> public Mono<Void> handle(ServerWebExchange exchange) {
<ide> if (logger.isDebugEnabled()) {
<ide> ServerHttpRequest request = exchange.getRequest();
<ide> logger.debug("Processing " + request.getMethod() + " request for [" + request.getURI() + "]");
<ide> public Mono<Void> handle(WebServerExchange exchange) {
<ide> .otherwise(ex -> Mono.error(this.errorMapper.apply(ex)));
<ide> }
<ide>
<del> private Mono<HandlerResult> invokeHandler(WebServerExchange exchange, Object handler) {
<add> private Mono<HandlerResult> invokeHandler(ServerWebExchange exchange, Object handler) {
<ide> for (HandlerAdapter handlerAdapter : this.handlerAdapters) {
<ide> if (handlerAdapter.supports(handler)) {
<ide> return handlerAdapter.handle(exchange, handler);
<ide> private Mono<HandlerResult> invokeHandler(WebServerExchange exchange, Object han
<ide> return Mono.error(new IllegalStateException("No HandlerAdapter: " + handler));
<ide> }
<ide>
<del> private Mono<Void> handleResult(WebServerExchange exchange, HandlerResult result) {
<add> private Mono<Void> handleResult(ServerWebExchange exchange, HandlerResult result) {
<ide> return getResultHandler(result).handleResult(exchange, result)
<ide> .otherwise(ex -> result.applyExceptionHandler(ex).then(exceptionResult ->
<ide> getResultHandler(result).handleResult(exchange, exceptionResult)));
<ide> private static class NotFoundHandlerMapping implements HandlerMapping {
<ide>
<ide>
<ide> @Override
<del> public Mono<Object> getHandler(WebServerExchange exchange) {
<add> public Mono<Object> getHandler(ServerWebExchange exchange) {
<ide> return Mono.error(HANDLER_NOT_FOUND_EXCEPTION);
<ide> }
<ide> }
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/HandlerAdapter.java
<ide>
<ide> import reactor.core.publisher.Mono;
<ide>
<del>import org.springframework.web.server.WebServerExchange;
<add>import org.springframework.web.server.ServerWebExchange;
<ide>
<ide> /**
<ide> * Contract that decouples the {@link DispatcherHandler} from the details of
<ide> public interface HandlerAdapter {
<ide> * @return {@link Mono} that emits a single {@code HandlerResult} or none if
<ide> * the request has been fully handled and doesn't require further handling.
<ide> */
<del> Mono<HandlerResult> handle(WebServerExchange exchange, Object handler);
<add> Mono<HandlerResult> handle(ServerWebExchange exchange, Object handler);
<ide>
<ide> }
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/HandlerMapping.java
<ide>
<ide> import reactor.core.publisher.Mono;
<ide>
<del>import org.springframework.web.server.WebServerExchange;
<add>import org.springframework.web.server.ServerWebExchange;
<ide>
<ide> /**
<ide> * Interface to be implemented by objects that define a mapping between
<ide> public interface HandlerMapping {
<ide> * @return A {@link Mono} that emits one value or none in case the request
<ide> * cannot be resolved to a handler
<ide> */
<del> Mono<Object> getHandler(WebServerExchange exchange);
<add> Mono<Object> getHandler(ServerWebExchange exchange);
<ide>
<ide> }
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/HandlerResultHandler.java
<ide>
<ide> import reactor.core.publisher.Mono;
<ide>
<del>import org.springframework.web.server.WebServerExchange;
<add>import org.springframework.web.server.ServerWebExchange;
<ide>
<ide> /**
<ide> * Process the {@link HandlerResult}, usually returned by an {@link HandlerAdapter}.
<ide> public interface HandlerResultHandler {
<ide> * @param result the result from the handling
<ide> * @return {@code Mono<Void>} to indicate when request handling is complete.
<ide> */
<del> Mono<Void> handleResult(WebServerExchange exchange, HandlerResult result);
<add> Mono<Void> handleResult(ServerWebExchange exchange, HandlerResult result);
<ide>
<ide> }
<ide>\ No newline at end of file
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/ResponseStatusExceptionHandler.java
<ide>
<ide> import org.springframework.web.ResponseStatusException;
<ide> import org.springframework.web.server.WebExceptionHandler;
<del>import org.springframework.web.server.WebServerExchange;
<add>import org.springframework.web.server.ServerWebExchange;
<ide>
<ide> /**
<ide> * Handle {@link ResponseStatusException} by setting the response status.
<ide> public class ResponseStatusExceptionHandler implements WebExceptionHandler {
<ide>
<ide>
<ide> @Override
<del> public Mono<Void> handle(WebServerExchange exchange, Throwable ex) {
<add> public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
<ide> if (ex instanceof ResponseStatusException) {
<ide> exchange.getResponse().setStatusCode(((ResponseStatusException) ex).getHttpStatus());
<ide> return Mono.empty();
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/handler/HttpHandlerHandlerAdapter.java
<ide> import org.springframework.web.reactive.HandlerAdapter;
<ide> import org.springframework.web.reactive.HandlerResult;
<ide> import org.springframework.web.server.WebHandler;
<del>import org.springframework.web.server.WebServerExchange;
<add>import org.springframework.web.server.ServerWebExchange;
<ide>
<ide> /**
<ide> * Support use of {@link org.springframework.web.server.WebHandler} through the
<ide> public boolean supports(Object handler) {
<ide> }
<ide>
<ide> @Override
<del> public Mono<HandlerResult> handle(WebServerExchange exchange, Object handler) {
<add> public Mono<HandlerResult> handle(ServerWebExchange exchange, Object handler) {
<ide> WebHandler webHandler = (WebHandler) handler;
<ide> Mono<Void> completion = webHandler.handle(exchange);
<ide> return Mono.just(new HandlerResult(webHandler, completion, PUBLISHER_VOID));
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/handler/SimpleHandlerResultHandler.java
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.web.reactive.HandlerResult;
<ide> import org.springframework.web.reactive.HandlerResultHandler;
<del>import org.springframework.web.server.WebServerExchange;
<add>import org.springframework.web.server.ServerWebExchange;
<ide>
<ide> /**
<ide> * Supports {@link HandlerResult} with a {@code void} or {@code Publisher<Void>} value.
<ide> private boolean isConvertibleToPublisher(ResolvableType type) {
<ide>
<ide> @SuppressWarnings("unchecked")
<ide> @Override
<del> public Mono<Void> handleResult(WebServerExchange exchange, HandlerResult result) {
<add> public Mono<Void> handleResult(ServerWebExchange exchange, HandlerResult result) {
<ide> Object value = result.getResult();
<ide> if (Void.TYPE.equals(result.getResultType().getRawClass())) {
<ide> return Mono.empty();
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/handler/SimpleUrlHandlerMapping.java
<ide> import reactor.core.publisher.Mono;
<ide>
<ide> import org.springframework.web.reactive.HandlerMapping;
<del>import org.springframework.web.server.WebServerExchange;
<add>import org.springframework.web.server.ServerWebExchange;
<ide>
<ide> /**
<ide> * @author Rossen Stoyanchev
<ide> public void setHandlers(Map<String, Object> handlers) {
<ide>
<ide>
<ide> @Override
<del> public Mono<Object> getHandler(WebServerExchange exchange) {
<add> public Mono<Object> getHandler(ServerWebExchange exchange) {
<ide> return Flux.create(subscriber -> {
<ide> String path = exchange.getRequest().getURI().getPath();
<ide> Object handler = this.handlerMap.get(path);
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/method/HandlerMethodArgumentResolver.java
<ide> import reactor.core.publisher.Mono;
<ide>
<ide> import org.springframework.core.MethodParameter;
<del>import org.springframework.web.server.WebServerExchange;
<add>import org.springframework.web.server.ServerWebExchange;
<ide>
<ide>
<ide> /**
<ide> public interface HandlerMethodArgumentResolver {
<ide> * does not resolve to any value, which will result in {@code null} passed
<ide> * as the argument value.
<ide> */
<del> Mono<Object> resolveArgument(MethodParameter parameter, WebServerExchange exchange);
<add> Mono<Object> resolveArgument(MethodParameter parameter, ServerWebExchange exchange);
<ide>
<ide> }
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/method/InvocableHandlerMethod.java
<ide> import org.springframework.util.ReflectionUtils;
<ide> import org.springframework.web.method.HandlerMethod;
<ide> import org.springframework.web.reactive.HandlerResult;
<del>import org.springframework.web.server.WebServerExchange;
<add>import org.springframework.web.server.ServerWebExchange;
<ide>
<ide>
<ide> /**
<ide> protected Method getBridgedMethod() {
<ide> * @return Publisher that produces a single HandlerResult or an error signal;
<ide> * never throws an exception
<ide> */
<del> public Mono<HandlerResult> invokeForRequest(WebServerExchange exchange, Object... providedArgs) {
<add> public Mono<HandlerResult> invokeForRequest(ServerWebExchange exchange, Object... providedArgs) {
<ide> return resolveArguments(exchange, providedArgs).then(args -> {
<ide> try {
<ide> Object value = doInvoke(args);
<ide> public Mono<HandlerResult> invokeForRequest(WebServerExchange exchange, Object..
<ide> });
<ide> }
<ide>
<del> private Mono<Object[]> resolveArguments(WebServerExchange exchange, Object... providedArgs) {
<add> private Mono<Object[]> resolveArguments(ServerWebExchange exchange, Object... providedArgs) {
<ide> if (ObjectUtils.isEmpty(getMethodParameters())) {
<ide> return NO_ARGS;
<ide> }
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/method/annotation/RequestBodyArgumentResolver.java
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.web.bind.annotation.RequestBody;
<ide> import org.springframework.web.reactive.method.HandlerMethodArgumentResolver;
<del>import org.springframework.web.server.WebServerExchange;
<add>import org.springframework.web.server.ServerWebExchange;
<ide>
<ide> /**
<ide> * @author Sebastien Deleuze
<ide> public boolean supportsParameter(MethodParameter parameter) {
<ide> }
<ide>
<ide> @Override
<del> public Mono<Object> resolveArgument(MethodParameter parameter, WebServerExchange exchange) {
<add> public Mono<Object> resolveArgument(MethodParameter parameter, ServerWebExchange exchange) {
<ide> MediaType mediaType = exchange.getRequest().getHeaders().getContentType();
<ide> if (mediaType == null) {
<ide> mediaType = MediaType.APPLICATION_OCTET_STREAM;
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/method/annotation/RequestMappingHandlerAdapter.java
<ide> import org.springframework.web.reactive.HandlerResult;
<ide> import org.springframework.web.reactive.method.HandlerMethodArgumentResolver;
<ide> import org.springframework.web.reactive.method.InvocableHandlerMethod;
<del>import org.springframework.web.server.WebServerExchange;
<add>import org.springframework.web.server.ServerWebExchange;
<ide>
<ide>
<ide> /**
<ide> public boolean supports(Object handler) {
<ide> }
<ide>
<ide> @Override
<del> public Mono<HandlerResult> handle(WebServerExchange exchange, Object handler) {
<add> public Mono<HandlerResult> handle(ServerWebExchange exchange, Object handler) {
<ide> HandlerMethod handlerMethod = (HandlerMethod) handler;
<ide> InvocableHandlerMethod invocable = new InvocableHandlerMethod(handlerMethod);
<ide> invocable.setHandlerMethodArgumentResolvers(this.argumentResolvers);
<ide> public Mono<HandlerResult> handle(WebServerExchange exchange, Object handler) {
<ide> }
<ide>
<ide> private Mono<HandlerResult> handleException(Throwable ex, HandlerMethod handlerMethod,
<del> WebServerExchange exchange) {
<add> ServerWebExchange exchange) {
<ide>
<ide> if (ex instanceof Exception) {
<ide> InvocableHandlerMethod invocable = findExceptionHandler(handlerMethod, (Exception) ex);
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/method/annotation/RequestMappingHandlerMapping.java
<ide> import org.springframework.web.method.HandlerMethod;
<ide> import org.springframework.web.method.HandlerMethodSelector;
<ide> import org.springframework.web.reactive.HandlerMapping;
<del>import org.springframework.web.server.WebServerExchange;
<add>import org.springframework.web.server.ServerWebExchange;
<ide>
<ide>
<ide> /**
<ide> protected void detectHandlerMethods(final Object bean) {
<ide> }
<ide>
<ide> @Override
<del> public Mono<Object> getHandler(WebServerExchange exchange) {
<add> public Mono<Object> getHandler(ServerWebExchange exchange) {
<ide> return Flux.create(subscriber -> {
<ide> for (Map.Entry<RequestMappingInfo, HandlerMethod> entry : this.methodMap.entrySet()) {
<ide> RequestMappingInfo info = entry.getKey();
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/method/annotation/RequestParamArgumentResolver.java
<ide> import org.springframework.core.MethodParameter;
<ide> import org.springframework.web.bind.annotation.RequestParam;
<ide> import org.springframework.web.reactive.method.HandlerMethodArgumentResolver;
<del>import org.springframework.web.server.WebServerExchange;
<add>import org.springframework.web.server.ServerWebExchange;
<ide> import org.springframework.web.util.UriComponents;
<ide> import org.springframework.web.util.UriComponentsBuilder;
<ide>
<ide> public boolean supportsParameter(MethodParameter parameter) {
<ide>
<ide>
<ide> @Override
<del> public Mono<Object> resolveArgument(MethodParameter param, WebServerExchange exchange) {
<add> public Mono<Object> resolveArgument(MethodParameter param, ServerWebExchange exchange) {
<ide> RequestParam annotation = param.getParameterAnnotation(RequestParam.class);
<ide> String name = (annotation.value().length() != 0 ? annotation.value() : param.getParameterName());
<ide> UriComponents uriComponents = UriComponentsBuilder.fromUri(exchange.getRequest().getURI()).build();
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/method/annotation/ResponseBodyResultHandler.java
<ide> import org.springframework.web.method.HandlerMethod;
<ide> import org.springframework.web.reactive.HandlerResult;
<ide> import org.springframework.web.reactive.HandlerResultHandler;
<del>import org.springframework.web.server.WebServerExchange;
<add>import org.springframework.web.server.ServerWebExchange;
<ide>
<ide>
<ide> /**
<ide> public boolean supports(HandlerResult result) {
<ide>
<ide> @Override
<ide> @SuppressWarnings("unchecked")
<del> public Mono<Void> handleResult(WebServerExchange exchange, HandlerResult result) {
<add> public Mono<Void> handleResult(ServerWebExchange exchange, HandlerResult result) {
<ide>
<ide> Object value = result.getResult();
<ide> if (value == null) {
<add><path>spring-web-reactive/src/main/java/org/springframework/web/server/ServerWebExchange.java
<del><path>spring-web-reactive/src/main/java/org/springframework/web/server/WebServerExchange.java
<ide> *
<ide> * @author Rossen Stoyanchev
<ide> */
<del>public interface WebServerExchange {
<add>public interface ServerWebExchange {
<ide>
<ide> /**
<ide> * Return the current HTTP request.
<ide> public interface WebServerExchange {
<ide> Map<String, Object> getAttributes();
<ide>
<ide> /**
<del> *
<add> * Return the web session for the current request. Always guaranteed to
<add> * return an instance either matching to the session id requested by the
<add> * client, or with a new session id either because the client did not
<add> * specify one or because the underlying session had expired. Use of this
<add> * method does not automatically create a session. See {@link WebSession}
<add> * for more details.
<ide> */
<ide> Mono<WebSession> getSession();
<ide>
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/server/WebExceptionHandler.java
<ide> public interface WebExceptionHandler {
<ide> * @param ex the exception to handle
<ide> * @return {@code Mono<Void>} to indicate when exception handling is complete
<ide> */
<del> Mono<Void> handle(WebServerExchange exchange, Throwable ex);
<add> Mono<Void> handle(ServerWebExchange exchange, Throwable ex);
<ide>
<ide> }
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/server/WebFilter.java
<ide> public interface WebFilter {
<ide> * @param chain provides a way to delegate to the next filter
<ide> * @return {@code Mono<Void>} to indicate when request processing is complete
<ide> */
<del> Mono<Void> filter(WebServerExchange exchange, WebFilterChain chain);
<add> Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain);
<ide>
<ide> }
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/server/WebFilterChain.java
<ide> public interface WebFilterChain {
<ide> * @param exchange the current server exchange
<ide> * @return {@code Mono<Void>} to indicate when request handling is complete
<ide> */
<del> Mono<Void> filter(WebServerExchange exchange);
<add> Mono<Void> filter(ServerWebExchange exchange);
<ide>
<ide> }
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/server/WebHandler.java
<ide>
<ide> import reactor.core.publisher.Mono;
<ide>
<del>import org.springframework.web.server.adapter.WebToHttpHandlerAdapter;
<del>import org.springframework.web.server.adapter.WebToHttpHandlerBuilder;
<add>import org.springframework.web.server.adapter.WebHttpHandlerAdapter;
<add>import org.springframework.web.server.adapter.WebHttpHandlerBuilder;
<ide>
<ide> /**
<ide> * Contract to handle a web server exchange.
<ide> *
<del> * <p>Use {@link WebToHttpHandlerAdapter} to adapt a {@code WebHandler} to an
<add> * <p>Use {@link WebHttpHandlerAdapter} to adapt a {@code WebHandler} to an
<ide> * {@link org.springframework.http.server.reactive.HttpHandler HttpHandler}.
<del> * The {@link WebToHttpHandlerBuilder} provides a convenient way to do that while
<add> * The {@link WebHttpHandlerBuilder} provides a convenient way to do that while
<ide> * also optionally configuring one or more filters and/or exception handlers.
<ide> *
<ide> * @author Rossen Stoyanchev
<del> * @see WebToHttpHandlerBuilder
<add> * @see WebHttpHandlerBuilder
<ide> */
<ide> public interface WebHandler {
<ide>
<ide> public interface WebHandler {
<ide> * @param exchange the current server exchange
<ide> * @return {@code Mono<Void>} to indicate when request handling is complete
<ide> */
<del> Mono<Void> handle(WebServerExchange exchange);
<add> Mono<Void> handle(ServerWebExchange exchange);
<ide>
<ide> }
<add><path>spring-web-reactive/src/main/java/org/springframework/web/server/adapter/DefaultServerWebExchange.java
<del><path>spring-web-reactive/src/main/java/org/springframework/web/server/adapter/DefaultWebServerExchange.java
<ide> import org.springframework.http.server.reactive.ServerHttpRequest;
<ide> import org.springframework.http.server.reactive.ServerHttpResponse;
<ide> import org.springframework.util.Assert;
<del>import org.springframework.web.server.WebServerExchange;
<add>import org.springframework.web.server.ServerWebExchange;
<ide> import org.springframework.web.server.WebSession;
<ide> import org.springframework.web.server.session.WebSessionManager;
<ide>
<ide> /**
<del> * Default implementation of {@link WebServerExchange}.
<add> * Default implementation of {@link ServerWebExchange}.
<ide> *
<ide> * @author Rossen Stoyanchev
<ide> */
<del>public class DefaultWebServerExchange implements WebServerExchange {
<add>public class DefaultServerWebExchange implements ServerWebExchange {
<ide>
<ide> private final ServerHttpRequest request;
<ide>
<ide> public class DefaultWebServerExchange implements WebServerExchange {
<ide>
<ide>
<ide>
<del> public DefaultWebServerExchange(ServerHttpRequest request, ServerHttpResponse response,
<add> public DefaultServerWebExchange(ServerHttpRequest request, ServerHttpResponse response,
<ide> WebSessionManager sessionManager) {
<ide>
<ide> Assert.notNull(request, "'request' is required.");
<add><path>spring-web-reactive/src/main/java/org/springframework/web/server/adapter/WebHttpHandlerAdapter.java
<del><path>spring-web-reactive/src/main/java/org/springframework/web/server/adapter/WebToHttpHandlerAdapter.java
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.web.server.WebHandler;
<ide> import org.springframework.web.server.handler.WebHandlerDecorator;
<del>import org.springframework.web.server.WebServerExchange;
<add>import org.springframework.web.server.ServerWebExchange;
<ide> import org.springframework.web.server.session.DefaultWebSessionManager;
<ide> import org.springframework.web.server.session.WebSessionManager;
<ide>
<ide> /**
<del> * Adapt {@link WebHandler} to {@link HttpHandler} also creating the
<del> * {@link WebServerExchange} before invoking the target {@code WebHandler}.
<add> * Default adapter of {@link WebHandler} to the {@link HttpHandler} contract.
<add> *
<add> * <p>By default creates and configures a {@link DefaultServerWebExchange} and
<add> * then invokes the target {@code WebHandler}.
<ide> *
<ide> * @author Rossen Stoyanchev
<ide> */
<del>public class WebToHttpHandlerAdapter extends WebHandlerDecorator implements HttpHandler {
<add>public class WebHttpHandlerAdapter extends WebHandlerDecorator implements HttpHandler {
<ide>
<del> private static Log logger = LogFactory.getLog(WebToHttpHandlerAdapter.class);
<add> private static Log logger = LogFactory.getLog(WebHttpHandlerAdapter.class);
<ide>
<ide>
<ide> private WebSessionManager sessionManager = new DefaultWebSessionManager();
<ide>
<ide>
<del> public WebToHttpHandlerAdapter(WebHandler delegate) {
<add> public WebHttpHandlerAdapter(WebHandler delegate) {
<ide> super(delegate);
<ide> }
<ide>
<ide>
<ide> /**
<del> *
<del> * @param sessionManager
<add> * Configure a custom {@link WebSessionManager} to use for managing web
<add> * sessions. The provided instance is set on each created
<add> * {@link DefaultServerWebExchange}.
<add> * <p>By default this is set to {@link DefaultWebSessionManager}.
<add> * @param sessionManager the session manager to use
<ide> */
<ide> public void setSessionManager(WebSessionManager sessionManager) {
<ide> Assert.notNull(sessionManager, "'sessionManager' must not be null.");
<ide> public WebSessionManager getSessionManager() {
<ide>
<ide> @Override
<ide> public Mono<Void> handle(ServerHttpRequest request, ServerHttpResponse response) {
<del> WebServerExchange exchange = createWebServerExchange(request, response);
<add> ServerWebExchange exchange = createExchange(request, response);
<ide> return getDelegate().handle(exchange)
<ide> .otherwise(ex -> {
<ide> if (logger.isDebugEnabled()) {
<ide> public Mono<Void> handle(ServerHttpRequest request, ServerHttpResponse response)
<ide> .after(response::setComplete);
<ide> }
<ide>
<del> protected WebServerExchange createWebServerExchange(ServerHttpRequest request, ServerHttpResponse response) {
<del> return new DefaultWebServerExchange(request, response, this.sessionManager);
<add> protected ServerWebExchange createExchange(ServerHttpRequest request, ServerHttpResponse response) {
<add> return new DefaultServerWebExchange(request, response, this.sessionManager);
<ide> }
<ide>
<ide> }
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/server/adapter/WebHttpHandlerBuilder.java
<add>/*
<add> * Copyright 2002-2015 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>package org.springframework.web.server.adapter;
<add>
<add>import java.util.ArrayList;
<add>import java.util.Arrays;
<add>import java.util.List;
<add>
<add>import org.springframework.http.server.reactive.HttpHandler;
<add>import org.springframework.util.Assert;
<add>import org.springframework.util.ObjectUtils;
<add>import org.springframework.web.server.ServerWebExchange;
<add>import org.springframework.web.server.WebExceptionHandler;
<add>import org.springframework.web.server.WebFilter;
<add>import org.springframework.web.server.WebHandler;
<add>import org.springframework.web.server.handler.ExceptionHandlingWebHandler;
<add>import org.springframework.web.server.handler.FilteringWebHandler;
<add>import org.springframework.web.server.session.WebSessionManager;
<add>
<add>/**
<add> * Build an {@link org.springframework.http.server.reactive.HttpHandler HttpHandler}
<add> * to handle requests with a chain of {@link #filters(WebFilter...) web filters},
<add> * a target {@link #webHandler(WebHandler) web handler}, and apply one or more
<add> * {@link #exceptionHandlers(WebExceptionHandler...) exception handlers}.
<add> *
<add> * <p>Effective this sets up the following {@code WebHandler} delegation:<br>
<add> * {@link WebHttpHandlerAdapter} {@code -->}
<add> * {@link ExceptionHandlingWebHandler} {@code -->}
<add> * {@link FilteringWebHandler} {@code -->}
<add> * {@link WebHandler}
<add> *
<add> * <p>Example usage:
<add> * <pre>
<add> * WebFilter myFilter = ... ;
<add> * WebHandler myHandler = ... ;
<add> *
<add> * HttpHandler httpHandler = WebToHttpHandlerBuilder.webHandler(myHandler)
<add> * .filters(myFilter)
<add> * .exceptionHandlers(new ResponseStatusExceptionHandler())
<add> * .build();
<add> *
<add> * // Configure the HttpServer with the created httpHandler
<add> * </pre>
<add> *
<add> * @author Rossen Stoyanchev
<add> */
<add>public class WebHttpHandlerBuilder {
<add>
<add> private final WebHandler targetHandler;
<add>
<add> private final List<WebFilter> filters = new ArrayList<>();
<add>
<add> private final List<WebExceptionHandler> exceptionHandlers = new ArrayList<>();
<add>
<add> private WebSessionManager sessionManager;
<add>
<add>
<add> /**
<add> * Private constructor.
<add> * See static factory method {@link #webHandler(WebHandler)}.
<add> */
<add> private WebHttpHandlerBuilder(WebHandler targetHandler) {
<add> Assert.notNull(targetHandler, "'targetHandler' must not be null");
<add> this.targetHandler = targetHandler;
<add> }
<add>
<add>
<add> /**
<add> * Factory method to create a new builder instance.
<add> * @param targetHandler the target handler to process requests with
<add> */
<add> public static WebHttpHandlerBuilder webHandler(WebHandler targetHandler) {
<add> return new WebHttpHandlerBuilder(targetHandler);
<add> }
<add>
<add>
<add> /**
<add> * Add the given filters to use for processing requests.
<add> * @param filters the filters to add
<add> */
<add> public WebHttpHandlerBuilder filters(WebFilter... filters) {
<add> if (!ObjectUtils.isEmpty(filters)) {
<add> this.filters.addAll(Arrays.asList(filters));
<add> }
<add> return this;
<add> }
<add>
<add> /**
<add> * Add the given exception handler to apply at the end of request processing.
<add> * @param exceptionHandlers the exception handlers
<add> */
<add> public WebHttpHandlerBuilder exceptionHandlers(WebExceptionHandler... exceptionHandlers) {
<add> if (!ObjectUtils.isEmpty(exceptionHandlers)) {
<add> this.exceptionHandlers.addAll(Arrays.asList(exceptionHandlers));
<add> }
<add> return this;
<add> }
<add>
<add> /**
<add> * Configure the {@link WebSessionManager} to set on the
<add> * {@link ServerWebExchange WebServerExchange}
<add> * created for each HTTP request.
<add> * @param sessionManager the session manager
<add> */
<add> public WebHttpHandlerBuilder sessionManager(WebSessionManager sessionManager) {
<add> this.sessionManager = sessionManager;
<add> return this;
<add> }
<add>
<add> /**
<add> * Build the {@link HttpHandler}.
<add> */
<add> public HttpHandler build() {
<add> WebHandler handler = createWebHandler();
<add> return adaptWebHandler(handler);
<add> }
<add>
<add> /**
<add> * Create the final (decorated) {@link WebHandler} to use.
<add> */
<add> protected WebHandler createWebHandler() {
<add> WebHandler webHandler = this.targetHandler;
<add> if (!this.exceptionHandlers.isEmpty()) {
<add> WebExceptionHandler[] array = new WebExceptionHandler[this.exceptionHandlers.size()];
<add> webHandler = new ExceptionHandlingWebHandler(webHandler, this.exceptionHandlers.toArray(array));
<add> }
<add> if (!this.filters.isEmpty()) {
<add> WebFilter[] array = new WebFilter[this.filters.size()];
<add> webHandler = new FilteringWebHandler(webHandler, this.filters.toArray(array));
<add> }
<add> return webHandler;
<add> }
<add>
<add> /**
<add> * Adapt the {@link WebHandler} to {@link HttpHandler}.
<add> */
<add> protected WebHttpHandlerAdapter adaptWebHandler(WebHandler handler) {
<add> WebHttpHandlerAdapter adapter = new WebHttpHandlerAdapter(handler);
<add> if (this.sessionManager != null) {
<add> adapter.setSessionManager(this.sessionManager);
<add> }
<add> return adapter;
<add> }
<add>
<add>}
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/server/adapter/WebToHttpHandlerBuilder.java
<del>/*
<del> * Copyright 2002-2015 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> * http://www.apache.org/licenses/LICENSE-2.0
<del> *
<del> * Unless required by applicable law or agreed to in writing, software
<del> * distributed under the License is distributed on an "AS IS" BASIS,
<del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<del> * See the License for the specific language governing permissions and
<del> * limitations under the License.
<del> */
<del>package org.springframework.web.server.adapter;
<del>
<del>import java.util.ArrayList;
<del>import java.util.Arrays;
<del>import java.util.List;
<del>
<del>import org.springframework.http.server.reactive.HttpHandler;
<del>import org.springframework.util.Assert;
<del>import org.springframework.util.ObjectUtils;
<del>import org.springframework.web.server.WebExceptionHandler;
<del>import org.springframework.web.server.WebFilter;
<del>import org.springframework.web.server.WebHandler;
<del>import org.springframework.web.server.handler.ExceptionHandlingWebHandler;
<del>import org.springframework.web.server.handler.FilteringWebHandler;
<del>import org.springframework.web.server.session.WebSessionManager;
<del>
<del>/**
<del> * Assist with building an
<del> * {@link org.springframework.http.server.reactive.HttpHandler HttpHandler} to
<del> * invoke a target {@link WebHandler} with an optional chain of
<del> * {@link WebFilter}s and one or more {@link WebExceptionHandler}s.
<del> *
<del> * <p>Effective this sets up the following {@code WebHandler} delegation:<br>
<del> * {@link WebToHttpHandlerAdapter} {@code -->}
<del> * {@link ExceptionHandlingWebHandler} {@code -->}
<del> * {@link FilteringWebHandler}
<del> *
<del> * @author Rossen Stoyanchev
<del> */
<del>public class WebToHttpHandlerBuilder {
<del>
<del> private final WebHandler targetHandler;
<del>
<del> private final List<WebFilter> filters = new ArrayList<>();
<del>
<del> private final List<WebExceptionHandler> exceptionHandlers = new ArrayList<>();
<del>
<del> private WebSessionManager sessionManager;
<del>
<del>
<del> private WebToHttpHandlerBuilder(WebHandler targetHandler) {
<del> Assert.notNull(targetHandler, "'targetHandler' must not be null");
<del> this.targetHandler = targetHandler;
<del> }
<del>
<del>
<del> public static WebToHttpHandlerBuilder webHandler(WebHandler webHandler) {
<del> return new WebToHttpHandlerBuilder(webHandler);
<del> }
<del>
<del> public WebToHttpHandlerBuilder filters(WebFilter... filters) {
<del> if (!ObjectUtils.isEmpty(filters)) {
<del> this.filters.addAll(Arrays.asList(filters));
<del> }
<del> return this;
<del> }
<del>
<del> public WebToHttpHandlerBuilder exceptionHandlers(WebExceptionHandler... exceptionHandlers) {
<del> if (!ObjectUtils.isEmpty(exceptionHandlers)) {
<del> this.exceptionHandlers.addAll(Arrays.asList(exceptionHandlers));
<del> }
<del> return this;
<del> }
<del>
<del> public WebToHttpHandlerBuilder sessionManager(WebSessionManager sessionManager) {
<del> this.sessionManager = sessionManager;
<del> return this;
<del> }
<del>
<del> public HttpHandler build() {
<del> WebHandler handler = this.targetHandler;
<del> if (!this.exceptionHandlers.isEmpty()) {
<del> WebExceptionHandler[] array = new WebExceptionHandler[this.exceptionHandlers.size()];
<del> handler = new ExceptionHandlingWebHandler(handler, this.exceptionHandlers.toArray(array));
<del> }
<del> if (!this.filters.isEmpty()) {
<del> WebFilter[] array = new WebFilter[this.filters.size()];
<del> handler = new FilteringWebHandler(handler, this.filters.toArray(array));
<del> }
<del> WebToHttpHandlerAdapter adapter = new WebToHttpHandlerAdapter(handler);
<del> if (this.sessionManager != null) {
<del> adapter.setSessionManager(this.sessionManager);
<del> }
<del> return adapter;
<del> }
<del>
<del>}
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/server/handler/ExceptionHandlingWebHandler.java
<ide> import org.springframework.http.HttpStatus;
<ide> import org.springframework.web.server.WebExceptionHandler;
<ide> import org.springframework.web.server.WebHandler;
<del>import org.springframework.web.server.WebServerExchange;
<add>import org.springframework.web.server.ServerWebExchange;
<ide>
<ide> /**
<del> * {@code WebHandler} that decorates another with exception handling using one
<del> * or more instances of {@link WebExceptionHandler}.
<add> * WebHandler that can invoke a target {@link WebHandler} and then apply
<add> * exception handling with one or more {@link WebExceptionHandler} instances.
<ide> *
<ide> * @author Rossen Stoyanchev
<ide> */
<ide> private static List<WebExceptionHandler> initList(WebExceptionHandler[] list) {
<ide>
<ide>
<ide> /**
<del> * @return a read-only list of the configured exception handlers.
<add> * Return a read-only list of the configured exception handlers.
<ide> */
<ide> public List<WebExceptionHandler> getExceptionHandlers() {
<ide> return this.exceptionHandlers;
<ide> }
<ide>
<ide>
<ide> @Override
<del> public Mono<Void> handle(WebServerExchange exchange) {
<add> public Mono<Void> handle(ServerWebExchange exchange) {
<ide> Mono<Void> mono;
<ide> try {
<ide> mono = getDelegate().handle(exchange);
<ide> public Mono<Void> handle(WebServerExchange exchange) {
<ide> return mono.otherwise(ex -> handleUnresolvedException(exchange, ex));
<ide> }
<ide>
<del> private Mono<? extends Void> handleUnresolvedException(WebServerExchange exchange, Throwable ex) {
<add> private Mono<? extends Void> handleUnresolvedException(ServerWebExchange exchange, Throwable ex) {
<ide> if (logger.isDebugEnabled()) {
<ide> logger.debug("Could not complete request", ex);
<ide> }
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/server/handler/FilteringWebHandler.java
<ide> import org.springframework.web.server.WebFilter;
<ide> import org.springframework.web.server.WebFilterChain;
<ide> import org.springframework.web.server.WebHandler;
<del>import org.springframework.web.server.WebServerExchange;
<add>import org.springframework.web.server.ServerWebExchange;
<ide>
<ide> /**
<del> * {@code WebHandler} that decorates another with a chain of {@link WebFilter}s.
<add> * WebHandler that delegates to a chain of {@link WebFilter} instances followed
<add> * by a target {@link WebHandler}.
<ide> *
<ide> * @author Rossen Stoyanchev
<ide> */
<ide> private static List<WebFilter> initList(WebFilter[] list) {
<ide>
<ide>
<ide> /**
<del> * @return a read-only list of the configured filters.
<add> * Return a read-only list of the configured filters.
<ide> */
<ide> public List<WebFilter> getFilters() {
<ide> return this.filters;
<ide> }
<ide>
<ide> @Override
<del> public Mono<Void> handle(WebServerExchange exchange) {
<add> public Mono<Void> handle(ServerWebExchange exchange) {
<ide> return new DefaultWebFilterChain().filter(exchange);
<ide> }
<ide>
<ide> private class DefaultWebFilterChain implements WebFilterChain {
<ide>
<ide>
<ide> @Override
<del> public Mono<Void> filter(WebServerExchange exchange) {
<add> public Mono<Void> filter(ServerWebExchange exchange) {
<ide> if (this.index < filters.size()) {
<ide> WebFilter filter = filters.get(this.index++);
<ide> return filter.filter(exchange, this);
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/server/handler/WebHandlerDecorator.java
<ide>
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.web.server.WebHandler;
<del>import org.springframework.web.server.WebServerExchange;
<add>import org.springframework.web.server.ServerWebExchange;
<ide>
<ide> /**
<del> * Base class for a {@link WebHandler} that decorates and delegates to another.
<add> * {@link WebHandler} that decorates and delegates to another.
<ide> *
<ide> * @author Rossen Stoyanchev
<ide> */
<ide> public WebHandler getDelegate() {
<ide>
<ide>
<ide> @Override
<del> public Mono<Void> handle(WebServerExchange exchange) {
<add> public Mono<Void> handle(ServerWebExchange exchange) {
<ide> return this.delegate.handle(exchange);
<ide> }
<ide>
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/server/session/CookieWebSessionIdResolver.java
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.util.CollectionUtils;
<ide> import org.springframework.util.StringUtils;
<del>import org.springframework.web.server.WebServerExchange;
<add>import org.springframework.web.server.ServerWebExchange;
<ide>
<ide> /**
<ide> * Cookie-based {@link WebSessionIdResolver}.
<ide> public Duration getCookieMaxAge() {
<ide>
<ide>
<ide> @Override
<del> public Optional<String> resolveSessionId(WebServerExchange exchange) {
<add> public Optional<String> resolveSessionId(ServerWebExchange exchange) {
<ide> HttpHeaders headers = exchange.getRequest().getHeaders();
<ide> List<HttpCookie> cookies = headers.getCookies().get(getCookieName());
<ide> return (CollectionUtils.isEmpty(cookies) ?
<ide> Optional.empty() : Optional.of(cookies.get(0).getValue()));
<ide> }
<ide>
<ide> @Override
<del> public void setSessionId(WebServerExchange exchange, String id) {
<add> public void setSessionId(ServerWebExchange exchange, String id) {
<ide> Duration maxAge = (StringUtils.hasText(id) ? getCookieMaxAge() : Duration.ofSeconds(0));
<ide> HttpCookie cookie = HttpCookie.serverCookie(getCookieName(), id).maxAge(maxAge).build();
<ide> HttpHeaders headers = exchange.getResponse().getHeaders();
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/server/session/DefaultWebSessionManager.java
<ide> import reactor.core.publisher.Mono;
<ide>
<ide> import org.springframework.util.Assert;
<del>import org.springframework.web.server.WebServerExchange;
<add>import org.springframework.web.server.ServerWebExchange;
<ide> import org.springframework.web.server.WebSession;
<ide>
<ide>
<ide> public Clock getClock() {
<ide>
<ide>
<ide> @Override
<del> public Mono<WebSession> getSession(WebServerExchange exchange) {
<add> public Mono<WebSession> getSession(ServerWebExchange exchange) {
<ide> return Mono.fromCallable(() -> getSessionIdResolver().resolveSessionId(exchange))
<ide> .where(Optional::isPresent)
<ide> .map(Optional::get)
<ide> public Mono<WebSession> getSession(WebServerExchange exchange) {
<ide> .map(session -> extendSession(exchange, session));
<ide> }
<ide>
<del> protected Mono<WebSession> validateSession(WebServerExchange exchange, WebSession session) {
<add> protected Mono<WebSession> validateSession(ServerWebExchange exchange, WebSession session) {
<ide> if (session.isExpired()) {
<ide> this.sessionIdResolver.setSessionId(exchange, "");
<ide> return this.sessionStore.removeSession(session.getId()).after(Mono::empty);
<ide> protected Mono<WebSession> validateSession(WebServerExchange exchange, WebSessio
<ide> }
<ide> }
<ide>
<del> protected Mono<WebSession> createSession(WebServerExchange exchange) {
<add> protected Mono<WebSession> createSession(ServerWebExchange exchange) {
<ide> String sessionId = UUID.randomUUID().toString();
<ide> WebSession session = new DefaultWebSession(sessionId, getClock());
<ide> return Mono.just(session);
<ide> }
<ide>
<del> protected WebSession extendSession(WebServerExchange exchange, WebSession session) {
<add> protected WebSession extendSession(ServerWebExchange exchange, WebSession session) {
<ide> if (session instanceof ConfigurableWebSession) {
<ide> ConfigurableWebSession managed = (ConfigurableWebSession) session;
<ide> managed.setSaveOperation(() -> saveSession(exchange, session));
<ide> protected WebSession extendSession(WebServerExchange exchange, WebSession sessio
<ide> return session;
<ide> }
<ide>
<del> protected Mono<Void> saveSession(WebServerExchange exchange, WebSession session) {
<add> protected Mono<Void> saveSession(ServerWebExchange exchange, WebSession session) {
<ide>
<ide> Assert.isTrue(!session.isExpired(), "Sessions are checked for expiration and have their " +
<ide> "access time updated when first accessed during request processing. " +
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/server/session/WebSessionIdResolver.java
<ide>
<ide> import java.util.Optional;
<ide>
<del>import org.springframework.web.server.WebServerExchange;
<del>import org.springframework.web.server.WebSession;
<add>import org.springframework.web.server.ServerWebExchange;
<ide>
<ide>
<ide> /**
<ide> public interface WebSessionIdResolver {
<ide> * @param exchange the current exchange
<ide> * @return the session id if present
<ide> */
<del> Optional<String> resolveSessionId(WebServerExchange exchange);
<add> Optional<String> resolveSessionId(ServerWebExchange exchange);
<ide>
<ide> /**
<ide> * Send the given session id to the client or if the session id is "null"
<ide> * instruct the client to end the current session.
<ide> * @param exchange the current exchange
<ide> * @param sessionId the session id
<ide> */
<del> void setSessionId(WebServerExchange exchange, String sessionId);
<add> void setSessionId(ServerWebExchange exchange, String sessionId);
<ide>
<ide> }
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/server/session/WebSessionManager.java
<ide>
<ide> import reactor.core.publisher.Mono;
<ide>
<del>import org.springframework.web.server.WebServerExchange;
<add>import org.springframework.web.server.ServerWebExchange;
<ide> import org.springframework.web.server.WebSession;
<ide>
<ide> /**
<ide> public interface WebSessionManager {
<ide> * @param exchange the current exchange
<ide> * @return {@code Mono} for async access to the session
<ide> */
<del> Mono<WebSession> getSession(WebServerExchange exchange);
<add> Mono<WebSession> getSession(ServerWebExchange exchange);
<ide>
<ide> }
<ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/DispatcherHandlerErrorTests.java
<ide> import org.springframework.web.reactive.method.annotation.RequestMappingHandlerAdapter;
<ide> import org.springframework.web.reactive.method.annotation.RequestMappingHandlerMapping;
<ide> import org.springframework.web.reactive.method.annotation.ResponseBodyResultHandler;
<del>import org.springframework.web.server.adapter.DefaultWebServerExchange;
<add>import org.springframework.web.server.adapter.DefaultServerWebExchange;
<ide> import org.springframework.web.server.handler.ExceptionHandlingWebHandler;
<ide> import org.springframework.web.server.handler.FilteringWebHandler;
<ide> import org.springframework.web.server.WebExceptionHandler;
<ide> import org.springframework.web.server.WebFilter;
<ide> import org.springframework.web.server.WebFilterChain;
<ide> import org.springframework.web.server.WebHandler;
<del>import org.springframework.web.server.WebServerExchange;
<add>import org.springframework.web.server.ServerWebExchange;
<ide> import org.springframework.web.server.session.WebSessionManager;
<ide>
<ide> import static org.hamcrest.CoreMatchers.startsWith;
<ide> public class DispatcherHandlerErrorTests {
<ide>
<ide> private MockServerHttpResponse response;
<ide>
<del> private WebServerExchange exchange;
<add> private ServerWebExchange exchange;
<ide>
<ide>
<ide> @Before
<ide> public void setUp() throws Exception {
<ide>
<ide> this.request = new MockServerHttpRequest(HttpMethod.GET, new URI("/"));
<ide> this.response = new MockServerHttpResponse();
<del> this.exchange = new DefaultWebServerExchange(this.request, this.response, sessionManager);
<add> this.exchange = new DefaultServerWebExchange(this.request, this.response, sessionManager);
<ide> }
<ide>
<ide>
<ide> private static class Foo {
<ide> private static class ServerError500ExceptionHandler implements WebExceptionHandler {
<ide>
<ide> @Override
<del> public Mono<Void> handle(WebServerExchange exchange, Throwable ex) {
<add> public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
<ide> exchange.getResponse().setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
<ide> return Mono.empty();
<ide> }
<ide> public Mono<Void> handle(WebServerExchange exchange, Throwable ex) {
<ide> private static class TestWebFilter implements WebFilter {
<ide>
<ide> @Override
<del> public Mono<Void> filter(WebServerExchange exchange, WebFilterChain chain) {
<add> public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
<ide> return chain.filter(exchange);
<ide> }
<ide> }
<ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/ResponseStatusExceptionHandlerTests.java
<ide> import org.springframework.http.server.reactive.MockServerHttpRequest;
<ide> import org.springframework.http.server.reactive.MockServerHttpResponse;
<ide> import org.springframework.web.ResponseStatusException;
<del>import org.springframework.web.server.adapter.DefaultWebServerExchange;
<del>import org.springframework.web.server.WebServerExchange;
<add>import org.springframework.web.server.adapter.DefaultServerWebExchange;
<add>import org.springframework.web.server.ServerWebExchange;
<ide> import org.springframework.web.server.session.WebSessionManager;
<ide>
<ide> import static org.junit.Assert.assertEquals;
<ide> public class ResponseStatusExceptionHandlerTests {
<ide>
<ide> private MockServerHttpResponse response;
<ide>
<del> private WebServerExchange exchange;
<add> private ServerWebExchange exchange;
<ide>
<ide>
<ide> @Before
<ide> public void setUp() throws Exception {
<ide> MockServerHttpRequest request = new MockServerHttpRequest(HttpMethod.GET, new URI("/path"));
<ide> WebSessionManager sessionManager = mock(WebSessionManager.class);
<ide> this.response = new MockServerHttpResponse();
<del> this.exchange = new DefaultWebServerExchange(request, this.response, sessionManager);
<add> this.exchange = new DefaultServerWebExchange(request, this.response, sessionManager);
<ide> }
<ide>
<ide>
<ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/handler/SimpleUrlHandlerMappingIntegrationTests.java
<ide> import org.springframework.web.reactive.DispatcherHandler;
<ide> import org.springframework.web.reactive.ResponseStatusExceptionHandler;
<ide> import org.springframework.web.server.WebHandler;
<del>import org.springframework.web.server.WebServerExchange;
<del>import org.springframework.web.server.adapter.WebToHttpHandlerBuilder;
<add>import org.springframework.web.server.ServerWebExchange;
<add>import org.springframework.web.server.adapter.WebHttpHandlerBuilder;
<ide>
<ide> import static org.junit.Assert.assertArrayEquals;
<ide> import static org.junit.Assert.assertEquals;
<ide> protected HttpHandler createHttpHandler() {
<ide> DispatcherHandler webHandler = new DispatcherHandler();
<ide> webHandler.setApplicationContext(wac);
<ide>
<del> return WebToHttpHandlerBuilder.webHandler(webHandler)
<add> return WebHttpHandlerBuilder.webHandler(webHandler)
<ide> .exceptionHandlers(new ResponseStatusExceptionHandler())
<ide> .build();
<ide> }
<ide> public TestHandlerMapping() {
<ide> private static class FooHandler implements WebHandler {
<ide>
<ide> @Override
<del> public Mono<Void> handle(WebServerExchange exchange) {
<add> public Mono<Void> handle(ServerWebExchange exchange) {
<ide> DataBuffer buffer = new DefaultDataBufferAllocator().allocateBuffer()
<ide> .write("foo".getBytes(StandardCharsets.UTF_8));
<ide> return exchange.getResponse().setBody(Flux.just(buffer));
<ide> public Mono<Void> handle(WebServerExchange exchange) {
<ide> private static class BarHandler implements WebHandler {
<ide>
<ide> @Override
<del> public Mono<Void> handle(WebServerExchange exchange) {
<add> public Mono<Void> handle(ServerWebExchange exchange) {
<ide> DataBuffer buffer = new DefaultDataBufferAllocator().allocateBuffer()
<ide> .write("bar".getBytes(StandardCharsets.UTF_8));
<ide> return exchange.getResponse().setBody(Flux.just(buffer));
<ide> public Mono<Void> handle(WebServerExchange exchange) {
<ide> private static class HeaderSettingHandler implements WebHandler {
<ide>
<ide> @Override
<del> public Mono<Void> handle(WebServerExchange exchange) {
<add> public Mono<Void> handle(ServerWebExchange exchange) {
<ide> exchange.getResponse().getHeaders().add("foo", "bar");
<ide> return Mono.empty();
<ide> }
<ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/method/InvocableHandlerMethodTests.java
<ide> import org.springframework.web.method.HandlerMethod;
<ide> import org.springframework.web.reactive.HandlerResult;
<ide> import org.springframework.web.reactive.method.annotation.RequestParamArgumentResolver;
<del>import org.springframework.web.server.adapter.DefaultWebServerExchange;
<del>import org.springframework.web.server.WebServerExchange;
<add>import org.springframework.web.server.adapter.DefaultServerWebExchange;
<add>import org.springframework.web.server.ServerWebExchange;
<ide> import org.springframework.web.server.session.WebSessionManager;
<ide>
<ide> import static org.junit.Assert.assertEquals;
<ide> public class InvocableHandlerMethodTests {
<ide>
<ide> private ServerHttpRequest request;
<ide>
<del> private WebServerExchange exchange;
<add> private ServerWebExchange exchange;
<ide>
<ide>
<ide> @Before
<ide> public void setUp() throws Exception {
<ide> WebSessionManager sessionManager = mock(WebSessionManager.class);
<ide> this.request = mock(ServerHttpRequest.class);
<del> this.exchange = new DefaultWebServerExchange(request, mock(ServerHttpResponse.class), sessionManager);
<add> this.exchange = new DefaultServerWebExchange(request, mock(ServerHttpResponse.class), sessionManager);
<ide> }
<ide>
<ide>
<ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/method/annotation/RequestMappingHandlerMappingTests.java
<ide> import org.springframework.web.bind.annotation.RequestMapping;
<ide> import org.springframework.web.bind.annotation.RequestMethod;
<ide> import org.springframework.web.method.HandlerMethod;
<del>import org.springframework.web.server.adapter.DefaultWebServerExchange;
<del>import org.springframework.web.server.WebServerExchange;
<add>import org.springframework.web.server.adapter.DefaultServerWebExchange;
<add>import org.springframework.web.server.ServerWebExchange;
<ide> import org.springframework.web.server.session.WebSessionManager;
<ide>
<ide> import static java.util.stream.Collectors.toList;
<ide> public void path() throws Exception {
<ide> ServerHttpRequest request = new MockServerHttpRequest(HttpMethod.GET, new URI("boo"));
<ide> MockServerHttpResponse response = new MockServerHttpResponse();
<ide> WebSessionManager sessionManager = mock(WebSessionManager.class);
<del> WebServerExchange exchange = new DefaultWebServerExchange(request, response, sessionManager);
<add> ServerWebExchange exchange = new DefaultServerWebExchange(request, response, sessionManager);
<ide> Publisher<?> handlerPublisher = this.mapping.getHandler(exchange);
<ide> HandlerMethod handlerMethod = toHandlerMethod(handlerPublisher);
<ide> assertEquals(TestController.class.getMethod("boo"), handlerMethod.getMethod());
<ide> public void method() throws Exception {
<ide> ServerHttpRequest request = new MockServerHttpRequest(HttpMethod.POST, new URI("foo"));
<ide> MockServerHttpResponse response = new MockServerHttpResponse();
<ide> WebSessionManager sessionManager = mock(WebSessionManager.class);
<del> WebServerExchange exchange = new DefaultWebServerExchange(request, response, sessionManager);
<add> ServerWebExchange exchange = new DefaultServerWebExchange(request, response, sessionManager);
<ide> Publisher<?> handlerPublisher = this.mapping.getHandler(exchange);
<ide> HandlerMethod handlerMethod = toHandlerMethod(handlerPublisher);
<ide> assertEquals(TestController.class.getMethod("postFoo"), handlerMethod.getMethod());
<ide>
<ide> request = new MockServerHttpRequest(HttpMethod.GET, new URI("foo"));
<del> exchange = new DefaultWebServerExchange(request, new MockServerHttpResponse(), sessionManager);
<add> exchange = new DefaultServerWebExchange(request, new MockServerHttpResponse(), sessionManager);
<ide> handlerPublisher = this.mapping.getHandler(exchange);
<ide> handlerMethod = toHandlerMethod(handlerPublisher);
<ide> assertEquals(TestController.class.getMethod("getFoo"), handlerMethod.getMethod());
<ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/method/annotation/RequestMappingIntegrationTests.java
<ide> import org.springframework.web.client.RestTemplate;
<ide> import org.springframework.web.reactive.DispatcherHandler;
<ide> import org.springframework.web.reactive.handler.SimpleHandlerResultHandler;
<del>import org.springframework.web.server.adapter.WebToHttpHandlerBuilder;
<add>import org.springframework.web.server.adapter.WebHttpHandlerBuilder;
<ide>
<ide> import static org.junit.Assert.assertArrayEquals;
<ide> import static org.junit.Assert.assertEquals;
<ide> protected HttpHandler createHttpHandler() {
<ide> DispatcherHandler webHandler = new DispatcherHandler();
<ide> webHandler.setApplicationContext(this.wac);
<ide>
<del> return WebToHttpHandlerBuilder.webHandler(webHandler).build();
<add> return WebHttpHandlerBuilder.webHandler(webHandler).build();
<ide> }
<ide>
<ide> @Test
<ide><path>spring-web-reactive/src/test/java/org/springframework/web/server/handler/ExceptionHandlingHttpHandlerTests.java
<ide> import org.springframework.http.server.reactive.MockServerHttpResponse;
<ide> import org.springframework.web.server.WebExceptionHandler;
<ide> import org.springframework.web.server.WebHandler;
<del>import org.springframework.web.server.WebServerExchange;
<del>import org.springframework.web.server.handler.ExceptionHandlingWebHandler;
<del>import org.springframework.web.server.adapter.DefaultWebServerExchange;
<add>import org.springframework.web.server.ServerWebExchange;
<add>import org.springframework.web.server.adapter.DefaultServerWebExchange;
<ide> import org.springframework.web.server.session.WebSessionManager;
<ide>
<ide> import static org.junit.Assert.assertEquals;
<ide> public class ExceptionHandlingHttpHandlerTests {
<ide>
<ide> private MockServerHttpResponse response;
<ide>
<del> private WebServerExchange exchange;
<add> private ServerWebExchange exchange;
<ide>
<ide> private WebHandler targetHandler;
<ide>
<ide> public void setUp() throws Exception {
<ide> WebSessionManager sessionManager = mock(WebSessionManager.class);
<ide> MockServerHttpRequest request = new MockServerHttpRequest(HttpMethod.GET, uri);
<ide> this.response = new MockServerHttpResponse();
<del> this.exchange = new DefaultWebServerExchange(request, this.response, sessionManager);
<add> this.exchange = new DefaultServerWebExchange(request, this.response, sessionManager);
<ide> this.targetHandler = new StubWebHandler(new IllegalStateException("boo"));
<ide> }
<ide>
<ide> public StubWebHandler(RuntimeException exception, boolean raise) {
<ide> }
<ide>
<ide> @Override
<del> public Mono<Void> handle(WebServerExchange exchange) {
<add> public Mono<Void> handle(ServerWebExchange exchange) {
<ide> if (this.raise) {
<ide> throw this.exception;
<ide> }
<ide> public Mono<Void> handle(WebServerExchange exchange) {
<ide> private static class BadRequestExceptionHandler implements WebExceptionHandler {
<ide>
<ide> @Override
<del> public Mono<Void> handle(WebServerExchange exchange, Throwable ex) {
<add> public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
<ide> exchange.getResponse().setStatusCode(HttpStatus.BAD_REQUEST);
<ide> return Mono.empty();
<ide> }
<ide> public Mono<Void> handle(WebServerExchange exchange, Throwable ex) {
<ide> private static class UnresolvedExceptionHandler implements WebExceptionHandler {
<ide>
<ide> @Override
<del> public Mono<Void> handle(WebServerExchange exchange, Throwable ex) {
<add> public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
<ide> return Mono.error(ex);
<ide> }
<ide> }
<ide><path>spring-web-reactive/src/test/java/org/springframework/web/server/handler/FilteringWebHandlerTests.java
<ide> import org.springframework.web.server.WebFilter;
<ide> import org.springframework.web.server.WebFilterChain;
<ide> import org.springframework.web.server.WebHandler;
<del>import org.springframework.web.server.WebServerExchange;
<del>import org.springframework.web.server.adapter.WebToHttpHandlerBuilder;
<add>import org.springframework.web.server.ServerWebExchange;
<add>import org.springframework.web.server.adapter.WebHttpHandlerBuilder;
<ide>
<ide> import static org.junit.Assert.assertFalse;
<ide> import static org.junit.Assert.assertTrue;
<ide> public void asyncFilter() throws Exception {
<ide> }
<ide>
<ide> private HttpHandler createHttpHandler(StubWebHandler webHandler, WebFilter... filters) {
<del> return WebToHttpHandlerBuilder.webHandler(webHandler).filters(filters).build();
<add> return WebHttpHandlerBuilder.webHandler(webHandler).filters(filters).build();
<ide> }
<ide>
<ide>
<ide> public boolean invoked() {
<ide> }
<ide>
<ide> @Override
<del> public Mono<Void> filter(WebServerExchange exchange, WebFilterChain chain) {
<add> public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
<ide> this.invoked = true;
<ide> return doFilter(exchange, chain);
<ide> }
<ide>
<del> public Mono<Void> doFilter(WebServerExchange exchange, WebFilterChain chain) {
<add> public Mono<Void> doFilter(ServerWebExchange exchange, WebFilterChain chain) {
<ide> return chain.filter(exchange);
<ide> }
<ide> }
<ide>
<ide> private static class ShortcircuitingFilter extends TestFilter {
<ide>
<ide> @Override
<del> public Mono<Void> doFilter(WebServerExchange exchange, WebFilterChain chain) {
<add> public Mono<Void> doFilter(ServerWebExchange exchange, WebFilterChain chain) {
<ide> return Mono.empty();
<ide> }
<ide> }
<ide>
<ide> private static class AsyncFilter extends TestFilter {
<ide>
<ide> @Override
<del> public Mono<Void> doFilter(WebServerExchange exchange, WebFilterChain chain) {
<add> public Mono<Void> doFilter(ServerWebExchange exchange, WebFilterChain chain) {
<ide> return doAsyncWork().then(asyncResult -> {
<ide> logger.debug("Async result: " + asyncResult);
<ide> return chain.filter(exchange);
<ide> public boolean invoked() {
<ide> }
<ide>
<ide> @Override
<del> public Mono<Void> handle(WebServerExchange exchange) {
<add> public Mono<Void> handle(ServerWebExchange exchange) {
<ide> logger.trace("StubHandler invoked.");
<ide> this.invoked = true;
<ide> return Mono.empty();
<ide><path>spring-web-reactive/src/test/java/org/springframework/web/server/session/DefaultWebSessionManagerTests.java
<ide> import org.springframework.http.HttpMethod;
<ide> import org.springframework.http.server.reactive.MockServerHttpRequest;
<ide> import org.springframework.http.server.reactive.MockServerHttpResponse;
<del>import org.springframework.web.server.adapter.DefaultWebServerExchange;
<del>import org.springframework.web.server.WebServerExchange;
<add>import org.springframework.web.server.adapter.DefaultServerWebExchange;
<add>import org.springframework.web.server.ServerWebExchange;
<ide> import org.springframework.web.server.WebSession;
<ide>
<ide> import static org.junit.Assert.assertEquals;
<ide> public class DefaultWebSessionManagerTests {
<ide>
<ide> private TestWebSessionIdResolver idResolver;
<ide>
<del> private DefaultWebServerExchange exchange;
<add> private DefaultServerWebExchange exchange;
<ide>
<ide>
<ide> @Before
<ide> public void setUp() throws Exception {
<ide>
<ide> MockServerHttpRequest request = new MockServerHttpRequest(HttpMethod.GET, new URI("/path"));
<ide> MockServerHttpResponse response = new MockServerHttpResponse();
<del> this.exchange = new DefaultWebServerExchange(request, response, this.manager);
<add> this.exchange = new DefaultServerWebExchange(request, response, this.manager);
<ide> }
<ide>
<ide>
<ide> public String getId() {
<ide> }
<ide>
<ide> @Override
<del> public Optional<String> resolveSessionId(WebServerExchange exchange) {
<add> public Optional<String> resolveSessionId(ServerWebExchange exchange) {
<ide> return this.idToResolve;
<ide> }
<ide>
<ide> @Override
<del> public void setSessionId(WebServerExchange exchange, String sessionId) {
<add> public void setSessionId(ServerWebExchange exchange, String sessionId) {
<ide> this.id = sessionId;
<ide> }
<ide> }
<ide><path>spring-web-reactive/src/test/java/org/springframework/web/server/session/WebSessionIntegrationTests.java
<ide> import org.springframework.util.StringUtils;
<ide> import org.springframework.web.client.RestTemplate;
<ide> import org.springframework.web.server.WebHandler;
<del>import org.springframework.web.server.WebServerExchange;
<del>import org.springframework.web.server.adapter.WebToHttpHandlerBuilder;
<add>import org.springframework.web.server.ServerWebExchange;
<add>import org.springframework.web.server.adapter.WebHttpHandlerBuilder;
<ide>
<ide> import static org.junit.Assert.assertEquals;
<ide> import static org.junit.Assert.assertNotNull;
<ide> protected URI createUri(String pathAndQuery) throws URISyntaxException {
<ide> protected HttpHandler createHttpHandler() {
<ide> this.sessionManager = new DefaultWebSessionManager();
<ide> this.handler = new TestWebHandler();
<del> return WebToHttpHandlerBuilder.webHandler(this.handler).sessionManager(this.sessionManager).build();
<add> return WebHttpHandlerBuilder.webHandler(this.handler).sessionManager(this.sessionManager).build();
<ide> }
<ide>
<ide> @Test
<ide> public int getCount() {
<ide> }
<ide>
<ide> @Override
<del> public Mono<Void> handle(WebServerExchange exchange) {
<add> public Mono<Void> handle(ServerWebExchange exchange) {
<ide> return exchange.getSession().map(session -> {
<ide> Map<String, Object> map = session.getAttributes();
<ide> int value = (map.get("counter") != null ? (int) map.get("counter") : 0); | 41 |
Javascript | Javascript | increase tests via permutation matrix | b04f2b661802adf5fd2c7731cd2d5e0f5cfe16d1 | <ide><path>lib/internal/modules/cjs/loader.js
<ide> function readPackage(requestPath) {
<ide> const existing = packageJsonCache.get(jsonPath);
<ide> if (existing !== undefined) return existing;
<ide>
<del> const result = packageJsonReader.read(path.toNamespacedPath(jsonPath));
<add> const result = packageJsonReader.read(jsonPath);
<ide> const json = result.containsKeys === false ? '{}' : result.string;
<ide> if (json === undefined) {
<ide> packageJsonCache.set(jsonPath, false);
<ide> return false;
<ide> }
<ide>
<del> if (manifest) {
<del> const jsonURL = pathToFileURL(jsonPath);
<del> manifest.assertIntegrity(jsonURL, json);
<del> }
<del>
<ide> try {
<ide> const parsed = JSONParse(json);
<ide> const filtered = {
<ide><path>lib/internal/modules/esm/get_source.js
<ide> 'use strict';
<ide>
<add>const { getOptionValue } = require('internal/options');
<add>const manifest = getOptionValue('--experimental-policy') ?
<add> require('internal/process/policy').manifest :
<add> null;
<add>
<ide> const { Buffer } = require('buffer');
<ide>
<ide> const fs = require('fs');
<ide> const DATA_URL_PATTERN = /^[^/]+\/[^,;]+(?:[^,]*?)(;base64)?,([\s\S]*)$/;
<ide>
<ide> async function defaultGetSource(url, { format } = {}, defaultGetSource) {
<ide> const parsed = new URL(url);
<add> let source;
<ide> if (parsed.protocol === 'file:') {
<del> return {
<del> source: await readFileAsync(parsed)
<del> };
<add> source = await readFileAsync(parsed);
<ide> } else if (parsed.protocol === 'data:') {
<ide> const match = DATA_URL_PATTERN.exec(parsed.pathname);
<ide> if (!match) {
<ide> throw new ERR_INVALID_URL(url);
<ide> }
<ide> const [ , base64, body ] = match;
<del> return {
<del> source: Buffer.from(body, base64 ? 'base64' : 'utf8')
<del> };
<add> source = Buffer.from(body, base64 ? 'base64' : 'utf8');
<add> } else {
<add> throw new ERR_INVALID_URL_SCHEME(['file', 'data']);
<add> }
<add> if (manifest) {
<add> manifest.assertIntegrity(parsed, source);
<ide> }
<del> throw new ERR_INVALID_URL_SCHEME(['file', 'data']);
<add> return { source };
<ide> }
<ide> exports.defaultGetSource = defaultGetSource;
<ide><path>lib/internal/modules/package_json_reader.js
<ide>
<ide> const { SafeMap } = primordials;
<ide> const { internalModuleReadJSON } = internalBinding('fs');
<add>const { pathToFileURL } = require('url');
<add>const { toNamespacedPath } = require('path');
<ide>
<ide> const cache = new SafeMap();
<ide>
<ide> /**
<ide> *
<del> * @param {string} path
<add> * @param {string} jsonPath
<ide> */
<del>function read(path) {
<del> if (cache.has(path)) {
<del> return cache.get(path);
<add>function read(jsonPath) {
<add> if (cache.has(jsonPath)) {
<add> return cache.get(jsonPath);
<ide> }
<ide>
<del> const [string, containsKeys] = internalModuleReadJSON(path);
<add> const [string, containsKeys] = internalModuleReadJSON(
<add> toNamespacedPath(jsonPath)
<add> );
<ide> const result = { string, containsKeys };
<del> cache.set(path, result);
<add> const { getOptionValue } = require('internal/options');
<add> if (string !== undefined) {
<add> const manifest = getOptionValue('--experimental-policy') ?
<add> require('internal/process/policy').manifest :
<add> null;
<add> if (manifest) {
<add> const jsonURL = pathToFileURL(jsonPath);
<add> manifest.assertIntegrity(jsonURL, string);
<add> }
<add> }
<add> cache.set(jsonPath, result);
<ide> return result;
<ide> }
<ide>
<ide><path>lib/internal/worker.js
<ide> class Worker extends EventEmitter {
<ide> cwdCounter: cwdCounter || workerIo.sharedCwdCounter,
<ide> workerData: options.workerData,
<ide> publicPort: port2,
<add> manifestURL: getOptionValue('--experimental-policy') ?
<add> require('internal/process/policy').url :
<add> null,
<ide> manifestSrc: getOptionValue('--experimental-policy') ?
<ide> require('internal/process/policy').src :
<ide> null,
<ide><path>test/parallel/test-policy-integrity.js
<del>'use strict';
<del>
<del>const common = require('../common');
<del>if (!common.hasCrypto)
<del> common.skip('missing crypto');
<del>
<del>const tmpdir = require('../common/tmpdir');
<del>const assert = require('assert');
<del>const { spawnSync } = require('child_process');
<del>const crypto = require('crypto');
<del>const fs = require('fs');
<del>const path = require('path');
<del>const { pathToFileURL } = require('url');
<del>
<del>tmpdir.refresh();
<del>
<del>function hash(algo, body) {
<del> const h = crypto.createHash(algo);
<del> h.update(body);
<del> return h.digest('base64');
<del>}
<del>
<del>const policyFilepath = path.join(tmpdir.path, 'policy');
<del>
<del>const packageFilepath = path.join(tmpdir.path, 'package.json');
<del>const packageURL = pathToFileURL(packageFilepath);
<del>const packageBody = '{"main": "dep.js"}';
<del>const policyToPackageRelativeURLString = `./${
<del> path.relative(path.dirname(policyFilepath), packageFilepath)
<del>}`;
<del>
<del>const parentFilepath = path.join(tmpdir.path, 'parent.js');
<del>const parentURL = pathToFileURL(parentFilepath);
<del>const parentBody = 'require(\'./dep.js\')';
<del>
<del>const workerSpawningFilepath = path.join(tmpdir.path, 'worker_spawner.js');
<del>const workerSpawningURL = pathToFileURL(workerSpawningFilepath);
<del>const workerSpawningBody = `
<del>const { Worker } = require('worker_threads');
<del>// make sure this is gone to ensure we don't do another fs read of it
<del>// will error out if we do
<del>require('fs').unlinkSync(${JSON.stringify(policyFilepath)});
<del>const w = new Worker(${JSON.stringify(parentFilepath)});
<del>w.on('exit', process.exit);
<del>`;
<del>
<del>const depFilepath = path.join(tmpdir.path, 'dep.js');
<del>const depURL = pathToFileURL(depFilepath);
<del>const depBody = '';
<del>const policyToDepRelativeURLString = `./${
<del> path.relative(path.dirname(policyFilepath), depFilepath)
<del>}`;
<del>
<del>fs.writeFileSync(parentFilepath, parentBody);
<del>fs.writeFileSync(depFilepath, depBody);
<del>
<del>const tmpdirURL = pathToFileURL(tmpdir.path);
<del>if (!tmpdirURL.pathname.endsWith('/')) {
<del> tmpdirURL.pathname += '/';
<del>}
<del>function test({
<del> shouldFail = false,
<del> preload = [],
<del> entry,
<del> onerror = undefined,
<del> resources = {}
<del>}) {
<del> const manifest = {
<del> onerror,
<del> resources: {}
<del> };
<del> for (const [url, { body, match }] of Object.entries(resources)) {
<del> manifest.resources[url] = {
<del> integrity: `sha256-${hash('sha256', match ? body : body + '\n')}`,
<del> dependencies: true
<del> };
<del> fs.writeFileSync(new URL(url, tmpdirURL.href), body);
<del> }
<del> fs.writeFileSync(policyFilepath, JSON.stringify(manifest, null, 2));
<del> const { status } = spawnSync(process.execPath, [
<del> '--experimental-policy', policyFilepath,
<del> ...preload.map((m) => ['-r', m]).flat(),
<del> entry
<del> ]);
<del> if (shouldFail) {
<del> assert.notStrictEqual(status, 0);
<del> } else {
<del> assert.strictEqual(status, 0);
<del> }
<del>}
<del>
<del>{
<del> const { status } = spawnSync(process.execPath, [
<del> '--experimental-policy', policyFilepath,
<del> '--experimental-policy', policyFilepath
<del> ], {
<del> stdio: 'pipe'
<del> });
<del> assert.notStrictEqual(status, 0, 'Should not allow multiple policies');
<del>}
<del>{
<del> const enoentFilepath = path.join(tmpdir.path, 'enoent');
<del> try { fs.unlinkSync(enoentFilepath); } catch {}
<del> const { status } = spawnSync(process.execPath, [
<del> '--experimental-policy', enoentFilepath, '-e', ''
<del> ], {
<del> stdio: 'pipe'
<del> });
<del> assert.notStrictEqual(status, 0, 'Should not allow missing policies');
<del>}
<del>
<del>test({
<del> shouldFail: true,
<del> entry: parentFilepath,
<del> resources: {
<del> }
<del>});
<del>test({
<del> shouldFail: false,
<del> entry: parentFilepath,
<del> onerror: 'log',
<del>});
<del>test({
<del> shouldFail: true,
<del> entry: parentFilepath,
<del> onerror: 'exit',
<del>});
<del>test({
<del> shouldFail: true,
<del> entry: parentFilepath,
<del> onerror: 'throw',
<del>});
<del>test({
<del> shouldFail: true,
<del> entry: parentFilepath,
<del> onerror: 'unknown-onerror-value',
<del>});
<del>test({
<del> shouldFail: true,
<del> entry: path.dirname(packageFilepath),
<del> resources: {
<del> }
<del>});
<del>test({
<del> shouldFail: true,
<del> entry: path.dirname(packageFilepath),
<del> resources: {
<del> [depURL]: {
<del> body: depBody,
<del> match: true,
<del> }
<del> }
<del>});
<del>test({
<del> shouldFail: false,
<del> entry: path.dirname(packageFilepath),
<del> onerror: 'log',
<del> resources: {
<del> [packageURL]: {
<del> body: packageBody,
<del> match: false,
<del> },
<del> [depURL]: {
<del> body: depBody,
<del> match: true,
<del> }
<del> }
<del>});
<del>test({
<del> shouldFail: true,
<del> entry: path.dirname(packageFilepath),
<del> resources: {
<del> [packageURL]: {
<del> body: packageBody,
<del> match: false,
<del> },
<del> [depURL]: {
<del> body: depBody,
<del> match: true,
<del> }
<del> }
<del>});
<del>test({
<del> shouldFail: true,
<del> entry: path.dirname(packageFilepath),
<del> resources: {
<del> [packageURL]: {
<del> body: packageBody,
<del> match: true,
<del> },
<del> [depURL]: {
<del> body: depBody,
<del> match: false,
<del> }
<del> }
<del>});
<del>test({
<del> shouldFail: false,
<del> entry: path.dirname(packageFilepath),
<del> resources: {
<del> [packageURL]: {
<del> body: packageBody,
<del> match: true,
<del> },
<del> [depURL]: {
<del> body: depBody,
<del> match: true,
<del> }
<del> }
<del>});
<del>test({
<del> shouldFail: false,
<del> entry: parentFilepath,
<del> resources: {
<del> [packageURL]: {
<del> body: packageBody,
<del> match: true,
<del> },
<del> [parentURL]: {
<del> body: parentBody,
<del> match: true,
<del> },
<del> [depURL]: {
<del> body: depBody,
<del> match: true,
<del> }
<del> }
<del>});
<del>test({
<del> shouldFail: false,
<del> preload: [depFilepath],
<del> entry: parentFilepath,
<del> resources: {
<del> [packageURL]: {
<del> body: packageBody,
<del> match: true,
<del> },
<del> [parentURL]: {
<del> body: parentBody,
<del> match: true,
<del> },
<del> [depURL]: {
<del> body: depBody,
<del> match: true,
<del> }
<del> }
<del>});
<del>test({
<del> shouldFail: true,
<del> entry: parentFilepath,
<del> resources: {
<del> [parentURL]: {
<del> body: parentBody,
<del> match: false,
<del> },
<del> [depURL]: {
<del> body: depBody,
<del> match: true,
<del> }
<del> }
<del>});
<del>test({
<del> shouldFail: true,
<del> entry: parentFilepath,
<del> resources: {
<del> [parentURL]: {
<del> body: parentBody,
<del> match: true,
<del> },
<del> [depURL]: {
<del> body: depBody,
<del> match: false,
<del> }
<del> }
<del>});
<del>test({
<del> shouldFail: true,
<del> entry: parentFilepath,
<del> resources: {
<del> [parentURL]: {
<del> body: parentBody,
<del> match: true,
<del> }
<del> }
<del>});
<del>test({
<del> shouldFail: false,
<del> entry: depFilepath,
<del> resources: {
<del> [packageURL]: {
<del> body: packageBody,
<del> match: true,
<del> },
<del> [depURL]: {
<del> body: depBody,
<del> match: true,
<del> }
<del> }
<del>});
<del>test({
<del> shouldFail: false,
<del> entry: depFilepath,
<del> resources: {
<del> [packageURL]: {
<del> body: packageBody,
<del> match: true,
<del> },
<del> [policyToDepRelativeURLString]: {
<del> body: depBody,
<del> match: true,
<del> }
<del> }
<del>});
<del>test({
<del> shouldFail: true,
<del> entry: depFilepath,
<del> resources: {
<del> [policyToDepRelativeURLString]: {
<del> body: depBody,
<del> match: false,
<del> }
<del> }
<del>});
<del>test({
<del> shouldFail: false,
<del> entry: depFilepath,
<del> resources: {
<del> [packageURL]: {
<del> body: packageBody,
<del> match: true,
<del> },
<del> [policyToDepRelativeURLString]: {
<del> body: depBody,
<del> match: true,
<del> },
<del> [depURL]: {
<del> body: depBody,
<del> match: true,
<del> }
<del> }
<del>});
<del>test({
<del> shouldFail: true,
<del> entry: depFilepath,
<del> resources: {
<del> [policyToPackageRelativeURLString]: {
<del> body: packageBody,
<del> match: true,
<del> },
<del> [packageURL]: {
<del> body: packageBody,
<del> match: true,
<del> },
<del> [depURL]: {
<del> body: depBody,
<del> match: false,
<del> }
<del> }
<del>});
<del>test({
<del> shouldFail: true,
<del> entry: workerSpawningFilepath,
<del> resources: {
<del> [workerSpawningURL]: {
<del> body: workerSpawningBody,
<del> match: true,
<del> },
<del> }
<del>});
<del>test({
<del> shouldFail: false,
<del> entry: workerSpawningFilepath,
<del> resources: {
<del> [packageURL]: {
<del> body: packageBody,
<del> match: true,
<del> },
<del> [workerSpawningURL]: {
<del> body: workerSpawningBody,
<del> match: true,
<del> },
<del> [parentURL]: {
<del> body: parentBody,
<del> match: true,
<del> },
<del> [depURL]: {
<del> body: depBody,
<del> match: true,
<del> }
<del> }
<del>});
<del>test({
<del> shouldFail: false,
<del> entry: workerSpawningFilepath,
<del> preload: [parentFilepath],
<del> resources: {
<del> [packageURL]: {
<del> body: packageBody,
<del> match: true,
<del> },
<del> [workerSpawningURL]: {
<del> body: workerSpawningBody,
<del> match: true,
<del> },
<del> [parentURL]: {
<del> body: parentBody,
<del> match: true,
<del> },
<del> [depURL]: {
<del> body: depBody,
<del> match: true,
<del> }
<del> }
<del>});
<ide><path>test/parallel/test-policy-parse-integrity.js
<ide> function hash(algo, body) {
<ide> return h.digest('base64');
<ide> }
<ide>
<del>const policyFilepath = path.join(tmpdir.path, 'policy');
<add>const tmpdirPath = path.join(tmpdir.path, 'test-policy-parse-integrity');
<add>fs.rmdirSync(tmpdirPath, { maxRetries: 3, recursive: true });
<add>fs.mkdirSync(tmpdirPath, { recursive: true });
<ide>
<del>const parentFilepath = path.join(tmpdir.path, 'parent.js');
<add>const policyFilepath = path.join(tmpdirPath, 'policy');
<add>
<add>const parentFilepath = path.join(tmpdirPath, 'parent.js');
<ide> const parentBody = "require('./dep.js')";
<ide>
<del>const depFilepath = path.join(tmpdir.path, 'dep.js');
<add>const depFilepath = path.join(tmpdirPath, 'dep.js');
<ide> const depURL = pathToFileURL(depFilepath);
<ide> const depBody = '';
<ide>
<ide> fs.writeFileSync(parentFilepath, parentBody);
<ide> fs.writeFileSync(depFilepath, depBody);
<ide>
<del>const tmpdirURL = pathToFileURL(tmpdir.path);
<add>const tmpdirURL = pathToFileURL(tmpdirPath);
<ide> if (!tmpdirURL.pathname.endsWith('/')) {
<ide> tmpdirURL.pathname += '/';
<ide> }
<ide>
<del>const packageFilepath = path.join(tmpdir.path, 'package.json');
<add>const packageFilepath = path.join(tmpdirPath, 'package.json');
<ide> const packageURL = pathToFileURL(packageFilepath);
<ide> const packageBody = '{"main": "dep.js"}';
<ide>
<ide><path>test/pummel/test-policy-integrity.js
<add>'use strict';
<add>
<add>const common = require('../common');
<add>if (!common.hasCrypto) common.skip('missing crypto');
<add>
<add>const { debuglog } = require('util');
<add>const debug = debuglog('test');
<add>const tmpdir = require('../common/tmpdir');
<add>const assert = require('assert');
<add>const { spawnSync, spawn } = require('child_process');
<add>const crypto = require('crypto');
<add>const fs = require('fs');
<add>const path = require('path');
<add>const { pathToFileURL } = require('url');
<add>
<add>function hash(algo, body) {
<add> const values = [];
<add> {
<add> const h = crypto.createHash(algo);
<add> h.update(body);
<add> values.push(`${algo}-${h.digest('base64')}`);
<add> }
<add> {
<add> const h = crypto.createHash(algo);
<add> h.update(body.replace('\n', '\r\n'));
<add> values.push(`${algo}-${h.digest('base64')}`);
<add> }
<add> return values;
<add>}
<add>
<add>const policyPath = './policy.json';
<add>const parentBody = {
<add> commonjs: `
<add> if (!process.env.DEP_FILE) {
<add> console.error(
<add> 'missing required DEP_FILE env to determine dependency'
<add> );
<add> process.exit(33);
<add> }
<add> require(process.env.DEP_FILE)
<add> `,
<add> module: `
<add> if (!process.env.DEP_FILE) {
<add> console.error(
<add> 'missing required DEP_FILE env to determine dependency'
<add> );
<add> process.exit(33);
<add> }
<add> import(process.env.DEP_FILE)
<add> `,
<add>};
<add>const workerSpawningBody = `
<add> const path = require('path');
<add> const { Worker } = require('worker_threads');
<add> if (!process.env.PARENT_FILE) {
<add> console.error(
<add> 'missing required PARENT_FILE env to determine worker entry point'
<add> );
<add> process.exit(33);
<add> }
<add> if (!process.env.DELETABLE_POLICY_FILE) {
<add> console.error(
<add> 'missing required DELETABLE_POLICY_FILE env to check reloading'
<add> );
<add> process.exit(33);
<add> }
<add> const w = new Worker(path.resolve(process.env.PARENT_FILE));
<add> w.on('exit', (status) => process.exit(status === 0 ? 0 : 1));
<add>`;
<add>
<add>let nextTestId = 1;
<add>function newTestId() {
<add> return nextTestId++;
<add>}
<add>tmpdir.refresh();
<add>
<add>let spawned = 0;
<add>const toSpawn = [];
<add>function queueSpawn(opts) {
<add> toSpawn.push(opts);
<add> drainQueue();
<add>}
<add>
<add>function drainQueue() {
<add> if (spawned > 50) {
<add> return;
<add> }
<add> if (toSpawn.length) {
<add> const config = toSpawn.shift();
<add> const {
<add> shouldSucceed, // = (() => { throw new Error('required')})(),
<add> preloads, // = (() =>{ throw new Error('required')})(),
<add> entryPath, // = (() => { throw new Error('required')})(),
<add> willDeletePolicy, // = (() => { throw new Error('required')})(),
<add> onError, // = (() => { throw new Error('required')})(),
<add> resources, // = (() => { throw new Error('required')})(),
<add> parentPath,
<add> depPath,
<add> } = config;
<add> const testId = newTestId();
<add> const configDirPath = path.join(
<add> tmpdir.path,
<add> `test-policy-integrity-permutation-${testId}`
<add> );
<add> const tmpPolicyPath = path.join(
<add> tmpdir.path,
<add> `deletable-policy-${testId}.json`
<add> );
<add> const cliPolicy = willDeletePolicy ? tmpPolicyPath : policyPath;
<add> fs.rmdirSync(configDirPath, { maxRetries: 3, recursive: true });
<add> fs.mkdirSync(configDirPath, { recursive: true });
<add> const manifest = {
<add> onerror: onError,
<add> resources: {},
<add> };
<add> const manifestPath = path.join(configDirPath, policyPath);
<add> for (const [resourcePath, { body, integrities }] of Object.entries(
<add> resources
<add> )) {
<add> const filePath = path.join(configDirPath, resourcePath);
<add> if (integrities !== null) {
<add> manifest.resources[pathToFileURL(filePath).href] = {
<add> integrity: integrities.join(' '),
<add> dependencies: true,
<add> };
<add> }
<add> fs.writeFileSync(filePath, body, 'utf8');
<add> }
<add> const manifestBody = JSON.stringify(manifest);
<add> fs.writeFileSync(manifestPath, manifestBody);
<add> if (cliPolicy === tmpPolicyPath) {
<add> fs.writeFileSync(tmpPolicyPath, manifestBody);
<add> }
<add> const spawnArgs = [
<add> process.execPath,
<add> [
<add> '--unhandled-rejections=strict',
<add> '--experimental-policy',
<add> cliPolicy,
<add> ...preloads.flatMap((m) => ['-r', m]),
<add> entryPath,
<add> '--',
<add> testId,
<add> configDirPath,
<add> ],
<add> {
<add> env: {
<add> ...process.env,
<add> DELETABLE_POLICY_FILE: tmpPolicyPath,
<add> PARENT_FILE: parentPath,
<add> DEP_FILE: depPath,
<add> },
<add> cwd: configDirPath,
<add> stdio: 'pipe',
<add> },
<add> ];
<add> spawned++;
<add> const stdout = [];
<add> const stderr = [];
<add> const child = spawn(...spawnArgs);
<add> child.stdout.on('data', (d) => stdout.push(d));
<add> child.stderr.on('data', (d) => stderr.push(d));
<add> child.on('exit', (status, signal) => {
<add> spawned--;
<add> try {
<add> if (shouldSucceed) {
<add> assert.strictEqual(status, 0);
<add> } else {
<add> assert.notStrictEqual(status, 0);
<add> }
<add> } catch (e) {
<add> console.log(
<add> 'permutation',
<add> testId,
<add> 'failed'
<add> );
<add> console.dir(
<add> { config, manifest },
<add> { depth: null }
<add> );
<add> console.log('exit code:', status, 'signal:', signal);
<add> console.log(`stdout: ${Buffer.concat(stdout)}`);
<add> console.log(`stderr: ${Buffer.concat(stderr)}`);
<add> throw e;
<add> }
<add> fs.rmdirSync(configDirPath, { maxRetries: 3, recursive: true });
<add> drainQueue();
<add> });
<add> }
<add>}
<add>
<add>{
<add> const { status } = spawnSync(
<add> process.execPath,
<add> ['--experimental-policy', policyPath, '--experimental-policy', policyPath],
<add> {
<add> stdio: 'pipe',
<add> }
<add> );
<add> assert.notStrictEqual(status, 0, 'Should not allow multiple policies');
<add>}
<add>{
<add> const enoentFilepath = path.join(tmpdir.path, 'enoent');
<add> try {
<add> fs.unlinkSync(enoentFilepath);
<add> } catch { }
<add> const { status } = spawnSync(
<add> process.execPath,
<add> ['--experimental-policy', enoentFilepath, '-e', ''],
<add> {
<add> stdio: 'pipe',
<add> }
<add> );
<add> assert.notStrictEqual(status, 0, 'Should not allow missing policies');
<add>}
<add>
<add>/**
<add> * @template {Record<string, Array<string | string[] | boolean>>} T
<add> * @param {T} configurations
<add> * @param {object} path
<add> * @returns {Array<{[key: keyof T]: T[keyof configurations]}>}
<add> */
<add>function permutations(configurations, path = {}) {
<add> const keys = Object.keys(configurations);
<add> if (keys.length === 0) {
<add> return path;
<add> }
<add> const config = keys[0];
<add> const { [config]: values, ...otherConfigs } = configurations;
<add> return values.flatMap((value) => {
<add> return permutations(otherConfigs, { ...path, [config]: value });
<add> });
<add>}
<add>const tests = new Set();
<add>function fileExtensionFormat(extension, packageType) {
<add> if (extension === '.js') {
<add> return packageType === 'module' ? 'module' : 'commonjs';
<add> } else if (extension === '.mjs') {
<add> return 'module';
<add> } else if (extension === '.cjs') {
<add> return 'commonjs';
<add> }
<add> throw new Error('unknown format ' + extension);
<add>}
<add>for (const permutation of permutations({
<add> entry: ['worker', 'parent', 'dep'],
<add> preloads: [[], ['parent'], ['dep']],
<add> onError: ['log', 'exit'],
<add> parentExtension: ['.js', '.mjs', '.cjs'],
<add> parentIntegrity: ['match', 'invalid', 'missing'],
<add> depExtension: ['.js', '.mjs', '.cjs'],
<add> depIntegrity: ['match', 'invalid', 'missing'],
<add> packageType: ['no-package-json', 'module', 'commonjs'],
<add> packageIntegrity: ['match', 'invalid', 'missing'],
<add>})) {
<add> let shouldSucceed = true;
<add> const parentPath = `./parent${permutation.parentExtension}`;
<add> const effectivePackageType =
<add> permutation.packageType === 'module' ? 'module' : 'commonjs';
<add> const parentFormat = fileExtensionFormat(
<add> permutation.parentExtension,
<add> effectivePackageType
<add> );
<add> const depFormat = fileExtensionFormat(
<add> permutation.depExtension,
<add> effectivePackageType
<add> );
<add> // non-sensical attempt to require ESM
<add> if (depFormat === 'module' && parentFormat === 'commonjs') {
<add> continue;
<add> }
<add> const depPath = `./dep${permutation.depExtension}`;
<add> const workerSpawnerPath = './worker-spawner.cjs';
<add> const entryPath = {
<add> dep: depPath,
<add> parent: parentPath,
<add> worker: workerSpawnerPath,
<add> }[permutation.entry];
<add> const packageJSON = {
<add> main: entryPath,
<add> type: permutation.packageType,
<add> };
<add> if (permutation.packageType === 'no-field') {
<add> delete packageJSON.type;
<add> }
<add> const resources = {
<add> [depPath]: {
<add> body: '',
<add> integrities: hash('sha256', ''),
<add> },
<add> };
<add> if (permutation.depIntegrity === 'invalid') {
<add> resources[depPath].body += '\n// INVALID INTEGRITY';
<add> shouldSucceed = false;
<add> } else if (permutation.depIntegrity === 'missing') {
<add> resources[depPath].integrities = null;
<add> shouldSucceed = false;
<add> } else if (permutation.depIntegrity === 'match') {
<add> } else {
<add> throw new Error('unreachable');
<add> }
<add> if (parentFormat !== 'commonjs') {
<add> permutation.preloads = permutation.preloads.filter((_) => _ !== 'parent');
<add> }
<add> const hasParent =
<add> permutation.entry !== 'dep' || permutation.preloads.includes('parent');
<add> if (hasParent) {
<add> resources[parentPath] = {
<add> body: parentBody[parentFormat],
<add> integrities: hash('sha256', parentBody[parentFormat]),
<add> };
<add> if (permutation.parentIntegrity === 'invalid') {
<add> resources[parentPath].body += '\n// INVALID INTEGRITY';
<add> shouldSucceed = false;
<add> } else if (permutation.parentIntegrity === 'missing') {
<add> resources[parentPath].integrities = null;
<add> shouldSucceed = false;
<add> } else if (permutation.parentIntegrity === 'match') {
<add> } else {
<add> throw new Error('unreachable');
<add> }
<add> }
<add> if (permutation.entry === 'worker') {
<add> resources[workerSpawnerPath] = {
<add> body: workerSpawningBody,
<add> integrities: hash('sha256', workerSpawningBody),
<add> };
<add> }
<add> if (permutation.packageType !== 'no-package-json') {
<add> let packageBody = JSON.stringify(packageJSON, null, 2);
<add> let packageIntegrities = hash('sha256', packageBody);
<add> if (
<add> permutation.parentExtension !== '.js' ||
<add> permutation.depExtension !== '.js'
<add> ) {
<add> // NO PACKAGE LOOKUP
<add> continue;
<add> }
<add> if (permutation.packageIntegrity === 'invalid') {
<add> packageJSON['//'] = 'INVALID INTEGRITY';
<add> packageBody = JSON.stringify(packageJSON, null, 2);
<add> shouldSucceed = false;
<add> } else if (permutation.packageIntegrity === 'missing') {
<add> packageIntegrities = [];
<add> shouldSucceed = false;
<add> } else if (permutation.packageIntegrity === 'match') {
<add> } else {
<add> throw new Error('unreachable');
<add> }
<add> resources['./package.json'] = {
<add> body: packageBody,
<add> integrities: packageIntegrities,
<add> };
<add> }
<add> const willDeletePolicy = permutation.entry === 'worker';
<add> if (permutation.onError === 'log') {
<add> shouldSucceed = true;
<add> }
<add> tests.add(
<add> JSON.stringify({
<add> // hasParent,
<add> // original: permutation,
<add> onError: permutation.onError,
<add> shouldSucceed,
<add> entryPath,
<add> willDeletePolicy,
<add> preloads: permutation.preloads
<add> .map((_) => {
<add> return {
<add> '': '',
<add> 'parent': parentFormat === 'commonjs' ? parentPath : '',
<add> 'dep': depFormat === 'commonjs' ? depPath : '',
<add> }[_];
<add> })
<add> .filter(Boolean),
<add> parentPath,
<add> depPath,
<add> resources,
<add> })
<add> );
<add>}
<add>debug(`spawning ${tests.size} policy integrity permutations`);
<add>debug(
<add> 'use NODE_DEBUG=test:policy-integrity:NUMBER to log a specific permutation'
<add>);
<add>for (const config of tests) {
<add> const parsed = JSON.parse(config);
<add> tests.delete(config);
<add> queueSpawn(parsed);
<add>} | 7 |
Text | Text | add a missing word to the static optimization doc | 41d4084c040bd74b9519bb347fdfff7ce1f5c3a6 | <ide><path>docs/advanced-features/automatic-static-optimization.md
<ide> This feature allows Next.js to emit hybrid applications that contain **both serv
<ide>
<ide> > Statically generated pages are still reactive: Next.js will hydrate your application client-side to give it full interactivity.
<ide>
<del>One of the main benefits this feature is that optimized pages require no server-side computation, and can be instantly streamed to the end-user from multiple CDN locations. The result is an _ultra fast_ loading experience for your users.
<add>One of the main benefits of this feature is that optimized pages require no server-side computation, and can be instantly streamed to the end-user from multiple CDN locations. The result is an _ultra fast_ loading experience for your users.
<ide>
<ide> ## How it works
<ide> | 1 |
Text | Text | add ruben to tsc | e45874723fa698df5c761b921c29a49c43af1a30 | <ide><path>README.md
<ide> For information about the governance of the Node.js project, see
<ide> **Anatoli Papirovski** <apapirovski@mac.com> (he/him)
<ide> * [BethGriggs](https://github.com/BethGriggs) -
<ide> **Beth Griggs** <Bethany.Griggs@uk.ibm.com> (she/her)
<add>* [BridgeAR](https://github.com/BridgeAR) -
<add>**Ruben Bridgewater** <ruben@bridgewater.de> (he/him)
<ide> * [ChALkeR](https://github.com/ChALkeR) -
<ide> **Сковорода Никита Андреевич** <chalkerx@gmail.com> (he/him)
<ide> * [cjihrig](https://github.com/cjihrig) - | 1 |
Text | Text | add link to a iterm2 customization guide | 3de690ae5dc1b4769f133f2d1e3546fd32162a4b | <ide><path>guide/english/terminal-commandline/macos-terminal/index.md
<ide> iTerm2 is an alternative to the legacy terminal in Mac OS. iTerm2 brings some ne
<ide> * and many [more](https://www.iterm2.com/features.html)
<ide>
<ide> Just download iTerm2 from the official [website](https://www.iterm2.com/downloads.html). Additional documentation can be found [here](https://www.iterm2.com/documentation.html).
<add>
<add>#### iTerm2 Improvements and Customizations
<add>
<add>This [guide](https://medium.com/the-code-review/make-your-terminal-more-colourful-and-productive-with-iterm2-and-zsh-11b91607b98c) shows you how you can improve terminal productivity, and have a bit more customization options. | 1 |
Python | Python | fix minor typo in multi.py | 845df9b88c1e5d70f098ecc20a1b7e8835bb832c | <ide><path>celery/bin/multi.py
<ide> $ # You need to add the same arguments when you restart,
<ide> $ # as these aren't persisted anywhere.
<ide> $ celery multi restart Leslie -E --pidfile=/var/run/celery/%n.pid
<del> --logfile=/var/run/celery/%n%I.log
<add> --logfile=/var/log/celery/%n%I.log
<ide>
<ide> $ # To stop the node, you need to specify the same pidfile.
<ide> $ celery multi stop Leslie --pidfile=/var/run/celery/%n.pid | 1 |
Text | Text | clarify maxsockets option of http.agent | 090f0cd7b697f7a77fa0f6e3210d2ef368bfdc6e | <ide><path>doc/api/http.md
<ide> changes:
<ide> the [initial delay](net.md#net_socket_setkeepalive_enable_initialdelay)
<ide> for TCP Keep-Alive packets. Ignored when the
<ide> `keepAlive` option is `false` or `undefined`. **Default:** `1000`.
<del> * `maxSockets` {number} Maximum number of sockets to allow per
<del> host. Each request will use a new socket until the maximum is reached.
<add> * `maxSockets` {number} Maximum number of sockets to allow per host.
<add> If the same host opens multiple concurrent connections, each request
<add> will use new socket until the `maxSockets` value is reached.
<add> If the host attempts to open more connections than `maxSockets`,
<add> the additional requests will enter into a pending request queue, and
<add> will enter active connection state when an existing connection terminates.
<add> This makes sure there are at most `maxSockets` active connections at
<add> any point in time, from a given host.
<ide> **Default:** `Infinity`.
<ide> * `maxTotalSockets` {number} Maximum number of sockets allowed for
<ide> all hosts in total. Each request will use a new socket | 1 |
Javascript | Javascript | fix bad indentation producing a code block | 37bdcc984a0240cf0ac125613acee12f1cee389d | <ide><path>src/ngResource/resource.js
<ide> });
<ide> </pre>
<ide> *
<del> * It's worth noting that the success callback for `get`, `query` and other method gets passed
<del> * in the response that came from the server as well as $http header getter function, so one
<del> * could rewrite the above example and get access to http headers as:
<add> * It's worth noting that the success callback for `get`, `query` and other method gets passed
<add> * in the response that came from the server as well as $http header getter function, so one
<add> * could rewrite the above example and get access to http headers as:
<ide> *
<ide> <pre>
<ide> var User = $resource('/user/:userId', {userId:'@id'}); | 1 |
Javascript | Javascript | remove `subobjectload` function, add comments | 0122d2545531626532a829a693df067e3c391e15 | <ide><path>examples/js/loaders/LDrawLoader.js
<ide> THREE.LDrawLoader = ( function () {
<ide> subobject.url = subobjectURL;
<ide>
<ide> // Load the subobject
<del> subobjectLoad( subobjectURL, onSubobjectLoaded, undefined, onSubobjectError, subobject );
<add> // Use another file loader here so we can keep track of the subobject information
<add> // and use it when processing the next model.
<add> var fileLoader = new THREE.FileLoader( scope.manager );
<add> fileLoader.setPath( scope.path );
<add> fileLoader.load( subobjectURL, function ( text ) {
<add>
<add> processObject( text, onSubobjectLoaded, subobject );
<add>
<add> }, undefined, onSubobjectError );
<ide>
<ide> }
<ide>
<ide> THREE.LDrawLoader = ( function () {
<ide>
<ide> case 'BFC':
<ide>
<add> // Changes to the backface culling state
<ide> while ( ! lp.isAtTheEnd() ) {
<ide>
<ide> var token = lp.getToken();
<ide> THREE.LDrawLoader = ( function () {
<ide>
<ide> }
<ide>
<add> // If the scale of the object is negated then the triangle winding order
<add> // needs to be flipped.
<ide> if ( scope.separateObjects === false && matrix.determinant() < 0 ) {
<ide>
<ide> bfcInverted = ! bfcInverted; | 1 |
Text | Text | improve asynclocalstorage sample | 82d6726dcb4e05a603e971f46956c142f9403968 | <ide><path>doc/api/async_hooks.md
<ide> chains. It allows storing data throughout the lifetime of a web request
<ide> or any other asynchronous duration. It is similar to thread-local storage
<ide> in other languages.
<ide>
<del>The following example builds a logger that will always know the current HTTP
<del>request and uses it to display enhanced logs without needing to explicitly
<del>provide the current HTTP request to it.
<add>The following example uses `AsyncLocalStorage` to build a simple logger
<add>that assigns IDs to incoming HTTP requests and includes them in messages
<add>logged within each request.
<ide>
<ide> ```js
<del>const { AsyncLocalStorage } = require('async_hooks');
<ide> const http = require('http');
<add>const { AsyncLocalStorage } = require('async_hooks');
<ide>
<del>const kReq = 'CURRENT_REQUEST';
<ide> const asyncLocalStorage = new AsyncLocalStorage();
<ide>
<del>function log(...args) {
<del> const store = asyncLocalStorage.getStore();
<del> // Make sure the store exists and it contains a request.
<del> if (store && store.has(kReq)) {
<del> const req = store.get(kReq);
<del> // Prints `GET /items ERR could not do something
<del> console.log(req.method, req.url, ...args);
<del> } else {
<del> console.log(...args);
<del> }
<add>function logWithId(msg) {
<add> const id = asyncLocalStorage.getStore();
<add> console.log(`${id !== undefined ? id : '-'}:`, msg);
<ide> }
<ide>
<del>http.createServer((request, response) => {
<del> asyncLocalStorage.run(new Map(), () => {
<del> const store = asyncLocalStorage.getStore();
<del> store.set(kReq, request);
<del> someAsyncOperation((err, result) => {
<del> if (err) {
<del> log('ERR', err.message);
<del> }
<add>let idSeq = 0;
<add>http.createServer((req, res) => {
<add> asyncLocalStorage.run(idSeq++, () => {
<add> logWithId('start');
<add> // Imagine any chain of async operations here
<add> setImmediate(() => {
<add> logWithId('finish');
<add> res.end();
<ide> });
<ide> });
<del>})
<del>.listen(8080);
<add>}).listen(8080);
<add>
<add>http.get('http://localhost:8080');
<add>http.get('http://localhost:8080');
<add>// Prints:
<add>// 0: start
<add>// 1: start
<add>// 0: finish
<add>// 1: finish
<ide> ```
<ide>
<ide> When having multiple instances of `AsyncLocalStorage`, they are independent | 1 |
Python | Python | fix syntax error | 9262fc482946c26fe0734a05484e59da84cf9435 | <ide><path>spacy/language.py
<ide> from .tagger import Tagger
<ide> from .lemmatizer import Lemmatizer
<ide> from .syntax.parser import get_templates
<del>from .syntax.import nonproj
<add>from .syntax import nonproj
<ide> from .pipeline import NeuralDependencyParser, EntityRecognizer
<ide> from .pipeline import TokenVectorEncoder, NeuralTagger, NeuralEntityRecognizer
<ide> from .pipeline import NeuralLabeller | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.