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
add test for a vm indexed property
b409eaaf25dabe38f26e400ff01ffef598f0760d
<ide><path>test/parallel/test-vm-context-property-forwarding.js <ide> assert.strictEqual(vm.runInContext('x;', ctx), 3); <ide> vm.runInContext('y = 4;', ctx); <ide> assert.strictEqual(sandbox.y, 4); <ide> assert.strictEqual(ctx.y, 4); <add> <add>// Test `IndexedPropertyGetterCallback` and `IndexedPropertyDeleterCallback` <add>const x = { get 1() { return 5; } }; <add>const pd_expected = Object.getOwnPropertyDescriptor(x, 1); <add>const ctx2 = vm.createContext(x); <add>const pd_actual = Object.getOwnPropertyDescriptor(ctx2, 1); <add> <add>assert.deepStrictEqual(pd_actual, pd_expected); <add>assert.strictEqual(ctx2[1], 5); <add>delete ctx2[1]; <add>assert.strictEqual(ctx2[1], undefined);
1
Ruby
Ruby
use a class attribute
7903e3ada80d7938b1b78b06d0f678e95367a56b
<ide><path>lib/action_mailbox/routing.rb <ide> module ActionMailbox <ide> module Routing <ide> extend ActiveSupport::Concern <ide> <del> class_methods do <del> attr_reader :router <add> included do <add> cattr_accessor :router, default: ActionMailbox::Router.new <add> end <ide> <add> class_methods do <ide> def routing(routes) <del> (@router ||= ActionMailbox::Router.new).add_routes(routes) <add> router.add_routes(routes) <ide> end <ide> <ide> def route(inbound_email) <del> @router.route(inbound_email) <add> router.route(inbound_email) <ide> end <ide> end <ide> end
1
Javascript
Javascript
add test for missing `close`/`finish` event"
fb05c8e27d29c6277e644c793eeaba1d7007178e
<ide><path>test/parallel/test-http-response-close-event-race.js <del>var common = require('../common'); <del>var assert = require('assert'); <del>var http = require('http'); <del> <del>var clientRequest = null; <del>var eventCount = 0; <del>var testTickCount = 3; <del> <del>var server = http.createServer(function(req, res) { <del> console.log('server: request'); <del> <del> res.on('finish', function() { <del> console.log('server: response finish'); <del> eventCount++; <del> }); <del> res.on('close', function() { <del> console.log('server: response close'); <del> eventCount++; <del> }); <del> <del> console.log('client: aborting request'); <del> clientRequest.abort(); <del> <del> var ticks = 0; <del> function tick() { <del> console.log('server: tick ' + ticks + <del> (req.connection.destroyed ? ' (connection destroyed!)' : '')); <del> <del> if (ticks < testTickCount) { <del> ticks++; <del> setImmediate(tick); <del> } else { <del> sendResponse(); <del> } <del> } <del> tick(); <del> <del> function sendResponse() { <del> console.log('server: sending response'); <del> res.writeHead(200, {'Content-Type': 'text/plain'}); <del> res.end('Response\n'); <del> console.log('server: res.end() returned'); <del> <del> handleResponseEnd(); <del> } <del>}); <del> <del>server.on('listening', function() { <del> console.log('server: listening on port ' + common.PORT); <del> console.log('-----------------------------------------------------'); <del> startRequest(); <del>}); <del> <del>server.on('connection', function(connection) { <del> console.log('server: connection'); <del> connection.on('close', function() { <del> console.log('server: connection close'); <del> }); <del>}); <del> <del>server.on('close', function() { <del> console.log('server: close'); <del>}); <del> <del>server.listen(common.PORT); <del> <del>function startRequest() { <del> console.log('client: starting request - testing with %d ticks after abort()', <del> testTickCount); <del> eventCount = 0; <del> <del> var options = {port: common.PORT, path: '/'}; <del> clientRequest = http.get(options, function() {}); <del> clientRequest.on('error', function() {}); <del>} <del> <del>function handleResponseEnd() { <del> setImmediate(function() { <del> setImmediate(function() { <del> assert.equal(eventCount, 1); <del> <del> if (testTickCount > 0) { <del> testTickCount--; <del> startRequest(); <del> } else { <del> server.close(); <del> } <del> }); <del> }); <del>}
1
Javascript
Javascript
remove trailing spaces
e626f4a7e8d7f662f229c0a42794b3cba4f60d59
<ide><path>packages/ember-runtime/lib/system/core_object.js <ide> var ClassMixinProps = { <ide> ``` <ide> <ide> This will return the original hash that was passed to `meta()`. <del> <add> <ide> @static <ide> @method metaForProperty <ide> @param key {String} property name <ide> var ClassMixinProps = { <ide> /** <ide> Iterate over each computed property for the class, passing its name <ide> and any associated metadata (see `metaForProperty`) to the callback. <del> <add> <ide> @static <ide> @method eachComputedProperty <ide> @param {Function} callback
1
Java
Java
fix empty payload handling in rsocketrequester
26d800cc936a9e1f6d326c3b48022267bb30ed0f
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/rsocket/DefaultRSocketRequester.java <ide> final class DefaultRSocketRequester implements RSocketRequester { <ide> <ide> private final RSocketStrategies strategies; <ide> <del> private final DataBuffer emptyDataBuffer; <add> private final Mono<DataBuffer> emptyBufferMono; <ide> <ide> <ide> DefaultRSocketRequester( <ide> final class DefaultRSocketRequester implements RSocketRequester { <ide> this.dataMimeType = dataMimeType; <ide> this.metadataMimeType = metadataMimeType; <ide> this.strategies = strategies; <del> this.emptyDataBuffer = this.strategies.dataBufferFactory().wrap(new byte[0]); <add> this.emptyBufferMono = Mono.just(this.strategies.dataBufferFactory().wrap(new byte[0])); <ide> } <ide> <ide> <ide> else if (adapter != null) { <ide> } <ide> <ide> if (isVoid(elementType) || (adapter != null && adapter.isNoValue())) { <del> this.payloadMono = firstPayload(Mono.when(publisher).then(Mono.just(emptyDataBuffer))); <add> this.payloadMono = Mono.when(publisher).then(firstPayload(emptyBufferMono)); <ide> this.payloadFlux = null; <ide> return; <ide> } <ide> else if (adapter != null) { <ide> if (adapter != null && !adapter.isMultiValue()) { <ide> Mono<DataBuffer> data = Mono.from(publisher) <ide> .map(value -> encodeData(value, elementType, encoder)) <del> .defaultIfEmpty(emptyDataBuffer); <add> .switchIfEmpty(emptyBufferMono); <ide> this.payloadMono = firstPayload(data); <ide> this.payloadFlux = null; <ide> return; <ide> else if (adapter != null) { <ide> this.payloadMono = null; <ide> this.payloadFlux = Flux.from(publisher) <ide> .map(value -> encodeData(value, elementType, encoder)) <del> .defaultIfEmpty(emptyDataBuffer) <add> .switchIfEmpty(emptyBufferMono) <ide> .switchOnFirst((signal, inner) -> { <ide> DataBuffer data = signal.get(); <ide> if (data != null) { <ide> private Mono<Payload> firstPayload(Mono<DataBuffer> encodedData) { <ide> <ide> @Override <ide> public Mono<Void> send() { <del> return getPayloadMonoRequired().flatMap(rsocket::fireAndForget); <del> } <del> <del> private Mono<Payload> getPayloadMonoRequired() { <del> Assert.state(this.payloadFlux == null, "No RSocket interaction model for Flux request to Mono response."); <del> return this.payloadMono != null ? this.payloadMono : firstPayload(Mono.just(emptyDataBuffer)); <add> return getPayloadMono().flatMap(rsocket::fireAndForget); <ide> } <ide> <ide> @Override <ide> public <T> Mono<T> retrieveMono(ParameterizedTypeReference<T> dataTypeRef) { <ide> return retrieveMono(ResolvableType.forType(dataTypeRef)); <ide> } <ide> <del> @Override <del> public <T> Flux<T> retrieveFlux(Class<T> dataType) { <del> return retrieveFlux(ResolvableType.forClass(dataType)); <del> } <del> <del> @Override <del> public <T> Flux<T> retrieveFlux(ParameterizedTypeReference<T> dataTypeRef) { <del> return retrieveFlux(ResolvableType.forType(dataTypeRef)); <del> } <del> <ide> @SuppressWarnings("unchecked") <ide> private <T> Mono<T> retrieveMono(ResolvableType elementType) { <del> Mono<Payload> payloadMono = getPayloadMonoRequired().flatMap(rsocket::requestResponse); <add> Mono<Payload> payloadMono = getPayloadMono().flatMap(rsocket::requestResponse); <ide> <ide> if (isVoid(elementType)) { <ide> return (Mono<T>) payloadMono.then(); <ide> private <T> Mono<T> retrieveMono(ResolvableType elementType) { <ide> .map(dataBuffer -> decoder.decode(dataBuffer, elementType, dataMimeType, EMPTY_HINTS)); <ide> } <ide> <add> @Override <add> public <T> Flux<T> retrieveFlux(Class<T> dataType) { <add> return retrieveFlux(ResolvableType.forClass(dataType)); <add> } <add> <add> @Override <add> public <T> Flux<T> retrieveFlux(ParameterizedTypeReference<T> dataTypeRef) { <add> return retrieveFlux(ResolvableType.forType(dataTypeRef)); <add> } <add> <ide> @SuppressWarnings("unchecked") <ide> private <T> Flux<T> retrieveFlux(ResolvableType elementType) { <del> Flux<Payload> payloadFlux = this.payloadMono != null ? <del> this.payloadMono.flatMapMany(rsocket::requestStream) : <del> rsocket.requestChannel(this.payloadFlux); <add> <add> Flux<Payload> payloadFlux = (this.payloadFlux != null ? <add> rsocket.requestChannel(this.payloadFlux) : <add> getPayloadMono().flatMapMany(rsocket::requestStream)); <ide> <ide> if (isVoid(elementType)) { <ide> return payloadFlux.thenMany(Flux.empty()); <ide> private <T> Flux<T> retrieveFlux(ResolvableType elementType) { <ide> (T) decoder.decode(dataBuffer, elementType, dataMimeType, EMPTY_HINTS)); <ide> } <ide> <add> private Mono<Payload> getPayloadMono() { <add> Assert.state(this.payloadFlux == null, "No RSocket interaction with Flux request and Mono response."); <add> return this.payloadMono != null ? this.payloadMono : firstPayload(emptyBufferMono); <add> } <add> <ide> private DataBuffer retainDataAndReleasePayload(Payload payload) { <ide> return PayloadUtils.retainDataAndReleasePayload(payload, bufferFactory()); <ide> } <ide><path>spring-messaging/src/test/java/org/springframework/messaging/rsocket/DefaultRSocketRequesterTests.java <ide> public void sendWithoutData() { <ide> assertThat(this.rsocket.getSavedPayload().getDataUtf8()).isEqualTo(""); <ide> } <ide> <del> @Test <del> public void sendMonoWithoutData() { <del> this.requester.route("toA").retrieveMono(String.class).block(Duration.ofSeconds(5)); <del> <del> assertThat(this.rsocket.getSavedMethodName()).isEqualTo("requestResponse"); <del> assertThat(this.rsocket.getSavedPayload().getMetadataUtf8()).isEqualTo("toA"); <del> assertThat(this.rsocket.getSavedPayload().getDataUtf8()).isEqualTo(""); <del> } <del> <ide> @Test <ide> public void testSendWithAsyncMetadata() { <ide> <ide> public void retrieveMonoVoid() { <ide> assertThat(this.rsocket.getSavedMethodName()).isEqualTo("requestResponse"); <ide> } <ide> <add> @Test <add> public void retrieveMonoWithoutData() { <add> this.requester.route("toA").retrieveMono(String.class).block(Duration.ofSeconds(5)); <add> <add> assertThat(this.rsocket.getSavedMethodName()).isEqualTo("requestResponse"); <add> assertThat(this.rsocket.getSavedPayload().getMetadataUtf8()).isEqualTo("toA"); <add> assertThat(this.rsocket.getSavedPayload().getDataUtf8()).isEqualTo(""); <add> } <add> <ide> @Test <ide> public void retrieveFlux() { <ide> String[] values = new String[] {"bodyA", "bodyB", "bodyC"}; <ide> public void retrieveFluxVoid() { <ide> assertThat(this.rsocket.getSavedMethodName()).isEqualTo("requestStream"); <ide> } <ide> <add> @Test <add> public void retrieveFluxWithoutData() { <add> this.requester.route("toA").retrieveFlux(String.class).blockLast(Duration.ofSeconds(5)); <add> <add> assertThat(this.rsocket.getSavedMethodName()).isEqualTo("requestStream"); <add> assertThat(this.rsocket.getSavedPayload().getMetadataUtf8()).isEqualTo("toA"); <add> assertThat(this.rsocket.getSavedPayload().getDataUtf8()).isEqualTo(""); <add> } <add> <ide> @Test <ide> public void fluxToMonoIsRejected() { <ide> assertThatIllegalStateException() <ide> .isThrownBy(() -> this.requester.route("").data(Flux.just("a", "b")).retrieveMono(String.class)) <del> .withMessage("No RSocket interaction model for Flux request to Mono response."); <add> .withMessage("No RSocket interaction with Flux request and Mono response."); <ide> } <ide> <ide> private Payload toPayload(String value) {
2
PHP
PHP
fix cs errors in tests
944caaaa99a6d8fd3937229d613ac3da9a289130
<ide><path>tests/TestCase/Cache/Engine/MemcachedEngineTest.php <ide> public function setUp() <ide> parent::setUp(); <ide> $this->skipIf(!class_exists('Memcached'), 'Memcached is not installed or configured properly.'); <ide> <add> // @codingStandardsIgnoreStart <ide> $socket = @fsockopen('127.0.0.1', 11211, $errno, $errstr, 1); <add> // @codingStandardsIgnoreEnd <ide> $this->skipIf(!$socket, 'Memcached is not running.'); <ide> fclose($socket); <ide> <ide><path>tests/TestCase/Cache/Engine/RedisEngineTest.php <ide> public function setUp() <ide> parent::setUp(); <ide> $this->skipIf(!class_exists('Redis'), 'Redis extension is not installed or configured properly.'); <ide> <add> // @codingStandardsIgnoreStart <ide> $socket = @fsockopen('127.0.0.1', 6379, $errno, $errstr, 1); <add> // @codingStandardsIgnoreEnd <ide> $this->skipIf(!$socket, 'Redis is not running.'); <ide> fclose($socket); <ide>
2
Java
Java
add naming strategy for @mvc request mappings
9d479feadded560b1d9a2c485730984ff5dcbfdb
<ide><path>spring-web/src/main/java/org/springframework/web/bind/annotation/RequestMapping.java <ide> @Mapping <ide> public @interface RequestMapping { <ide> <add> <add> /** <add> * Assign a name to this mapping. <add> * <p><b>Supported at the method and also at type level!</b> <add> * When used on both levels, a combined name is derived by <add> * concatenation with "#" as separator. <add> * <add> * @see org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder <add> * @see org.springframework.web.servlet.handler.HandlerMethodMappingNamingStrategy <add> */ <add> String name() default ""; <add> <ide> /** <ide> * The primary mapping expressed by this annotation. <ide> * <p>In a Servlet environment: the path mapping URIs (e.g. "/myPath.do"). <ide><path>spring-web/src/main/java/org/springframework/web/method/annotation/RequestParamMethodArgumentResolver.java <ide> protected void handleMissingValue(String paramName, MethodParameter parameter) t <ide> } <ide> <ide> @Override <del> public void contributeMethodArgument(MethodParameter parameter, Object value, <add> public void contributeMethodArgument(MethodParameter param, Object value, <ide> UriComponentsBuilder builder, Map<String, Object> uriVariables, ConversionService conversionService) { <ide> <del> Class<?> paramType = parameter.getParameterType(); <add> Class<?> paramType = param.getParameterType(); <ide> if (Map.class.isAssignableFrom(paramType) || MultipartFile.class.equals(paramType) || <ide> "javax.servlet.http.Part".equals(paramType.getName())) { <ide> return; <ide> } <ide> <del> RequestParam annot = parameter.getParameterAnnotation(RequestParam.class); <del> String name = StringUtils.isEmpty(annot.value()) ? parameter.getParameterName() : annot.value(); <add> RequestParam annot = param.getParameterAnnotation(RequestParam.class); <add> String name = (annot == null || StringUtils.isEmpty(annot.value()) ? param.getParameterName() : annot.value()); <ide> <ide> if (value == null) { <ide> builder.queryParam(name); <ide> } <ide> else if (value instanceof Collection) { <ide> for (Object element : (Collection<?>) value) { <del> element = formatUriValue(conversionService, TypeDescriptor.nested(parameter, 1), element); <add> element = formatUriValue(conversionService, TypeDescriptor.nested(param, 1), element); <ide> builder.queryParam(name, element); <ide> } <ide> } <ide> else { <del> builder.queryParam(name, formatUriValue(conversionService, new TypeDescriptor(parameter), value)); <add> builder.queryParam(name, formatUriValue(conversionService, new TypeDescriptor(param), value)); <ide> } <ide> } <ide> <ide> protected String formatUriValue(ConversionService cs, TypeDescriptor sourceType, Object value) { <del> return (cs != null ? (String) cs.convert(value, sourceType, STRING_TYPE_DESCRIPTOR) : null); <add> if (value == null) { <add> return null; <add> } <add> else if (value instanceof String) { <add> return (String) value; <add> } <add> else if (cs != null) { <add> return (String) cs.convert(value, sourceType, STRING_TYPE_DESCRIPTOR); <add> } <add> else { <add> return value.toString(); <add> } <ide> } <ide> <ide> <ide><path>spring-web/src/main/java/org/springframework/web/method/support/CompositeUriComponentsContributor.java <ide> */ <ide> public class CompositeUriComponentsContributor implements UriComponentsContributor { <ide> <del> private final List<UriComponentsContributor> contributors = new LinkedList<UriComponentsContributor>(); <add> private final List<Object> contributors = new LinkedList<Object>(); <ide> <ide> private final ConversionService conversionService; <ide> <ide> public CompositeUriComponentsContributor(Collection<?> contributors) { <ide> * will be used by default. <ide> * @param contributors a collection of {@link UriComponentsContributor} <ide> * or {@link HandlerMethodArgumentResolver}s. <del> * @param conversionService a ConversionService to use when method argument values <add> * @param cs a ConversionService to use when method argument values <ide> * need to be formatted as Strings before being added to the URI <ide> */ <del> public CompositeUriComponentsContributor(Collection<?> contributors, ConversionService conversionService) { <add> public CompositeUriComponentsContributor(Collection<?> contributors, ConversionService cs) { <ide> Assert.notNull(contributors, "'uriComponentsContributors' must not be null"); <del> for (Object contributor : contributors) { <del> if (contributor instanceof UriComponentsContributor) { <del> this.contributors.add((UriComponentsContributor) contributor); <del> } <del> } <del> this.conversionService = <del> (conversionService != null ? conversionService : new DefaultFormattingConversionService()); <add> this.contributors.addAll(contributors); <add> this.conversionService = (cs != null ? cs : new DefaultFormattingConversionService()); <ide> } <ide> <ide> <ide> public boolean hasContributors() { <ide> <ide> @Override <ide> public boolean supportsParameter(MethodParameter parameter) { <del> for (UriComponentsContributor contributor : this.contributors) { <del> if (contributor.supportsParameter(parameter)) { <del> return true; <add> for (Object c : this.contributors) { <add> if (c instanceof UriComponentsContributor) { <add> UriComponentsContributor contributor = (UriComponentsContributor) c; <add> if (contributor.supportsParameter(parameter)) { <add> return true; <add> } <add> } <add> else if (c instanceof HandlerMethodArgumentResolver) { <add> if (((HandlerMethodArgumentResolver) c).supportsParameter(parameter)) { <add> return false; <add> } <ide> } <ide> } <ide> return false; <ide> public boolean supportsParameter(MethodParameter parameter) { <ide> public void contributeMethodArgument(MethodParameter parameter, Object value, <ide> UriComponentsBuilder builder, Map<String, Object> uriVariables, ConversionService conversionService) { <ide> <del> for (UriComponentsContributor contributor : this.contributors) { <del> if (contributor.supportsParameter(parameter)) { <del> contributor.contributeMethodArgument(parameter, value, builder, uriVariables, conversionService); <del> break; <add> for (Object c : this.contributors) { <add> if (c instanceof UriComponentsContributor) { <add> UriComponentsContributor contributor = (UriComponentsContributor) c; <add> if (contributor.supportsParameter(parameter)) { <add> contributor.contributeMethodArgument(parameter, value, builder, uriVariables, conversionService); <add> break; <add> } <add> } <add> else if (c instanceof HandlerMethodArgumentResolver) { <add> if (((HandlerMethodArgumentResolver) c).supportsParameter(parameter)) { <add> break; <add> } <ide> } <ide> } <ide> } <ide><path>spring-web/src/test/java/org/springframework/web/method/support/CompositeUriComponentsContributorTests.java <add>/* <add> * Copyright 2002-2014 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.web.method.support; <add> <add>import org.junit.Test; <add>import org.springframework.core.MethodParameter; <add>import org.springframework.util.ClassUtils; <add>import org.springframework.web.bind.annotation.RequestHeader; <add>import org.springframework.web.bind.annotation.RequestParam; <add>import org.springframework.web.method.annotation.RequestHeaderMethodArgumentResolver; <add>import org.springframework.web.method.annotation.RequestParamMethodArgumentResolver; <add> <add>import java.lang.reflect.Method; <add>import java.util.ArrayList; <add>import java.util.List; <add> <add>import static org.junit.Assert.assertFalse; <add>import static org.junit.Assert.assertTrue; <add> <add>/** <add> * Unit tests for <add> * {@link org.springframework.web.method.support.CompositeUriComponentsContributor}. <add> * <add> * @author Rossen Stoyanchev <add> */ <add>public class CompositeUriComponentsContributorTests { <add> <add> <add> @Test <add> public void supportsParameter() { <add> <add> List<HandlerMethodArgumentResolver> resolvers = new ArrayList<HandlerMethodArgumentResolver>(); <add> resolvers.add(new RequestParamMethodArgumentResolver(false)); <add> resolvers.add(new RequestHeaderMethodArgumentResolver(null)); <add> resolvers.add(new RequestParamMethodArgumentResolver(true)); <add> <add> Method method = ClassUtils.getMethod(this.getClass(), "handleRequest", String.class, String.class, String.class); <add> <add> CompositeUriComponentsContributor contributor = new CompositeUriComponentsContributor(resolvers); <add> assertTrue(contributor.supportsParameter(new MethodParameter(method, 0))); <add> assertTrue(contributor.supportsParameter(new MethodParameter(method, 1))); <add> assertFalse(contributor.supportsParameter(new MethodParameter(method, 2))); <add> } <add> <add> <add> @SuppressWarnings("unused") <add> public void handleRequest(@RequestParam String p1, String p2, @RequestHeader String h) { <add> } <add> <add>} <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerMethodMapping.java <ide> <ide> private boolean detectHandlerMethodsInAncestorContexts = false; <ide> <add> private HandlerMethodMappingNamingStrategy<T> namingStrategy; <add> <add> <ide> private final Map<T, HandlerMethod> handlerMethods = new LinkedHashMap<T, HandlerMethod>(); <ide> <ide> private final MultiValueMap<String, T> urlMap = new LinkedMultiValueMap<String, T>(); <ide> <add> private final MultiValueMap<String, HandlerMethod> nameMap = new LinkedMultiValueMap<String, HandlerMethod>(); <add> <ide> <ide> /** <ide> * Whether to detect handler methods in beans in ancestor ApplicationContexts. <ide> public void setDetectHandlerMethodsInAncestorContexts(boolean detectHandlerMetho <ide> this.detectHandlerMethodsInAncestorContexts = detectHandlerMethodsInAncestorContexts; <ide> } <ide> <add> /** <add> * Configure the naming strategy to use for assigning a default name to every <add> * mapped handler method. <add> * <add> * @param namingStrategy strategy to use. <add> */ <add> public void setHandlerMethodMappingNamingStrategy(HandlerMethodMappingNamingStrategy<T> namingStrategy) { <add> this.namingStrategy = namingStrategy; <add> } <add> <ide> /** <ide> * Return a map with all handler methods and their mappings. <ide> */ <ide> public Map<T, HandlerMethod> getHandlerMethods() { <ide> return Collections.unmodifiableMap(this.handlerMethods); <ide> } <ide> <add> /** <add> * Return the handler methods mapped to the mapping with the given name. <add> * @param mappingName the mapping name <add> */ <add> public List<HandlerMethod> getHandlerMethodsForMappingName(String mappingName) { <add> return this.nameMap.get(mappingName); <add> } <add> <ide> /** <ide> * Detects handler methods at initialization. <ide> */ <ide> protected void registerHandlerMethod(Object handler, Method method, T mapping) { <ide> this.urlMap.add(pattern, mapping); <ide> } <ide> } <add> <add> if (this.namingStrategy != null) { <add> String name = this.namingStrategy.getName(newHandlerMethod, mapping); <add> updateNameMap(name, newHandlerMethod); <add> } <add> } <add> <add> private void updateNameMap(String name, HandlerMethod newHandlerMethod) { <add> <add> List<HandlerMethod> handlerMethods = this.nameMap.get(name); <add> if (handlerMethods != null) { <add> for (HandlerMethod handlerMethod : handlerMethods) { <add> if (handlerMethod.getMethod().equals(newHandlerMethod.getMethod())) { <add> logger.trace("Mapping name already registered. Multiple controller instances perhaps?"); <add> return; <add> } <add> } <add> } <add> <add> logger.trace("Mapping name=" + name); <add> this.nameMap.add(name, newHandlerMethod); <add> <add> if (this.nameMap.get(name).size() > 1) { <add> if (logger.isDebugEnabled()) { <add> logger.debug("Mapping name clash for handlerMethods=" + this.nameMap.get(name) + <add> ". Consider assigning explicit names."); <add> } <add> } <ide> } <ide> <ide> /** <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/handler/HandlerMethodMappingNamingStrategy.java <add>/* <add> * Copyright 2002-2014 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.web.servlet.handler; <add> <add>import org.springframework.web.method.HandlerMethod; <add> <add>import java.lang.reflect.Method; <add> <add>/** <add> * A strategy for assigning a name to a controller method mapping. <add> * <add> * @author Rossen Stoyanchev <add> * @since 4.1 <add> */ <add>public interface HandlerMethodMappingNamingStrategy<T> { <add> <add> /** <add> * Determine the name for the given HandlerMethod and mapping. <add> * <add> * @param handlerMethod the handler method <add> * @param mapping the mapping <add> * <add> * @return the name <add> */ <add> String getName(HandlerMethod handlerMethod, T mapping); <add> <add>} <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/RequestMappingInfo.java <ide> <ide> import javax.servlet.http.HttpServletRequest; <ide> <add>import org.springframework.util.StringUtils; <ide> import org.springframework.web.servlet.mvc.condition.ConsumesRequestCondition; <ide> import org.springframework.web.servlet.mvc.condition.HeadersRequestCondition; <ide> import org.springframework.web.servlet.mvc.condition.ParamsRequestCondition; <ide> */ <ide> public final class RequestMappingInfo implements RequestCondition<RequestMappingInfo> { <ide> <add> private final String name; <add> <ide> private final PatternsRequestCondition patternsCondition; <ide> <ide> private final RequestMethodsRequestCondition methodsCondition; <ide> public final class RequestMappingInfo implements RequestCondition<RequestMapping <ide> private final RequestConditionHolder customConditionHolder; <ide> <ide> <del> /** <del> * Creates a new instance with the given request conditions. <del> */ <del> public RequestMappingInfo(PatternsRequestCondition patterns, RequestMethodsRequestCondition methods, <add> public RequestMappingInfo(String name, PatternsRequestCondition patterns, RequestMethodsRequestCondition methods, <ide> ParamsRequestCondition params, HeadersRequestCondition headers, ConsumesRequestCondition consumes, <ide> ProducesRequestCondition produces, RequestCondition<?> custom) { <ide> <add> this.name = (StringUtils.hasText(name) ? name : null); <ide> this.patternsCondition = (patterns != null ? patterns : new PatternsRequestCondition()); <ide> this.methodsCondition = (methods != null ? methods : new RequestMethodsRequestCondition()); <ide> this.paramsCondition = (params != null ? params : new ParamsRequestCondition()); <ide> public RequestMappingInfo(PatternsRequestCondition patterns, RequestMethodsReque <ide> this.customConditionHolder = new RequestConditionHolder(custom); <ide> } <ide> <add> /** <add> * Creates a new instance with the given request conditions. <add> */ <add> public RequestMappingInfo(PatternsRequestCondition patterns, RequestMethodsRequestCondition methods, <add> ParamsRequestCondition params, HeadersRequestCondition headers, ConsumesRequestCondition consumes, <add> ProducesRequestCondition produces, RequestCondition<?> custom) { <add> <add> this(null, patterns, methods, params, headers, consumes, produces, custom); <add> } <add> <ide> /** <ide> * Re-create a RequestMappingInfo with the given custom request condition. <ide> */ <ide> public RequestMappingInfo(RequestMappingInfo info, RequestCondition<?> customRequestCondition) { <del> this(info.patternsCondition, info.methodsCondition, info.paramsCondition, info.headersCondition, <add> this(info.name, info.patternsCondition, info.methodsCondition, info.paramsCondition, info.headersCondition, <ide> info.consumesCondition, info.producesCondition, customRequestCondition); <ide> } <ide> <ide> <add> /** <add> * Return the name for this mapping, or {@code null}. <add> */ <add> public String getName() { <add> return this.name; <add> } <add> <ide> /** <ide> * Returns the URL patterns of this {@link RequestMappingInfo}; <ide> * or instance with 0 patterns, never {@code null}. <ide> public RequestCondition<?> getCustomCondition() { <ide> */ <ide> @Override <ide> public RequestMappingInfo combine(RequestMappingInfo other) { <add> String name = combineNames(other); <ide> PatternsRequestCondition patterns = this.patternsCondition.combine(other.patternsCondition); <ide> RequestMethodsRequestCondition methods = this.methodsCondition.combine(other.methodsCondition); <ide> ParamsRequestCondition params = this.paramsCondition.combine(other.paramsCondition); <ide> public RequestMappingInfo combine(RequestMappingInfo other) { <ide> ProducesRequestCondition produces = this.producesCondition.combine(other.producesCondition); <ide> RequestConditionHolder custom = this.customConditionHolder.combine(other.customConditionHolder); <ide> <del> return new RequestMappingInfo(patterns, methods, params, headers, consumes, produces, custom.getCondition()); <add> return new RequestMappingInfo(name, patterns, <add> methods, params, headers, consumes, produces, custom.getCondition()); <add> } <add> <add> private String combineNames(RequestMappingInfo other) { <add> if (this.name != null && other.name != null) { <add> String separator = RequestMappingInfoHandlerMethodMappingNamingStrategy.SEPARATOR; <add> return this.name + separator + other.name; <add> } <add> else if (this.name != null) { <add> return this.name; <add> } <add> else { <add> return (other.name != null ? other.name : null); <add> } <ide> } <ide> <ide> /** <ide> public RequestMappingInfo getMatchingCondition(HttpServletRequest request) { <ide> return null; <ide> } <ide> <del> return new RequestMappingInfo(patterns, methods, params, headers, consumes, produces, custom.getCondition()); <add> return new RequestMappingInfo(this.name, patterns, <add> methods, params, headers, consumes, produces, custom.getCondition()); <ide> } <ide> <ide> <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMapping.java <ide> */ <ide> public abstract class RequestMappingInfoHandlerMapping extends AbstractHandlerMethodMapping<RequestMappingInfo> { <ide> <add> <add> protected RequestMappingInfoHandlerMapping() { <add> setHandlerMethodMappingNamingStrategy(new RequestMappingInfoHandlerMethodMappingNamingStrategy()); <add> } <add> <ide> /** <ide> * Get the URL path patterns associated with this {@link RequestMappingInfo}. <ide> */ <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMethodMappingNamingStrategy.java <add>/* <add> * Copyright 2002-2014 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.web.servlet.mvc.method; <add> <add>import org.springframework.web.method.HandlerMethod; <add>import org.springframework.web.servlet.handler.HandlerMethodMappingNamingStrategy; <add> <add>import java.lang.reflect.Method; <add> <add>/** <add> * A {@link org.springframework.web.servlet.handler.HandlerMethodMappingNamingStrategy <add> * HandlerMethodMappingNamingStrategy} for {@code RequestMappingInfo}-based handler <add> * method mappings. <add> * <add> * If the {@code RequestMappingInfo} name attribute is set, its value is used. <add> * Otherwise the name is based on the capital letters of the class name, <add> * followed by "#" as a separator, and the method name. For example "TC#getFoo" <add> * for a class named TestController with method getFoo. <add> * <add> * @author Rossen Stoyanchev <add> * @since 4.1 <add> */ <add>public class RequestMappingInfoHandlerMethodMappingNamingStrategy <add> implements HandlerMethodMappingNamingStrategy<RequestMappingInfo> { <add> <add> /** Separator between the type and method-level parts of a HandlerMethod mapping name */ <add> public static final String SEPARATOR = "#"; <add> <add> <add> @Override <add> public String getName(HandlerMethod handlerMethod, RequestMappingInfo mapping) { <add> if (mapping.getName() != null) { <add> return mapping.getName(); <add> } <add> StringBuilder sb = new StringBuilder(); <add> String simpleTypeName = handlerMethod.getBeanType().getSimpleName(); <add> for (int i = 0 ; i < simpleTypeName.length(); i++) { <add> if (Character.isUpperCase(simpleTypeName.charAt(i))) { <add> sb.append(simpleTypeName.charAt(i)); <add> } <add> } <add> sb.append(SEPARATOR).append(handlerMethod.getMethod().getName()); <add> return sb.toString(); <add> } <add> <add>} <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/MvcUriComponentsBuilder.java <ide> import java.lang.reflect.Method; <ide> import java.util.Arrays; <ide> import java.util.HashMap; <add>import java.util.List; <ide> import java.util.Map; <ide> import javax.servlet.http.HttpServletRequest; <ide> <ide> import org.springframework.aop.framework.ProxyFactory; <ide> import org.springframework.aop.target.EmptyTargetSource; <ide> import org.springframework.beans.factory.NoSuchBeanDefinitionException; <add>import org.springframework.beans.factory.NoUniqueBeanDefinitionException; <ide> import org.springframework.cglib.core.SpringNamingPolicy; <ide> import org.springframework.cglib.proxy.Callback; <ide> import org.springframework.cglib.proxy.Enhancer; <ide> import org.springframework.web.context.request.RequestAttributes; <ide> import org.springframework.web.context.request.RequestContextHolder; <ide> import org.springframework.web.context.request.ServletRequestAttributes; <add>import org.springframework.web.method.HandlerMethod; <ide> import org.springframework.web.method.annotation.RequestParamMethodArgumentResolver; <ide> import org.springframework.web.method.support.CompositeUriComponentsContributor; <ide> import org.springframework.web.servlet.DispatcherServlet; <add>import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping; <ide> import org.springframework.web.servlet.support.ServletUriComponentsBuilder; <ide> import org.springframework.web.util.UriComponents; <ide> import org.springframework.web.util.UriComponentsBuilder; <ide> public static UriComponentsBuilder fromMethodCall(Object invocationInfo) { <ide> return fromMethod(info.getControllerMethod(), info.getArgumentValues()); <ide> } <ide> <add> /** <add> * Create a {@link UriComponentsBuilder} from a request mapping identified <add> * by name. The configured <add> * {@link org.springframework.web.servlet.handler.HandlerMethodMappingNamingStrategy <add> * HandlerMethodMappingNamingStrategy} assigns a default name to every <add> * {@code @RequestMapping} method but an explicit name may also be assigned <add> * through the {@code @RequestMapping} name attribute. <add> * <add> * <p>This is intended for use in EL expressions, typically in JSPs or other <add> * view templates, which can use the convenience method: <add> * {@link org.springframework.web.servlet.support.RequestContext#getMvcUrl(String, Object...) <add> * RequestContext.getMvcUrl(String, Object...)}). <add> * <add> * <p>The default naming convention for mappings is based on the capital <add> * letters of the class name, followed by "#" as a separator, and the method <add> * name. For example "TC#getFoo" for a class named TestController with method <add> * getFoo. Use explicit names where the naming convention does not produce <add> * unique results. <add> * <add> * @param name the mapping name <add> * @param argumentValues argument values for the controller method; those values <add> * are important for {@code @RequestParam} and {@code @PathVariable} arguments <add> * but may be passed as {@code null} otherwise. <add> * <add> * @return the UriComponentsBuilder <add> * <add> * @throws java.lang.IllegalStateException if the mapping name is not found <add> * or there is no unique match <add> */ <add> public static UriComponentsBuilder fromMappingName(String name, Object... argumentValues) { <add> RequestMappingInfoHandlerMapping hm = getRequestMappingInfoHandlerMapping(); <add> List<HandlerMethod> handlerMethods = hm.getHandlerMethodsForMappingName(name); <add> Assert.state(handlerMethods != null, "Mapping name not found: " + name); <add> Assert.state(handlerMethods.size() == 1, "No unique match for mapping name " + name + ": " + handlerMethods); <add> return fromMethod(handlerMethods.get(0).getMethod(), argumentValues); <add> } <add> <ide> /** <ide> * Create a {@link UriComponentsBuilder} from the mapping of a controller method <ide> * and an array of method argument values. The array of values must match the <ide> public Object getValue(String name) { <ide> } <ide> <ide> protected static CompositeUriComponentsContributor getConfiguredUriComponentsContributor() { <add> WebApplicationContext wac = getWebApplicationContext(); <add> if (wac == null) { <add> return null; <add> } <add> try { <add> return wac.getBean(MVC_URI_COMPONENTS_CONTRIBUTOR_BEAN_NAME, CompositeUriComponentsContributor.class); <add> } <add> catch (NoSuchBeanDefinitionException ex) { <add> if (logger.isDebugEnabled()) { <add> logger.debug("No CompositeUriComponentsContributor bean with name '" + <add> MVC_URI_COMPONENTS_CONTRIBUTOR_BEAN_NAME + "'"); <add> } <add> return null; <add> } <add> } <add> <add> protected static RequestMappingInfoHandlerMapping getRequestMappingInfoHandlerMapping() { <add> WebApplicationContext wac = getWebApplicationContext(); <add> Assert.notNull(wac, "Cannot lookup handler method mappings without WebApplicationContext"); <add> try { <add> return wac.getBean(RequestMappingInfoHandlerMapping.class); <add> } <add> catch (NoUniqueBeanDefinitionException ex) { <add> throw new IllegalStateException("More than one RequestMappingInfoHandlerMapping beans found", ex); <add> } <add> catch (NoSuchBeanDefinitionException ex) { <add> throw new IllegalStateException("No RequestMappingInfoHandlerMapping bean", ex); <add> } <add> } <add> <add> private static WebApplicationContext getWebApplicationContext() { <ide> RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); <ide> if (requestAttributes == null) { <ide> logger.debug("No request bound to the current thread: is DispatcherSerlvet used?"); <ide> protected static CompositeUriComponentsContributor getConfiguredUriComponentsCon <ide> logger.debug("No WebApplicationContext found: not in a DispatcherServlet request?"); <ide> return null; <ide> } <del> <del> try { <del> return wac.getBean(MVC_URI_COMPONENTS_CONTRIBUTOR_BEAN_NAME, CompositeUriComponentsContributor.class); <del> } <del> catch (NoSuchBeanDefinitionException ex) { <del> if (logger.isDebugEnabled()) { <del> logger.debug("No CompositeUriComponentsContributor bean with name '" + <del> MVC_URI_COMPONENTS_CONTRIBUTOR_BEAN_NAME + "'"); <del> } <del> return null; <del> } <add> return wac; <ide> } <ide> <ide> /** <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/PathVariableMethodArgumentResolver.java <ide> protected void handleResolvedValue(Object arg, String name, MethodParameter para <ide> } <ide> <ide> @Override <del> public void contributeMethodArgument(MethodParameter parameter, Object value, <del> UriComponentsBuilder builder, Map<String, Object> uriVariables, ConversionService conversionService) { <add> public void contributeMethodArgument(MethodParameter param, Object value, <add> UriComponentsBuilder builder, Map<String, Object> uriVariables, ConversionService cs) { <ide> <del> if (Map.class.isAssignableFrom(parameter.getParameterType())) { <add> if (Map.class.isAssignableFrom(param.getParameterType())) { <ide> return; <ide> } <ide> <del> PathVariable annot = parameter.getParameterAnnotation(PathVariable.class); <del> String name = StringUtils.isEmpty(annot.value()) ? parameter.getParameterName() : annot.value(); <add> PathVariable annot = param.getParameterAnnotation(PathVariable.class); <add> String name = (StringUtils.isEmpty(annot.value()) ? param.getParameterName() : annot.value()); <add> value = formatUriValue(cs, new TypeDescriptor(param), value); <add> uriVariables.put(name, value); <add> } <ide> <del> if (conversionService != null) { <del> value = conversionService.convert(value, new TypeDescriptor(parameter), STRING_TYPE_DESCRIPTOR); <add> protected String formatUriValue(ConversionService cs, TypeDescriptor sourceType, Object value) { <add> if (value == null) { <add> return null; <add> } <add> else if (value instanceof String) { <add> return (String) value; <add> } <add> else if (cs != null) { <add> return (String) cs.convert(value, sourceType, STRING_TYPE_DESCRIPTOR); <add> } <add> else { <add> return value.toString(); <ide> } <del> <del> uriVariables.put(name, value); <ide> } <ide> <ide> <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerMapping.java <ide> protected RequestCondition<?> getCustomMethodCondition(Method method) { <ide> protected RequestMappingInfo createRequestMappingInfo(RequestMapping annotation, RequestCondition<?> customCondition) { <ide> String[] patterns = resolveEmbeddedValuesInPatterns(annotation.value()); <ide> return new RequestMappingInfo( <add> annotation.name(), <ide> new PatternsRequestCondition(patterns, getUrlPathHelper(), getPathMatcher(), <ide> this.useSuffixPatternMatch, this.useTrailingSlashMatch, this.fileExtensions), <ide> new RequestMethodsRequestCondition(annotation.method()), <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/support/RequestContext.java <ide> import org.springframework.web.servlet.LocaleContextResolver; <ide> import org.springframework.web.servlet.LocaleResolver; <ide> import org.springframework.web.servlet.ThemeResolver; <add>import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder; <ide> import org.springframework.web.util.HtmlUtils; <ide> import org.springframework.web.util.UriTemplate; <ide> import org.springframework.web.util.UrlPathHelper; <ide> public String getQueryString() { <ide> return this.urlPathHelper.getOriginatingQueryString(this.request); <ide> } <ide> <add> /** <add> * Return a URL derived from a controller method's {@code @RequestMapping}. <add> * This method internally uses <add> * {@link org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder#fromMappingName(String, Object...) <add> * MvcUriComponentsBuilder#fromMappingName(String, Object...)}. See its <add> * Javadoc for more details. <add> */ <add> public String getMvcUrl(String mappingName, Object... handlerMethodArguments) { <add> return MvcUriComponentsBuilder.fromMappingName( <add> mappingName, handlerMethodArguments).build().encode().toUriString(); <add> } <add> <ide> /** <ide> * Retrieve the message for the given code, using the "defaultHtmlEscape" setting. <ide> * @param code code of the message <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMethodMappingNamingStrategyTests.java <add>/* <add> * Copyright 2002-2014 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.web.servlet.mvc.method; <add> <add>import org.junit.Test; <add>import org.springframework.util.ClassUtils; <add>import org.springframework.web.bind.annotation.RequestMapping; <add>import org.springframework.web.method.HandlerMethod; <add>import org.springframework.web.servlet.handler.HandlerMethodMappingNamingStrategy; <add> <add>import java.lang.reflect.Method; <add> <add>import static org.junit.Assert.assertEquals; <add> <add>/** <add> * Unit tests for <add> * {@link org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMethodMappingNamingStrategy}. <add> * <add> * @author Rossen Stoyanchev <add> */ <add>public class RequestMappingInfoHandlerMethodMappingNamingStrategyTests { <add> <add> <add> @Test <add> public void getNameExplicit() { <add> <add> Method method = ClassUtils.getMethod(TestController.class, "handle"); <add> HandlerMethod handlerMethod = new HandlerMethod(new TestController(), method); <add> <add> RequestMappingInfo rmi = new RequestMappingInfo("foo", null, null, null, null, null, null, null); <add> <add> HandlerMethodMappingNamingStrategy strategy = new RequestMappingInfoHandlerMethodMappingNamingStrategy(); <add> <add> assertEquals("foo", strategy.getName(handlerMethod, rmi)); <add> } <add> <add> @Test <add> public void getNameConvention() { <add> <add> Method method = ClassUtils.getMethod(TestController.class, "handle"); <add> HandlerMethod handlerMethod = new HandlerMethod(new TestController(), method); <add> <add> RequestMappingInfo rmi = new RequestMappingInfo(null, null, null, null, null, null, null, null); <add> <add> HandlerMethodMappingNamingStrategy strategy = new RequestMappingInfoHandlerMethodMappingNamingStrategy(); <add> <add> assertEquals("TC#handle", strategy.getName(handlerMethod, rmi)); <add> } <add> <add> <add> private static class TestController { <add> <add> @RequestMapping <add> public void handle() { <add> } <add> } <add> <add>}
14
Mixed
Go
remove files for no longer used docker/swarm godep
87e4661332cbf649250a384dbfe8491c8eb7c1e7
<ide><path>libnetwork/Godeps/_workspace/src/github.com/docker/swarm/discovery/README.md <del>--- <del>page_title: Docker Swarm discovery <del>page_description: Swarm discovery <del>page_keywords: docker, swarm, clustering, discovery <del>--- <del> <del># Discovery <del> <del>Docker Swarm comes with multiple Discovery backends. <del> <del>## Backends <del> <del>### Hosted Discovery with Docker Hub <del> <del>First we create a cluster. <del> <del>```bash <del># create a cluster <del>$ swarm create <del>6856663cdefdec325839a4b7e1de38e8 # <- this is your unique <cluster_id> <del>``` <del> <del>Then we create each node and join them to the cluster. <del> <del>```bash <del># on each of your nodes, start the swarm agent <del># <node_ip> doesn't have to be public (eg. 192.168.0.X), <del># as long as the swarm manager can access it. <del>$ swarm join --advertise=<node_ip:2375> token://<cluster_id> <del>``` <del> <del>Finally, we start the Swarm manager. This can be on any machine or even <del>your laptop. <del> <del>```bash <del>$ swarm manage -H tcp://<swarm_ip:swarm_port> token://<cluster_id> <del>``` <del> <del>You can then use regular Docker commands to interact with your swarm. <del> <del>```bash <del>docker -H tcp://<swarm_ip:swarm_port> info <del>docker -H tcp://<swarm_ip:swarm_port> run ... <del>docker -H tcp://<swarm_ip:swarm_port> ps <del>docker -H tcp://<swarm_ip:swarm_port> logs ... <del>... <del>``` <del> <del>You can also list the nodes in your cluster. <del> <del>```bash <del>swarm list token://<cluster_id> <del><node_ip:2375> <del>``` <del> <del>### Using a static file describing the cluster <del> <del>For each of your nodes, add a line to a file. The node IP address <del>doesn't need to be public as long the Swarm manager can access it. <del> <del>```bash <del>echo <node_ip1:2375> >> /tmp/my_cluster <del>echo <node_ip2:2375> >> /tmp/my_cluster <del>echo <node_ip3:2375> >> /tmp/my_cluster <del>``` <del> <del>Then start the Swarm manager on any machine. <del> <del>```bash <del>swarm manage -H tcp://<swarm_ip:swarm_port> file:///tmp/my_cluster <del>``` <del> <del>And then use the regular Docker commands. <del> <del>```bash <del>docker -H tcp://<swarm_ip:swarm_port> info <del>docker -H tcp://<swarm_ip:swarm_port> run ... <del>docker -H tcp://<swarm_ip:swarm_port> ps <del>docker -H tcp://<swarm_ip:swarm_port> logs ... <del>... <del>``` <del> <del>You can list the nodes in your cluster. <del> <del>```bash <del>$ swarm list file:///tmp/my_cluster <del><node_ip1:2375> <del><node_ip2:2375> <del><node_ip3:2375> <del>``` <del> <del>### Using etcd <del> <del>On each of your nodes, start the Swarm agent. The node IP address <del>doesn't have to be public as long as the swarm manager can access it. <del> <del>```bash <del>swarm join --advertise=<node_ip:2375> etcd://<etcd_ip>/<path> <del>``` <del> <del>Start the manager on any machine or your laptop. <del> <del>```bash <del>swarm manage -H tcp://<swarm_ip:swarm_port> etcd://<etcd_ip>/<path> <del>``` <del> <del>And then use the regular Docker commands. <del> <del>```bash <del>docker -H tcp://<swarm_ip:swarm_port> info <del>docker -H tcp://<swarm_ip:swarm_port> run ... <del>docker -H tcp://<swarm_ip:swarm_port> ps <del>docker -H tcp://<swarm_ip:swarm_port> logs ... <del>... <del>``` <del> <del>You can list the nodes in your cluster. <del> <del>```bash <del>swarm list etcd://<etcd_ip>/<path> <del><node_ip:2375> <del>``` <del> <del>### Using consul <del> <del>On each of your nodes, start the Swarm agent. The node IP address <del>doesn't need to be public as long as the Swarm manager can access it. <del> <del>```bash <del>swarm join --advertise=<node_ip:2375> consul://<consul_addr>/<path> <del>``` <del> <del>Start the manager on any machine or your laptop. <del> <del>```bash <del>swarm manage -H tcp://<swarm_ip:swarm_port> consul://<consul_addr>/<path> <del>``` <del> <del>And then use the regular Docker commands. <del> <del>```bash <del>docker -H tcp://<swarm_ip:swarm_port> info <del>docker -H tcp://<swarm_ip:swarm_port> run ... <del>docker -H tcp://<swarm_ip:swarm_port> ps <del>docker -H tcp://<swarm_ip:swarm_port> logs ... <del>... <del>``` <del> <del>You can list the nodes in your cluster. <del> <del>```bash <del>swarm list consul://<consul_addr>/<path> <del><node_ip:2375> <del>``` <del> <del>### Using zookeeper <del> <del>On each of your nodes, start the Swarm agent. The node IP doesn't have <del>to be public as long as the swarm manager can access it. <del> <del>```bash <del>swarm join --advertise=<node_ip:2375> zk://<zookeeper_addr1>,<zookeeper_addr2>/<path> <del>``` <del> <del>Start the manager on any machine or your laptop. <del> <del>```bash <del>swarm manage -H tcp://<swarm_ip:swarm_port> zk://<zookeeper_addr1>,<zookeeper_addr2>/<path> <del>``` <del> <del>You can then use the regular Docker commands. <del> <del>```bash <del>docker -H tcp://<swarm_ip:swarm_port> info <del>docker -H tcp://<swarm_ip:swarm_port> run ... <del>docker -H tcp://<swarm_ip:swarm_port> ps <del>docker -H tcp://<swarm_ip:swarm_port> logs ... <del>... <del>``` <del> <del>You can list the nodes in the cluster. <del> <del>```bash <del>swarm list zk://<zookeeper_addr1>,<zookeeper_addr2>/<path> <del><node_ip:2375> <del>``` <del> <del>### Using a static list of IP addresses <del> <del>Start the manager on any machine or your laptop <del> <del>```bash <del>swarm manage -H <swarm_ip:swarm_port> nodes://<node_ip1:2375>,<node_ip2:2375> <del>``` <del> <del>Or <del> <del>```bash <del>swarm manage -H <swarm_ip:swarm_port> <node_ip1:2375>,<node_ip2:2375> <del>``` <del> <del>Then use the regular Docker commands. <del> <del>```bash <del>docker -H <swarm_ip:swarm_port> info <del>docker -H <swarm_ip:swarm_port> run ... <del>docker -H <swarm_ip:swarm_port> ps <del>docker -H <swarm_ip:swarm_port> logs ... <del>... <del>``` <del> <del>### Range pattern for IP addresses <del> <del>The `file` and `nodes` discoveries support a range pattern to specify IP <del>addresses, i.e., `10.0.0.[10:200]` will be a list of nodes starting from <del>`10.0.0.10` to `10.0.0.200`. <del> <del>For example for the `file` discovery method. <del> <del>```bash <del>$ echo "10.0.0.[11:100]:2375" >> /tmp/my_cluster <del>$ echo "10.0.1.[15:20]:2375" >> /tmp/my_cluster <del>$ echo "192.168.1.2:[2:20]375" >> /tmp/my_cluster <del>``` <del> <del>Then start the manager. <del> <del>```bash <del>swarm manage -H tcp://<swarm_ip:swarm_port> file:///tmp/my_cluster <del>``` <del> <del>And for the `nodes` discovery method. <del> <del>```bash <del>swarm manage -H <swarm_ip:swarm_port> "nodes://10.0.0.[10:200]:2375,10.0.1.[2:250]:2375" <del>``` <del> <del>## Contributing a new discovery backend <del> <del>Contributing a new discovery backend is easy, simply implement this <del>interface: <del> <del>```go <del>type Discovery interface { <del> Initialize(string, int) error <del> Fetch() ([]string, error) <del> Watch(WatchCallback) <del> Register(string) error <del>} <del>``` <del> <del>### Initialize <del> <del>The parameters are `discovery` location without the scheme and a heartbeat (in seconds). <del> <del>### Fetch <del> <del>Returns the list of all the nodes from the discovery. <del> <del>### Watch <del> <del>Triggers an update (`Fetch`). This can happen either via a timer (like <del>`token`) or use backend specific features (like `etcd`). <del> <del>### Register <del> <del>Add a new node to the discovery service. <del> <del>## Docker Swarm documentation index <del> <del>- [User guide](./index.md) <del>- [Sheduler strategies](./scheduler/strategy.md) <del>- [Sheduler filters](./scheduler/filter.md) <del>- [Swarm API](./API.md) <ide><path>libnetwork/Godeps/_workspace/src/github.com/docker/swarm/discovery/discovery.go <del>package discovery <del> <del>import ( <del> "errors" <del> "fmt" <del> "net" <del> "strings" <del> "time" <del> <del> log "github.com/Sirupsen/logrus" <del>) <del> <del>// An Entry represents a swarm host. <del>type Entry struct { <del> Host string <del> Port string <del>} <del> <del>// NewEntry creates a new entry. <del>func NewEntry(url string) (*Entry, error) { <del> host, port, err := net.SplitHostPort(url) <del> if err != nil { <del> return nil, err <del> } <del> return &Entry{host, port}, nil <del>} <del> <del>// String returns the string form of an entry. <del>func (e *Entry) String() string { <del> return fmt.Sprintf("%s:%s", e.Host, e.Port) <del>} <del> <del>// Equals returns true if cmp contains the same data. <del>func (e *Entry) Equals(cmp *Entry) bool { <del> return e.Host == cmp.Host && e.Port == cmp.Port <del>} <del> <del>// Entries is a list of *Entry with some helpers. <del>type Entries []*Entry <del> <del>// Equals returns true if cmp contains the same data. <del>func (e Entries) Equals(cmp Entries) bool { <del> // Check if the file has really changed. <del> if len(e) != len(cmp) { <del> return false <del> } <del> for i := range e { <del> if !e[i].Equals(cmp[i]) { <del> return false <del> } <del> } <del> return true <del>} <del> <del>// Contains returns true if the Entries contain a given Entry. <del>func (e Entries) Contains(entry *Entry) bool { <del> for _, curr := range e { <del> if curr.Equals(entry) { <del> return true <del> } <del> } <del> return false <del>} <del> <del>// Diff compares two entries and returns the added and removed entries. <del>func (e Entries) Diff(cmp Entries) (Entries, Entries) { <del> added := Entries{} <del> for _, entry := range cmp { <del> if !e.Contains(entry) { <del> added = append(added, entry) <del> } <del> } <del> <del> removed := Entries{} <del> for _, entry := range e { <del> if !cmp.Contains(entry) { <del> removed = append(removed, entry) <del> } <del> } <del> <del> return added, removed <del>} <del> <del>// The Discovery interface is implemented by Discovery backends which <del>// manage swarm host entries. <del>type Discovery interface { <del> // Initialize the discovery with URIs, a heartbeat and a ttl. <del> Initialize(string, time.Duration, time.Duration) error <del> <del> // Watch the discovery for entry changes. <del> // Returns a channel that will receive changes or an error. <del> // Providing a non-nil stopCh can be used to stop watching. <del> Watch(stopCh <-chan struct{}) (<-chan Entries, <-chan error) <del> <del> // Register to the discovery <del> Register(string) error <del>} <del> <del>var ( <del> discoveries map[string]Discovery <del> // ErrNotSupported is returned when a discovery service is not supported. <del> ErrNotSupported = errors.New("discovery service not supported") <del> // ErrNotImplemented is returned when discovery feature is not implemented <del> // by discovery backend. <del> ErrNotImplemented = errors.New("not implemented in this discovery service") <del>) <del> <del>func init() { <del> discoveries = make(map[string]Discovery) <del>} <del> <del>// Register makes a discovery backend available by the provided scheme. <del>// If Register is called twice with the same scheme an error is returned. <del>func Register(scheme string, d Discovery) error { <del> if _, exists := discoveries[scheme]; exists { <del> return fmt.Errorf("scheme already registered %s", scheme) <del> } <del> log.WithField("name", scheme).Debug("Registering discovery service") <del> discoveries[scheme] = d <del> <del> return nil <del>} <del> <del>func parse(rawurl string) (string, string) { <del> parts := strings.SplitN(rawurl, "://", 2) <del> <del> // nodes:port,node2:port => nodes://node1:port,node2:port <del> if len(parts) == 1 { <del> return "nodes", parts[0] <del> } <del> return parts[0], parts[1] <del>} <del> <del>// New returns a new Discovery given a URL, heartbeat and ttl settings. <del>// Returns an error if the URL scheme is not supported. <del>func New(rawurl string, heartbeat time.Duration, ttl time.Duration) (Discovery, error) { <del> scheme, uri := parse(rawurl) <del> <del> if discovery, exists := discoveries[scheme]; exists { <del> log.WithFields(log.Fields{"name": scheme, "uri": uri}).Debug("Initializing discovery service") <del> err := discovery.Initialize(uri, heartbeat, ttl) <del> return discovery, err <del> } <del> <del> return nil, ErrNotSupported <del>} <del> <del>// CreateEntries returns an array of entries based on the given addresses. <del>func CreateEntries(addrs []string) (Entries, error) { <del> entries := Entries{} <del> if addrs == nil { <del> return entries, nil <del> } <del> <del> for _, addr := range addrs { <del> if len(addr) == 0 { <del> continue <del> } <del> entry, err := NewEntry(addr) <del> if err != nil { <del> return nil, err <del> } <del> entries = append(entries, entry) <del> } <del> return entries, nil <del>} <ide><path>libnetwork/Godeps/_workspace/src/github.com/docker/swarm/discovery/discovery_test.go <del>package discovery <del> <del>import ( <del> "testing" <del> <del> "github.com/stretchr/testify/assert" <del>) <del> <del>func TestNewEntry(t *testing.T) { <del> entry, err := NewEntry("127.0.0.1:2375") <del> assert.NoError(t, err) <del> assert.True(t, entry.Equals(&Entry{Host: "127.0.0.1", Port: "2375"})) <del> assert.Equal(t, entry.String(), "127.0.0.1:2375") <del> <del> _, err = NewEntry("127.0.0.1") <del> assert.Error(t, err) <del>} <del> <del>func TestParse(t *testing.T) { <del> scheme, uri := parse("127.0.0.1:2375") <del> assert.Equal(t, scheme, "nodes") <del> assert.Equal(t, uri, "127.0.0.1:2375") <del> <del> scheme, uri = parse("localhost:2375") <del> assert.Equal(t, scheme, "nodes") <del> assert.Equal(t, uri, "localhost:2375") <del> <del> scheme, uri = parse("scheme://127.0.0.1:2375") <del> assert.Equal(t, scheme, "scheme") <del> assert.Equal(t, uri, "127.0.0.1:2375") <del> <del> scheme, uri = parse("scheme://localhost:2375") <del> assert.Equal(t, scheme, "scheme") <del> assert.Equal(t, uri, "localhost:2375") <del> <del> scheme, uri = parse("") <del> assert.Equal(t, scheme, "nodes") <del> assert.Equal(t, uri, "") <del>} <del> <del>func TestCreateEntries(t *testing.T) { <del> entries, err := CreateEntries(nil) <del> assert.Equal(t, entries, Entries{}) <del> assert.NoError(t, err) <del> <del> entries, err = CreateEntries([]string{"127.0.0.1:2375", "127.0.0.2:2375", ""}) <del> assert.NoError(t, err) <del> expected := Entries{ <del> &Entry{Host: "127.0.0.1", Port: "2375"}, <del> &Entry{Host: "127.0.0.2", Port: "2375"}, <del> } <del> assert.True(t, entries.Equals(expected)) <del> <del> _, err = CreateEntries([]string{"127.0.0.1", "127.0.0.2"}) <del> assert.Error(t, err) <del>} <del> <del>func TestContainsEntry(t *testing.T) { <del> entries, err := CreateEntries([]string{"127.0.0.1:2375", "127.0.0.2:2375", ""}) <del> assert.NoError(t, err) <del> assert.True(t, entries.Contains(&Entry{Host: "127.0.0.1", Port: "2375"})) <del> assert.False(t, entries.Contains(&Entry{Host: "127.0.0.3", Port: "2375"})) <del>} <del> <del>func TestEntriesEquality(t *testing.T) { <del> entries := Entries{ <del> &Entry{Host: "127.0.0.1", Port: "2375"}, <del> &Entry{Host: "127.0.0.2", Port: "2375"}, <del> } <del> <del> // Same <del> assert.True(t, entries.Equals(Entries{ <del> &Entry{Host: "127.0.0.1", Port: "2375"}, <del> &Entry{Host: "127.0.0.2", Port: "2375"}, <del> })) <del> <del> // Different size <del> assert.False(t, entries.Equals(Entries{ <del> &Entry{Host: "127.0.0.1", Port: "2375"}, <del> &Entry{Host: "127.0.0.2", Port: "2375"}, <del> &Entry{Host: "127.0.0.3", Port: "2375"}, <del> })) <del> <del> // Different content <del> assert.False(t, entries.Equals(Entries{ <del> &Entry{Host: "127.0.0.1", Port: "2375"}, <del> &Entry{Host: "127.0.0.42", Port: "2375"}, <del> })) <del>} <del> <del>func TestEntriesDiff(t *testing.T) { <del> entry1 := &Entry{Host: "1.1.1.1", Port: "1111"} <del> entry2 := &Entry{Host: "2.2.2.2", Port: "2222"} <del> entry3 := &Entry{Host: "3.3.3.3", Port: "3333"} <del> entries := Entries{entry1, entry2} <del> <del> // No diff <del> added, removed := entries.Diff(Entries{entry2, entry1}) <del> assert.Empty(t, added) <del> assert.Empty(t, removed) <del> <del> // Add <del> added, removed = entries.Diff(Entries{entry2, entry3, entry1}) <del> assert.Len(t, added, 1) <del> assert.True(t, added.Contains(entry3)) <del> assert.Empty(t, removed) <del> <del> // Remove <del> added, removed = entries.Diff(Entries{entry2}) <del> assert.Empty(t, added) <del> assert.Len(t, removed, 1) <del> assert.True(t, removed.Contains(entry1)) <del> <del> // Add and remove <del> added, removed = entries.Diff(Entries{entry1, entry3}) <del> assert.Len(t, added, 1) <del> assert.True(t, added.Contains(entry3)) <del> assert.Len(t, removed, 1) <del> assert.True(t, removed.Contains(entry2)) <del>} <ide><path>libnetwork/Godeps/_workspace/src/github.com/docker/swarm/discovery/file/file.go <del>package file <del> <del>import ( <del> "fmt" <del> "io/ioutil" <del> "strings" <del> "time" <del> <del> "github.com/docker/swarm/discovery" <del>) <del> <del>// Discovery is exported <del>type Discovery struct { <del> heartbeat time.Duration <del> path string <del>} <del> <del>func init() { <del> Init() <del>} <del> <del>// Init is exported <del>func Init() { <del> discovery.Register("file", &Discovery{}) <del>} <del> <del>// Initialize is exported <del>func (s *Discovery) Initialize(path string, heartbeat time.Duration, ttl time.Duration) error { <del> s.path = path <del> s.heartbeat = heartbeat <del> return nil <del>} <del> <del>func parseFileContent(content []byte) []string { <del> var result []string <del> for _, line := range strings.Split(strings.TrimSpace(string(content)), "\n") { <del> line = strings.TrimSpace(line) <del> // Ignoring line starts with # <del> if strings.HasPrefix(line, "#") { <del> continue <del> } <del> // Inlined # comment also ignored. <del> if strings.Contains(line, "#") { <del> line = line[0:strings.Index(line, "#")] <del> // Trim additional spaces caused by above stripping. <del> line = strings.TrimSpace(line) <del> } <del> for _, ip := range discovery.Generate(line) { <del> result = append(result, ip) <del> } <del> } <del> return result <del>} <del> <del>func (s *Discovery) fetch() (discovery.Entries, error) { <del> fileContent, err := ioutil.ReadFile(s.path) <del> if err != nil { <del> return nil, fmt.Errorf("failed to read '%s': %v", s.path, err) <del> } <del> return discovery.CreateEntries(parseFileContent(fileContent)) <del>} <del> <del>// Watch is exported <del>func (s *Discovery) Watch(stopCh <-chan struct{}) (<-chan discovery.Entries, <-chan error) { <del> ch := make(chan discovery.Entries) <del> errCh := make(chan error) <del> ticker := time.NewTicker(s.heartbeat) <del> <del> go func() { <del> defer close(errCh) <del> defer close(ch) <del> <del> // Send the initial entries if available. <del> currentEntries, err := s.fetch() <del> if err != nil { <del> errCh <- err <del> } else { <del> ch <- currentEntries <del> } <del> <del> // Periodically send updates. <del> for { <del> select { <del> case <-ticker.C: <del> newEntries, err := s.fetch() <del> if err != nil { <del> errCh <- err <del> continue <del> } <del> <del> // Check if the file has really changed. <del> if !newEntries.Equals(currentEntries) { <del> ch <- newEntries <del> } <del> currentEntries = newEntries <del> case <-stopCh: <del> ticker.Stop() <del> return <del> } <del> } <del> }() <del> <del> return ch, errCh <del>} <del> <del>// Register is exported <del>func (s *Discovery) Register(addr string) error { <del> return discovery.ErrNotImplemented <del>} <ide><path>libnetwork/Godeps/_workspace/src/github.com/docker/swarm/discovery/file/file_test.go <del>package file <del> <del>import ( <del> "io/ioutil" <del> "os" <del> "testing" <del> <del> "github.com/docker/swarm/discovery" <del> "github.com/stretchr/testify/assert" <del>) <del> <del>func TestInitialize(t *testing.T) { <del> d := &Discovery{} <del> d.Initialize("/path/to/file", 1000, 0) <del> assert.Equal(t, d.path, "/path/to/file") <del>} <del> <del>func TestNew(t *testing.T) { <del> d, err := discovery.New("file:///path/to/file", 0, 0) <del> assert.NoError(t, err) <del> assert.Equal(t, d.(*Discovery).path, "/path/to/file") <del>} <del> <del>func TestContent(t *testing.T) { <del> data := ` <del>1.1.1.[1:2]:1111 <del>2.2.2.[2:4]:2222 <del>` <del> ips := parseFileContent([]byte(data)) <del> assert.Len(t, ips, 5) <del> assert.Equal(t, ips[0], "1.1.1.1:1111") <del> assert.Equal(t, ips[1], "1.1.1.2:1111") <del> assert.Equal(t, ips[2], "2.2.2.2:2222") <del> assert.Equal(t, ips[3], "2.2.2.3:2222") <del> assert.Equal(t, ips[4], "2.2.2.4:2222") <del>} <del> <del>func TestRegister(t *testing.T) { <del> discovery := &Discovery{path: "/path/to/file"} <del> assert.Error(t, discovery.Register("0.0.0.0")) <del>} <del> <del>func TestParsingContentsWithComments(t *testing.T) { <del> data := ` <del>### test ### <del>1.1.1.1:1111 # inline comment <del># 2.2.2.2:2222 <del> ### empty line with comment <del> 3.3.3.3:3333 <del>### test ### <del>` <del> ips := parseFileContent([]byte(data)) <del> assert.Len(t, ips, 2) <del> assert.Equal(t, "1.1.1.1:1111", ips[0]) <del> assert.Equal(t, "3.3.3.3:3333", ips[1]) <del>} <del> <del>func TestWatch(t *testing.T) { <del> data := ` <del>1.1.1.1:1111 <del>2.2.2.2:2222 <del>` <del> expected := discovery.Entries{ <del> &discovery.Entry{Host: "1.1.1.1", Port: "1111"}, <del> &discovery.Entry{Host: "2.2.2.2", Port: "2222"}, <del> } <del> <del> // Create a temporary file and remove it. <del> tmp, err := ioutil.TempFile(os.TempDir(), "discovery-file-test") <del> assert.NoError(t, err) <del> assert.NoError(t, tmp.Close()) <del> assert.NoError(t, os.Remove(tmp.Name())) <del> <del> // Set up file discovery. <del> d := &Discovery{} <del> d.Initialize(tmp.Name(), 1000, 0) <del> stopCh := make(chan struct{}) <del> ch, errCh := d.Watch(stopCh) <del> <del> // Make sure it fires errors since the file doesn't exist. <del> assert.Error(t, <-errCh) <del> // We have to drain the error channel otherwise Watch will get stuck. <del> go func() { <del> for _ = range errCh { <del> } <del> }() <del> <del> // Write the file and make sure we get the expected value back. <del> assert.NoError(t, ioutil.WriteFile(tmp.Name(), []byte(data), 0600)) <del> assert.Equal(t, expected, <-ch) <del> <del> // Add a new entry and look it up. <del> expected = append(expected, &discovery.Entry{Host: "3.3.3.3", Port: "3333"}) <del> f, err := os.OpenFile(tmp.Name(), os.O_APPEND|os.O_WRONLY, 0600) <del> assert.NoError(t, err) <del> assert.NotNil(t, f) <del> _, err = f.WriteString("\n3.3.3.3:3333\n") <del> assert.NoError(t, err) <del> f.Close() <del> assert.Equal(t, expected, <-ch) <del> <del> // Stop and make sure it closes all channels. <del> close(stopCh) <del> assert.Nil(t, <-ch) <del> assert.Nil(t, <-errCh) <del>} <ide><path>libnetwork/Godeps/_workspace/src/github.com/docker/swarm/discovery/generator.go <del>package discovery <del> <del>import ( <del> "fmt" <del> "regexp" <del> "strconv" <del>) <del> <del>// Generate takes care of IP generation <del>func Generate(pattern string) []string { <del> re, _ := regexp.Compile(`\[(.+):(.+)\]`) <del> submatch := re.FindStringSubmatch(pattern) <del> if submatch == nil { <del> return []string{pattern} <del> } <del> <del> from, err := strconv.Atoi(submatch[1]) <del> if err != nil { <del> return []string{pattern} <del> } <del> to, err := strconv.Atoi(submatch[2]) <del> if err != nil { <del> return []string{pattern} <del> } <del> <del> template := re.ReplaceAllString(pattern, "%d") <del> <del> var result []string <del> for val := from; val <= to; val++ { <del> entry := fmt.Sprintf(template, val) <del> result = append(result, entry) <del> } <del> <del> return result <del>} <ide><path>libnetwork/Godeps/_workspace/src/github.com/docker/swarm/discovery/generator_test.go <del>package discovery <del> <del>import ( <del> "testing" <del> <del> "github.com/stretchr/testify/assert" <del>) <del> <del>func TestGeneratorNotGenerate(t *testing.T) { <del> ips := Generate("127.0.0.1") <del> assert.Equal(t, len(ips), 1) <del> assert.Equal(t, ips[0], "127.0.0.1") <del>} <del> <del>func TestGeneratorWithPortNotGenerate(t *testing.T) { <del> ips := Generate("127.0.0.1:8080") <del> assert.Equal(t, len(ips), 1) <del> assert.Equal(t, ips[0], "127.0.0.1:8080") <del>} <del> <del>func TestGeneratorMatchFailedNotGenerate(t *testing.T) { <del> ips := Generate("127.0.0.[1]") <del> assert.Equal(t, len(ips), 1) <del> assert.Equal(t, ips[0], "127.0.0.[1]") <del>} <del> <del>func TestGeneratorWithPort(t *testing.T) { <del> ips := Generate("127.0.0.[1:11]:2375") <del> assert.Equal(t, len(ips), 11) <del> assert.Equal(t, ips[0], "127.0.0.1:2375") <del> assert.Equal(t, ips[1], "127.0.0.2:2375") <del> assert.Equal(t, ips[2], "127.0.0.3:2375") <del> assert.Equal(t, ips[3], "127.0.0.4:2375") <del> assert.Equal(t, ips[4], "127.0.0.5:2375") <del> assert.Equal(t, ips[5], "127.0.0.6:2375") <del> assert.Equal(t, ips[6], "127.0.0.7:2375") <del> assert.Equal(t, ips[7], "127.0.0.8:2375") <del> assert.Equal(t, ips[8], "127.0.0.9:2375") <del> assert.Equal(t, ips[9], "127.0.0.10:2375") <del> assert.Equal(t, ips[10], "127.0.0.11:2375") <del>} <del> <del>func TestGenerateWithMalformedInputAtRangeStart(t *testing.T) { <del> malformedInput := "127.0.0.[x:11]:2375" <del> ips := Generate(malformedInput) <del> assert.Equal(t, len(ips), 1) <del> assert.Equal(t, ips[0], malformedInput) <del>} <del> <del>func TestGenerateWithMalformedInputAtRangeEnd(t *testing.T) { <del> malformedInput := "127.0.0.[1:x]:2375" <del> ips := Generate(malformedInput) <del> assert.Equal(t, len(ips), 1) <del> assert.Equal(t, ips[0], malformedInput) <del>} <ide><path>libnetwork/Godeps/_workspace/src/github.com/docker/swarm/discovery/kv/kv.go <del>package kv <del> <del>import ( <del> "fmt" <del> "path" <del> "strings" <del> "time" <del> <del> log "github.com/Sirupsen/logrus" <del> "github.com/docker/swarm/discovery" <del> "github.com/docker/swarm/pkg/store" <del>) <del> <del>const ( <del> discoveryPath = "docker/swarm/nodes" <del>) <del> <del>// Discovery is exported <del>type Discovery struct { <del> backend store.Backend <del> store store.Store <del> heartbeat time.Duration <del> ttl time.Duration <del> path string <del>} <del> <del>func init() { <del> Init() <del>} <del> <del>// Init is exported <del>func Init() { <del> discovery.Register("zk", &Discovery{backend: store.ZK}) <del> discovery.Register("consul", &Discovery{backend: store.CONSUL}) <del> discovery.Register("etcd", &Discovery{backend: store.ETCD}) <del>} <del> <del>// Initialize is exported <del>func (s *Discovery) Initialize(uris string, heartbeat time.Duration, ttl time.Duration) error { <del> var ( <del> parts = strings.SplitN(uris, "/", 2) <del> addrs = strings.Split(parts[0], ",") <del> prefix = "" <del> err error <del> ) <del> <del> // A custom prefix to the path can be optionally used. <del> if len(parts) == 2 { <del> prefix = parts[1] <del> } <del> <del> s.heartbeat = heartbeat <del> s.ttl = ttl <del> s.path = path.Join(prefix, discoveryPath) <del> <del> // Creates a new store, will ignore options given <del> // if not supported by the chosen store <del> s.store, err = store.NewStore( <del> s.backend, <del> addrs, <del> &store.Config{ <del> EphemeralTTL: s.ttl, <del> }, <del> ) <del> <del> return err <del>} <del> <del>// Watch the store until either there's a store error or we receive a stop request. <del>// Returns false if we shouldn't attempt watching the store anymore (stop request received). <del>func (s *Discovery) watchOnce(stopCh <-chan struct{}, watchCh <-chan []*store.KVPair, discoveryCh chan discovery.Entries, errCh chan error) bool { <del> for { <del> select { <del> case pairs := <-watchCh: <del> if pairs == nil { <del> return true <del> } <del> <del> log.WithField("discovery", s.backend).Debugf("Watch triggered with %d nodes", len(pairs)) <del> <del> // Convert `KVPair` into `discovery.Entry`. <del> addrs := make([]string, len(pairs)) <del> for _, pair := range pairs { <del> addrs = append(addrs, string(pair.Value)) <del> } <del> <del> entries, err := discovery.CreateEntries(addrs) <del> if err != nil { <del> errCh <- err <del> } else { <del> discoveryCh <- entries <del> } <del> case <-stopCh: <del> // We were requested to stop watching. <del> return false <del> } <del> } <del>} <del> <del>// Watch is exported <del>func (s *Discovery) Watch(stopCh <-chan struct{}) (<-chan discovery.Entries, <-chan error) { <del> ch := make(chan discovery.Entries) <del> errCh := make(chan error) <del> <del> go func() { <del> defer close(ch) <del> defer close(errCh) <del> <del> // Forever: Create a store watch, watch until we get an error and then try again. <del> // Will only stop if we receive a stopCh request. <del> for { <del> // Set up a watch. <del> watchCh, err := s.store.WatchTree(s.path, stopCh) <del> if err != nil { <del> errCh <- err <del> } else { <del> if !s.watchOnce(stopCh, watchCh, ch, errCh) { <del> return <del> } <del> } <del> <del> // If we get here it means the store watch channel was closed. This <del> // is unexpected so let's retry later. <del> errCh <- fmt.Errorf("Unexpected watch error") <del> time.Sleep(s.heartbeat) <del> } <del> }() <del> return ch, errCh <del>} <del> <del>// Register is exported <del>func (s *Discovery) Register(addr string) error { <del> opts := &store.WriteOptions{Ephemeral: true, Heartbeat: s.heartbeat} <del> return s.store.Put(path.Join(s.path, addr), []byte(addr), opts) <del>} <del> <del>// Store returns the underlying store used by KV discovery. <del>func (s *Discovery) Store() store.Store { <del> return s.store <del>} <ide><path>libnetwork/Godeps/_workspace/src/github.com/docker/swarm/discovery/kv/kv_test.go <del>package kv <del> <del>import ( <del> "errors" <del> "path" <del> "testing" <del> "time" <del> <del> "github.com/docker/swarm/discovery" <del> "github.com/docker/swarm/pkg/store" <del> "github.com/stretchr/testify/assert" <del> "github.com/stretchr/testify/mock" <del>) <del> <del>func TestInitialize(t *testing.T) { <del> d := &Discovery{backend: store.MOCK} <del> assert.NoError(t, d.Initialize("127.0.0.1", 0, 0)) <del> s := d.store.(*store.Mock) <del> assert.Len(t, s.Endpoints, 1) <del> assert.Equal(t, s.Endpoints[0], "127.0.0.1") <del> assert.Equal(t, d.path, discoveryPath) <del> <del> d = &Discovery{backend: store.MOCK} <del> assert.NoError(t, d.Initialize("127.0.0.1:1234/path", 0, 0)) <del> s = d.store.(*store.Mock) <del> assert.Len(t, s.Endpoints, 1) <del> assert.Equal(t, s.Endpoints[0], "127.0.0.1:1234") <del> assert.Equal(t, d.path, "path/"+discoveryPath) <del> <del> d = &Discovery{backend: store.MOCK} <del> assert.NoError(t, d.Initialize("127.0.0.1:1234,127.0.0.2:1234,127.0.0.3:1234/path", 0, 0)) <del> s = d.store.(*store.Mock) <del> assert.Len(t, s.Endpoints, 3) <del> assert.Equal(t, s.Endpoints[0], "127.0.0.1:1234") <del> assert.Equal(t, s.Endpoints[1], "127.0.0.2:1234") <del> assert.Equal(t, s.Endpoints[2], "127.0.0.3:1234") <del> assert.Equal(t, d.path, "path/"+discoveryPath) <del>} <del> <del>func TestWatch(t *testing.T) { <del> d := &Discovery{backend: store.MOCK} <del> assert.NoError(t, d.Initialize("127.0.0.1:1234/path", 0, 0)) <del> s := d.store.(*store.Mock) <del> <del> mockCh := make(chan []*store.KVPair) <del> <del> // The first watch will fail. <del> s.On("WatchTree", "path/"+discoveryPath, mock.Anything).Return(mockCh, errors.New("test error")).Once() <del> // The second one will succeed. <del> s.On("WatchTree", "path/"+discoveryPath, mock.Anything).Return(mockCh, nil).Once() <del> expected := discovery.Entries{ <del> &discovery.Entry{Host: "1.1.1.1", Port: "1111"}, <del> &discovery.Entry{Host: "2.2.2.2", Port: "2222"}, <del> } <del> kvs := []*store.KVPair{ <del> {Key: path.Join("path", discoveryPath, "1.1.1.1"), Value: []byte("1.1.1.1:1111")}, <del> {Key: path.Join("path", discoveryPath, "2.2.2.2"), Value: []byte("2.2.2.2:2222")}, <del> } <del> <del> stopCh := make(chan struct{}) <del> ch, errCh := d.Watch(stopCh) <del> <del> // It should fire an error since the first WatchRange call failed. <del> assert.EqualError(t, <-errCh, "test error") <del> // We have to drain the error channel otherwise Watch will get stuck. <del> go func() { <del> for _ = range errCh { <del> } <del> }() <del> <del> // Push the entries into the store channel and make sure discovery emits. <del> mockCh <- kvs <del> assert.Equal(t, <-ch, expected) <del> <del> // Add a new entry. <del> expected = append(expected, &discovery.Entry{Host: "3.3.3.3", Port: "3333"}) <del> kvs = append(kvs, &store.KVPair{Key: path.Join("path", discoveryPath, "3.3.3.3"), Value: []byte("3.3.3.3:3333")}) <del> mockCh <- kvs <del> assert.Equal(t, <-ch, expected) <del> <del> // Make sure that if an error occurs it retries. <del> // This third call to WatchTree will be checked later by AssertExpectations. <del> s.On("WatchTree", "path/"+discoveryPath, mock.Anything).Return(mockCh, nil) <del> close(mockCh) <del> // Give it enough time to call WatchTree. <del> time.Sleep(3) <del> <del> // Stop and make sure it closes all channels. <del> close(stopCh) <del> assert.Nil(t, <-ch) <del> assert.Nil(t, <-errCh) <del> <del> s.AssertExpectations(t) <del>} <ide><path>libnetwork/Godeps/_workspace/src/github.com/docker/swarm/discovery/nodes/nodes.go <del>package nodes <del> <del>import ( <del> "strings" <del> "time" <del> <del> "github.com/docker/swarm/discovery" <del>) <del> <del>// Discovery is exported <del>type Discovery struct { <del> entries discovery.Entries <del>} <del> <del>func init() { <del> Init() <del>} <del> <del>// Init is exported <del>func Init() { <del> discovery.Register("nodes", &Discovery{}) <del>} <del> <del>// Initialize is exported <del>func (s *Discovery) Initialize(uris string, _ time.Duration, _ time.Duration) error { <del> for _, input := range strings.Split(uris, ",") { <del> for _, ip := range discovery.Generate(input) { <del> entry, err := discovery.NewEntry(ip) <del> if err != nil { <del> return err <del> } <del> s.entries = append(s.entries, entry) <del> } <del> } <del> <del> return nil <del>} <del> <del>// Watch is exported <del>func (s *Discovery) Watch(stopCh <-chan struct{}) (<-chan discovery.Entries, <-chan error) { <del> ch := make(chan discovery.Entries) <del> go func() { <del> defer close(ch) <del> ch <- s.entries <del> <-stopCh <del> }() <del> return ch, nil <del>} <del> <del>// Register is exported <del>func (s *Discovery) Register(addr string) error { <del> return discovery.ErrNotImplemented <del>} <ide><path>libnetwork/Godeps/_workspace/src/github.com/docker/swarm/discovery/nodes/nodes_test.go <del>package nodes <del> <del>import ( <del> "testing" <del> <del> "github.com/docker/swarm/discovery" <del> "github.com/stretchr/testify/assert" <del>) <del> <del>func TestInitialize(t *testing.T) { <del> d := &Discovery{} <del> d.Initialize("1.1.1.1:1111,2.2.2.2:2222", 0, 0) <del> assert.Equal(t, len(d.entries), 2) <del> assert.Equal(t, d.entries[0].String(), "1.1.1.1:1111") <del> assert.Equal(t, d.entries[1].String(), "2.2.2.2:2222") <del>} <del> <del>func TestInitializeWithPattern(t *testing.T) { <del> d := &Discovery{} <del> d.Initialize("1.1.1.[1:2]:1111,2.2.2.[2:4]:2222", 0, 0) <del> assert.Equal(t, len(d.entries), 5) <del> assert.Equal(t, d.entries[0].String(), "1.1.1.1:1111") <del> assert.Equal(t, d.entries[1].String(), "1.1.1.2:1111") <del> assert.Equal(t, d.entries[2].String(), "2.2.2.2:2222") <del> assert.Equal(t, d.entries[3].String(), "2.2.2.3:2222") <del> assert.Equal(t, d.entries[4].String(), "2.2.2.4:2222") <del>} <del> <del>func TestWatch(t *testing.T) { <del> d := &Discovery{} <del> d.Initialize("1.1.1.1:1111,2.2.2.2:2222", 0, 0) <del> expected := discovery.Entries{ <del> &discovery.Entry{Host: "1.1.1.1", Port: "1111"}, <del> &discovery.Entry{Host: "2.2.2.2", Port: "2222"}, <del> } <del> ch, _ := d.Watch(nil) <del> assert.True(t, expected.Equals(<-ch)) <del>} <del> <del>func TestRegister(t *testing.T) { <del> d := &Discovery{} <del> assert.Error(t, d.Register("0.0.0.0")) <del>} <ide><path>libnetwork/Godeps/_workspace/src/github.com/docker/swarm/discovery/token/README.md <del>#discovery-stage.hub.docker.com <del> <del>Docker Swarm comes with a simple discovery service built into the [Docker Hub](http://hub.docker.com) <del> <del>The discovery service is still in alpha stage and currently hosted at `https://discovery-stage.hub.docker.com` <del> <del>#####Create a new cluster <del>`-> POST https://discovery-stage.hub.docker.com/v1/clusters` <del> <del>`<- <token>` <del> <del>#####Add new nodes to a cluster <del>`-> POST https://discovery-stage.hub.docker.com/v1/clusters/<token> Request body: "<ip>:<port1>"` <del> <del>`<- OK` <del> <del>`-> POST https://discovery-stage.hub.docker.com/v1/clusters/<token> Request body: "<ip>:<port2>")` <del> <del>`<- OK` <del> <del> <del>#####List nodes in a cluster <del>`-> GET https://discovery-stage.hub.docker.com/v1/clusters/<token>` <del> <del>`<- ["<ip>:<port1>", "<ip>:<port2>"]` <del> <del> <del>#####Delete a cluster (all the nodes in a cluster) <del>`-> DELETE https://discovery-stage.hub.docker.com/v1/clusters/<token>` <del> <del>`<- OK` <ide><path>libnetwork/Godeps/_workspace/src/github.com/docker/swarm/discovery/token/token.go <del>package token <del> <del>import ( <del> "encoding/json" <del> "errors" <del> "fmt" <del> "io/ioutil" <del> "net/http" <del> "strings" <del> "time" <del> <del> "github.com/docker/swarm/discovery" <del>) <del> <del>// DiscoveryUrl is exported <del>const DiscoveryURL = "https://discovery-stage.hub.docker.com/v1" <del> <del>// Discovery is exported <del>type Discovery struct { <del> heartbeat time.Duration <del> ttl time.Duration <del> url string <del> token string <del>} <del> <del>func init() { <del> Init() <del>} <del> <del>// Init is exported <del>func Init() { <del> discovery.Register("token", &Discovery{}) <del>} <del> <del>// Initialize is exported <del>func (s *Discovery) Initialize(urltoken string, heartbeat time.Duration, ttl time.Duration) error { <del> if i := strings.LastIndex(urltoken, "/"); i != -1 { <del> s.url = "https://" + urltoken[:i] <del> s.token = urltoken[i+1:] <del> } else { <del> s.url = DiscoveryURL <del> s.token = urltoken <del> } <del> <del> if s.token == "" { <del> return errors.New("token is empty") <del> } <del> s.heartbeat = heartbeat <del> s.ttl = ttl <del> <del> return nil <del>} <del> <del>// Fetch returns the list of entries for the discovery service at the specified endpoint <del>func (s *Discovery) fetch() (discovery.Entries, error) { <del> resp, err := http.Get(fmt.Sprintf("%s/%s/%s", s.url, "clusters", s.token)) <del> if err != nil { <del> return nil, err <del> } <del> <del> defer resp.Body.Close() <del> <del> var addrs []string <del> if resp.StatusCode == http.StatusOK { <del> if err := json.NewDecoder(resp.Body).Decode(&addrs); err != nil { <del> return nil, fmt.Errorf("Failed to decode response: %v", err) <del> } <del> } else { <del> return nil, fmt.Errorf("Failed to fetch entries, Discovery service returned %d HTTP status code", resp.StatusCode) <del> } <del> <del> return discovery.CreateEntries(addrs) <del>} <del> <del>// Watch is exported <del>func (s *Discovery) Watch(stopCh <-chan struct{}) (<-chan discovery.Entries, <-chan error) { <del> ch := make(chan discovery.Entries) <del> ticker := time.NewTicker(s.heartbeat) <del> errCh := make(chan error) <del> <del> go func() { <del> defer close(ch) <del> defer close(errCh) <del> <del> // Send the initial entries if available. <del> currentEntries, err := s.fetch() <del> if err != nil { <del> errCh <- err <del> } else { <del> ch <- currentEntries <del> } <del> <del> // Periodically send updates. <del> for { <del> select { <del> case <-ticker.C: <del> newEntries, err := s.fetch() <del> if err != nil { <del> errCh <- err <del> continue <del> } <del> <del> // Check if the file has really changed. <del> if !newEntries.Equals(currentEntries) { <del> ch <- newEntries <del> } <del> currentEntries = newEntries <del> case <-stopCh: <del> ticker.Stop() <del> return <del> } <del> } <del> }() <del> <del> return ch, nil <del>} <del> <del>// Register adds a new entry identified by the into the discovery service <del>func (s *Discovery) Register(addr string) error { <del> buf := strings.NewReader(addr) <del> <del> resp, err := http.Post(fmt.Sprintf("%s/%s/%s", s.url, <del> "clusters", s.token), "application/json", buf) <del> <del> if err != nil { <del> return err <del> } <del> <del> resp.Body.Close() <del> return nil <del>} <del> <del>// CreateCluster returns a unique cluster token <del>func (s *Discovery) CreateCluster() (string, error) { <del> resp, err := http.Post(fmt.Sprintf("%s/%s", s.url, "clusters"), "", nil) <del> if err != nil { <del> return "", err <del> } <del> <del> defer resp.Body.Close() <del> token, err := ioutil.ReadAll(resp.Body) <del> return string(token), err <del>} <ide><path>libnetwork/Godeps/_workspace/src/github.com/docker/swarm/discovery/token/token_test.go <del>package token <del> <del>import ( <del> "testing" <del> "time" <del> <del> "github.com/docker/swarm/discovery" <del> "github.com/stretchr/testify/assert" <del>) <del> <del>func TestInitialize(t *testing.T) { <del> discovery := &Discovery{} <del> err := discovery.Initialize("token", 0, 0) <del> assert.NoError(t, err) <del> assert.Equal(t, discovery.token, "token") <del> assert.Equal(t, discovery.url, DiscoveryURL) <del> <del> err = discovery.Initialize("custom/path/token", 0, 0) <del> assert.NoError(t, err) <del> assert.Equal(t, discovery.token, "token") <del> assert.Equal(t, discovery.url, "https://custom/path") <del> <del> err = discovery.Initialize("", 0, 0) <del> assert.Error(t, err) <del>} <del> <del>func TestRegister(t *testing.T) { <del> d := &Discovery{token: "TEST_TOKEN", url: DiscoveryURL, heartbeat: 1} <del> expected := "127.0.0.1:2675" <del> expectedEntries, err := discovery.CreateEntries([]string{expected}) <del> assert.NoError(t, err) <del> <del> // Register <del> assert.NoError(t, d.Register(expected)) <del> <del> // Watch <del> ch, errCh := d.Watch(nil) <del> select { <del> case entries := <-ch: <del> assert.True(t, entries.Equals(expectedEntries)) <del> case err := <-errCh: <del> t.Fatal(err) <del> case <-time.After(5 * time.Second): <del> t.Fatal("Timed out") <del> } <del> <del> assert.NoError(t, d.Register(expected)) <del>} <ide><path>libnetwork/Godeps/_workspace/src/github.com/docker/swarm/pkg/store/README.md <del># Storage <del> <del>The goal of `pkg/store` is to abstract common store operations for multiple Key/Value backends. <del> <del>For example, you can use it to store your metadata or for service discovery to register machines and endpoints inside your cluster. <del> <del>As of now, `pkg/store` offers support for `Consul`, `Etcd` and `Zookeeper`. <del> <del>## Example of usage <del> <del>### Create a new store and use Put/Get <del> <del>```go <del>package main <del> <del>import ( <del> "fmt" <del> "time" <del> <del> log "github.com/Sirupsen/logrus" <del> "github.com/docker/swarm/store" <del>) <del> <del>func main() { <del> var ( <del> // Consul local address <del> client = "localhost:8500" <del> ) <del> <del> // Initialize a new store with consul <del> kv, err = store.NewStore( <del> store.CONSUL, // or "consul" <del> []string{client}, <del> &store.Config{ <del> Timeout: 10*time.Second, <del> }, <del> ) <del> if err != nil { <del> log.Error("Cannot create store consul") <del> } <del> <del> key := "foo" <del> err = kv.Put(key, []byte("bar"), nil) <del> if err != nil { <del> log.Error("Error trying to put value at key `", key, "`") <del> } <del> <del> pair, err := kv.Get(key) <del> if err != nil { <del> log.Error("Error trying accessing value at key `", key, "`") <del> } <del> <del> log.Info("value: ", string(pair.Value)) <del>} <del>``` <del> <del> <del> <del>## Contributing to a new storage backend <del> <del>A new **storage backend** should include those calls: <del> <del>```go <del>type Store interface { <del> Put(key string, value []byte, options *WriteOptions) error <del> Get(key string) (*KVPair, error) <del> Delete(key string) error <del> Exists(key string) (bool, error) <del> Watch(key string, stopCh <-chan struct{}) (<-chan *KVPair, error) <del> WatchTree(prefix string, stopCh <-chan struct{}) (<-chan []*KVPair, error) <del> NewLock(key string, options *LockOptions) (Locker, error) <del> List(prefix string) ([]*KVPair, error) <del> DeleteTree(prefix string) error <del> AtomicPut(key string, value []byte, previous *KVPair, options *WriteOptions) (bool, *KVPair, error) <del> AtomicDelete(key string, previous *KVPair) (bool, error) <del>} <del>``` <del> <del>In the case of Swarm and to be eligible as a **discovery backend** only, a K/V store implementation should at least offer `Get`, `Put`, `WatchTree` and `List`. <del> <del>`Put` should support usage of `ttl` to be able to remove entries in case of a node failure. <del> <del>You can get inspiration from existing backends to create a new one. This interface could be subject to changes to improve the experience of using the library and contributing to a new backend. <ide><path>libnetwork/Godeps/_workspace/src/github.com/docker/swarm/pkg/store/consul.go <del>package store <del> <del>import ( <del> "crypto/tls" <del> "net/http" <del> "strings" <del> "sync" <del> "time" <del> <del> log "github.com/Sirupsen/logrus" <del> api "github.com/hashicorp/consul/api" <del>) <del> <del>const ( <del> // DefaultWatchWaitTime is how long we block for at a time to check if the <del> // watched key has changed. This affects the minimum time it takes to <del> // cancel a watch. <del> DefaultWatchWaitTime = 15 * time.Second <del>) <del> <del>// Consul embeds the client and watches <del>type Consul struct { <del> sync.Mutex <del> config *api.Config <del> client *api.Client <del> ephemeralTTL time.Duration <del> ephemeralSession string <del>} <del> <del>type consulLock struct { <del> lock *api.Lock <del>} <del> <del>// InitializeConsul creates a new Consul client given <del>// a list of endpoints and optional tls config <del>func InitializeConsul(endpoints []string, options *Config) (Store, error) { <del> s := &Consul{} <del> <del> // Create Consul client <del> config := api.DefaultConfig() <del> s.config = config <del> config.HttpClient = http.DefaultClient <del> config.Address = endpoints[0] <del> config.Scheme = "http" <del> <del> // Set options <del> if options != nil { <del> if options.TLS != nil { <del> s.setTLS(options.TLS) <del> } <del> if options.ConnectionTimeout != 0 { <del> s.setTimeout(options.ConnectionTimeout) <del> } <del> if options.EphemeralTTL != 0 { <del> s.setEphemeralTTL(options.EphemeralTTL) <del> } <del> } <del> <del> // Creates a new client <del> client, err := api.NewClient(config) <del> if err != nil { <del> log.Errorf("Couldn't initialize consul client..") <del> return nil, err <del> } <del> s.client = client <del> <del> return s, nil <del>} <del> <del>// SetTLS sets Consul TLS options <del>func (s *Consul) setTLS(tls *tls.Config) { <del> s.config.HttpClient.Transport = &http.Transport{ <del> TLSClientConfig: tls, <del> } <del> s.config.Scheme = "https" <del>} <del> <del>// SetTimeout sets the timout for connecting to Consul <del>func (s *Consul) setTimeout(time time.Duration) { <del> s.config.WaitTime = time <del>} <del> <del>// SetEphemeralTTL sets the ttl for ephemeral nodes <del>func (s *Consul) setEphemeralTTL(ttl time.Duration) { <del> s.ephemeralTTL = ttl <del>} <del> <del>// createEphemeralSession creates the global session <del>// once that is used to delete keys at node failure <del>func (s *Consul) createEphemeralSession() error { <del> s.Lock() <del> defer s.Unlock() <del> <del> // Create new session <del> if s.ephemeralSession == "" { <del> entry := &api.SessionEntry{ <del> Behavior: api.SessionBehaviorDelete, <del> TTL: s.ephemeralTTL.String(), <del> } <del> // Create global ephemeral keys session <del> session, _, err := s.client.Session().Create(entry, nil) <del> if err != nil { <del> return err <del> } <del> s.ephemeralSession = session <del> } <del> return nil <del>} <del> <del>// checkActiveSession checks if the key already has a session attached <del>func (s *Consul) checkActiveSession(key string) (string, error) { <del> pair, _, err := s.client.KV().Get(key, nil) <del> if err != nil { <del> return "", err <del> } <del> if pair != nil && pair.Session != "" { <del> return pair.Session, nil <del> } <del> return "", nil <del>} <del> <del>// Normalize the key for usage in Consul <del>func (s *Consul) normalize(key string) string { <del> key = normalize(key) <del> return strings.TrimPrefix(key, "/") <del>} <del> <del>// Get the value at "key", returns the last modified index <del>// to use in conjunction to CAS calls <del>func (s *Consul) Get(key string) (*KVPair, error) { <del> options := &api.QueryOptions{ <del> AllowStale: false, <del> RequireConsistent: true, <del> } <del> pair, meta, err := s.client.KV().Get(s.normalize(key), options) <del> if err != nil { <del> return nil, err <del> } <del> if pair == nil { <del> return nil, ErrKeyNotFound <del> } <del> return &KVPair{pair.Key, pair.Value, meta.LastIndex}, nil <del>} <del> <del>// Put a value at "key" <del>func (s *Consul) Put(key string, value []byte, opts *WriteOptions) error { <del> <del> key = s.normalize(key) <del> <del> p := &api.KVPair{ <del> Key: key, <del> Value: value, <del> } <del> <del> if opts != nil && opts.Ephemeral { <del> // Check if there is any previous session with an active TTL <del> previous, err := s.checkActiveSession(key) <del> if err != nil { <del> return err <del> } <del> <del> // Create the global ephemeral session if it does not exist yet <del> if s.ephemeralSession == "" { <del> if err = s.createEphemeralSession(); err != nil { <del> return err <del> } <del> } <del> <del> // If a previous session is still active for that key, use it <del> // else we use the global ephemeral session <del> if previous != "" { <del> p.Session = previous <del> } else { <del> p.Session = s.ephemeralSession <del> } <del> <del> // Create lock option with the <del> // EphemeralSession <del> lockOpts := &api.LockOptions{ <del> Key: key, <del> Session: p.Session, <del> } <del> <del> // Lock and ignore if lock is held <del> // It's just a placeholder for the <del> // ephemeral behavior <del> lock, _ := s.client.LockOpts(lockOpts) <del> if lock != nil { <del> lock.Lock(nil) <del> } <del> <del> // Renew the session <del> _, _, err = s.client.Session().Renew(p.Session, nil) <del> if err != nil { <del> s.ephemeralSession = "" <del> return err <del> } <del> } <del> <del> _, err := s.client.KV().Put(p, nil) <del> return err <del>} <del> <del>// Delete a value at "key" <del>func (s *Consul) Delete(key string) error { <del> _, err := s.client.KV().Delete(s.normalize(key), nil) <del> return err <del>} <del> <del>// Exists checks that the key exists inside the store <del>func (s *Consul) Exists(key string) (bool, error) { <del> _, err := s.Get(key) <del> if err != nil && err == ErrKeyNotFound { <del> return false, err <del> } <del> return true, nil <del>} <del> <del>// List the content of a given prefix <del>func (s *Consul) List(prefix string) ([]*KVPair, error) { <del> pairs, _, err := s.client.KV().List(s.normalize(prefix), nil) <del> if err != nil { <del> return nil, err <del> } <del> if len(pairs) == 0 { <del> return nil, ErrKeyNotFound <del> } <del> kv := []*KVPair{} <del> for _, pair := range pairs { <del> if pair.Key == prefix { <del> continue <del> } <del> kv = append(kv, &KVPair{pair.Key, pair.Value, pair.ModifyIndex}) <del> } <del> return kv, nil <del>} <del> <del>// DeleteTree deletes a range of keys based on prefix <del>func (s *Consul) DeleteTree(prefix string) error { <del> _, err := s.client.KV().DeleteTree(s.normalize(prefix), nil) <del> return err <del>} <del> <del>// Watch changes on a key. <del>// Returns a channel that will receive changes or an error. <del>// Upon creating a watch, the current value will be sent to the channel. <del>// Providing a non-nil stopCh can be used to stop watching. <del>func (s *Consul) Watch(key string, stopCh <-chan struct{}) (<-chan *KVPair, error) { <del> key = s.normalize(key) <del> kv := s.client.KV() <del> watchCh := make(chan *KVPair) <del> <del> go func() { <del> defer close(watchCh) <del> <del> // Use a wait time in order to check if we should quit from time to <del> // time. <del> opts := &api.QueryOptions{WaitTime: DefaultWatchWaitTime} <del> for { <del> // Check if we should quit <del> select { <del> case <-stopCh: <del> return <del> default: <del> } <del> pair, meta, err := kv.Get(key, opts) <del> if err != nil { <del> log.Errorf("consul: %v", err) <del> return <del> } <del> // If LastIndex didn't change then it means `Get` returned because <del> // of the WaitTime and the key didn't change. <del> if opts.WaitIndex == meta.LastIndex { <del> continue <del> } <del> opts.WaitIndex = meta.LastIndex <del> // FIXME: What happens when a key is deleted? <del> if pair != nil { <del> watchCh <- &KVPair{pair.Key, pair.Value, pair.ModifyIndex} <del> } <del> } <del> }() <del> <del> return watchCh, nil <del>} <del> <del>// WatchTree watches changes on a "directory" <del>// Returns a channel that will receive changes or an error. <del>// Upon creating a watch, the current value will be sent to the channel. <del>// Providing a non-nil stopCh can be used to stop watching. <del>func (s *Consul) WatchTree(prefix string, stopCh <-chan struct{}) (<-chan []*KVPair, error) { <del> prefix = s.normalize(prefix) <del> kv := s.client.KV() <del> watchCh := make(chan []*KVPair) <del> <del> go func() { <del> defer close(watchCh) <del> <del> // Use a wait time in order to check if we should quit from time to <del> // time. <del> opts := &api.QueryOptions{WaitTime: DefaultWatchWaitTime} <del> for { <del> // Check if we should quit <del> select { <del> case <-stopCh: <del> return <del> default: <del> } <del> <del> pairs, meta, err := kv.List(prefix, opts) <del> if err != nil { <del> log.Errorf("consul: %v", err) <del> return <del> } <del> // If LastIndex didn't change then it means `Get` returned because <del> // of the WaitTime and the key didn't change. <del> if opts.WaitIndex == meta.LastIndex { <del> continue <del> } <del> opts.WaitIndex = meta.LastIndex <del> kv := []*KVPair{} <del> for _, pair := range pairs { <del> if pair.Key == prefix { <del> continue <del> } <del> kv = append(kv, &KVPair{pair.Key, pair.Value, pair.ModifyIndex}) <del> } <del> watchCh <- kv <del> } <del> }() <del> <del> return watchCh, nil <del>} <del> <del>// NewLock returns a handle to a lock struct which can be used to acquire and <del>// release the mutex. <del>func (s *Consul) NewLock(key string, options *LockOptions) (Locker, error) { <del> consulOpts := &api.LockOptions{ <del> Key: s.normalize(key), <del> } <del> if options != nil { <del> consulOpts.Value = options.Value <del> } <del> l, err := s.client.LockOpts(consulOpts) <del> if err != nil { <del> return nil, err <del> } <del> return &consulLock{lock: l}, nil <del>} <del> <del>// Lock attempts to acquire the lock and blocks while doing so. <del>// Returns a channel that is closed if our lock is lost or an error. <del>func (l *consulLock) Lock() (<-chan struct{}, error) { <del> return l.lock.Lock(nil) <del>} <del> <del>// Unlock released the lock. It is an error to call this <del>// if the lock is not currently held. <del>func (l *consulLock) Unlock() error { <del> return l.lock.Unlock() <del>} <del> <del>// AtomicPut put a value at "key" if the key has not been <del>// modified in the meantime, throws an error if this is the case <del>func (s *Consul) AtomicPut(key string, value []byte, previous *KVPair, options *WriteOptions) (bool, *KVPair, error) { <del> if previous == nil { <del> return false, nil, ErrPreviousNotSpecified <del> } <del> <del> p := &api.KVPair{Key: s.normalize(key), Value: value, ModifyIndex: previous.LastIndex} <del> if work, _, err := s.client.KV().CAS(p, nil); err != nil { <del> return false, nil, err <del> } else if !work { <del> return false, nil, ErrKeyModified <del> } <del> <del> pair, err := s.Get(key) <del> if err != nil { <del> return false, nil, err <del> } <del> return true, pair, nil <del>} <del> <del>// AtomicDelete deletes a value at "key" if the key has not <del>// been modified in the meantime, throws an error if this is the case <del>func (s *Consul) AtomicDelete(key string, previous *KVPair) (bool, error) { <del> if previous == nil { <del> return false, ErrPreviousNotSpecified <del> } <del> <del> p := &api.KVPair{Key: s.normalize(key), ModifyIndex: previous.LastIndex} <del> if work, _, err := s.client.KV().DeleteCAS(p, nil); err != nil { <del> return false, err <del> } else if !work { <del> return false, ErrKeyModified <del> } <del> return true, nil <del>} <del> <del>// Close closes the client connection <del>func (s *Consul) Close() { <del> return <del>} <ide><path>libnetwork/Godeps/_workspace/src/github.com/docker/swarm/pkg/store/consul_test.go <del>package store <del> <del>import ( <del> "testing" <del> "time" <del> <del> "github.com/stretchr/testify/assert" <del>) <del> <del>func makeConsulClient(t *testing.T) Store { <del> client := "localhost:8500" <del> <del> kv, err := NewStore( <del> CONSUL, <del> []string{client}, <del> &Config{ <del> ConnectionTimeout: 3 * time.Second, <del> EphemeralTTL: 2 * time.Second, <del> }, <del> ) <del> if err != nil { <del> t.Fatalf("cannot create store: %v", err) <del> } <del> <del> return kv <del>} <del> <del>func TestConsulStore(t *testing.T) { <del> kv := makeConsulClient(t) <del> <del> testStore(t, kv) <del>} <del> <del>func TestCreateEphemeralSession(t *testing.T) { <del> kv := makeConsulClient(t) <del> <del> consul := kv.(*Consul) <del> <del> err := consul.createEphemeralSession() <del> assert.NoError(t, err) <del> assert.NotEqual(t, consul.ephemeralSession, "") <del>} <del> <del>func TestCheckActiveSession(t *testing.T) { <del> kv := makeConsulClient(t) <del> <del> consul := kv.(*Consul) <del> <del> key := "foo" <del> value := []byte("bar") <del> <del> // Put the first key with the Ephemeral flag <del> err := kv.Put(key, value, &WriteOptions{Ephemeral: true}) <del> assert.NoError(t, err) <del> <del> // Session should not be empty <del> session, err := consul.checkActiveSession(key) <del> assert.NoError(t, err) <del> assert.NotEqual(t, session, "") <del> <del> // Delete the key <del> err = kv.Delete(key) <del> assert.NoError(t, err) <del> <del> // Check the session again, it should return nothing <del> session, err = consul.checkActiveSession(key) <del> assert.NoError(t, err) <del> assert.Equal(t, session, "") <del>} <ide><path>libnetwork/Godeps/_workspace/src/github.com/docker/swarm/pkg/store/etcd.go <del>package store <del> <del>import ( <del> "crypto/tls" <del> "net" <del> "net/http" <del> "strings" <del> "time" <del> <del> etcd "github.com/coreos/go-etcd/etcd" <del>) <del> <del>// Etcd embeds the client <del>type Etcd struct { <del> client *etcd.Client <del> ephemeralTTL time.Duration <del>} <del> <del>type etcdLock struct { <del> client *etcd.Client <del> stopLock chan struct{} <del> key string <del> value string <del> last *etcd.Response <del> ttl uint64 <del>} <del> <del>const ( <del> defaultLockTTL = 20 * time.Second <del> defaultUpdateTime = 5 * time.Second <del> <del> // periodicSync is the time between each call to SyncCluster <del> periodicSync = 10 * time.Minute <del>) <del> <del>// InitializeEtcd creates a new Etcd client given <del>// a list of endpoints and optional tls config <del>func InitializeEtcd(addrs []string, options *Config) (Store, error) { <del> s := &Etcd{} <del> <del> entries := createEndpoints(addrs, "http") <del> s.client = etcd.NewClient(entries) <del> <del> // Set options <del> if options != nil { <del> if options.TLS != nil { <del> s.setTLS(options.TLS) <del> } <del> if options.ConnectionTimeout != 0 { <del> s.setTimeout(options.ConnectionTimeout) <del> } <del> if options.EphemeralTTL != 0 { <del> s.setEphemeralTTL(options.EphemeralTTL) <del> } <del> } <del> <del> go func() { <del> for { <del> s.client.SyncCluster() <del> time.Sleep(periodicSync) <del> } <del> }() <del> return s, nil <del>} <del> <del>// SetTLS sets the tls configuration given the path <del>// of certificate files <del>func (s *Etcd) setTLS(tls *tls.Config) { <del> // Change to https scheme <del> var addrs []string <del> entries := s.client.GetCluster() <del> for _, entry := range entries { <del> addrs = append(addrs, strings.Replace(entry, "http", "https", -1)) <del> } <del> s.client.SetCluster(addrs) <del> <del> // Set transport <del> t := http.Transport{ <del> Dial: (&net.Dialer{ <del> Timeout: 30 * time.Second, // default timeout <del> KeepAlive: 30 * time.Second, <del> }).Dial, <del> TLSHandshakeTimeout: 10 * time.Second, <del> TLSClientConfig: tls, <del> } <del> s.client.SetTransport(&t) <del>} <del> <del>// SetTimeout sets the timeout used for connecting to the store <del>func (s *Etcd) setTimeout(time time.Duration) { <del> s.client.SetDialTimeout(time) <del>} <del> <del>// SetHeartbeat sets the heartbeat value to notify we are alive <del>func (s *Etcd) setEphemeralTTL(time time.Duration) { <del> s.ephemeralTTL = time <del>} <del> <del>// Create the entire path for a directory that does not exist <del>func (s *Etcd) createDirectory(path string) error { <del> if _, err := s.client.CreateDir(normalize(path), 10); err != nil { <del> if etcdError, ok := err.(*etcd.EtcdError); ok { <del> if etcdError.ErrorCode != 105 { // Skip key already exists <del> return err <del> } <del> } else { <del> return err <del> } <del> } <del> return nil <del>} <del> <del>// Get the value at "key", returns the last modified index <del>// to use in conjunction to CAS calls <del>func (s *Etcd) Get(key string) (*KVPair, error) { <del> result, err := s.client.Get(normalize(key), false, false) <del> if err != nil { <del> if etcdError, ok := err.(*etcd.EtcdError); ok { <del> // Not a Directory or Not a file <del> if etcdError.ErrorCode == 102 || etcdError.ErrorCode == 104 { <del> return nil, ErrKeyNotFound <del> } <del> } <del> return nil, err <del> } <del> return &KVPair{key, []byte(result.Node.Value), result.Node.ModifiedIndex}, nil <del>} <del> <del>// Put a value at "key" <del>func (s *Etcd) Put(key string, value []byte, opts *WriteOptions) error { <del> <del> // Default TTL = 0 means no expiration <del> var ttl uint64 <del> if opts != nil && opts.Ephemeral { <del> ttl = uint64(s.ephemeralTTL.Seconds()) <del> } <del> <del> if _, err := s.client.Set(key, string(value), ttl); err != nil { <del> if etcdError, ok := err.(*etcd.EtcdError); ok { <del> if etcdError.ErrorCode == 104 { // Not a directory <del> // Remove the last element (the actual key) and set the prefix as a dir <del> err = s.createDirectory(getDirectory(key)) <del> if _, err := s.client.Set(key, string(value), ttl); err != nil { <del> return err <del> } <del> } <del> } <del> return err <del> } <del> return nil <del>} <del> <del>// Delete a value at "key" <del>func (s *Etcd) Delete(key string) error { <del> if _, err := s.client.Delete(normalize(key), false); err != nil { <del> return err <del> } <del> return nil <del>} <del> <del>// Exists checks if the key exists inside the store <del>func (s *Etcd) Exists(key string) (bool, error) { <del> entry, err := s.Get(key) <del> if err != nil { <del> if err == ErrKeyNotFound || entry.Value == nil { <del> return false, nil <del> } <del> return false, err <del> } <del> return true, nil <del>} <del> <del>// Watch changes on a key. <del>// Returns a channel that will receive changes or an error. <del>// Upon creating a watch, the current value will be sent to the channel. <del>// Providing a non-nil stopCh can be used to stop watching. <del>func (s *Etcd) Watch(key string, stopCh <-chan struct{}) (<-chan *KVPair, error) { <del> // Get the current value <del> current, err := s.Get(key) <del> if err != nil { <del> return nil, err <del> } <del> <del> // Start an etcd watch. <del> // Note: etcd will send the current value through the channel. <del> etcdWatchCh := make(chan *etcd.Response) <del> etcdStopCh := make(chan bool) <del> go s.client.Watch(normalize(key), 0, false, etcdWatchCh, etcdStopCh) <del> <del> // Adapter goroutine: The goal here is to convert wathever format etcd is <del> // using into our interface. <del> watchCh := make(chan *KVPair) <del> go func() { <del> defer close(watchCh) <del> <del> // Push the current value through the channel. <del> watchCh <- current <del> <del> for { <del> select { <del> case result := <-etcdWatchCh: <del> watchCh <- &KVPair{ <del> key, <del> []byte(result.Node.Value), <del> result.Node.ModifiedIndex, <del> } <del> case <-stopCh: <del> etcdStopCh <- true <del> return <del> } <del> } <del> }() <del> return watchCh, nil <del>} <del> <del>// WatchTree watches changes on a "directory" <del>// Returns a channel that will receive changes or an error. <del>// Upon creating a watch, the current value will be sent to the channel. <del>// Providing a non-nil stopCh can be used to stop watching. <del>func (s *Etcd) WatchTree(prefix string, stopCh <-chan struct{}) (<-chan []*KVPair, error) { <del> // Get the current value <del> current, err := s.List(prefix) <del> if err != nil { <del> return nil, err <del> } <del> <del> // Start an etcd watch. <del> etcdWatchCh := make(chan *etcd.Response) <del> etcdStopCh := make(chan bool) <del> go s.client.Watch(normalize(prefix), 0, true, etcdWatchCh, etcdStopCh) <del> <del> // Adapter goroutine: The goal here is to convert wathever format etcd is <del> // using into our interface. <del> watchCh := make(chan []*KVPair) <del> go func() { <del> defer close(watchCh) <del> <del> // Push the current value through the channel. <del> watchCh <- current <del> <del> for { <del> select { <del> case <-etcdWatchCh: <del> // FIXME: We should probably use the value pushed by the channel. <del> // However, .Node.Nodes seems to be empty. <del> if list, err := s.List(prefix); err == nil { <del> watchCh <- list <del> } <del> case <-stopCh: <del> etcdStopCh <- true <del> return <del> } <del> } <del> }() <del> return watchCh, nil <del>} <del> <del>// AtomicPut put a value at "key" if the key has not been <del>// modified in the meantime, throws an error if this is the case <del>func (s *Etcd) AtomicPut(key string, value []byte, previous *KVPair, options *WriteOptions) (bool, *KVPair, error) { <del> if previous == nil { <del> return false, nil, ErrPreviousNotSpecified <del> } <del> <del> meta, err := s.client.CompareAndSwap(normalize(key), string(value), 0, "", previous.LastIndex) <del> if err != nil { <del> if etcdError, ok := err.(*etcd.EtcdError); ok { <del> if etcdError.ErrorCode == 101 { // Compare failed <del> return false, nil, ErrKeyModified <del> } <del> } <del> return false, nil, err <del> } <del> return true, &KVPair{Key: key, Value: value, LastIndex: meta.Node.ModifiedIndex}, nil <del>} <del> <del>// AtomicDelete deletes a value at "key" if the key has not <del>// been modified in the meantime, throws an error if this is the case <del>func (s *Etcd) AtomicDelete(key string, previous *KVPair) (bool, error) { <del> if previous == nil { <del> return false, ErrPreviousNotSpecified <del> } <del> <del> _, err := s.client.CompareAndDelete(normalize(key), "", previous.LastIndex) <del> if err != nil { <del> if etcdError, ok := err.(*etcd.EtcdError); ok { <del> if etcdError.ErrorCode == 101 { // Compare failed <del> return false, ErrKeyModified <del> } <del> } <del> return false, err <del> } <del> return true, nil <del>} <del> <del>// List the content of a given prefix <del>func (s *Etcd) List(prefix string) ([]*KVPair, error) { <del> resp, err := s.client.Get(normalize(prefix), true, true) <del> if err != nil { <del> return nil, err <del> } <del> kv := []*KVPair{} <del> for _, n := range resp.Node.Nodes { <del> key := strings.TrimLeft(n.Key, "/") <del> kv = append(kv, &KVPair{key, []byte(n.Value), n.ModifiedIndex}) <del> } <del> return kv, nil <del>} <del> <del>// DeleteTree deletes a range of keys based on prefix <del>func (s *Etcd) DeleteTree(prefix string) error { <del> if _, err := s.client.Delete(normalize(prefix), true); err != nil { <del> return err <del> } <del> return nil <del>} <del> <del>// NewLock returns a handle to a lock struct which can be used to acquire and <del>// release the mutex. <del>func (s *Etcd) NewLock(key string, options *LockOptions) (Locker, error) { <del> var value string <del> ttl := uint64(time.Duration(defaultLockTTL).Seconds()) <del> <del> // Apply options <del> if options != nil { <del> if options.Value != nil { <del> value = string(options.Value) <del> } <del> if options.TTL != 0 { <del> ttl = uint64(options.TTL.Seconds()) <del> } <del> } <del> <del> // Create lock object <del> lock := &etcdLock{ <del> client: s.client, <del> key: key, <del> value: value, <del> ttl: ttl, <del> } <del> <del> return lock, nil <del>} <del> <del>// Lock attempts to acquire the lock and blocks while doing so. <del>// Returns a channel that is closed if our lock is lost or an error. <del>func (l *etcdLock) Lock() (<-chan struct{}, error) { <del> <del> key := normalize(l.key) <del> <del> // Lock holder channels <del> lockHeld := make(chan struct{}) <del> stopLocking := make(chan struct{}) <del> <del> var lastIndex uint64 <del> <del> for { <del> resp, err := l.client.Create(key, l.value, l.ttl) <del> if err != nil { <del> if etcdError, ok := err.(*etcd.EtcdError); ok { <del> // Key already exists <del> if etcdError.ErrorCode != 105 { <del> lastIndex = ^uint64(0) <del> } <del> } <del> } else { <del> lastIndex = resp.Node.ModifiedIndex <del> } <del> <del> _, err = l.client.CompareAndSwap(key, l.value, l.ttl, "", lastIndex) <del> <del> if err == nil { <del> // Leader section <del> l.stopLock = stopLocking <del> go l.holdLock(key, lockHeld, stopLocking) <del> break <del> } else { <del> // Seeker section <del> chW := make(chan *etcd.Response) <del> chWStop := make(chan bool) <del> l.waitLock(key, chW, chWStop) <del> <del> // Delete or Expire event occured <del> // Retry <del> } <del> } <del> <del> return lockHeld, nil <del>} <del> <del>// Hold the lock as long as we can <del>// Updates the key ttl periodically until we receive <del>// an explicit stop signal from the Unlock method <del>func (l *etcdLock) holdLock(key string, lockHeld chan struct{}, stopLocking chan struct{}) { <del> defer close(lockHeld) <del> <del> update := time.NewTicker(defaultUpdateTime) <del> defer update.Stop() <del> <del> var err error <del> <del> for { <del> select { <del> case <-update.C: <del> l.last, err = l.client.Update(key, l.value, l.ttl) <del> if err != nil { <del> return <del> } <del> <del> case <-stopLocking: <del> return <del> } <del> } <del>} <del> <del>// WaitLock simply waits for the key to be available for creation <del>func (l *etcdLock) waitLock(key string, eventCh chan *etcd.Response, stopWatchCh chan bool) { <del> go l.client.Watch(key, 0, false, eventCh, stopWatchCh) <del> for event := range eventCh { <del> if event.Action == "delete" || event.Action == "expire" { <del> return <del> } <del> } <del>} <del> <del>// Unlock released the lock. It is an error to call this <del>// if the lock is not currently held. <del>func (l *etcdLock) Unlock() error { <del> if l.stopLock != nil { <del> l.stopLock <- struct{}{} <del> } <del> if l.last != nil { <del> _, err := l.client.CompareAndDelete(normalize(l.key), l.value, l.last.Node.ModifiedIndex) <del> if err != nil { <del> return err <del> } <del> } <del> return nil <del>} <del> <del>// Close closes the client connection <del>func (s *Etcd) Close() { <del> return <del>} <ide><path>libnetwork/Godeps/_workspace/src/github.com/docker/swarm/pkg/store/etcd_test.go <del>package store <del> <del>import ( <del> "testing" <del> "time" <del>) <del> <del>func makeEtcdClient(t *testing.T) Store { <del> client := "localhost:4001" <del> <del> kv, err := NewStore( <del> ETCD, <del> []string{client}, <del> &Config{ <del> ConnectionTimeout: 3 * time.Second, <del> EphemeralTTL: 2 * time.Second, <del> }, <del> ) <del> if err != nil { <del> t.Fatalf("cannot create store: %v", err) <del> } <del> <del> return kv <del>} <del> <del>func TestEtcdStore(t *testing.T) { <del> kv := makeEtcdClient(t) <del> <del> testStore(t, kv) <del>} <ide><path>libnetwork/Godeps/_workspace/src/github.com/docker/swarm/pkg/store/helpers.go <del>package store <del> <del>import ( <del> "strings" <del>) <del> <del>// Creates a list of endpoints given the right scheme <del>func createEndpoints(addrs []string, scheme string) (entries []string) { <del> for _, addr := range addrs { <del> entries = append(entries, scheme+"://"+addr) <del> } <del> return entries <del>} <del> <del>// Normalize the key for each store to the form: <del>// <del>// /path/to/key <del>// <del>func normalize(key string) string { <del> return "/" + join(splitKey(key)) <del>} <del> <del>// Get the full directory part of the key to the form: <del>// <del>// /path/to/ <del>// <del>func getDirectory(key string) string { <del> parts := splitKey(key) <del> parts = parts[:len(parts)-1] <del> return "/" + join(parts) <del>} <del> <del>// SplitKey splits the key to extract path informations <del>func splitKey(key string) (path []string) { <del> if strings.Contains(key, "/") { <del> path = strings.Split(key, "/") <del> } else { <del> path = []string{key} <del> } <del> return path <del>} <del> <del>// Join the path parts with '/' <del>func join(parts []string) string { <del> return strings.Join(parts, "/") <del>} <ide><path>libnetwork/Godeps/_workspace/src/github.com/docker/swarm/pkg/store/mock.go <del>package store <del> <del>import "github.com/stretchr/testify/mock" <del> <del>// Mock store. Mocks all Store functions using testify.Mock. <del>type Mock struct { <del> mock.Mock <del> <del> // Endpoints passed to InitializeMock <del> Endpoints []string <del> // Options passed to InitializeMock <del> Options *Config <del>} <del> <del>// InitializeMock creates a Mock store. <del>func InitializeMock(endpoints []string, options *Config) (Store, error) { <del> s := &Mock{} <del> s.Endpoints = endpoints <del> s.Options = options <del> return s, nil <del>} <del> <del>// Put mock <del>func (s *Mock) Put(key string, value []byte, opts *WriteOptions) error { <del> args := s.Mock.Called(key, value, opts) <del> return args.Error(0) <del>} <del> <del>// Get mock <del>func (s *Mock) Get(key string) (*KVPair, error) { <del> args := s.Mock.Called(key) <del> return args.Get(0).(*KVPair), args.Error(1) <del>} <del> <del>// Delete mock <del>func (s *Mock) Delete(key string) error { <del> args := s.Mock.Called(key) <del> return args.Error(0) <del>} <del> <del>// Exists mock <del>func (s *Mock) Exists(key string) (bool, error) { <del> args := s.Mock.Called(key) <del> return args.Bool(0), args.Error(1) <del>} <del> <del>// Watch mock <del>func (s *Mock) Watch(key string, stopCh <-chan struct{}) (<-chan *KVPair, error) { <del> args := s.Mock.Called(key, stopCh) <del> return args.Get(0).(<-chan *KVPair), args.Error(1) <del>} <del> <del>// WatchTree mock <del>func (s *Mock) WatchTree(prefix string, stopCh <-chan struct{}) (<-chan []*KVPair, error) { <del> args := s.Mock.Called(prefix, stopCh) <del> return args.Get(0).(chan []*KVPair), args.Error(1) <del>} <del> <del>// NewLock mock <del>func (s *Mock) NewLock(key string, options *LockOptions) (Locker, error) { <del> args := s.Mock.Called(key, options) <del> return args.Get(0).(Locker), args.Error(1) <del>} <del> <del>// List mock <del>func (s *Mock) List(prefix string) ([]*KVPair, error) { <del> args := s.Mock.Called(prefix) <del> return args.Get(0).([]*KVPair), args.Error(1) <del>} <del> <del>// DeleteTree mock <del>func (s *Mock) DeleteTree(prefix string) error { <del> args := s.Mock.Called(prefix) <del> return args.Error(0) <del>} <del> <del>// AtomicPut mock <del>func (s *Mock) AtomicPut(key string, value []byte, previous *KVPair, opts *WriteOptions) (bool, *KVPair, error) { <del> args := s.Mock.Called(key, value, previous, opts) <del> return args.Bool(0), args.Get(1).(*KVPair), args.Error(2) <del>} <del> <del>// AtomicDelete mock <del>func (s *Mock) AtomicDelete(key string, previous *KVPair) (bool, error) { <del> args := s.Mock.Called(key, previous) <del> return args.Bool(0), args.Error(1) <del>} <del> <del>// MockLock mock implementation of Locker <del>type MockLock struct { <del> mock.Mock <del>} <del> <del>// Lock mock <del>func (l *MockLock) Lock() (<-chan struct{}, error) { <del> args := l.Mock.Called() <del> return args.Get(0).(<-chan struct{}), args.Error(1) <del>} <del> <del>// Unlock mock <del>func (l *MockLock) Unlock() error { <del> args := l.Mock.Called() <del> return args.Error(0) <del>} <del> <del>// Close mock <del>func (s *Mock) Close() { <del> return <del>} <ide><path>libnetwork/Godeps/_workspace/src/github.com/docker/swarm/pkg/store/store.go <del>package store <del> <del>import ( <del> "crypto/tls" <del> "errors" <del> "time" <del> <del> log "github.com/Sirupsen/logrus" <del>) <del> <del>// Backend represents a KV Store Backend <del>type Backend string <del> <del>const ( <del> // MOCK backend <del> MOCK Backend = "mock" <del> // CONSUL backend <del> CONSUL = "consul" <del> // ETCD backend <del> ETCD = "etcd" <del> // ZK backend <del> ZK = "zk" <del>) <del> <del>var ( <del> // ErrInvalidTTL is a specific error to consul <del> ErrInvalidTTL = errors.New("Invalid TTL, please change the value to the miminum allowed ttl for the chosen store") <del> // ErrNotSupported is exported <del> ErrNotSupported = errors.New("Backend storage not supported yet, please choose another one") <del> // ErrNotImplemented is exported <del> ErrNotImplemented = errors.New("Call not implemented in current backend") <del> // ErrNotReachable is exported <del> ErrNotReachable = errors.New("Api not reachable") <del> // ErrCannotLock is exported <del> ErrCannotLock = errors.New("Error acquiring the lock") <del> // ErrWatchDoesNotExist is exported <del> ErrWatchDoesNotExist = errors.New("No watch found for specified key") <del> // ErrKeyModified is exported <del> ErrKeyModified = errors.New("Unable to complete atomic operation, key modified") <del> // ErrKeyNotFound is exported <del> ErrKeyNotFound = errors.New("Key not found in store") <del> // ErrPreviousNotSpecified is exported <del> ErrPreviousNotSpecified = errors.New("Previous K/V pair should be provided for the Atomic operation") <del>) <del> <del>// Config contains the options for a storage client <del>type Config struct { <del> TLS *tls.Config <del> ConnectionTimeout time.Duration <del> EphemeralTTL time.Duration <del>} <del> <del>// Store represents the backend K/V storage <del>// Each store should support every call listed <del>// here. Or it couldn't be implemented as a K/V <del>// backend for libkv <del>type Store interface { <del> // Put a value at the specified key <del> Put(key string, value []byte, options *WriteOptions) error <del> <del> // Get a value given its key <del> Get(key string) (*KVPair, error) <del> <del> // Delete the value at the specified key <del> Delete(key string) error <del> <del> // Verify if a Key exists in the store <del> Exists(key string) (bool, error) <del> <del> // Watch changes on a key. <del> // Returns a channel that will receive changes or an error. <del> // Upon creating a watch, the current value will be sent to the channel. <del> // Providing a non-nil stopCh can be used to stop watching. <del> Watch(key string, stopCh <-chan struct{}) (<-chan *KVPair, error) <del> <del> // WatchTree watches changes on a "directory" <del> // Returns a channel that will receive changes or an error. <del> // Upon creating a watch, the current value will be sent to the channel. <del> // Providing a non-nil stopCh can be used to stop watching. <del> WatchTree(prefix string, stopCh <-chan struct{}) (<-chan []*KVPair, error) <del> <del> // CreateLock for a given key. <del> // The returned Locker is not held and must be acquired with `.Lock`. <del> // value is optional. <del> NewLock(key string, options *LockOptions) (Locker, error) <del> <del> // List the content of a given prefix <del> List(prefix string) ([]*KVPair, error) <del> <del> // DeleteTree deletes a range of keys based on prefix <del> DeleteTree(prefix string) error <del> <del> // Atomic operation on a single value <del> AtomicPut(key string, value []byte, previous *KVPair, options *WriteOptions) (bool, *KVPair, error) <del> <del> // Atomic delete of a single value <del> AtomicDelete(key string, previous *KVPair) (bool, error) <del> <del> // Close the store connection <del> Close() <del>} <del> <del>// KVPair represents {Key, Value, Lastindex} tuple <del>type KVPair struct { <del> Key string <del> Value []byte <del> LastIndex uint64 <del>} <del> <del>// WriteOptions contains optional request parameters <del>type WriteOptions struct { <del> Heartbeat time.Duration <del> Ephemeral bool <del>} <del> <del>// LockOptions contains optional request parameters <del>type LockOptions struct { <del> Value []byte // Optional, value to associate with the lock <del> TTL time.Duration // Optional, expiration ttl associated with the lock <del>} <del> <del>// WatchCallback is used for watch methods on keys <del>// and is triggered on key change <del>type WatchCallback func(entries ...*KVPair) <del> <del>// Locker provides locking mechanism on top of the store. <del>// Similar to `sync.Lock` except it may return errors. <del>type Locker interface { <del> Lock() (<-chan struct{}, error) <del> Unlock() error <del>} <del> <del>// Initialize creates a new Store object, initializing the client <del>type Initialize func(addrs []string, options *Config) (Store, error) <del> <del>var ( <del> // Backend initializers <del> initializers = map[Backend]Initialize{ <del> MOCK: InitializeMock, <del> CONSUL: InitializeConsul, <del> ETCD: InitializeEtcd, <del> ZK: InitializeZookeeper, <del> } <del>) <del> <del>// NewStore creates a an instance of store <del>func NewStore(backend Backend, addrs []string, options *Config) (Store, error) { <del> if init, exists := initializers[backend]; exists { <del> log.WithFields(log.Fields{"backend": backend}).Debug("Initializing store service") <del> return init(addrs, options) <del> } <del> <del> return nil, ErrNotSupported <del>} <ide><path>libnetwork/Godeps/_workspace/src/github.com/docker/swarm/pkg/store/store_test.go <del>package store <del> <del>import ( <del> "testing" <del> "time" <del> <del> "github.com/stretchr/testify/assert" <del>) <del> <del>func testStore(t *testing.T, kv Store) { <del> testPutGetDelete(t, kv) <del> testWatch(t, kv) <del> testWatchTree(t, kv) <del> testAtomicPut(t, kv) <del> testAtomicDelete(t, kv) <del> testLockUnlock(t, kv) <del> testPutEphemeral(t, kv) <del> testList(t, kv) <del> testDeleteTree(t, kv) <del>} <del> <del>func testPutGetDelete(t *testing.T, kv Store) { <del> key := "foo" <del> value := []byte("bar") <del> <del> // Put the key <del> err := kv.Put(key, value, nil) <del> assert.NoError(t, err) <del> <del> // Get should return the value and an incremented index <del> pair, err := kv.Get(key) <del> assert.NoError(t, err) <del> if assert.NotNil(t, pair) { <del> assert.NotNil(t, pair.Value) <del> } <del> assert.Equal(t, pair.Value, value) <del> assert.NotEqual(t, pair.LastIndex, 0) <del> <del> // Delete the key <del> err = kv.Delete(key) <del> assert.NoError(t, err) <del> <del> // Get should fail <del> pair, err = kv.Get(key) <del> assert.Error(t, err) <del> assert.Nil(t, pair) <del>} <del> <del>func testWatch(t *testing.T, kv Store) { <del> key := "hello" <del> value := []byte("world") <del> newValue := []byte("world!") <del> <del> // Put the key <del> err := kv.Put(key, value, nil) <del> assert.NoError(t, err) <del> <del> stopCh := make(<-chan struct{}) <del> events, err := kv.Watch(key, stopCh) <del> assert.NoError(t, err) <del> assert.NotNil(t, events) <del> <del> // Update loop <del> go func() { <del> timeout := time.After(1 * time.Second) <del> tick := time.Tick(250 * time.Millisecond) <del> for { <del> select { <del> case <-timeout: <del> return <del> case <-tick: <del> err := kv.Put(key, newValue, nil) <del> if assert.NoError(t, err) { <del> continue <del> } <del> return <del> } <del> } <del> }() <del> <del> // Check for updates <del> timeout := time.After(2 * time.Second) <del> eventCount := 1 <del> for { <del> select { <del> case event := <-events: <del> assert.NotNil(t, event) <del> if eventCount == 1 { <del> assert.Equal(t, event.Key, key) <del> assert.Equal(t, event.Value, value) <del> } else { <del> assert.Equal(t, event.Key, key) <del> assert.Equal(t, event.Value, newValue) <del> } <del> eventCount++ <del> // We received all the events we wanted to check <del> if eventCount >= 4 { <del> return <del> } <del> case <-timeout: <del> t.Fatal("Timeout reached") <del> return <del> } <del> } <del>} <del> <del>func testWatchTree(t *testing.T, kv Store) { <del> dir := "tree" <del> <del> node1 := "tree/node1" <del> value1 := []byte("node1") <del> <del> node2 := "tree/node2" <del> value2 := []byte("node2") <del> <del> node3 := "tree/node3" <del> value3 := []byte("node3") <del> <del> err := kv.Put(node1, value1, nil) <del> assert.NoError(t, err) <del> err = kv.Put(node2, value2, nil) <del> assert.NoError(t, err) <del> err = kv.Put(node3, value3, nil) <del> assert.NoError(t, err) <del> <del> stopCh := make(<-chan struct{}) <del> events, err := kv.WatchTree(dir, stopCh) <del> assert.NoError(t, err) <del> assert.NotNil(t, events) <del> <del> // Update loop <del> go func() { <del> timeout := time.After(250 * time.Millisecond) <del> for { <del> select { <del> case <-timeout: <del> err := kv.Delete(node3) <del> assert.NoError(t, err) <del> return <del> } <del> } <del> }() <del> <del> // Check for updates <del> timeout := time.After(4 * time.Second) <del> for { <del> select { <del> case event := <-events: <del> assert.NotNil(t, event) <del> // We received the Delete event on a child node <del> // Exit test successfully <del> if len(event) == 2 { <del> return <del> } <del> case <-timeout: <del> t.Fatal("Timeout reached") <del> return <del> } <del> } <del>} <del> <del>func testAtomicPut(t *testing.T, kv Store) { <del> key := "hello" <del> value := []byte("world") <del> <del> // Put the key <del> err := kv.Put(key, value, nil) <del> assert.NoError(t, err) <del> <del> // Get should return the value and an incremented index <del> pair, err := kv.Get(key) <del> assert.NoError(t, err) <del> if assert.NotNil(t, pair) { <del> assert.NotNil(t, pair.Value) <del> } <del> assert.Equal(t, pair.Value, value) <del> assert.NotEqual(t, pair.LastIndex, 0) <del> <del> // This CAS should succeed <del> success, _, err := kv.AtomicPut("hello", []byte("WORLD"), pair, nil) <del> assert.NoError(t, err) <del> assert.True(t, success) <del> <del> // This CAS should fail <del> pair.LastIndex = 0 <del> success, _, err = kv.AtomicPut("hello", []byte("WORLDWORLD"), pair, nil) <del> assert.Error(t, err) <del> assert.False(t, success) <del>} <del> <del>func testAtomicDelete(t *testing.T, kv Store) { <del> key := "atomic" <del> value := []byte("world") <del> <del> // Put the key <del> err := kv.Put(key, value, nil) <del> assert.NoError(t, err) <del> <del> // Get should return the value and an incremented index <del> pair, err := kv.Get(key) <del> assert.NoError(t, err) <del> if assert.NotNil(t, pair) { <del> assert.NotNil(t, pair.Value) <del> } <del> assert.Equal(t, pair.Value, value) <del> assert.NotEqual(t, pair.LastIndex, 0) <del> <del> tempIndex := pair.LastIndex <del> <del> // AtomicDelete should fail <del> pair.LastIndex = 0 <del> success, err := kv.AtomicDelete(key, pair) <del> assert.Error(t, err) <del> assert.False(t, success) <del> <del> // AtomicDelete should succeed <del> pair.LastIndex = tempIndex <del> success, err = kv.AtomicDelete(key, pair) <del> assert.NoError(t, err) <del> assert.True(t, success) <del>} <del> <del>func testLockUnlock(t *testing.T, kv Store) { <del> t.Parallel() <del> <del> key := "foo" <del> value := []byte("bar") <del> <del> // We should be able to create a new lock on key <del> lock, err := kv.NewLock(key, &LockOptions{Value: value}) <del> assert.NoError(t, err) <del> assert.NotNil(t, lock) <del> <del> // Lock should successfully succeed or block <del> lockChan, err := lock.Lock() <del> assert.NoError(t, err) <del> assert.NotNil(t, lockChan) <del> <del> // Get should work <del> pair, err := kv.Get(key) <del> assert.NoError(t, err) <del> if assert.NotNil(t, pair) { <del> assert.NotNil(t, pair.Value) <del> } <del> assert.Equal(t, pair.Value, value) <del> assert.NotEqual(t, pair.LastIndex, 0) <del> <del> // Unlock should succeed <del> err = lock.Unlock() <del> assert.NoError(t, err) <del> <del> // Get should work <del> pair, err = kv.Get(key) <del> assert.NoError(t, err) <del> if assert.NotNil(t, pair) { <del> assert.NotNil(t, pair.Value) <del> } <del> assert.Equal(t, pair.Value, value) <del> assert.NotEqual(t, pair.LastIndex, 0) <del>} <del> <del>// FIXME Gracefully handle Zookeeper <del>func testPutEphemeral(t *testing.T, kv Store) { <del> // Zookeeper: initialize client here (Close() hangs otherwise) <del> zookeeper := false <del> if _, ok := kv.(*Zookeeper); ok { <del> zookeeper = true <del> kv = makeZkClient(t) <del> } <del> <del> firstKey := "first" <del> firstValue := []byte("foo") <del> <del> secondKey := "second" <del> secondValue := []byte("bar") <del> <del> // Put the first key with the Ephemeral flag <del> err := kv.Put(firstKey, firstValue, &WriteOptions{Ephemeral: true}) <del> assert.NoError(t, err) <del> <del> // Put a second key with the Ephemeral flag <del> err = kv.Put(secondKey, secondValue, &WriteOptions{Ephemeral: true}) <del> assert.NoError(t, err) <del> <del> // Get on firstKey should work <del> pair, err := kv.Get(firstKey) <del> assert.NoError(t, err) <del> assert.NotNil(t, pair) <del> <del> // Get on secondKey should work <del> pair, err = kv.Get(secondKey) <del> assert.NoError(t, err) <del> assert.NotNil(t, pair) <del> <del> // Zookeeper: close client connection <del> if zookeeper { <del> kv.Close() <del> } <del> <del> // Let the session expire <del> time.Sleep(5 * time.Second) <del> <del> // Zookeeper: re-create the client <del> if zookeeper { <del> kv = makeZkClient(t) <del> } <del> <del> // Get on firstKey shouldn't work <del> pair, err = kv.Get(firstKey) <del> assert.Error(t, err) <del> assert.Nil(t, pair) <del> <del> // Get on secondKey shouldn't work <del> pair, err = kv.Get(secondKey) <del> assert.Error(t, err) <del> assert.Nil(t, pair) <del>} <del> <del>func testList(t *testing.T, kv Store) { <del> prefix := "nodes" <del> <del> firstKey := "nodes/first" <del> firstValue := []byte("first") <del> <del> secondKey := "nodes/second" <del> secondValue := []byte("second") <del> <del> // Put the first key <del> err := kv.Put(firstKey, firstValue, nil) <del> assert.NoError(t, err) <del> <del> // Put the second key <del> err = kv.Put(secondKey, secondValue, nil) <del> assert.NoError(t, err) <del> <del> // List should work and return the two correct values <del> pairs, err := kv.List(prefix) <del> assert.NoError(t, err) <del> if assert.NotNil(t, pairs) { <del> assert.Equal(t, len(pairs), 2) <del> } <del> <del> // Check pairs, those are not necessarily in Put order <del> for _, pair := range pairs { <del> if pair.Key == firstKey { <del> assert.Equal(t, pair.Value, firstValue) <del> } <del> if pair.Key == secondKey { <del> assert.Equal(t, pair.Value, secondValue) <del> } <del> } <del>} <del> <del>func testDeleteTree(t *testing.T, kv Store) { <del> prefix := "nodes" <del> <del> firstKey := "nodes/first" <del> firstValue := []byte("first") <del> <del> secondKey := "nodes/second" <del> secondValue := []byte("second") <del> <del> // Put the first key <del> err := kv.Put(firstKey, firstValue, nil) <del> assert.NoError(t, err) <del> <del> // Put the second key <del> err = kv.Put(secondKey, secondValue, nil) <del> assert.NoError(t, err) <del> <del> // Get should work on the first Key <del> pair, err := kv.Get(firstKey) <del> assert.NoError(t, err) <del> if assert.NotNil(t, pair) { <del> assert.NotNil(t, pair.Value) <del> } <del> assert.Equal(t, pair.Value, firstValue) <del> assert.NotEqual(t, pair.LastIndex, 0) <del> <del> // Get should work on the second Key <del> pair, err = kv.Get(secondKey) <del> assert.NoError(t, err) <del> if assert.NotNil(t, pair) { <del> assert.NotNil(t, pair.Value) <del> } <del> assert.Equal(t, pair.Value, secondValue) <del> assert.NotEqual(t, pair.LastIndex, 0) <del> <del> // Delete Values under directory `nodes` <del> err = kv.DeleteTree(prefix) <del> assert.NoError(t, err) <del> <del> // Get should fail on both keys <del> pair, err = kv.Get(firstKey) <del> assert.Error(t, err) <del> assert.Nil(t, pair) <del> <del> pair, err = kv.Get(secondKey) <del> assert.Error(t, err) <del> assert.Nil(t, pair) <del>} <ide><path>libnetwork/Godeps/_workspace/src/github.com/docker/swarm/pkg/store/zookeeper.go <del>package store <del> <del>import ( <del> "strings" <del> "time" <del> <del> log "github.com/Sirupsen/logrus" <del> zk "github.com/samuel/go-zookeeper/zk" <del>) <del> <del>const defaultTimeout = 10 * time.Second <del> <del>// Zookeeper embeds the zookeeper client <del>type Zookeeper struct { <del> timeout time.Duration <del> client *zk.Conn <del>} <del> <del>type zookeeperLock struct { <del> client *zk.Conn <del> lock *zk.Lock <del> key string <del> value []byte <del>} <del> <del>// InitializeZookeeper creates a new Zookeeper client <del>// given a list of endpoints and optional tls config <del>func InitializeZookeeper(endpoints []string, options *Config) (Store, error) { <del> s := &Zookeeper{} <del> s.timeout = defaultTimeout <del> <del> // Set options <del> if options != nil { <del> if options.ConnectionTimeout != 0 { <del> s.setTimeout(options.ConnectionTimeout) <del> } <del> } <del> <del> conn, _, err := zk.Connect(endpoints, s.timeout) <del> if err != nil { <del> log.Error(err) <del> return nil, err <del> } <del> s.client = conn <del> return s, nil <del>} <del> <del>// SetTimeout sets the timout for connecting to Zookeeper <del>func (s *Zookeeper) setTimeout(time time.Duration) { <del> s.timeout = time <del>} <del> <del>// Get the value at "key", returns the last modified index <del>// to use in conjunction to CAS calls <del>func (s *Zookeeper) Get(key string) (*KVPair, error) { <del> resp, meta, err := s.client.Get(normalize(key)) <del> if err != nil { <del> return nil, err <del> } <del> if resp == nil { <del> return nil, ErrKeyNotFound <del> } <del> return &KVPair{key, resp, uint64(meta.Version)}, nil <del>} <del> <del>// Create the entire path for a directory that does not exist <del>func (s *Zookeeper) createFullpath(path []string, ephemeral bool) error { <del> for i := 1; i <= len(path); i++ { <del> newpath := "/" + strings.Join(path[:i], "/") <del> if i == len(path) && ephemeral { <del> _, err := s.client.Create(newpath, []byte{1}, zk.FlagEphemeral, zk.WorldACL(zk.PermAll)) <del> return err <del> } <del> _, err := s.client.Create(newpath, []byte{1}, 0, zk.WorldACL(zk.PermAll)) <del> if err != nil { <del> // Skip if node already exists <del> if err != zk.ErrNodeExists { <del> return err <del> } <del> } <del> } <del> return nil <del>} <del> <del>// Put a value at "key" <del>func (s *Zookeeper) Put(key string, value []byte, opts *WriteOptions) error { <del> fkey := normalize(key) <del> exists, err := s.Exists(key) <del> if err != nil { <del> return err <del> } <del> if !exists { <del> if opts != nil && opts.Ephemeral { <del> s.createFullpath(splitKey(key), opts.Ephemeral) <del> } else { <del> s.createFullpath(splitKey(key), false) <del> } <del> } <del> _, err = s.client.Set(fkey, value, -1) <del> return err <del>} <del> <del>// Delete a value at "key" <del>func (s *Zookeeper) Delete(key string) error { <del> err := s.client.Delete(normalize(key), -1) <del> return err <del>} <del> <del>// Exists checks if the key exists inside the store <del>func (s *Zookeeper) Exists(key string) (bool, error) { <del> exists, _, err := s.client.Exists(normalize(key)) <del> if err != nil { <del> return false, err <del> } <del> return exists, nil <del>} <del> <del>// Watch changes on a key. <del>// Returns a channel that will receive changes or an error. <del>// Upon creating a watch, the current value will be sent to the channel. <del>// Providing a non-nil stopCh can be used to stop watching. <del>func (s *Zookeeper) Watch(key string, stopCh <-chan struct{}) (<-chan *KVPair, error) { <del> fkey := normalize(key) <del> pair, err := s.Get(key) <del> if err != nil { <del> return nil, err <del> } <del> <del> // Catch zk notifications and fire changes into the channel. <del> watchCh := make(chan *KVPair) <del> go func() { <del> defer close(watchCh) <del> <del> // Get returns the current value before setting the watch. <del> watchCh <- pair <del> for { <del> _, _, eventCh, err := s.client.GetW(fkey) <del> if err != nil { <del> return <del> } <del> select { <del> case e := <-eventCh: <del> if e.Type == zk.EventNodeDataChanged { <del> if entry, err := s.Get(key); err == nil { <del> watchCh <- entry <del> } <del> } <del> case <-stopCh: <del> // There is no way to stop GetW so just quit <del> return <del> } <del> } <del> }() <del> <del> return watchCh, nil <del>} <del> <del>// WatchTree watches changes on a "directory" <del>// Returns a channel that will receive changes or an error. <del>// Upon creating a watch, the current value will be sent to the channel. <del>// Providing a non-nil stopCh can be used to stop watching. <del>func (s *Zookeeper) WatchTree(prefix string, stopCh <-chan struct{}) (<-chan []*KVPair, error) { <del> fprefix := normalize(prefix) <del> entries, err := s.List(prefix) <del> if err != nil { <del> return nil, err <del> } <del> <del> // Catch zk notifications and fire changes into the channel. <del> watchCh := make(chan []*KVPair) <del> go func() { <del> defer close(watchCh) <del> <del> // List returns the current values before setting the watch. <del> watchCh <- entries <del> <del> for { <del> _, _, eventCh, err := s.client.ChildrenW(fprefix) <del> if err != nil { <del> return <del> } <del> select { <del> case e := <-eventCh: <del> if e.Type == zk.EventNodeChildrenChanged { <del> if kv, err := s.List(prefix); err == nil { <del> watchCh <- kv <del> } <del> } <del> case <-stopCh: <del> // There is no way to stop GetW so just quit <del> return <del> } <del> } <del> }() <del> <del> return watchCh, nil <del>} <del> <del>// List the content of a given prefix <del>func (s *Zookeeper) List(prefix string) ([]*KVPair, error) { <del> keys, stat, err := s.client.Children(normalize(prefix)) <del> if err != nil { <del> return nil, err <del> } <del> kv := []*KVPair{} <del> for _, key := range keys { <del> // FIXME Costly Get request for each child key.. <del> pair, err := s.Get(prefix + normalize(key)) <del> if err != nil { <del> return nil, err <del> } <del> kv = append(kv, &KVPair{key, []byte(pair.Value), uint64(stat.Version)}) <del> } <del> return kv, nil <del>} <del> <del>// DeleteTree deletes a range of keys based on prefix <del>func (s *Zookeeper) DeleteTree(prefix string) error { <del> pairs, err := s.List(prefix) <del> if err != nil { <del> return err <del> } <del> var reqs []interface{} <del> for _, pair := range pairs { <del> reqs = append(reqs, &zk.DeleteRequest{ <del> Path: normalize(prefix + "/" + pair.Key), <del> Version: -1, <del> }) <del> } <del> _, err = s.client.Multi(reqs...) <del> return err <del>} <del> <del>// AtomicPut put a value at "key" if the key has not been <del>// modified in the meantime, throws an error if this is the case <del>func (s *Zookeeper) AtomicPut(key string, value []byte, previous *KVPair, _ *WriteOptions) (bool, *KVPair, error) { <del> if previous == nil { <del> return false, nil, ErrPreviousNotSpecified <del> } <del> <del> meta, err := s.client.Set(normalize(key), value, int32(previous.LastIndex)) <del> if err != nil { <del> if err == zk.ErrBadVersion { <del> return false, nil, ErrKeyModified <del> } <del> return false, nil, err <del> } <del> return true, &KVPair{Key: key, Value: value, LastIndex: uint64(meta.Version)}, nil <del>} <del> <del>// AtomicDelete deletes a value at "key" if the key has not <del>// been modified in the meantime, throws an error if this is the case <del>func (s *Zookeeper) AtomicDelete(key string, previous *KVPair) (bool, error) { <del> if previous == nil { <del> return false, ErrPreviousNotSpecified <del> } <del> <del> err := s.client.Delete(normalize(key), int32(previous.LastIndex)) <del> if err != nil { <del> if err == zk.ErrBadVersion { <del> return false, ErrKeyModified <del> } <del> return false, err <del> } <del> return true, nil <del>} <del> <del>// NewLock returns a handle to a lock struct which can be used to acquire and <del>// release the mutex. <del>func (s *Zookeeper) NewLock(key string, options *LockOptions) (Locker, error) { <del> value := []byte("") <del> <del> // Apply options <del> if options != nil { <del> if options.Value != nil { <del> value = options.Value <del> } <del> } <del> <del> return &zookeeperLock{ <del> client: s.client, <del> key: normalize(key), <del> value: value, <del> lock: zk.NewLock(s.client, normalize(key), zk.WorldACL(zk.PermAll)), <del> }, nil <del>} <del> <del>// Lock attempts to acquire the lock and blocks while doing so. <del>// Returns a channel that is closed if our lock is lost or an error. <del>func (l *zookeeperLock) Lock() (<-chan struct{}, error) { <del> err := l.lock.Lock() <del> <del> if err == nil { <del> // We hold the lock, we can set our value <del> // FIXME: When the last leader leaves the election, this value will be left behind <del> _, err = l.client.Set(l.key, l.value, -1) <del> } <del> <del> return make(chan struct{}), err <del>} <del> <del>// Unlock released the lock. It is an error to call this <del>// if the lock is not currently held. <del>func (l *zookeeperLock) Unlock() error { <del> return l.lock.Unlock() <del>} <del> <del>// Close closes the client connection <del>func (s *Zookeeper) Close() { <del> s.client.Close() <del>} <ide><path>libnetwork/Godeps/_workspace/src/github.com/docker/swarm/pkg/store/zookeeper_test.go <del>package store <del> <del>import ( <del> "testing" <del> "time" <del>) <del> <del>func makeZkClient(t *testing.T) Store { <del> client := "localhost:2181" <del> <del> kv, err := NewStore( <del> ZK, <del> []string{client}, <del> &Config{ <del> ConnectionTimeout: 3 * time.Second, <del> EphemeralTTL: 2 * time.Second, <del> }, <del> ) <del> if err != nil { <del> t.Fatalf("cannot create store: %v", err) <del> } <del> <del> return kv <del>} <del> <del>func TestZkStore(t *testing.T) { <del> kv := makeZkClient(t) <del> <del> testStore(t, kv) <del>}
25
Python
Python
create "embeddings" layer category
0b96fc2855a835e86b36c5255daab44f57af8624
<ide><path>examples/imdb_lstm.py <ide> from keras.optimizers import SGD, RMSprop, Adagrad <ide> from keras.utils import np_utils <ide> from keras.models import Sequential <del>from keras.layers.core import Dense, Dropout, Activation, Embedding <add>from keras.layers.core import Dense, Dropout, Activation <add>from keras.layers.embeddings import Embedding <ide> from keras.layers.recurrent import LSTM, GRU <ide> from keras.datasets import imdb <ide> <ide><path>examples/reuters_mlp.py <ide> model = Sequential() <ide> model.add(Dense(max_words, 256, init='normal')) <ide> model.add(Activation('relu')) <del>#model.add(BatchNormalization(input_shape=(256,))) # try without batch normalization (doesn't work as well!) <add>model.add(BatchNormalization(input_shape=(256,))) # try without batch normalization (doesn't work as well!) <ide> model.add(Dropout(0.5)) <ide> model.add(Dense(256, nb_classes, init='normal')) <ide> model.add(Activation('softmax')) <ide><path>keras/layers/core.py <ide> def act_func(X): <ide> outputs_info=None) <ide> return output.dimshuffle(1,0,2) <ide> <del>class Embedding(Layer): <del> ''' <del> Turn a list of integers >=0 into a dense vector of fixed size. <del> eg. [4, 50, 123, 26] -> [0.25, 0.1] <del> <del> @input_dim: size of vocabulary (highest input integer + 1) <del> @out_dim: size of dense representation <del> ''' <del> def __init__(self, input_dim, output_dim, init='uniform', weights=None): <del> self.init = initializations.get(init) <del> self.input_dim = input_dim <del> self.output_dim = output_dim <del> <del> self.input = T.imatrix() <del> self.W = self.init((self.input_dim, self.output_dim)) <del> self.params = [self.W] <del> <del> if weights is not None: <del> self.set_weights(weights) <del> <del> def output(self, train): <del> X = self.get_input(train) <del> return self.W[X] <ide> <ide><path>keras/layers/embeddings.py <add>import theano <add>import theano.tensor as T <add> <add>from .. import activations, initializations <add>from ..layers.core import Layer <add> <add> <add>class Embedding(Layer): <add> ''' <add> Turn a list of integers >=0 into a dense vector of fixed size. <add> eg. [4, 50, 123, 26] -> [0.25, 0.1] <add> <add> @input_dim: size of vocabulary (highest input integer + 1) <add> @out_dim: size of dense representation <add> ''' <add> def __init__(self, input_dim, output_dim, init='uniform', weights=None): <add> self.init = initializations.get(init) <add> self.input_dim = input_dim <add> self.output_dim = output_dim <add> self.normalize = normalize <add> <add> self.input = T.imatrix() <add> self.W = self.init((self.input_dim, self.output_dim)) <add> self.params = [self.W] <add> <add> if weights is not None: <add> self.set_weights(weights) <add> <add> def output(self, train=False): <add> X = self.get_input(train) <add> out = self.W[X] <add> return out <add> <add> <add>class WordContextProduct(Layer): <add> ''' <add> This layer turns a pair of words (a pivot word + a context word, <add> ie. a word from the same context, or a random, out-of-context word), <add> indentified by their index in a vocabulary, into two dense reprensentations <add> (word representation and context representation). <add> <add> Then it returns activation(dot(pivot_embedding, context_embedding)), <add> which can be trained to encode the probability <add> of finding the context word in the context of the pivot word <add> (or reciprocally depending on your training procedure). <add> <add> The layer ingests integer tensors of shape: <add> (nb_samples, 2) <add> and outputs a float tensor of shape <add> (nb_samples, 1) <add> <add> The 2nd dimension encodes (pivot, context). <add> input_dim is the size of the vocabulary. <add> <add> For more context, see Mikolov et al.: <add> Efficient Estimation of Word reprensentations in Vector Space <add> http://arxiv.org/pdf/1301.3781v3.pdf <add> ''' <add> def __init__(self, input_dim, proj_dim=128, <add> init='uniform', activation='sigmoid', weights=None): <add> self.input_dim = input_dim <add> self.proj_dim = proj_dim <add> self.normalize = normalize <add> self.init = initializations.get(init) <add> self.activation = activations.get(activation) <add> <add> self.input = T.imatrix() <add> # two different embeddings for pivot word and its context <add> # because p(w|c) != p(c|w) <add> self.W_w = self.init((input_dim, proj_dim)) <add> self.W_c = self.init((input_dim, proj_dim)) <add> <add> self.params = [self.W_w, self.W_c] <add> <add> if weights is not None: <add> self.set_weights(weights) <add> <add> <add> def output(self, train=False): <add> X = self.get_input(train) <add> w = self.W_w[X[:, 0]] # nb_samples, proj_dim <add> c = self.W_c[X[:, 1]] # nb_samples, proj_dim <add> <add> dot = T.sum(w * c, axis=1) <add> dot = theano.tensor.reshape(dot, (X.shape[0], 1)) <add> return self.activation(dot) <add>
4
Javascript
Javascript
improve error message for non-existent local files
c604cc22d17d544ed084dfd512c7223903a94f93
<ide><path>src/core/network.js <ide> var NetworkManager = (function NetworkManagerClosure() { <ide> }); <ide> } else if (pendingRequest.onProgressiveData) { <ide> pendingRequest.onDone(null); <del> } else { <add> } else if (chunk) { <ide> pendingRequest.onDone({ <ide> begin: 0, <ide> chunk: chunk <ide> }); <add> } else if (pendingRequest.onError) { <add> pendingRequest.onError(xhr.status); <ide> } <ide> }, <ide> <ide><path>src/core/worker.js <ide> var WorkerMessageHandler = PDFJS.WorkerMessageHandler = { <ide> <ide> onError: function onError(status) { <ide> var exception; <del> if (status === 404) { <add> if (status === 404 || status === 0 && /^file:/.test(source.url)) { <ide> exception = new MissingPDFException('Missing PDF "' + <ide> source.url + '".'); <ide> handler.send('MissingPDF', exception);
2
Python
Python
add versionadded tags to meshgrid arguments
b8222cbedb5428d2b9eac73aac90ef2409799384
<ide><path>numpy/lib/function_base.py <ide> def meshgrid(*xi, **kwargs): <ide> indexing : {'xy', 'ij'}, optional <ide> Cartesian ('xy', default) or matrix ('ij') indexing of output. <ide> See Notes for more details. <add> .. versionadded:: 1.7.0 <ide> sparse : bool, optional <ide> If True a sparse grid is returned in order to conserve memory. <ide> Default is False. <add> .. versionadded:: 1.7.0 <ide> copy : bool, optional <ide> If False, a view into the original arrays are returned in order to <ide> conserve memory. Default is True. Please note that <ide> ``sparse=False, copy=False`` will likely return non-contiguous <ide> arrays. Furthermore, more than one element of a broadcast array <ide> may refer to a single memory location. If you need to write to the <ide> arrays, make copies first. <add> .. versionadded:: 1.7.0 <ide> <ide> Returns <ide> -------
1
Javascript
Javascript
parse expression only once during compile phase
9a828738cd2e959bc2a198989e96c8e416d28b71
<ide><path>src/ng/directive/ngEventDirs.js <ide> forEach( <ide> function(name) { <ide> var directiveName = directiveNormalize('ng-' + name); <ide> ngEventDirectives[directiveName] = ['$parse', function($parse) { <del> return function(scope, element, attr) { <del> var fn = $parse(attr[directiveName]); <del> element.on(lowercase(name), function(event) { <del> scope.$apply(function() { <del> fn(scope, {$event:event}); <del> }); <del> }); <add> return { <add> compile: function($element, attr) { <add> var fn = $parse(attr[directiveName]); <add> return function(scope, element, attr) { <add> element.on(lowercase(name), function(event) { <add> scope.$apply(function() { <add> fn(scope, {$event:event}); <add> }); <add> }); <add> }; <add> } <ide> }; <ide> }]; <ide> }
1
Java
Java
move remaining jaxb2 test files from core to http
6d089cdc08e54091224cf2ec61ca4c81a6c40ca2
<ide><path>spring-web-reactive/src/main/java/org/springframework/core/codec/support/CharSequenceEncoder.java <add>/* <add> * Copyright 2002-2016 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add>package org.springframework.core.codec.support; <add> <add>import org.reactivestreams.Publisher; <add>import reactor.core.publisher.Flux; <add> <add>import org.springframework.core.ResolvableType; <add>import org.springframework.core.io.buffer.DataBuffer; <add>import org.springframework.core.io.buffer.DataBufferFactory; <add>import org.springframework.util.MimeType; <add> <add>/** <add> * <add> * @author Rossen Stoyanchev <add> */ <add>public class CharSequenceEncoder extends AbstractEncoder<CharSequence> { <add> <add> private final StringEncoder stringEncoder; <add> <add> <add> public CharSequenceEncoder(StringEncoder encoder) { <add> super(encoder.getEncodableMimeTypes().toArray(new MimeType[encoder.getEncodableMimeTypes().size()])); <add> this.stringEncoder = encoder; <add> } <add> <add> <add> @Override <add> public Flux<DataBuffer> encode(Publisher<? extends CharSequence> inputStream, <add> DataBufferFactory bufferFactory, ResolvableType elementType, <add> MimeType mimeType, Object... hints) { <add> <add> return this.stringEncoder.encode( <add> Flux.from(inputStream).map(CharSequence::toString), <add> bufferFactory, elementType, mimeType, hints); <add> } <add> <add>} <ide><path>spring-web-reactive/src/test/java/org/springframework/http/codec/xml/Jaxb2DecoderTests.java <ide> import reactor.core.test.TestSubscriber; <ide> <ide> import org.springframework.core.ResolvableType; <del>import org.springframework.core.codec.support.jaxb.XmlRootElement; <del>import org.springframework.core.codec.support.jaxb.XmlRootElementWithName; <del>import org.springframework.core.codec.support.jaxb.XmlRootElementWithNameAndNamespace; <del>import org.springframework.core.codec.support.jaxb.XmlType; <del>import org.springframework.core.codec.support.jaxb.XmlTypeWithName; <del>import org.springframework.core.codec.support.jaxb.XmlTypeWithNameAndNamespace; <ide> import org.springframework.core.io.buffer.AbstractDataBufferAllocatingTestCase; <ide> import org.springframework.core.io.buffer.DataBuffer; <ide> import org.springframework.http.MediaType; <ide> import org.springframework.http.codec.Pojo; <del>import org.springframework.http.codec.xml.Jaxb2Decoder; <del>import org.springframework.http.codec.xml.XmlEventDecoder; <ide> <del>import static org.junit.Assert.*; <add>import static org.junit.Assert.assertEquals; <add>import static org.junit.Assert.assertFalse; <add>import static org.junit.Assert.assertTrue; <ide> <ide> /** <ide> * @author Sebastien Deleuze <ide><path>spring-web-reactive/src/test/java/org/springframework/http/codec/xml/XmlEventDecoderTests.java <ide> import reactor.core.test.TestSubscriber; <ide> <ide> import org.springframework.core.io.buffer.AbstractDataBufferAllocatingTestCase; <del>import org.springframework.http.codec.xml.XmlEventDecoder; <ide> <ide> import static org.junit.Assert.assertEquals; <ide> import static org.junit.Assert.assertTrue; <add><path>spring-web-reactive/src/test/java/org/springframework/http/codec/xml/XmlRootElement.java <del><path>spring-web-reactive/src/test/java/org/springframework/core/codec/support/jaxb/XmlRootElement.java <ide> * limitations under the License. <ide> */ <ide> <del>package org.springframework.core.codec.support.jaxb; <add>package org.springframework.http.codec.xml; <ide> <ide> /** <ide> * @author Arjen Poutsma <add><path>spring-web-reactive/src/test/java/org/springframework/http/codec/xml/XmlRootElementWithName.java <del><path>spring-web-reactive/src/test/java/org/springframework/core/codec/support/jaxb/XmlRootElementWithName.java <ide> * limitations under the License. <ide> */ <ide> <del>package org.springframework.core.codec.support.jaxb; <add>package org.springframework.http.codec.xml; <ide> <ide> import javax.xml.bind.annotation.XmlRootElement; <ide> <add><path>spring-web-reactive/src/test/java/org/springframework/http/codec/xml/XmlRootElementWithNameAndNamespace.java <del><path>spring-web-reactive/src/test/java/org/springframework/core/codec/support/jaxb/XmlRootElementWithNameAndNamespace.java <ide> * limitations under the License. <ide> */ <ide> <del>package org.springframework.core.codec.support.jaxb; <add>package org.springframework.http.codec.xml; <ide> <ide> import javax.xml.bind.annotation.XmlRootElement; <ide> <add><path>spring-web-reactive/src/test/java/org/springframework/http/codec/xml/XmlType.java <del><path>spring-web-reactive/src/test/java/org/springframework/core/codec/support/jaxb/XmlType.java <ide> * limitations under the License. <ide> */ <ide> <del>package org.springframework.core.codec.support.jaxb; <add>package org.springframework.http.codec.xml; <ide> <ide> /** <ide> * @author Arjen Poutsma <add><path>spring-web-reactive/src/test/java/org/springframework/http/codec/xml/XmlTypeWithName.java <del><path>spring-web-reactive/src/test/java/org/springframework/core/codec/support/jaxb/XmlTypeWithName.java <ide> * limitations under the License. <ide> */ <ide> <del>package org.springframework.core.codec.support.jaxb; <add>package org.springframework.http.codec.xml; <ide> <ide> import javax.xml.bind.annotation.XmlType; <ide> <add><path>spring-web-reactive/src/test/java/org/springframework/http/codec/xml/XmlTypeWithNameAndNamespace.java <del><path>spring-web-reactive/src/test/java/org/springframework/core/codec/support/jaxb/XmlTypeWithNameAndNamespace.java <ide> * limitations under the License. <ide> */ <ide> <del>package org.springframework.core.codec.support.jaxb; <add>package org.springframework.http.codec.xml; <ide> <ide> import javax.xml.bind.annotation.XmlType; <ide> <add><path>spring-web-reactive/src/test/java/org/springframework/http/codec/xml/package-info.java <del><path>spring-web-reactive/src/test/java/org/springframework/core/codec/support/jaxb/package-info.java <ide> @javax.xml.bind.annotation.XmlSchema(namespace = "namespace") <del>package org.springframework.core.codec.support.jaxb; <add>package org.springframework.http.codec.xml;
10
Javascript
Javascript
fix eslint errors and warnings in preprocessor.js
88be0cefac62076c43b5fb327990deb6bbce9f8f
<ide><path>jest/preprocessor.js <ide> const babelRegisterOnly = require('metro-babel-register'); <ide> const createCacheKeyFunction = require('fbjs-scripts/jest/createCacheKeyFunction'); <ide> const generate = require('@babel/generator').default; <ide> <del>const nodeFiles = RegExp( <add>const nodeFiles = new RegExp( <ide> [ <ide> '/local-cli/', <ide> '/metro(?:-[^/]*)?/', // metro, metro-core, metro-source-map, metro-etc
1
Text
Text
remove deploy to now buttons
3fa04620e78bb6ff9ee2368076b004a9a59bfd25
<ide><path>examples/active-class-name/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/active-class-name) <del> <ide> # activeClassName example <ide> <ide> ## How to use <ide><path>examples/amp/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/amp) <del> <ide> # Google AMP <ide> <ide> ## How to use <ide><path>examples/analyze-bundles/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/analyze-bundles) <del> <ide> # Analyzer Bundles example <ide> <ide> ## How to use <ide><path>examples/basic-css/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/basic-css) <del> <ide> # Basic CSS example <ide> <ide> ## How to use <ide><path>examples/basic-export/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/basic-export) <del> <ide> # Basic export example <ide> <ide> ## How to use <ide><path>examples/custom-charset/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/custom-charset) <del> <ide> # Custom server example <ide> <ide> ## How to use <ide><path>examples/custom-server-express/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/custom-server-express) <del> <ide> # Custom Express Server example <ide> <ide> ## How to use <ide><path>examples/custom-server-fastify/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/custom-server-fastify) <del> <ide> # Custom Fastify Server example <ide> <ide> ## How to use <ide><path>examples/custom-server-hapi/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/custom-server-hapi) <del> <ide> # Custom server using Hapi example <ide> <ide> ## How to use <ide><path>examples/custom-server-koa/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/custom-server-koa) <del> <ide> # Custom Koa Server example <ide> <ide> ## How to use <ide><path>examples/custom-server-micro/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/custom-server-micro) <del> <ide> # Custom Micro Server example <ide> <ide> ## How to use <ide><path>examples/custom-server-nodemon/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/custom-server-nodemon) <del> <ide> # Custom server with Nodemon example <ide> <ide> ## How to use <ide><path>examples/custom-server-polka/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/custom-server-polka) <del> <ide> # Custom [Polka](https://github.com/lukeed/polka) Server example <ide> <ide> ## How to use <ide><path>examples/custom-server-typescript/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/custom-server-typescript) <del> <ide> # Custom server with TypeScript + Nodemon example <ide> <ide> ## How to use <ide><path>examples/custom-server/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/custom-server) <del> <ide> # Custom server example <ide> <ide> ## How to use <ide><path>examples/data-fetch/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/data-fetch) <del> <ide> # Data fetch example <ide> <ide> ## How to use <ide><path>examples/form-handler/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/form-handler) <del> <ide> # Form Handler <ide> <ide> ## How to use <ide><path>examples/head-elements/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/head-elements) <del> <ide> # Head elements example <ide> <ide> ## How to use <ide><path>examples/hello-world/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/hello-world) <del> <ide> # Hello World example <ide> <ide> ## How to use <ide><path>examples/layout-component/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/layout-component) <del> <ide> # Layout component example <ide> <ide> ## How to use <ide><path>examples/nested-components/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/nested-components) <del> <ide> # Example app using nested components <ide> <ide> ## How to use <ide><path>examples/only-client-render-external-dependencies/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/only-client-render-external-dependencies) <del> <ide> # Only client render for external dependencies <ide> <ide> ## How to use <ide><path>examples/parameterized-routing/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/parameterized-routing) <del> <ide> # Parametrized routes example (dynamic routing) <ide> <ide> ## How to use <ide><path>examples/pass-server-data/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/pass-server-data) <del> <ide> # Pass Server Data Directly to a Next.js Page during SSR <ide> <ide> ## How to use <ide><path>examples/progressive-render/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/progressive-render) <ide> # Example app implementing progressive server-side render <ide> <ide> ## How to use <ide><path>examples/root-static-files/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/root-static-files) <del> <ide> # Root static files example <ide> <ide> ## How to use <ide><path>examples/shared-modules/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/shared-modules) <ide> # Example app using shared modules <ide> <ide> ## How to use <ide><path>examples/ssr-caching/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/ssr-caching) <del> <ide> # Example app where it caches SSR'ed pages in the memory <ide> <ide> ## How to use <ide><path>examples/svg-components/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/svg-components) <del> <ide> # SVG components example <ide> <ide> ## How to use <ide><path>examples/using-inferno/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/using-inferno) <del> <ide> # Hello World example <ide> <ide> ## How to use <ide><path>examples/using-nerv/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/using-nerv) <del> <ide> # Hello World example <ide> <ide> ## How to use <ide><path>examples/using-preact/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/using-preact) <del> <ide> # Hello World example <ide> <ide> ## How to use <ide><path>examples/using-router/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/using-router) <ide> # Example app utilizing next/router for routing <ide> <ide> ## How to use <ide><path>examples/using-with-router/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/using-with-router) <ide> # Example app utilizing `withRouter` utility for routing <ide> <ide> ## How to use <ide><path>examples/with-algolia-react-instantsearch/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-algolia-react-instantsearch) <del> <ide> # With Algolia React InstantSearch example <ide> <ide> ## How to use <ide><path>examples/with-ant-design-less/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-ant-design-less) <del> <ide> # Ant Design example <ide> <ide> ## How to use <ide><path>examples/with-ant-design/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-ant-design) <del> <ide> # Ant Design example <ide> <ide> ## How to use <ide><path>examples/with-antd-mobile/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-antd-mobile) <ide> # Ant Design Mobile example <ide> <ide> ## How to use <ide><path>examples/with-aphrodite/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-aphrodite) <del> <ide> # Example app with aphrodite <ide> <ide> ## How to use <ide><path>examples/with-apollo-and-redux-saga/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-apollo-and-redux-saga) <ide> # Apollo & Redux Saga Example <ide> <ide> ## How to use <ide><path>examples/with-apollo-and-redux/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-apollo-and-redux) <ide> # Apollo & Redux Example <ide> <ide> ## How to use <ide><path>examples/with-apollo-auth/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-apollo-auth) <ide> # Apollo With Authentication Example <ide> <ide> ## How to use <ide><path>examples/with-apollo/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-apollo) <ide> # Apollo Example <ide> <ide> ## Demo <ide><path>examples/with-app-layout/readme.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-app-layout) <del> <ide> # With `App` layout example <ide> <ide> ## How to use <ide><path>examples/with-astroturf/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-astroturf) <del> <ide> # Example app with [astroturf](https://github.com/4Catalyzer/astroturf) <ide> <ide> ## How to use <ide><path>examples/with-babel-macros/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-babel-macros) <del> <ide> # Example app with [babel-macros](https://github.com/kentcdodds/babel-macros) <ide> <ide> ## How to use <ide><path>examples/with-cerebral/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-cerebral) <del> <ide> # Declarative State & Side-effect management with [CerebralJS](https://cerebraljs.com/) <ide> <ide> ## How to use <ide><path>examples/with-componentdidcatch/readme.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-componentdidcatch) <del> <ide> # With `componentDidCatch` example <ide> <ide> ## How to use <ide><path>examples/with-configured-preset-env/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-configured-preset-env) <del> <ide> # Example preconfigured Babel [preset-env](https://github.com/babel/babel/tree/master/packages/babel-preset-env) <ide> <ide> ## How to use <ide><path>examples/with-context-api/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-context-api) <del> <ide> # Hello World example <ide> <ide> ## How to use <ide><path>examples/with-cookie-auth/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-cookie-auth) <del> <ide> # Example app utilizing cookie-based authentication <ide> <ide> ## How to use <ide><path>examples/with-custom-babel-config/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-custom-babel-config) <del> <ide> # Using a custom Babel config <ide> <ide> ## How to use <ide><path>examples/with-cxs/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-cxs) <del> <ide> # Example app with cxs <ide> <ide> ## How to use <ide><path>examples/with-data-prefetch/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-data-prefetch) <ide> # Example app with prefetching data <ide> <ide> ## How to use <ide><path>examples/with-docker/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-docker&env=API_URL&docker=true) <del> <ide> # With Docker <ide> <ide> ## How to use <ide><path>examples/with-dotenv/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-dotenv) <del> <ide> # With Dotenv example <ide> <ide> ## How to use <ide><path>examples/with-draft-js/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-draft-js) <ide> # DraftJS Medium editor inspiration <ide> <ide> ## How to use <ide><path>examples/with-dynamic-app-layout/readme.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-dynamic-app-layout) <del> <ide> # With dynamic `App` layout example <ide> <ide> ## How to use <ide><path>examples/with-emotion-fiber/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-emotion-fiber) <del> <ide> # Pass Server Data Directly to a Next.js Page during SSR <ide> <ide> ## How to use <ide><path>examples/with-emotion/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-emotion) <del> <ide> # Example app with [emotion](https://github.com/tkh44/emotion) <ide> <ide> ## How to use <ide><path>examples/with-env-from-next-config-js/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-dotenv) <del> <ide> # With env From next.js.config <ide> <ide> ## How to use <ide><path>examples/with-external-styled-jsx-sass/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-external-styled-jsx-sass) <del> <ide> # Example app with next-sass <ide> <ide> ## How to use <ide><path>examples/with-fela/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-fela) <del> <ide> # Example app with Fela <ide> <ide> ## How to use <ide><path>examples/with-firebase-authentication/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-firebase-authentication) <del> <ide> # With Firebase Authentication example <ide> <ide> ## How to use <ide><path>examples/with-firebase-cloud-messaging/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-firebase-cloud-messaging) <del> <ide> ## How to run <ide> <ide> Install it and run: <ide><path>examples/with-flow/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-flow) <ide> # Example app with [Flow](https://flowtype.org/) <ide> <ide> ## How to use <ide><path>examples/with-freactal/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-freactal) <del> <ide> # Freactal example <ide> <ide> ## How to use <ide><path>examples/with-glamor/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-glamor) <del> <ide> # Example app with glamor <ide> <ide> ## How to use <ide><path>examples/with-glamorous/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-glamorous) <del> <ide> # Example app with [glamorous](https://github.com/kentcdodds/glamorous) <ide> <ide> ## How to use <ide><path>examples/with-google-analytics/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-google-analytics) <del> <ide> # Example app with analytics <ide> <ide> ## How to use <ide><path>examples/with-graphql-hooks/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-graphql-hooks) <del> <ide> # GraphQL Hooks Example <ide> <ide> This started life as a copy of the `with-apollo` example. We then stripped out Apollo and replaced it with `graphql-hooks`. This was mostly as an exercise in ensuring basic functionality could be achieved in a similar way to Apollo. The [bundle size](https://bundlephobia.com/[email protected]) of `graphql-hooks` is tiny in comparison to Apollo and should cover a fair amount of use cases. <ide><path>examples/with-graphql-react/README.md <ide> See how it can be used in a Next.js app for GraphQL queries with server side ren <ide> ```sh <ide> npm run dev <ide> ``` <del> <del>## Deploy <del> <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-graphl-react) <ide><path>examples/with-grommet/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-grommet) <del> <ide> # Example app with Grommet <ide> <ide> ## How to use <ide><path>examples/with-higher-order-component/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-higher-order-component) <del> <ide> # Higher Order Component example <ide> <ide> ## How to use <ide><path>examples/with-http2/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-http2) <del> <ide> # HTTP2 server example <ide> <ide> ## How to use <ide><path>examples/with-immutable-redux-wrapper/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-immutable-redux-wrapper) <del> <ide> # Immutable Redux Example <ide> <ide> > This example and documentation is based on the [with-redux](https://github.com/zeit/next.js/tree/master/examples/with-redux) example. <ide><path>examples/with-ioc/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-ioc) <ide> # Dependency Injection (IoC) example ([ioc](https://github.com/alexindigo/ioc)) <ide> <ide> ## How to use <ide><path>examples/with-jest-react-testing-library/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-jest-react-testing-library) <del> <ide> # Example app with React Testing Library and Jest <ide> <ide> ## How to use <ide><path>examples/with-jest/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-jest) <del> <ide> # Example app with Jest tests <ide> <ide> ## How to use <ide><path>examples/with-kea/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-kea) <del> <ide> # kea example <ide> <ide> ## How to use <ide><path>examples/with-linaria/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-linaria) <del> <ide> # Example app with [linaria](https://linaria.now.sh/) <ide> <ide> ## How to use <ide><path>examples/with-lingui/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-lingui) <del> <ide> # With Lingui example <ide> <ide> ## How to use <ide><path>examples/with-loading/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-loading) <ide> # Example app with page loading indicator <ide> <ide> ## How to use <ide><path>examples/with-markdown/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-markdown) <del> <ide> # With Markdown example <ide> <ide> ## How to use <ide><path>examples/with-mdx/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-mdx) <del> <ide> # Example app with MDX <ide> <ide> ## How to use <ide><path>examples/with-mobx-react-lite/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-mobx-react-lite) <del> <ide> # MobX example <ide> <ide> ## How to use <ide><path>examples/with-mobx-state-tree-typescript/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-mobx-state-tree) <del> <ide> # MobX State Tree example <ide> <ide> ## How to use <ide><path>examples/with-mobx-state-tree/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-mobx-state-tree) <del> <ide> # MobX State Tree example <ide> <ide> ## How to use <ide><path>examples/with-mobx/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-mobx) <del> <ide> # MobX example <ide> <ide> ## How to use <ide><path>examples/with-mocha/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-mocha) <del> <ide> # Example app with Mocha tests <ide> <ide> ## How to use <ide><path>examples/with-next-css/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-next-css) <del> <ide> # next-css example <ide> <ide> ## How to use <ide><path>examples/with-next-less/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-next-less) <del> <ide> # Example App with next-less <ide> <ide> ## How to use <ide><path>examples/with-next-page-transitions/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-next-page-transitions) <del> <ide> # next-page-transitions example <ide> <ide> ## How to use <ide><path>examples/with-next-routes/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-next-routes) <ide> # Named routes example ([next-routes](https://github.com/fridays/next-routes)) <ide> <ide> ## How to use <ide><path>examples/with-next-sass/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-next-sass) <del> <ide> # Example app with next-sass <ide> <ide> ## How to use <ide><path>examples/with-next-seo/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-next-seo) <del> <ide> # Next SEO example <ide> <ide> ## How to use <ide><path>examples/with-noscript/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-noscript) <del> <ide> # Noscript example <ide> <ide> ## How to use <ide><path>examples/with-now-env/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-now-env) <del> <ide> # Now-env example <ide> <ide> ## How to use <ide><path>examples/with-office-ui-fabric-react/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-office-ui-fabric-react) <del> <ide> # Office UI Fabric React example <ide> <ide> ## How to use <ide><path>examples/with-orbit-components/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-orbit-components) <del> <ide> # Example app with styled-components <ide> <ide> ## How to use <ide><path>examples/with-overmind/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-overmind) <del> <ide> # Overmind example <ide> <ide> ## How to use <ide><path>examples/with-polyfills/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-polyfills) <del> <ide> # Example app with polyfills <ide> <ide> ## How to use <ide><path>examples/with-prefetching/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-prefetching) <ide> # Example app with prefetching pages <ide> <ide> ## How to use <ide><path>examples/with-pretty-url-routing/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-pretty-url-routing) <del> <ide> # Example app with pretty url routing <ide> <ide> ## How to use <ide><path>examples/with-react-esi/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-react-esi) <ide> # React ESI example <ide> <ide> # Example app with prefetching pages <ide><path>examples/with-react-ga/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-react-ga) <del> <ide> # React-GA example <ide> <ide> ## How to use <ide><path>examples/with-react-helmet/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-react-helmet) <del> <ide> # react-helmet example <ide> <ide> ## How to use <ide><path>examples/with-react-intl/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-react-intl) <ide> # Example app with [React Intl][] <ide> <ide> ## How to use <ide><path>examples/with-react-jss/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-react-jss) <del> <ide> # react-jss example <ide> <ide> ## How to use <ide><path>examples/with-react-md/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-react-md) <del> <ide> # Example app with react-md <ide> <ide> ![Screenshot](https://cloud.githubusercontent.com/assets/304265/22472564/b2e04ff0-e7de-11e6-921e-d0c9833ac805.png) <ide><path>examples/with-react-native-web/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-react-native-web) <del> <ide> ## How to use <ide> <ide> ### Using `create-next-app` <ide><path>examples/with-react-relay-network-modern/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-relay-modern) <del> <ide> # Relay Modern Example <ide> <ide> ## How to use <ide><path>examples/with-react-toolbox/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-react-toolbox) <del> <ide> # With react-toolbox example <ide> <ide> ## How to use <ide><path>examples/with-react-useragent/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-react-useragent) <del> <ide> # react-useragent example <ide> <ide> Show how to setup [@quentin-sommer/react-useragent](https://github.com/quentin-sommer/react-useragent) using next.js client side and server side rendering. <ide><path>examples/with-react-uwp/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-react-uwp) <ide> # React-UWP example <ide> <ide> ## How to use <ide><path>examples/with-react-with-styles/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-react-with-styles) <del> <ide> # Example app with react-with-styles <ide> <ide> ## How to use <ide><path>examples/with-reasonml/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-reasonml) <del> <ide> # Example app using ReasonML & ReasonReact components <ide> <ide> ## How to use <ide><path>examples/with-rebass/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-rebass) <del> <ide> # Example app with Rebass <ide> <ide> ![Screenshot](https://cloud.githubusercontent.com/assets/304265/22472564/b2e04ff0-e7de-11e6-921e-d0c9833ac805.png) <ide><path>examples/with-recompose/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-recompose) <del> <ide> # Recompose example <ide> <ide> ## How to use <ide><path>examples/with-redux-code-splitting/README.md <ide> <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-redux-code-splitting) <del> <ide> # Redux with code splitting example <ide> <ide> ## How to use <ide><path>examples/with-redux-reselect-recompose/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-redux-reselect-recompose) <del> <ide> # Redux with reselect and recompose example <ide> <ide> ## How to use <ide><path>examples/with-redux-saga/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-redux-saga) <del> <ide> # redux-saga example <ide> <ide> > This example and documentation is based on the [with-redux](https://github.com/zeit/next.js/tree/master/examples/with-redux) example. <ide><path>examples/with-redux-thunk/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-redux-thunk) <del> <ide> # Redux Thunk example <ide> <ide> ## How to use <ide><path>examples/with-redux-wrapper/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-redux-wrapper) <del> <ide> # Redux example <ide> <ide> ## How to use <ide><path>examples/with-redux/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-redux) <del> <ide> # Redux example <ide> <ide> ## How to use <ide><path>examples/with-reflux/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-reflux) <del> <ide> # Pass Server Data Directly to a Next.js Page during SSR <ide> <ide> ## How to use <ide><path>examples/with-refnux/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-refnux) <del> <ide> # Refnux example <ide> <ide> ## How to use <ide><path>examples/with-relay-modern-server-express/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-relay-modern) <del> <ide> # Relay Modern Server Express Example <ide> <ide> ## How to use <ide><path>examples/with-relay-modern/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-relay-modern) <del> <ide> # Relay Modern Example <ide> <ide> ## How to use <ide><path>examples/with-rematch/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-rematch) <del> <ide> # Rematch example <ide> <ide> ## How to use <ide><path>examples/with-segment-analytics/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-segment-analytics) <del> <ide> # Example app with analytics <ide> <ide> ## How to use <ide><path>examples/with-semantic-ui/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-semantic-ui) <del> <ide> # Semantic UI example <ide> <ide> ## How to use <ide><path>examples/with-sentry/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-sentry) <del> <ide> # Sentry example <ide> <ide> ## How to use <ide><path>examples/with-shallow-routing/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-shallow-routing) <del> <ide> # Shallow Routing Example <ide> <ide> ## How to use <ide><path>examples/with-sitemap-and-robots-express-server-typescript/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-sitemap-and-robots-typescript) <del> <ide> # Example with sitemap.xml and robots.txt using Express server and typescript <ide> <ide> ## How to use <ide><path>examples/with-sitemap-and-robots-express-server/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-sitemap-and-robots) <del> <ide> # Example with sitemap.xml and robots.txt using Express server <ide> <ide> ## How to use <ide><path>examples/with-slate/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-slate) <del> <ide> # slate.js example <ide> <ide> ## How to use <ide><path>examples/with-socket.io/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-socket.io) <del> <ide> # Socket.io example <ide> <ide> ## How to use <ide><path>examples/with-storybook/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-storybook) <del> <ide> # Example app with Storybook <ide> <ide> ## How to use <ide><path>examples/with-strict-csp-hash/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-strict-csp-hash) <del> <ide> # Example app with strict CSP generating script hash <ide> <ide> ## How to use <ide><path>examples/with-strict-csp/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-strict-csp) <del> <ide> # Strict CSP example <ide> <ide> ## How to use <ide><path>examples/with-style-sheet/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-style-sheet) <del> <ide> # Using the style-sheet CSS in JS library and extract CSS to file. <ide> <ide> ## How to use <ide><path>examples/with-styled-components/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-styled-components) <del> <ide> # Example app with styled-components <ide> <ide> ## How to use <ide><path>examples/with-styled-jsx-plugins/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-styled-jsx-plugins) <del> <ide> # With styled-jsx plugins <ide> <ide> ## How to use <ide><path>examples/with-styled-jsx-scss/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-styled-jsx-scss) <del> <ide> # With styled-jsx SASS / SCSS <ide> <ide> ## How to use <ide><path>examples/with-styletron/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-styletron) <del> <ide> # Example app with styletron <ide> <ide> ## How to use <ide><path>examples/with-sw-precache/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-sw-precache) <del> <ide> # sw-precache example <ide> <ide> ## How to use <ide><path>examples/with-tailwindcss/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-tailwindcss) <del> <ide> # Tailwind CSS example <ide> <ide> This is an example of how you can include a global stylesheet in a next.js webapp. <ide><path>examples/with-ts-node/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-ts-node) <del> <ide> # Custom server with fully TypeScript + ts-node example (without babel and tsc), require next js 7+ <ide> <ide> ## How to use <ide><path>examples/with-typescript-styled-components/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-typescript-styled-components) <del> <ide> # TypeScript & Styled Components Next.js example <ide> <ide> This is a really simple project that show the usage of Next.js with TypeScript and Styled Components. <ide><path>examples/with-typescript/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-typescript) <del> <ide> # TypeScript Next.js example <ide> <ide> This is a really simple project that show the usage of Next.js with TypeScript. <ide><path>examples/with-typestyle/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-typestyle) <del> <ide> # Example app with typestyle <ide> <ide> ## How to use <ide><path>examples/with-typings-for-css-modules/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-typings-for-css-modules) <del> <ide> # Typings for CSS Modules example <ide> <ide> ## How to use <ide><path>examples/with-universal-configuration-build-time/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-universal-configuration-build-time) <del> <ide> # With universal configuration <ide> <ide> ## How to use <ide><path>examples/with-universal-configuration-runtime/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-universal-configuration-runtime) <del> <ide> # With universal runtime configuration <ide> <ide> ## How to use <ide><path>examples/with-unstated/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/canary/examples/with-unstated) <del> <ide> # Unstated example <ide> <ide> ## How to use <ide><path>examples/with-url-object-routing/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-url-object-routing) <ide> # URL object routing <ide> <ide> ## How to use <ide><path>examples/with-videojs/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-videojs) <del> <ide> # video.js example <ide> <ide> ## How to use <ide><path>examples/with-webassembly/readme.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-webassembly) <del> <ide> # WebAssembly example <ide> <ide> ## How to use <ide><path>examples/with-webpack-bundle-size-analyzer/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-webpack-bundle-size-analyzer) <del> <ide> # Webpack Bundle Size Analyzer <ide> <ide> ## How to use <ide><path>examples/with-yarn-workspaces/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-yarn-workspaces) <del> <ide> # Yarn workspaces example <ide> <ide> ## How to use <ide><path>examples/with-zones/README.md <del>[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-zones) <del> <ide> # Using multiple zones <ide> <ide> ## How to use
162
Javascript
Javascript
move all animation parsing to animation parser
9a970e016f5066dbb2ef79db1962888ad2a992ce
<ide><path>examples/js/loaders/FBXLoader.js <ide> THREE.FBXLoader = ( function () { <ide> <ide> }, <ide> <del> <ide> // create the main THREE.Group() to be returned by the loader <ide> parseScene: function ( deformers, geometryMap, materialMap ) { <ide> <ide> THREE.FBXLoader = ( function () { <ide> } ); <ide> <ide> this.bindSkeleton( deformers.skeletons, geometryMap, modelMap ); <del> this.addAnimations( sceneGraph ); <ide> <ide> this.createAmbientLight( sceneGraph ); <ide> <ide> this.setupMorphMaterials( sceneGraph ); <ide> <add> var animations = new AnimationParser().parse( sceneGraph ); <add> <ide> // if all the models where already combined in a single group, just return that <ide> if ( sceneGraph.children.length === 1 && sceneGraph.children[ 0 ].isGroup ) { <ide> <del> sceneGraph.children[ 0 ].animations = sceneGraph.animations; <add> sceneGraph.children[ 0 ].animations = animations; <ide> return sceneGraph.children[ 0 ]; <ide> <ide> } <ide> <add> sceneGraph.animations = animations; <add> <ide> return sceneGraph; <ide> <ide> }, <ide> THREE.FBXLoader = ( function () { <ide> <ide> }, <ide> <del> // take raw animation clips and turn them into three.js animation clips <del> addAnimations: function ( sceneGraph ) { <del> <del> sceneGraph.animations = []; <del> <del> var rawClips = new AnimationParser( connections ).parse(); <add> // Parse ambient color in FBXTree.GlobalSettings - if it's not set to black (default), create an ambient light <add> createAmbientLight: function ( sceneGraph ) { <ide> <del> if ( rawClips === undefined ) return; <add> if ( 'GlobalSettings' in FBXTree && 'AmbientColor' in FBXTree.GlobalSettings ) { <ide> <del> for ( var key in rawClips ) { <add> var ambientColor = FBXTree.GlobalSettings.AmbientColor.value; <add> var r = ambientColor[ 0 ]; <add> var g = ambientColor[ 1 ]; <add> var b = ambientColor[ 2 ]; <ide> <del> var rawClip = rawClips[ key ]; <add> if ( r !== 0 || g !== 0 || b !== 0 ) { <ide> <del> var clip = this.addClip( rawClip, sceneGraph ); <add> var color = new THREE.Color( r, g, b ); <add> sceneGraph.add( new THREE.AmbientLight( color, 1 ) ); <ide> <del> sceneGraph.animations.push( clip ); <add> } <ide> <ide> } <ide> <ide> }, <ide> <del> addClip: function ( rawClip, sceneGraph ) { <del> <del> var tracks = []; <add> setupMorphMaterials: function ( sceneGraph ) { <ide> <del> var self = this; <del> rawClip.layer.forEach( function ( rawTracks ) { <add> sceneGraph.traverse( function ( child ) { <ide> <del> tracks = tracks.concat( self.generateTracks( rawTracks, sceneGraph ) ); <add> if ( child.isMesh ) { <ide> <del> } ); <add> if ( child.geometry.morphAttributes.position || child.geometry.morphAttributes.normal ) { <ide> <del> return new THREE.AnimationClip( rawClip.name, - 1, tracks ); <add> var uuid = child.uuid; <add> var matUuid = child.material.uuid; <ide> <del> }, <add> // if a geometry has morph targets, it cannot share the material with other geometries <add> var sharedMat = false; <ide> <del> generateTracks: function ( rawTracks, sceneGraph ) { <add> sceneGraph.traverse( function ( child ) { <ide> <del> var tracks = []; <add> if ( child.isMesh ) { <ide> <del> var initialPosition = new THREE.Vector3(); <del> var initialRotation = new THREE.Quaternion(); <del> var initialScale = new THREE.Vector3(); <add> if ( child.material.uuid === matUuid && child.uuid !== uuid ) sharedMat = true; <ide> <del> if ( rawTracks.transform ) rawTracks.transform.decompose( initialPosition, initialRotation, initialScale ); <add> } <ide> <del> initialPosition = initialPosition.toArray(); <del> initialRotation = new THREE.Euler().setFromQuaternion( initialRotation ).toArray(); // todo: euler order <del> initialScale = initialScale.toArray(); <add> } ); <ide> <del> if ( rawTracks.T !== undefined && Object.keys( rawTracks.T.curves ).length > 0 ) { <add> if ( sharedMat === true ) child.material = child.material.clone(); <ide> <del> var positionTrack = this.generateVectorTrack( rawTracks.modelName, rawTracks.T.curves, initialPosition, 'position' ); <del> if ( positionTrack !== undefined ) tracks.push( positionTrack ); <add> child.material.morphTargets = true; <ide> <del> } <add> } <ide> <del> if ( rawTracks.R !== undefined && Object.keys( rawTracks.R.curves ).length > 0 ) { <add> } <ide> <del> var rotationTrack = this.generateRotationTrack( rawTracks.modelName, rawTracks.R.curves, initialRotation, rawTracks.preRotations, rawTracks.postRotations ); <del> if ( rotationTrack !== undefined ) tracks.push( rotationTrack ); <add> } ); <ide> <del> } <add> }, <ide> <del> if ( rawTracks.S !== undefined && Object.keys( rawTracks.S.curves ).length > 0 ) { <add> }; <ide> <del> var scaleTrack = this.generateVectorTrack( rawTracks.modelName, rawTracks.S.curves, initialScale, 'scale' ); <del> if ( scaleTrack !== undefined ) tracks.push( scaleTrack ); <add> // parse Geometry data from FBXTree and return map of BufferGeometries <add> function GeometryParser() {} <ide> <del> } <add> GeometryParser.prototype = { <ide> <del> if ( rawTracks.DeformPercent !== undefined ) { <add> constructor: GeometryParser, <ide> <del> var morphTrack = this.generateMorphTrack( rawTracks, sceneGraph ); <del> if ( morphTrack !== undefined ) tracks.push( morphTrack ); <add> // Parse nodes in FBXTree.Objects.Geometry <add> parse: function ( deformers ) { <ide> <del> } <add> var geometryMap = new Map(); <ide> <del> return tracks; <add> if ( 'Geometry' in FBXTree.Objects ) { <ide> <del> }, <add> var geoNodes = FBXTree.Objects.Geometry; <ide> <del> generateVectorTrack: function ( modelName, curves, initialValue, type ) { <add> for ( var nodeID in geoNodes ) { <ide> <del> var times = this.getTimesForAllAxes( curves ); <del> var values = this.getKeyframeTrackValues( times, curves, initialValue ); <add> var relationships = connections.get( parseInt( nodeID ) ); <add> var geo = this.parseGeometry( relationships, geoNodes[ nodeID ], deformers ); <ide> <del> return new THREE.VectorKeyframeTrack( modelName + '.' + type, times, values ); <add> geometryMap.set( parseInt( nodeID ), geo ); <ide> <del> }, <add> } <ide> <del> generateRotationTrack: function ( modelName, curves, initialValue, preRotations, postRotations ) { <add> } <ide> <del> if ( curves.x !== undefined ) { <add> return geometryMap; <ide> <del> this.interpolateRotations( curves.x ); <del> curves.x.values = curves.x.values.map( THREE.Math.degToRad ); <add> }, <ide> <del> } <del> if ( curves.y !== undefined ) { <add> // Parse single node in FBXTree.Objects.Geometry <add> parseGeometry: function ( relationships, geoNode, deformers ) { <ide> <del> this.interpolateRotations( curves.y ); <del> curves.y.values = curves.y.values.map( THREE.Math.degToRad ); <add> switch ( geoNode.attrType ) { <ide> <del> } <del> if ( curves.z !== undefined ) { <add> case 'Mesh': <add> return this.parseMeshGeometry( relationships, geoNode, deformers ); <add> break; <ide> <del> this.interpolateRotations( curves.z ); <del> curves.z.values = curves.z.values.map( THREE.Math.degToRad ); <add> case 'NurbsCurve': <add> return this.parseNurbsGeometry( geoNode ); <add> break; <ide> <ide> } <ide> <del> var times = this.getTimesForAllAxes( curves ); <del> var values = this.getKeyframeTrackValues( times, curves, initialValue ); <del> <del> if ( preRotations !== undefined ) { <add> }, <ide> <del> preRotations = preRotations.map( THREE.Math.degToRad ); <del> preRotations.push( 'ZYX' ); <add> // Parse single node mesh geometry in FBXTree.Objects.Geometry <add> parseMeshGeometry: function ( relationships, geoNode, deformers ) { <ide> <del> preRotations = new THREE.Euler().fromArray( preRotations ); <del> preRotations = new THREE.Quaternion().setFromEuler( preRotations ); <add> var skeletons = deformers.skeletons; <add> var morphTargets = deformers.morphTargets; <ide> <del> } <add> var modelNodes = relationships.parents.map( function ( parent ) { <ide> <del> if ( postRotations !== undefined ) { <add> return FBXTree.Objects.Model[ parent.ID ]; <ide> <del> postRotations = postRotations.map( THREE.Math.degToRad ); <del> postRotations.push( 'ZYX' ); <add> } ); <ide> <del> postRotations = new THREE.Euler().fromArray( postRotations ); <del> postRotations = new THREE.Quaternion().setFromEuler( postRotations ).inverse(); <add> // don't create geometry if it is not associated with any models <add> if ( modelNodes.length === 0 ) return; <ide> <del> } <add> var skeleton = relationships.children.reduce( function ( skeleton, child ) { <ide> <del> var quaternion = new THREE.Quaternion(); <del> var euler = new THREE.Euler(); <add> if ( skeletons[ child.ID ] !== undefined ) skeleton = skeletons[ child.ID ]; <ide> <del> var quaternionValues = []; <add> return skeleton; <ide> <del> for ( var i = 0; i < values.length; i += 3 ) { <add> }, null ); <ide> <del> euler.set( values[ i ], values[ i + 1 ], values[ i + 2 ], 'ZYX' ); <add> var morphTarget = relationships.children.reduce( function ( morphTarget, child ) { <ide> <del> quaternion.setFromEuler( euler ); <add> if ( morphTargets[ child.ID ] !== undefined ) morphTarget = morphTargets[ child.ID ]; <ide> <del> if ( preRotations !== undefined ) quaternion.premultiply( preRotations ); <del> if ( postRotations !== undefined ) quaternion.multiply( postRotations ); <add> return morphTarget; <ide> <del> quaternion.toArray( quaternionValues, ( i / 3 ) * 4 ); <add> }, null ); <ide> <del> } <add> // TODO: if there is more than one model associated with the geometry, AND the models have <add> // different geometric transforms, then this will cause problems <add> // if ( modelNodes.length > 1 ) { } <ide> <del> return new THREE.QuaternionKeyframeTrack( modelName + '.quaternion', times, quaternionValues ); <add> // For now just assume one model and get the preRotations from that <add> var modelNode = modelNodes[ 0 ]; <ide> <del> }, <add> var transformData = {}; <ide> <del> generateMorphTrack: function ( rawTracks, sceneGraph ) { <add> if ( 'RotationOrder' in modelNode ) transformData.eulerOrder = modelNode.RotationOrder.value; <add> if ( 'GeometricTranslation' in modelNode ) transformData.translation = modelNode.GeometricTranslation.value; <add> if ( 'GeometricRotation' in modelNode ) transformData.rotation = modelNode.GeometricRotation.value; <add> if ( 'GeometricScaling' in modelNode ) transformData.scale = modelNode.GeometricScaling.value; <ide> <del> var curves = rawTracks.DeformPercent.curves.morph; <del> var values = curves.values.map( function ( val ) { <add> var transform = generateTransform( transformData ); <ide> <del> return val / 100; <add> return this.genGeometry( geoNode, skeleton, morphTarget, transform ); <ide> <del> } ); <add> }, <ide> <del> var morphNum = sceneGraph.getObjectByName( rawTracks.modelName ).morphTargetDictionary[ rawTracks.morphName ]; <add> // Generate a THREE.BufferGeometry from a node in FBXTree.Objects.Geometry <add> genGeometry: function ( geoNode, skeleton, morphTarget, preTransform ) { <ide> <del> return new THREE.NumberKeyframeTrack( rawTracks.modelName + '.morphTargetInfluences[' + morphNum + ']', curves.times, values ); <add> var geo = new THREE.BufferGeometry(); <add> if ( geoNode.attrName ) geo.name = geoNode.attrName; <ide> <del> }, <add> var geoInfo = this.parseGeoNode( geoNode, skeleton ); <add> var buffers = this.genBuffers( geoInfo ); <ide> <del> // For all animated objects, times are defined separately for each axis <del> // Here we'll combine the times into one sorted array without duplicates <del> getTimesForAllAxes: function ( curves ) { <add> var positionAttribute = new THREE.Float32BufferAttribute( buffers.vertex, 3 ); <ide> <del> var times = []; <add> preTransform.applyToBufferAttribute( positionAttribute ); <ide> <del> // first join together the times for each axis, if defined <del> if ( curves.x !== undefined ) times = times.concat( curves.x.times ); <del> if ( curves.y !== undefined ) times = times.concat( curves.y.times ); <del> if ( curves.z !== undefined ) times = times.concat( curves.z.times ); <add> geo.addAttribute( 'position', positionAttribute ); <ide> <del> // then sort them and remove duplicates <del> times = times.sort( function ( a, b ) { <add> if ( buffers.colors.length > 0 ) { <ide> <del> return a - b; <add> geo.addAttribute( 'color', new THREE.Float32BufferAttribute( buffers.colors, 3 ) ); <ide> <del> } ).filter( function ( elem, index, array ) { <add> } <ide> <del> return array.indexOf( elem ) == index; <add> if ( skeleton ) { <ide> <del> } ); <add> geo.addAttribute( 'skinIndex', new THREE.Uint16BufferAttribute( buffers.weightsIndices, 4 ) ); <ide> <del> return times; <add> geo.addAttribute( 'skinWeight', new THREE.Float32BufferAttribute( buffers.vertexWeights, 4 ) ); <ide> <del> }, <add> // used later to bind the skeleton to the model <add> geo.FBX_Deformer = skeleton; <ide> <del> getKeyframeTrackValues: function ( times, curves, initialValue ) { <add> } <ide> <del> var prevValue = initialValue; <add> if ( buffers.normal.length > 0 ) { <ide> <del> var values = []; <add> var normalAttribute = new THREE.Float32BufferAttribute( buffers.normal, 3 ); <ide> <del> var xIndex = - 1; <del> var yIndex = - 1; <del> var zIndex = - 1; <add> var normalMatrix = new THREE.Matrix3().getNormalMatrix( preTransform ); <add> normalMatrix.applyToBufferAttribute( normalAttribute ); <ide> <del> times.forEach( function ( time ) { <add> geo.addAttribute( 'normal', normalAttribute ); <ide> <del> if ( curves.x ) xIndex = curves.x.times.indexOf( time ); <del> if ( curves.y ) yIndex = curves.y.times.indexOf( time ); <del> if ( curves.z ) zIndex = curves.z.times.indexOf( time ); <add> } <ide> <del> // if there is an x value defined for this frame, use that <del> if ( xIndex !== - 1 ) { <add> buffers.uvs.forEach( function ( uvBuffer, i ) { <ide> <del> var xValue = curves.x.values[ xIndex ]; <del> values.push( xValue ); <del> prevValue[ 0 ] = xValue; <add> // subsequent uv buffers are called 'uv1', 'uv2', ... <add> var name = 'uv' + ( i + 1 ).toString(); <ide> <del> } else { <add> // the first uv buffer is just called 'uv' <add> if ( i === 0 ) { <ide> <del> // otherwise use the x value from the previous frame <del> values.push( prevValue[ 0 ] ); <add> name = 'uv'; <ide> <ide> } <ide> <del> if ( yIndex !== - 1 ) { <add> geo.addAttribute( name, new THREE.Float32BufferAttribute( buffers.uvs[ i ], 2 ) ); <ide> <del> var yValue = curves.y.values[ yIndex ]; <del> values.push( yValue ); <del> prevValue[ 1 ] = yValue; <add> } ); <ide> <del> } else { <add> if ( geoInfo.material && geoInfo.material.mappingType !== 'AllSame' ) { <ide> <del> values.push( prevValue[ 1 ] ); <add> // Convert the material indices of each vertex into rendering groups on the geometry. <add> var prevMaterialIndex = buffers.materialIndex[ 0 ]; <add> var startIndex = 0; <ide> <del> } <add> buffers.materialIndex.forEach( function ( currentIndex, i ) { <ide> <del> if ( zIndex !== - 1 ) { <add> if ( currentIndex !== prevMaterialIndex ) { <ide> <del> var zValue = curves.z.values[ zIndex ]; <del> values.push( zValue ); <del> prevValue[ 2 ] = zValue; <add> geo.addGroup( startIndex, i - startIndex, prevMaterialIndex ); <ide> <del> } else { <add> prevMaterialIndex = currentIndex; <add> startIndex = i; <ide> <del> values.push( prevValue[ 2 ] ); <add> } <ide> <del> } <add> } ); <ide> <del> } ); <add> // the loop above doesn't add the last group, do that here. <add> if ( geo.groups.length > 0 ) { <ide> <del> return values; <add> var lastGroup = geo.groups[ geo.groups.length - 1 ]; <add> var lastIndex = lastGroup.start + lastGroup.count; <ide> <del> }, <add> if ( lastIndex !== buffers.materialIndex.length ) { <ide> <del> // Rotations are defined as Euler angles which can have values of any size <del> // These will be converted to quaternions which don't support values greater than <del> // PI, so we'll interpolate large rotations <del> interpolateRotations: function ( curve ) { <add> geo.addGroup( lastIndex, buffers.materialIndex.length - lastIndex, prevMaterialIndex ); <ide> <del> for ( var i = 1; i < curve.values.length; i ++ ) { <add> } <ide> <del> var initialValue = curve.values[ i - 1 ]; <del> var valuesSpan = curve.values[ i ] - initialValue; <add> } <ide> <del> var absoluteSpan = Math.abs( valuesSpan ); <add> // case where there are multiple materials but the whole geometry is only <add> // using one of them <add> if ( geo.groups.length === 0 ) { <ide> <del> if ( absoluteSpan >= 180 ) { <add> geo.addGroup( 0, buffers.materialIndex.length, buffers.materialIndex[ 0 ] ); <ide> <del> var numSubIntervals = absoluteSpan / 180; <add> } <ide> <del> var step = valuesSpan / numSubIntervals; <del> var nextValue = initialValue + step; <add> } <ide> <del> var initialTime = curve.times[ i - 1 ]; <del> var timeSpan = curve.times[ i ] - initialTime; <del> var interval = timeSpan / numSubIntervals; <del> var nextTime = initialTime + interval; <add> this.addMorphTargets( geo, geoNode, morphTarget, preTransform ); <ide> <del> var interpolatedTimes = []; <del> var interpolatedValues = []; <add> return geo; <ide> <del> while ( nextTime < curve.times[ i ] ) { <add> }, <ide> <del> interpolatedTimes.push( nextTime ); <del> nextTime += interval; <add> parseGeoNode: function ( geoNode, skeleton ) { <ide> <del> interpolatedValues.push( nextValue ); <del> nextValue += step; <add> var geoInfo = {}; <ide> <del> } <add> geoInfo.vertexPositions = ( geoNode.Vertices !== undefined ) ? geoNode.Vertices.a : []; <add> geoInfo.vertexIndices = ( geoNode.PolygonVertexIndex !== undefined ) ? geoNode.PolygonVertexIndex.a : []; <ide> <del> curve.times = inject( curve.times, i, interpolatedTimes ); <del> curve.values = inject( curve.values, i, interpolatedValues ); <add> if ( geoNode.LayerElementColor ) { <ide> <del> } <add> geoInfo.color = this.parseVertexColors( geoNode.LayerElementColor[ 0 ] ); <ide> <ide> } <ide> <del> }, <add> if ( geoNode.LayerElementMaterial ) { <ide> <del> // Parse ambient color in FBXTree.GlobalSettings - if it's not set to black (default), create an ambient light <del> createAmbientLight: function ( sceneGraph ) { <add> geoInfo.material = this.parseMaterialIndices( geoNode.LayerElementMaterial[ 0 ] ); <ide> <del> if ( 'GlobalSettings' in FBXTree && 'AmbientColor' in FBXTree.GlobalSettings ) { <add> } <ide> <del> var ambientColor = FBXTree.GlobalSettings.AmbientColor.value; <del> var r = ambientColor[ 0 ]; <del> var g = ambientColor[ 1 ]; <del> var b = ambientColor[ 2 ]; <add> if ( geoNode.LayerElementNormal ) { <ide> <del> if ( r !== 0 || g !== 0 || b !== 0 ) { <add> geoInfo.normal = this.parseNormals( geoNode.LayerElementNormal[ 0 ] ); <ide> <del> var color = new THREE.Color( r, g, b ); <del> sceneGraph.add( new THREE.AmbientLight( color, 1 ) ); <add> } <ide> <del> } <add> if ( geoNode.LayerElementUV ) { <ide> <del> } <add> geoInfo.uv = []; <ide> <del> }, <add> var i = 0; <add> while ( geoNode.LayerElementUV[ i ] ) { <ide> <del> setupMorphMaterials: function ( sceneGraph ) { <add> geoInfo.uv.push( this.parseUVs( geoNode.LayerElementUV[ i ] ) ); <add> i ++; <ide> <del> sceneGraph.traverse( function ( child ) { <add> } <ide> <del> if ( child.isMesh ) { <add> } <ide> <del> if ( child.geometry.morphAttributes.position || child.geometry.morphAttributes.normal ) { <add> geoInfo.weightTable = {}; <ide> <del> var uuid = child.uuid; <del> var matUuid = child.material.uuid; <add> if ( skeleton !== null ) { <ide> <del> // if a geometry has morph targets, it cannot share the material with other geometries <del> var sharedMat = false; <add> geoInfo.skeleton = skeleton; <ide> <del> sceneGraph.traverse( function ( child ) { <add> skeleton.rawBones.forEach( function ( rawBone, i ) { <ide> <del> if ( child.isMesh ) { <add> // loop over the bone's vertex indices and weights <add> rawBone.indices.forEach( function ( index, j ) { <ide> <del> if ( child.material.uuid === matUuid && child.uuid !== uuid ) sharedMat = true; <add> if ( geoInfo.weightTable[ index ] === undefined ) geoInfo.weightTable[ index ] = []; <ide> <del> } <add> geoInfo.weightTable[ index ].push( { <ide> <del> } ); <add> id: i, <add> weight: rawBone.weights[ j ], <ide> <del> if ( sharedMat === true ) child.material = child.material.clone(); <add> } ); <ide> <del> child.material.morphTargets = true; <add> } ); <ide> <del> } <add> } ); <ide> <del> } <add> } <ide> <del> } ); <add> return geoInfo; <ide> <ide> }, <ide> <del> }; <add> genBuffers: function ( geoInfo ) { <ide> <del> // parse Geometry data from FBXTree and return map of BufferGeometries and nurbs curves <del> function GeometryParser() {} <add> var buffers = { <add> vertex: [], <add> normal: [], <add> colors: [], <add> uvs: [], <add> materialIndex: [], <add> vertexWeights: [], <add> weightsIndices: [], <add> }; <ide> <del> GeometryParser.prototype = { <add> var polygonIndex = 0; <add> var faceLength = 0; <add> var displayedWeightsWarning = false; <ide> <del> constructor: GeometryParser, <add> // these will hold data for a single face <add> var facePositionIndexes = []; <add> var faceNormals = []; <add> var faceColors = []; <add> var faceUVs = []; <add> var faceWeights = []; <add> var faceWeightIndices = []; <ide> <del> // Parse nodes in FBXTree.Objects.Geometry <del> parse: function ( deformers ) { <add> var self = this; <add> geoInfo.vertexIndices.forEach( function ( vertexIndex, polygonVertexIndex ) { <ide> <del> var geometryMap = new Map(); <add> var endOfFace = false; <ide> <del> if ( 'Geometry' in FBXTree.Objects ) { <add> // Face index and vertex index arrays are combined in a single array <add> // A cube with quad faces looks like this: <add> // PolygonVertexIndex: *24 { <add> // a: 0, 1, 3, -3, 2, 3, 5, -5, 4, 5, 7, -7, 6, 7, 1, -1, 1, 7, 5, -4, 6, 0, 2, -5 <add> // } <add> // Negative numbers mark the end of a face - first face here is 0, 1, 3, -3 <add> // to find index of last vertex bit shift the index: ^ - 1 <add> if ( vertexIndex < 0 ) { <ide> <del> var geoNodes = FBXTree.Objects.Geometry; <add> vertexIndex = vertexIndex ^ - 1; // equivalent to ( x * -1 ) - 1 <add> endOfFace = true; <ide> <del> for ( var nodeID in geoNodes ) { <add> } <ide> <del> var relationships = connections.get( parseInt( nodeID ) ); <del> var geo = this.parseGeometry( relationships, geoNodes[ nodeID ], deformers ); <add> var weightIndices = []; <add> var weights = []; <ide> <del> geometryMap.set( parseInt( nodeID ), geo ); <add> facePositionIndexes.push( vertexIndex * 3, vertexIndex * 3 + 1, vertexIndex * 3 + 2 ); <ide> <del> } <add> if ( geoInfo.color ) { <ide> <del> } <add> var data = getData( polygonVertexIndex, polygonIndex, vertexIndex, geoInfo.color ); <ide> <del> return geometryMap; <add> faceColors.push( data[ 0 ], data[ 1 ], data[ 2 ] ); <ide> <del> }, <add> } <ide> <del> // Parse single node in FBXTree.Objects.Geometry <del> parseGeometry: function ( relationships, geoNode, deformers ) { <add> if ( geoInfo.skeleton ) { <ide> <del> switch ( geoNode.attrType ) { <add> if ( geoInfo.weightTable[ vertexIndex ] !== undefined ) { <ide> <del> case 'Mesh': <del> return this.parseMeshGeometry( relationships, geoNode, deformers ); <del> break; <add> geoInfo.weightTable[ vertexIndex ].forEach( function ( wt ) { <ide> <del> case 'NurbsCurve': <del> return this.parseNurbsGeometry( geoNode ); <del> break; <add> weights.push( wt.weight ); <add> weightIndices.push( wt.id ); <ide> <del> } <add> } ); <ide> <del> }, <ide> <del> // Parse single node mesh geometry in FBXTree.Objects.Geometry <del> parseMeshGeometry: function ( relationships, geoNode, deformers ) { <add> } <ide> <del> var skeletons = deformers.skeletons; <del> var morphTargets = deformers.morphTargets; <add> if ( weights.length > 4 ) { <ide> <del> var modelNodes = relationships.parents.map( function ( parent ) { <add> if ( ! displayedWeightsWarning ) { <ide> <del> return FBXTree.Objects.Model[ parent.ID ]; <add> console.warn( 'THREE.FBXLoader: Vertex has more than 4 skinning weights assigned to vertex. Deleting additional weights.' ); <add> displayedWeightsWarning = true; <ide> <del> } ); <add> } <ide> <del> // don't create geometry if it is not associated with any models <del> if ( modelNodes.length === 0 ) return; <add> var wIndex = [ 0, 0, 0, 0 ]; <add> var Weight = [ 0, 0, 0, 0 ]; <ide> <del> var skeleton = relationships.children.reduce( function ( skeleton, child ) { <add> weights.forEach( function ( weight, weightIndex ) { <ide> <del> if ( skeletons[ child.ID ] !== undefined ) skeleton = skeletons[ child.ID ]; <add> var currentWeight = weight; <add> var currentIndex = weightIndices[ weightIndex ]; <ide> <del> return skeleton; <add> Weight.forEach( function ( comparedWeight, comparedWeightIndex, comparedWeightArray ) { <ide> <del> }, null ); <add> if ( currentWeight > comparedWeight ) { <ide> <del> var morphTarget = relationships.children.reduce( function ( morphTarget, child ) { <add> comparedWeightArray[ comparedWeightIndex ] = currentWeight; <add> currentWeight = comparedWeight; <ide> <del> if ( morphTargets[ child.ID ] !== undefined ) morphTarget = morphTargets[ child.ID ]; <add> var tmp = wIndex[ comparedWeightIndex ]; <add> wIndex[ comparedWeightIndex ] = currentIndex; <add> currentIndex = tmp; <ide> <del> return morphTarget; <add> } <ide> <del> }, null ); <add> } ); <ide> <del> // TODO: if there is more than one model associated with the geometry, AND the models have <del> // different geometric transforms, then this will cause problems <del> // if ( modelNodes.length > 1 ) { } <add> } ); <ide> <del> // For now just assume one model and get the preRotations from that <del> var modelNode = modelNodes[ 0 ]; <add> weightIndices = wIndex; <add> weights = Weight; <ide> <del> var transformData = {}; <add> } <ide> <del> if ( 'RotationOrder' in modelNode ) transformData.eulerOrder = modelNode.RotationOrder.value; <del> if ( 'GeometricTranslation' in modelNode ) transformData.translation = modelNode.GeometricTranslation.value; <del> if ( 'GeometricRotation' in modelNode ) transformData.rotation = modelNode.GeometricRotation.value; <del> if ( 'GeometricScaling' in modelNode ) transformData.scale = modelNode.GeometricScaling.value; <add> // if the weight array is shorter than 4 pad with 0s <add> while ( weights.length < 4 ) { <ide> <del> var transform = generateTransform( transformData ); <add> weights.push( 0 ); <add> weightIndices.push( 0 ); <ide> <del> return this.genGeometry( geoNode, skeleton, morphTarget, transform ); <add> } <ide> <del> }, <add> for ( var i = 0; i < 4; ++ i ) { <ide> <del> // Generate a THREE.BufferGeometry from a node in FBXTree.Objects.Geometry <del> genGeometry: function ( geoNode, skeleton, morphTarget, preTransform ) { <add> faceWeights.push( weights[ i ] ); <add> faceWeightIndices.push( weightIndices[ i ] ); <ide> <del> var geo = new THREE.BufferGeometry(); <del> if ( geoNode.attrName ) geo.name = geoNode.attrName; <add> } <ide> <del> var geoInfo = this.parseGeoNode( geoNode, skeleton ); <del> var buffers = this.genBuffers( geoInfo ); <add> } <ide> <del> var positionAttribute = new THREE.Float32BufferAttribute( buffers.vertex, 3 ); <add> if ( geoInfo.normal ) { <ide> <del> preTransform.applyToBufferAttribute( positionAttribute ); <add> var data = getData( polygonVertexIndex, polygonIndex, vertexIndex, geoInfo.normal ); <ide> <del> geo.addAttribute( 'position', positionAttribute ); <add> faceNormals.push( data[ 0 ], data[ 1 ], data[ 2 ] ); <ide> <del> if ( buffers.colors.length > 0 ) { <add> } <ide> <del> geo.addAttribute( 'color', new THREE.Float32BufferAttribute( buffers.colors, 3 ) ); <add> if ( geoInfo.material && geoInfo.material.mappingType !== 'AllSame' ) { <ide> <del> } <add> var materialIndex = getData( polygonVertexIndex, polygonIndex, vertexIndex, geoInfo.material )[ 0 ]; <ide> <del> if ( skeleton ) { <add> } <ide> <del> geo.addAttribute( 'skinIndex', new THREE.Uint16BufferAttribute( buffers.weightsIndices, 4 ) ); <add> if ( geoInfo.uv ) { <ide> <del> geo.addAttribute( 'skinWeight', new THREE.Float32BufferAttribute( buffers.vertexWeights, 4 ) ); <add> geoInfo.uv.forEach( function ( uv, i ) { <ide> <del> // used later to bind the skeleton to the model <del> geo.FBX_Deformer = skeleton; <add> var data = getData( polygonVertexIndex, polygonIndex, vertexIndex, uv ); <ide> <del> } <add> if ( faceUVs[ i ] === undefined ) { <ide> <del> if ( buffers.normal.length > 0 ) { <add> faceUVs[ i ] = []; <ide> <del> var normalAttribute = new THREE.Float32BufferAttribute( buffers.normal, 3 ); <add> } <ide> <del> var normalMatrix = new THREE.Matrix3().getNormalMatrix( preTransform ); <del> normalMatrix.applyToBufferAttribute( normalAttribute ); <add> faceUVs[ i ].push( data[ 0 ] ); <add> faceUVs[ i ].push( data[ 1 ] ); <ide> <del> geo.addAttribute( 'normal', normalAttribute ); <add> } ); <ide> <del> } <add> } <ide> <del> buffers.uvs.forEach( function ( uvBuffer, i ) { <add> faceLength ++; <ide> <del> // subsequent uv buffers are called 'uv1', 'uv2', ... <del> var name = 'uv' + ( i + 1 ).toString(); <add> if ( endOfFace ) { <ide> <del> // the first uv buffer is just called 'uv' <del> if ( i === 0 ) { <add> self.genFace( buffers, geoInfo, facePositionIndexes, materialIndex, faceNormals, faceColors, faceUVs, faceWeights, faceWeightIndices, faceLength ); <ide> <del> name = 'uv'; <add> polygonIndex ++; <add> faceLength = 0; <ide> <del> } <add> // reset arrays for the next face <add> facePositionIndexes = []; <add> faceNormals = []; <add> faceColors = []; <add> faceUVs = []; <add> faceWeights = []; <add> faceWeightIndices = []; <ide> <del> geo.addAttribute( name, new THREE.Float32BufferAttribute( buffers.uvs[ i ], 2 ) ); <add> } <ide> <ide> } ); <ide> <del> if ( geoInfo.material && geoInfo.material.mappingType !== 'AllSame' ) { <del> <del> // Convert the material indices of each vertex into rendering groups on the geometry. <del> var prevMaterialIndex = buffers.materialIndex[ 0 ]; <del> var startIndex = 0; <del> <del> buffers.materialIndex.forEach( function ( currentIndex, i ) { <add> return buffers; <ide> <del> if ( currentIndex !== prevMaterialIndex ) { <add> }, <ide> <del> geo.addGroup( startIndex, i - startIndex, prevMaterialIndex ); <add> // Generate data for a single face in a geometry. If the face is a quad then split it into 2 tris <add> genFace: function ( buffers, geoInfo, facePositionIndexes, materialIndex, faceNormals, faceColors, faceUVs, faceWeights, faceWeightIndices, faceLength ) { <ide> <del> prevMaterialIndex = currentIndex; <del> startIndex = i; <add> for ( var i = 2; i < faceLength; i ++ ) { <ide> <del> } <add> buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ 0 ] ] ); <add> buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ 1 ] ] ); <add> buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ 2 ] ] ); <ide> <del> } ); <add> buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ ( i - 1 ) * 3 ] ] ); <add> buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ ( i - 1 ) * 3 + 1 ] ] ); <add> buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ ( i - 1 ) * 3 + 2 ] ] ); <ide> <del> // the loop above doesn't add the last group, do that here. <del> if ( geo.groups.length > 0 ) { <add> buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ i * 3 ] ] ); <add> buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ i * 3 + 1 ] ] ); <add> buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ i * 3 + 2 ] ] ); <ide> <del> var lastGroup = geo.groups[ geo.groups.length - 1 ]; <del> var lastIndex = lastGroup.start + lastGroup.count; <add> if ( geoInfo.skeleton ) { <ide> <del> if ( lastIndex !== buffers.materialIndex.length ) { <add> buffers.vertexWeights.push( faceWeights[ 0 ] ); <add> buffers.vertexWeights.push( faceWeights[ 1 ] ); <add> buffers.vertexWeights.push( faceWeights[ 2 ] ); <add> buffers.vertexWeights.push( faceWeights[ 3 ] ); <ide> <del> geo.addGroup( lastIndex, buffers.materialIndex.length - lastIndex, prevMaterialIndex ); <add> buffers.vertexWeights.push( faceWeights[ ( i - 1 ) * 4 ] ); <add> buffers.vertexWeights.push( faceWeights[ ( i - 1 ) * 4 + 1 ] ); <add> buffers.vertexWeights.push( faceWeights[ ( i - 1 ) * 4 + 2 ] ); <add> buffers.vertexWeights.push( faceWeights[ ( i - 1 ) * 4 + 3 ] ); <ide> <del> } <add> buffers.vertexWeights.push( faceWeights[ i * 4 ] ); <add> buffers.vertexWeights.push( faceWeights[ i * 4 + 1 ] ); <add> buffers.vertexWeights.push( faceWeights[ i * 4 + 2 ] ); <add> buffers.vertexWeights.push( faceWeights[ i * 4 + 3 ] ); <ide> <del> } <add> buffers.weightsIndices.push( faceWeightIndices[ 0 ] ); <add> buffers.weightsIndices.push( faceWeightIndices[ 1 ] ); <add> buffers.weightsIndices.push( faceWeightIndices[ 2 ] ); <add> buffers.weightsIndices.push( faceWeightIndices[ 3 ] ); <ide> <del> // case where there are multiple materials but the whole geometry is only <del> // using one of them <del> if ( geo.groups.length === 0 ) { <add> buffers.weightsIndices.push( faceWeightIndices[ ( i - 1 ) * 4 ] ); <add> buffers.weightsIndices.push( faceWeightIndices[ ( i - 1 ) * 4 + 1 ] ); <add> buffers.weightsIndices.push( faceWeightIndices[ ( i - 1 ) * 4 + 2 ] ); <add> buffers.weightsIndices.push( faceWeightIndices[ ( i - 1 ) * 4 + 3 ] ); <ide> <del> geo.addGroup( 0, buffers.materialIndex.length, buffers.materialIndex[ 0 ] ); <add> buffers.weightsIndices.push( faceWeightIndices[ i * 4 ] ); <add> buffers.weightsIndices.push( faceWeightIndices[ i * 4 + 1 ] ); <add> buffers.weightsIndices.push( faceWeightIndices[ i * 4 + 2 ] ); <add> buffers.weightsIndices.push( faceWeightIndices[ i * 4 + 3 ] ); <ide> <ide> } <ide> <del> } <add> if ( geoInfo.color ) { <ide> <del> this.addMorphTargets( geo, geoNode, morphTarget, preTransform ); <add> buffers.colors.push( faceColors[ 0 ] ); <add> buffers.colors.push( faceColors[ 1 ] ); <add> buffers.colors.push( faceColors[ 2 ] ); <ide> <del> return geo; <add> buffers.colors.push( faceColors[ ( i - 1 ) * 3 ] ); <add> buffers.colors.push( faceColors[ ( i - 1 ) * 3 + 1 ] ); <add> buffers.colors.push( faceColors[ ( i - 1 ) * 3 + 2 ] ); <ide> <del> }, <add> buffers.colors.push( faceColors[ i * 3 ] ); <add> buffers.colors.push( faceColors[ i * 3 + 1 ] ); <add> buffers.colors.push( faceColors[ i * 3 + 2 ] ); <ide> <del> parseGeoNode: function ( geoNode, skeleton ) { <add> } <ide> <del> var geoInfo = {}; <add> if ( geoInfo.material && geoInfo.material.mappingType !== 'AllSame' ) { <ide> <del> geoInfo.vertexPositions = ( geoNode.Vertices !== undefined ) ? geoNode.Vertices.a : []; <del> geoInfo.vertexIndices = ( geoNode.PolygonVertexIndex !== undefined ) ? geoNode.PolygonVertexIndex.a : []; <add> buffers.materialIndex.push( materialIndex ); <add> buffers.materialIndex.push( materialIndex ); <add> buffers.materialIndex.push( materialIndex ); <ide> <del> if ( geoNode.LayerElementColor ) { <add> } <ide> <del> geoInfo.color = this.parseVertexColors( geoNode.LayerElementColor[ 0 ] ); <add> if ( geoInfo.normal ) { <ide> <del> } <add> buffers.normal.push( faceNormals[ 0 ] ); <add> buffers.normal.push( faceNormals[ 1 ] ); <add> buffers.normal.push( faceNormals[ 2 ] ); <ide> <del> if ( geoNode.LayerElementMaterial ) { <add> buffers.normal.push( faceNormals[ ( i - 1 ) * 3 ] ); <add> buffers.normal.push( faceNormals[ ( i - 1 ) * 3 + 1 ] ); <add> buffers.normal.push( faceNormals[ ( i - 1 ) * 3 + 2 ] ); <ide> <del> geoInfo.material = this.parseMaterialIndices( geoNode.LayerElementMaterial[ 0 ] ); <add> buffers.normal.push( faceNormals[ i * 3 ] ); <add> buffers.normal.push( faceNormals[ i * 3 + 1 ] ); <add> buffers.normal.push( faceNormals[ i * 3 + 2 ] ); <ide> <del> } <add> } <ide> <del> if ( geoNode.LayerElementNormal ) { <add> if ( geoInfo.uv ) { <ide> <del> geoInfo.normal = this.parseNormals( geoNode.LayerElementNormal[ 0 ] ); <add> geoInfo.uv.forEach( function ( uv, j ) { <ide> <del> } <add> if ( buffers.uvs[ j ] === undefined ) buffers.uvs[ j ] = []; <ide> <del> if ( geoNode.LayerElementUV ) { <add> buffers.uvs[ j ].push( faceUVs[ j ][ 0 ] ); <add> buffers.uvs[ j ].push( faceUVs[ j ][ 1 ] ); <ide> <del> geoInfo.uv = []; <add> buffers.uvs[ j ].push( faceUVs[ j ][ ( i - 1 ) * 2 ] ); <add> buffers.uvs[ j ].push( faceUVs[ j ][ ( i - 1 ) * 2 + 1 ] ); <ide> <del> var i = 0; <del> while ( geoNode.LayerElementUV[ i ] ) { <add> buffers.uvs[ j ].push( faceUVs[ j ][ i * 2 ] ); <add> buffers.uvs[ j ].push( faceUVs[ j ][ i * 2 + 1 ] ); <ide> <del> geoInfo.uv.push( this.parseUVs( geoNode.LayerElementUV[ i ] ) ); <del> i ++; <add> } ); <ide> <ide> } <ide> <ide> } <ide> <del> geoInfo.weightTable = {}; <add> }, <ide> <del> if ( skeleton !== null ) { <add> addMorphTargets: function ( parentGeo, parentGeoNode, morphTarget, preTransform ) { <ide> <del> geoInfo.skeleton = skeleton; <add> if ( morphTarget === null ) return; <ide> <del> skeleton.rawBones.forEach( function ( rawBone, i ) { <add> parentGeo.morphAttributes.position = []; <add> parentGeo.morphAttributes.normal = []; <ide> <del> // loop over the bone's vertex indices and weights <del> rawBone.indices.forEach( function ( index, j ) { <add> var self = this; <add> morphTarget.rawTargets.forEach( function ( rawTarget ) { <ide> <del> if ( geoInfo.weightTable[ index ] === undefined ) geoInfo.weightTable[ index ] = []; <add> var morphGeoNode = FBXTree.Objects.Geometry[ rawTarget.geoID ]; <ide> <del> geoInfo.weightTable[ index ].push( { <add> if ( morphGeoNode !== undefined ) { <ide> <del> id: i, <del> weight: rawBone.weights[ j ], <add> self.genMorphGeometry( parentGeo, parentGeoNode, morphGeoNode, preTransform ); <ide> <del> } ); <add> } <ide> <del> } ); <add> } ); <ide> <del> } ); <add> }, <ide> <del> } <add> // a morph geometry node is similar to a standard node, and the node is also contained <add> // in FBXTree.Objects.Geometry, however it can only have attributes for position, normal <add> // and a special attribute Index defining which vertices of the original geometry are affected <add> // Normal and position attributes only have data for the vertices that are affected by the morph <add> genMorphGeometry: function ( parentGeo, parentGeoNode, morphGeoNode, preTransform ) { <ide> <del> return geoInfo; <add> var morphGeo = new THREE.BufferGeometry(); <add> if ( morphGeoNode.attrName ) morphGeo.name = morphGeoNode.attrName; <ide> <del> }, <add> var vertexIndices = ( parentGeoNode.PolygonVertexIndex !== undefined ) ? parentGeoNode.PolygonVertexIndex.a : []; <ide> <del> genBuffers: function ( geoInfo ) { <add> // make a copy of the parent's vertex positions <add> var vertexPositions = ( parentGeoNode.Vertices !== undefined ) ? parentGeoNode.Vertices.a.slice() : []; <ide> <del> var buffers = { <del> vertex: [], <del> normal: [], <del> colors: [], <del> uvs: [], <del> materialIndex: [], <del> vertexWeights: [], <del> weightsIndices: [], <del> }; <add> var morphPositions = ( morphGeoNode.Vertices !== undefined ) ? morphGeoNode.Vertices.a : []; <add> var indices = ( morphGeoNode.Indexes !== undefined ) ? morphGeoNode.Indexes.a : []; <ide> <del> var polygonIndex = 0; <del> var faceLength = 0; <del> var displayedWeightsWarning = false; <add> for ( var i = 0; i < indices.length; i ++ ) { <ide> <del> // these will hold data for a single face <del> var facePositionIndexes = []; <del> var faceNormals = []; <del> var faceColors = []; <del> var faceUVs = []; <del> var faceWeights = []; <del> var faceWeightIndices = []; <add> var morphIndex = indices[ i ] * 3; <ide> <del> var self = this; <del> geoInfo.vertexIndices.forEach( function ( vertexIndex, polygonVertexIndex ) { <add> // FBX format uses blend shapes rather than morph targets. This can be converted <add> // by additively combining the blend shape positions with the original geometry's positions <add> vertexPositions[ morphIndex ] += morphPositions[ i * 3 ]; <add> vertexPositions[ morphIndex + 1 ] += morphPositions[ i * 3 + 1 ]; <add> vertexPositions[ morphIndex + 2 ] += morphPositions[ i * 3 + 2 ]; <ide> <del> var endOfFace = false; <add> } <ide> <del> // Face index and vertex index arrays are combined in a single array <del> // A cube with quad faces looks like this: <del> // PolygonVertexIndex: *24 { <del> // a: 0, 1, 3, -3, 2, 3, 5, -5, 4, 5, 7, -7, 6, 7, 1, -1, 1, 7, 5, -4, 6, 0, 2, -5 <del> // } <del> // Negative numbers mark the end of a face - first face here is 0, 1, 3, -3 <del> // to find index of last vertex bit shift the index: ^ - 1 <del> if ( vertexIndex < 0 ) { <add> // TODO: add morph normal support <add> var morphGeoInfo = { <add> vertexIndices: vertexIndices, <add> vertexPositions: vertexPositions, <add> }; <ide> <del> vertexIndex = vertexIndex ^ - 1; // equivalent to ( x * -1 ) - 1 <del> endOfFace = true; <add> var morphBuffers = this.genBuffers( morphGeoInfo ); <ide> <del> } <add> var positionAttribute = new THREE.Float32BufferAttribute( morphBuffers.vertex, 3 ); <add> positionAttribute.name = morphGeoNode.attrName; <ide> <del> var weightIndices = []; <del> var weights = []; <add> preTransform.applyToBufferAttribute( positionAttribute ); <ide> <del> facePositionIndexes.push( vertexIndex * 3, vertexIndex * 3 + 1, vertexIndex * 3 + 2 ); <add> parentGeo.morphAttributes.position.push( positionAttribute ); <ide> <del> if ( geoInfo.color ) { <add> }, <ide> <del> var data = getData( polygonVertexIndex, polygonIndex, vertexIndex, geoInfo.color ); <add> // Parse normal from FBXTree.Objects.Geometry.LayerElementNormal if it exists <add> parseNormals: function ( NormalNode ) { <ide> <del> faceColors.push( data[ 0 ], data[ 1 ], data[ 2 ] ); <add> var mappingType = NormalNode.MappingInformationType; <add> var referenceType = NormalNode.ReferenceInformationType; <add> var buffer = NormalNode.Normals.a; <add> var indexBuffer = []; <add> if ( referenceType === 'IndexToDirect' ) { <ide> <del> } <add> if ( 'NormalIndex' in NormalNode ) { <ide> <del> if ( geoInfo.skeleton ) { <add> indexBuffer = NormalNode.NormalIndex.a; <ide> <del> if ( geoInfo.weightTable[ vertexIndex ] !== undefined ) { <add> } else if ( 'NormalsIndex' in NormalNode ) { <ide> <del> geoInfo.weightTable[ vertexIndex ].forEach( function ( wt ) { <add> indexBuffer = NormalNode.NormalsIndex.a; <ide> <del> weights.push( wt.weight ); <del> weightIndices.push( wt.id ); <add> } <ide> <del> } ); <add> } <ide> <add> return { <add> dataSize: 3, <add> buffer: buffer, <add> indices: indexBuffer, <add> mappingType: mappingType, <add> referenceType: referenceType <add> }; <ide> <del> } <add> }, <ide> <del> if ( weights.length > 4 ) { <add> // Parse UVs from FBXTree.Objects.Geometry.LayerElementUV if it exists <add> parseUVs: function ( UVNode ) { <ide> <del> if ( ! displayedWeightsWarning ) { <add> var mappingType = UVNode.MappingInformationType; <add> var referenceType = UVNode.ReferenceInformationType; <add> var buffer = UVNode.UV.a; <add> var indexBuffer = []; <add> if ( referenceType === 'IndexToDirect' ) { <ide> <del> console.warn( 'THREE.FBXLoader: Vertex has more than 4 skinning weights assigned to vertex. Deleting additional weights.' ); <del> displayedWeightsWarning = true; <add> indexBuffer = UVNode.UVIndex.a; <ide> <del> } <add> } <ide> <del> var wIndex = [ 0, 0, 0, 0 ]; <del> var Weight = [ 0, 0, 0, 0 ]; <add> return { <add> dataSize: 2, <add> buffer: buffer, <add> indices: indexBuffer, <add> mappingType: mappingType, <add> referenceType: referenceType <add> }; <ide> <del> weights.forEach( function ( weight, weightIndex ) { <add> }, <ide> <del> var currentWeight = weight; <del> var currentIndex = weightIndices[ weightIndex ]; <add> // Parse Vertex Colors from FBXTree.Objects.Geometry.LayerElementColor if it exists <add> parseVertexColors: function ( ColorNode ) { <ide> <del> Weight.forEach( function ( comparedWeight, comparedWeightIndex, comparedWeightArray ) { <add> var mappingType = ColorNode.MappingInformationType; <add> var referenceType = ColorNode.ReferenceInformationType; <add> var buffer = ColorNode.Colors.a; <add> var indexBuffer = []; <add> if ( referenceType === 'IndexToDirect' ) { <ide> <del> if ( currentWeight > comparedWeight ) { <add> indexBuffer = ColorNode.ColorIndex.a; <ide> <del> comparedWeightArray[ comparedWeightIndex ] = currentWeight; <del> currentWeight = comparedWeight; <add> } <ide> <del> var tmp = wIndex[ comparedWeightIndex ]; <del> wIndex[ comparedWeightIndex ] = currentIndex; <del> currentIndex = tmp; <add> return { <add> dataSize: 4, <add> buffer: buffer, <add> indices: indexBuffer, <add> mappingType: mappingType, <add> referenceType: referenceType <add> }; <ide> <del> } <add> }, <ide> <del> } ); <add> // Parse mapping and material data in FBXTree.Objects.Geometry.LayerElementMaterial if it exists <add> parseMaterialIndices: function ( MaterialNode ) { <ide> <del> } ); <add> var mappingType = MaterialNode.MappingInformationType; <add> var referenceType = MaterialNode.ReferenceInformationType; <ide> <del> weightIndices = wIndex; <del> weights = Weight; <add> if ( mappingType === 'NoMappingInformation' ) { <ide> <del> } <add> return { <add> dataSize: 1, <add> buffer: [ 0 ], <add> indices: [ 0 ], <add> mappingType: 'AllSame', <add> referenceType: referenceType <add> }; <ide> <del> // if the weight array is shorter than 4 pad with 0s <del> while ( weights.length < 4 ) { <add> } <ide> <del> weights.push( 0 ); <del> weightIndices.push( 0 ); <add> var materialIndexBuffer = MaterialNode.Materials.a; <ide> <del> } <add> // Since materials are stored as indices, there's a bit of a mismatch between FBX and what <add> // we expect.So we create an intermediate buffer that points to the index in the buffer, <add> // for conforming with the other functions we've written for other data. <add> var materialIndices = []; <ide> <del> for ( var i = 0; i < 4; ++ i ) { <add> for ( var i = 0; i < materialIndexBuffer.length; ++ i ) { <ide> <del> faceWeights.push( weights[ i ] ); <del> faceWeightIndices.push( weightIndices[ i ] ); <add> materialIndices.push( i ); <ide> <del> } <add> } <ide> <del> } <add> return { <add> dataSize: 1, <add> buffer: materialIndexBuffer, <add> indices: materialIndices, <add> mappingType: mappingType, <add> referenceType: referenceType <add> }; <ide> <del> if ( geoInfo.normal ) { <add> }, <ide> <del> var data = getData( polygonVertexIndex, polygonIndex, vertexIndex, geoInfo.normal ); <add> // Generate a NurbGeometry from a node in FBXTree.Objects.Geometry <add> parseNurbsGeometry: function ( geoNode ) { <ide> <del> faceNormals.push( data[ 0 ], data[ 1 ], data[ 2 ] ); <add> if ( THREE.NURBSCurve === undefined ) { <ide> <del> } <add> console.error( 'THREE.FBXLoader: The loader relies on THREE.NURBSCurve for any nurbs present in the model. Nurbs will show up as empty geometry.' ); <add> return new THREE.BufferGeometry(); <ide> <del> if ( geoInfo.material && geoInfo.material.mappingType !== 'AllSame' ) { <add> } <ide> <del> var materialIndex = getData( polygonVertexIndex, polygonIndex, vertexIndex, geoInfo.material )[ 0 ]; <add> var order = parseInt( geoNode.Order ); <ide> <del> } <add> if ( isNaN( order ) ) { <ide> <del> if ( geoInfo.uv ) { <add> console.error( 'THREE.FBXLoader: Invalid Order %s given for geometry ID: %s', geoNode.Order, geoNode.id ); <add> return new THREE.BufferGeometry(); <ide> <del> geoInfo.uv.forEach( function ( uv, i ) { <add> } <ide> <del> var data = getData( polygonVertexIndex, polygonIndex, vertexIndex, uv ); <add> var degree = order - 1; <ide> <del> if ( faceUVs[ i ] === undefined ) { <add> var knots = geoNode.KnotVector.a; <add> var controlPoints = []; <add> var pointsValues = geoNode.Points.a; <ide> <del> faceUVs[ i ] = []; <add> for ( var i = 0, l = pointsValues.length; i < l; i += 4 ) { <ide> <del> } <add> controlPoints.push( new THREE.Vector4().fromArray( pointsValues, i ) ); <ide> <del> faceUVs[ i ].push( data[ 0 ] ); <del> faceUVs[ i ].push( data[ 1 ] ); <add> } <ide> <del> } ); <add> var startKnot, endKnot; <ide> <del> } <add> if ( geoNode.Form === 'Closed' ) { <ide> <del> faceLength ++; <add> controlPoints.push( controlPoints[ 0 ] ); <ide> <del> if ( endOfFace ) { <add> } else if ( geoNode.Form === 'Periodic' ) { <ide> <del> self.genFace( buffers, geoInfo, facePositionIndexes, materialIndex, faceNormals, faceColors, faceUVs, faceWeights, faceWeightIndices, faceLength ); <add> startKnot = degree; <add> endKnot = knots.length - 1 - startKnot; <ide> <del> polygonIndex ++; <del> faceLength = 0; <add> for ( var i = 0; i < degree; ++ i ) { <ide> <del> // reset arrays for the next face <del> facePositionIndexes = []; <del> faceNormals = []; <del> faceColors = []; <del> faceUVs = []; <del> faceWeights = []; <del> faceWeightIndices = []; <add> controlPoints.push( controlPoints[ i ] ); <ide> <ide> } <ide> <del> } ); <del> <del> return buffers; <del> <del> }, <del> <del> // Generate data for a single face in a geometry. If the face is a quad then split it into 2 tris <del> genFace: function ( buffers, geoInfo, facePositionIndexes, materialIndex, faceNormals, faceColors, faceUVs, faceWeights, faceWeightIndices, faceLength ) { <del> <del> for ( var i = 2; i < faceLength; i ++ ) { <add> } <ide> <del> buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ 0 ] ] ); <del> buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ 1 ] ] ); <del> buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ 2 ] ] ); <add> var curve = new THREE.NURBSCurve( degree, knots, controlPoints, startKnot, endKnot ); <add> var vertices = curve.getPoints( controlPoints.length * 7 ); <ide> <del> buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ ( i - 1 ) * 3 ] ] ); <del> buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ ( i - 1 ) * 3 + 1 ] ] ); <del> buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ ( i - 1 ) * 3 + 2 ] ] ); <add> var positions = new Float32Array( vertices.length * 3 ); <ide> <del> buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ i * 3 ] ] ); <del> buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ i * 3 + 1 ] ] ); <del> buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ i * 3 + 2 ] ] ); <add> vertices.forEach( function ( vertex, i ) { <ide> <del> if ( geoInfo.skeleton ) { <add> vertex.toArray( positions, i * 3 ); <ide> <del> buffers.vertexWeights.push( faceWeights[ 0 ] ); <del> buffers.vertexWeights.push( faceWeights[ 1 ] ); <del> buffers.vertexWeights.push( faceWeights[ 2 ] ); <del> buffers.vertexWeights.push( faceWeights[ 3 ] ); <add> } ); <ide> <del> buffers.vertexWeights.push( faceWeights[ ( i - 1 ) * 4 ] ); <del> buffers.vertexWeights.push( faceWeights[ ( i - 1 ) * 4 + 1 ] ); <del> buffers.vertexWeights.push( faceWeights[ ( i - 1 ) * 4 + 2 ] ); <del> buffers.vertexWeights.push( faceWeights[ ( i - 1 ) * 4 + 3 ] ); <add> var geometry = new THREE.BufferGeometry(); <add> geometry.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) ); <ide> <del> buffers.vertexWeights.push( faceWeights[ i * 4 ] ); <del> buffers.vertexWeights.push( faceWeights[ i * 4 + 1 ] ); <del> buffers.vertexWeights.push( faceWeights[ i * 4 + 2 ] ); <del> buffers.vertexWeights.push( faceWeights[ i * 4 + 3 ] ); <add> return geometry; <ide> <del> buffers.weightsIndices.push( faceWeightIndices[ 0 ] ); <del> buffers.weightsIndices.push( faceWeightIndices[ 1 ] ); <del> buffers.weightsIndices.push( faceWeightIndices[ 2 ] ); <del> buffers.weightsIndices.push( faceWeightIndices[ 3 ] ); <add> }, <ide> <del> buffers.weightsIndices.push( faceWeightIndices[ ( i - 1 ) * 4 ] ); <del> buffers.weightsIndices.push( faceWeightIndices[ ( i - 1 ) * 4 + 1 ] ); <del> buffers.weightsIndices.push( faceWeightIndices[ ( i - 1 ) * 4 + 2 ] ); <del> buffers.weightsIndices.push( faceWeightIndices[ ( i - 1 ) * 4 + 3 ] ); <add> }; <ide> <del> buffers.weightsIndices.push( faceWeightIndices[ i * 4 ] ); <del> buffers.weightsIndices.push( faceWeightIndices[ i * 4 + 1 ] ); <del> buffers.weightsIndices.push( faceWeightIndices[ i * 4 + 2 ] ); <del> buffers.weightsIndices.push( faceWeightIndices[ i * 4 + 3 ] ); <add> // parse animation data from FBXTree <add> function AnimationParser() {} <ide> <del> } <add> AnimationParser.prototype = { <ide> <del> if ( geoInfo.color ) { <add> constructor: AnimationParser, <ide> <del> buffers.colors.push( faceColors[ 0 ] ); <del> buffers.colors.push( faceColors[ 1 ] ); <del> buffers.colors.push( faceColors[ 2 ] ); <add> // take raw animation clips and turn them into three.js animation clips <add> parse: function ( sceneGraph ) { <ide> <del> buffers.colors.push( faceColors[ ( i - 1 ) * 3 ] ); <del> buffers.colors.push( faceColors[ ( i - 1 ) * 3 + 1 ] ); <del> buffers.colors.push( faceColors[ ( i - 1 ) * 3 + 2 ] ); <add> var animationClips = []; <ide> <del> buffers.colors.push( faceColors[ i * 3 ] ); <del> buffers.colors.push( faceColors[ i * 3 + 1 ] ); <del> buffers.colors.push( faceColors[ i * 3 + 2 ] ); <ide> <del> } <add> var rawClips = this.parseClips(); <ide> <del> if ( geoInfo.material && geoInfo.material.mappingType !== 'AllSame' ) { <add> if ( rawClips === undefined ) return; <ide> <del> buffers.materialIndex.push( materialIndex ); <del> buffers.materialIndex.push( materialIndex ); <del> buffers.materialIndex.push( materialIndex ); <add> for ( var key in rawClips ) { <ide> <del> } <add> var rawClip = rawClips[ key ]; <ide> <del> if ( geoInfo.normal ) { <add> var clip = this.addClip( rawClip, sceneGraph ); <ide> <del> buffers.normal.push( faceNormals[ 0 ] ); <del> buffers.normal.push( faceNormals[ 1 ] ); <del> buffers.normal.push( faceNormals[ 2 ] ); <add> animationClips.push( clip ); <ide> <del> buffers.normal.push( faceNormals[ ( i - 1 ) * 3 ] ); <del> buffers.normal.push( faceNormals[ ( i - 1 ) * 3 + 1 ] ); <del> buffers.normal.push( faceNormals[ ( i - 1 ) * 3 + 2 ] ); <add> } <ide> <del> buffers.normal.push( faceNormals[ i * 3 ] ); <del> buffers.normal.push( faceNormals[ i * 3 + 1 ] ); <del> buffers.normal.push( faceNormals[ i * 3 + 2 ] ); <add> return animationClips; <ide> <del> } <add> }, <ide> <del> if ( geoInfo.uv ) { <add> parseClips: function () { <ide> <del> geoInfo.uv.forEach( function ( uv, j ) { <add> // since the actual transformation data is stored in FBXTree.Objects.AnimationCurve, <add> // if this is undefined we can safely assume there are no animations <add> if ( FBXTree.Objects.AnimationCurve === undefined ) return undefined; <ide> <del> if ( buffers.uvs[ j ] === undefined ) buffers.uvs[ j ] = []; <add> var curveNodesMap = this.parseAnimationCurveNodes(); <ide> <del> buffers.uvs[ j ].push( faceUVs[ j ][ 0 ] ); <del> buffers.uvs[ j ].push( faceUVs[ j ][ 1 ] ); <add> this.parseAnimationCurves( curveNodesMap ); <ide> <del> buffers.uvs[ j ].push( faceUVs[ j ][ ( i - 1 ) * 2 ] ); <del> buffers.uvs[ j ].push( faceUVs[ j ][ ( i - 1 ) * 2 + 1 ] ); <add> var layersMap = this.parseAnimationLayers( curveNodesMap ); <add> var rawClips = this.parseAnimStacks( layersMap ); <ide> <del> buffers.uvs[ j ].push( faceUVs[ j ][ i * 2 ] ); <del> buffers.uvs[ j ].push( faceUVs[ j ][ i * 2 + 1 ] ); <add> return rawClips; <ide> <del> } ); <add> }, <ide> <del> } <add> // parse nodes in FBXTree.Objects.AnimationCurveNode <add> // each AnimationCurveNode holds data for an animation transform for a model (e.g. left arm rotation ) <add> // and is referenced by an AnimationLayer <add> parseAnimationCurveNodes: function () { <ide> <del> } <add> var rawCurveNodes = FBXTree.Objects.AnimationCurveNode; <ide> <del> }, <add> var curveNodesMap = new Map(); <ide> <del> addMorphTargets: function ( parentGeo, parentGeoNode, morphTarget, preTransform ) { <add> for ( var nodeID in rawCurveNodes ) { <ide> <del> if ( morphTarget === null ) return; <add> var rawCurveNode = rawCurveNodes[ nodeID ]; <ide> <del> parentGeo.morphAttributes.position = []; <del> parentGeo.morphAttributes.normal = []; <add> if ( rawCurveNode.attrName.match( /S|R|T|DeformPercent/ ) !== null ) { <ide> <del> var self = this; <del> morphTarget.rawTargets.forEach( function ( rawTarget ) { <add> var curveNode = { <ide> <del> var morphGeoNode = FBXTree.Objects.Geometry[ rawTarget.geoID ]; <add> id: rawCurveNode.id, <add> attr: rawCurveNode.attrName, <add> curves: {}, <ide> <del> if ( morphGeoNode !== undefined ) { <add> }; <ide> <del> self.genMorphGeometry( parentGeo, parentGeoNode, morphGeoNode, preTransform ); <add> curveNodesMap.set( curveNode.id, curveNode ); <ide> <ide> } <ide> <del> } ); <del> <del> }, <add> } <ide> <del> // a morph geometry node is similar to a standard node, and the node is also contained <del> // in FBXTree.Objects.Geometry, however it can only have attributes for position, normal <del> // and a special attribute Index defining which vertices of the original geometry are affected <del> // Normal and position attributes only have data for the vertices that are affected by the morph <del> genMorphGeometry: function ( parentGeo, parentGeoNode, morphGeoNode, preTransform ) { <add> return curveNodesMap; <ide> <del> var morphGeo = new THREE.BufferGeometry(); <del> if ( morphGeoNode.attrName ) morphGeo.name = morphGeoNode.attrName; <add> }, <ide> <del> var vertexIndices = ( parentGeoNode.PolygonVertexIndex !== undefined ) ? parentGeoNode.PolygonVertexIndex.a : []; <add> // parse nodes in FBXTree.Objects.AnimationCurve and connect them up to <add> // previously parsed AnimationCurveNodes. Each AnimationCurve holds data for a single animated <add> // axis ( e.g. times and values of x rotation) <add> parseAnimationCurves: function ( curveNodesMap ) { <ide> <del> // make a copy of the parent's vertex positions <del> var vertexPositions = ( parentGeoNode.Vertices !== undefined ) ? parentGeoNode.Vertices.a.slice() : []; <add> var rawCurves = FBXTree.Objects.AnimationCurve; <ide> <del> var morphPositions = ( morphGeoNode.Vertices !== undefined ) ? morphGeoNode.Vertices.a : []; <del> var indices = ( morphGeoNode.Indexes !== undefined ) ? morphGeoNode.Indexes.a : []; <add> // TODO: Many values are identical up to roundoff error, but won't be optimised <add> // e.g. position times: [0, 0.4, 0. 8] <add> // position values: [7.23538335023477e-7, 93.67518615722656, -0.9982695579528809, 7.23538335023477e-7, 93.67518615722656, -0.9982695579528809, 7.235384487103147e-7, 93.67520904541016, -0.9982695579528809] <add> // clearly, this should be optimised to <add> // times: [0], positions [7.23538335023477e-7, 93.67518615722656, -0.9982695579528809] <add> // this shows up in nearly every FBX file, and generally time array is length > 100 <ide> <del> for ( var i = 0; i < indices.length; i ++ ) { <add> for ( var nodeID in rawCurves ) { <ide> <del> var morphIndex = indices[ i ] * 3; <add> var animationCurve = { <ide> <del> // FBX format uses blend shapes rather than morph targets. This can be converted <del> // by additively combining the blend shape positions with the original geometry's positions <del> vertexPositions[ morphIndex ] += morphPositions[ i * 3 ]; <del> vertexPositions[ morphIndex + 1 ] += morphPositions[ i * 3 + 1 ]; <del> vertexPositions[ morphIndex + 2 ] += morphPositions[ i * 3 + 2 ]; <add> id: rawCurves[ nodeID ].id, <add> times: rawCurves[ nodeID ].KeyTime.a.map( convertFBXTimeToSeconds ), <add> values: rawCurves[ nodeID ].KeyValueFloat.a, <ide> <del> } <add> }; <ide> <del> // TODO: add morph normal support <del> var morphGeoInfo = { <del> vertexIndices: vertexIndices, <del> vertexPositions: vertexPositions, <del> }; <add> var relationships = connections.get( animationCurve.id ); <ide> <del> var morphBuffers = this.genBuffers( morphGeoInfo ); <add> if ( relationships !== undefined ) { <ide> <del> var positionAttribute = new THREE.Float32BufferAttribute( morphBuffers.vertex, 3 ); <del> positionAttribute.name = morphGeoNode.attrName; <add> var animationCurveID = relationships.parents[ 0 ].ID; <add> var animationCurveRelationship = relationships.parents[ 0 ].relationship; <ide> <del> preTransform.applyToBufferAttribute( positionAttribute ); <add> if ( animationCurveRelationship.match( /X/ ) ) { <ide> <del> parentGeo.morphAttributes.position.push( positionAttribute ); <add> curveNodesMap.get( animationCurveID ).curves[ 'x' ] = animationCurve; <ide> <del> }, <add> } else if ( animationCurveRelationship.match( /Y/ ) ) { <ide> <del> // Parse normal from FBXTree.Objects.Geometry.LayerElementNormal if it exists <del> parseNormals: function ( NormalNode ) { <add> curveNodesMap.get( animationCurveID ).curves[ 'y' ] = animationCurve; <ide> <del> var mappingType = NormalNode.MappingInformationType; <del> var referenceType = NormalNode.ReferenceInformationType; <del> var buffer = NormalNode.Normals.a; <del> var indexBuffer = []; <del> if ( referenceType === 'IndexToDirect' ) { <add> } else if ( animationCurveRelationship.match( /Z/ ) ) { <ide> <del> if ( 'NormalIndex' in NormalNode ) { <add> curveNodesMap.get( animationCurveID ).curves[ 'z' ] = animationCurve; <ide> <del> indexBuffer = NormalNode.NormalIndex.a; <add> } else if ( animationCurveRelationship.match( /d|DeformPercent/ ) && curveNodesMap.has( animationCurveID ) ) { <ide> <del> } else if ( 'NormalsIndex' in NormalNode ) { <add> curveNodesMap.get( animationCurveID ).curves[ 'morph' ] = animationCurve; <ide> <del> indexBuffer = NormalNode.NormalsIndex.a; <add> } <ide> <ide> } <ide> <ide> } <ide> <del> return { <del> dataSize: 3, <del> buffer: buffer, <del> indices: indexBuffer, <del> mappingType: mappingType, <del> referenceType: referenceType <del> }; <del> <ide> }, <ide> <del> // Parse UVs from FBXTree.Objects.Geometry.LayerElementUV if it exists <del> parseUVs: function ( UVNode ) { <del> <del> var mappingType = UVNode.MappingInformationType; <del> var referenceType = UVNode.ReferenceInformationType; <del> var buffer = UVNode.UV.a; <del> var indexBuffer = []; <del> if ( referenceType === 'IndexToDirect' ) { <add> // parse nodes in FBXTree.Objects.AnimationLayer. Each layers holds references <add> // to various AnimationCurveNodes and is referenced by an AnimationStack node <add> // note: theoretically a stack can have multiple layers, however in practice there always seems to be one per stack <add> parseAnimationLayers: function ( curveNodesMap ) { <ide> <del> indexBuffer = UVNode.UVIndex.a; <add> var rawLayers = FBXTree.Objects.AnimationLayer; <ide> <del> } <add> var layersMap = new Map(); <ide> <del> return { <del> dataSize: 2, <del> buffer: buffer, <del> indices: indexBuffer, <del> mappingType: mappingType, <del> referenceType: referenceType <del> }; <add> for ( var nodeID in rawLayers ) { <ide> <del> }, <add> var layerCurveNodes = []; <ide> <del> // Parse Vertex Colors from FBXTree.Objects.Geometry.LayerElementColor if it exists <del> parseVertexColors: function ( ColorNode ) { <add> var connection = connections.get( parseInt( nodeID ) ); <ide> <del> var mappingType = ColorNode.MappingInformationType; <del> var referenceType = ColorNode.ReferenceInformationType; <del> var buffer = ColorNode.Colors.a; <del> var indexBuffer = []; <del> if ( referenceType === 'IndexToDirect' ) { <add> if ( connection !== undefined ) { <ide> <del> indexBuffer = ColorNode.ColorIndex.a; <add> // all the animationCurveNodes used in the layer <add> var children = connection.children; <ide> <del> } <add> var self = this; <add> children.forEach( function ( child, i ) { <ide> <del> return { <del> dataSize: 4, <del> buffer: buffer, <del> indices: indexBuffer, <del> mappingType: mappingType, <del> referenceType: referenceType <del> }; <add> if ( curveNodesMap.has( child.ID ) ) { <ide> <del> }, <add> var curveNode = curveNodesMap.get( child.ID ); <ide> <del> // Parse mapping and material data in FBXTree.Objects.Geometry.LayerElementMaterial if it exists <del> parseMaterialIndices: function ( MaterialNode ) { <add> // check that the curves are defined for at least one axis, otherwise ignore the curveNode <add> if ( curveNode.curves.x !== undefined || curveNode.curves.y !== undefined || curveNode.curves.z !== undefined ) { <ide> <del> var mappingType = MaterialNode.MappingInformationType; <del> var referenceType = MaterialNode.ReferenceInformationType; <add> if ( layerCurveNodes[ i ] === undefined ) { <ide> <del> if ( mappingType === 'NoMappingInformation' ) { <add> var modelID; <ide> <del> return { <del> dataSize: 1, <del> buffer: [ 0 ], <del> indices: [ 0 ], <del> mappingType: 'AllSame', <del> referenceType: referenceType <del> }; <add> connections.get( child.ID ).parents.forEach( function ( parent ) { <ide> <del> } <add> if ( parent.relationship !== undefined ) modelID = parent.ID; <ide> <del> var materialIndexBuffer = MaterialNode.Materials.a; <add> } ); <ide> <del> // Since materials are stored as indices, there's a bit of a mismatch between FBX and what <del> // we expect.So we create an intermediate buffer that points to the index in the buffer, <del> // for conforming with the other functions we've written for other data. <del> var materialIndices = []; <add> var rawModel = FBXTree.Objects.Model[ modelID.toString() ]; <ide> <del> for ( var i = 0; i < materialIndexBuffer.length; ++ i ) { <add> var node = { <ide> <del> materialIndices.push( i ); <add> modelName: THREE.PropertyBinding.sanitizeNodeName( rawModel.attrName ), <add> initialPosition: [ 0, 0, 0 ], <add> initialRotation: [ 0, 0, 0 ], <add> initialScale: [ 1, 1, 1 ], <add> transform: self.getModelAnimTransform( rawModel ), <ide> <del> } <add> }; <ide> <del> return { <del> dataSize: 1, <del> buffer: materialIndexBuffer, <del> indices: materialIndices, <del> mappingType: mappingType, <del> referenceType: referenceType <del> }; <add> // if the animated model is pre rotated, we'll have to apply the pre rotations to every <add> // animation value as well <add> if ( 'PreRotation' in rawModel ) node.preRotations = rawModel.PreRotation.value; <add> if ( 'PostRotation' in rawModel ) node.postRotations = rawModel.PostRotation.value; <ide> <del> }, <add> layerCurveNodes[ i ] = node; <ide> <del> // Generate a NurbGeometry from a node in FBXTree.Objects.Geometry <del> parseNurbsGeometry: function ( geoNode ) { <add> } <ide> <del> if ( THREE.NURBSCurve === undefined ) { <add> layerCurveNodes[ i ][ curveNode.attr ] = curveNode; <ide> <del> console.error( 'THREE.FBXLoader: The loader relies on THREE.NURBSCurve for any nurbs present in the model. Nurbs will show up as empty geometry.' ); <del> return new THREE.BufferGeometry(); <add> } else if ( curveNode.curves.morph !== undefined ) { <ide> <del> } <add> if ( layerCurveNodes[ i ] === undefined ) { <ide> <del> var order = parseInt( geoNode.Order ); <add> var deformerID; <ide> <del> if ( isNaN( order ) ) { <add> connections.get( child.ID ).parents.forEach( function ( parent ) { <ide> <del> console.error( 'THREE.FBXLoader: Invalid Order %s given for geometry ID: %s', geoNode.Order, geoNode.id ); <del> return new THREE.BufferGeometry(); <add> if ( parent.relationship !== undefined ) deformerID = parent.ID; <ide> <del> } <add> } ); <ide> <del> var degree = order - 1; <add> var morpherID = connections.get( deformerID ).parents[ 0 ].ID; <add> var geoID = connections.get( morpherID ).parents[ 0 ].ID; <ide> <del> var knots = geoNode.KnotVector.a; <del> var controlPoints = []; <del> var pointsValues = geoNode.Points.a; <add> // assuming geometry is not used in more than one model <add> var modelID = connections.get( geoID ).parents[ 0 ].ID; <ide> <del> for ( var i = 0, l = pointsValues.length; i < l; i += 4 ) { <add> var rawModel = FBXTree.Objects.Model[ modelID ]; <ide> <del> controlPoints.push( new THREE.Vector4().fromArray( pointsValues, i ) ); <add> var node = { <ide> <del> } <add> modelName: THREE.PropertyBinding.sanitizeNodeName( rawModel.attrName ), <add> morphName: FBXTree.Objects.Deformer[ deformerID ].attrName, <ide> <del> var startKnot, endKnot; <add> }; <ide> <del> if ( geoNode.Form === 'Closed' ) { <add> layerCurveNodes[ i ] = node; <ide> <del> controlPoints.push( controlPoints[ 0 ] ); <add> } <ide> <del> } else if ( geoNode.Form === 'Periodic' ) { <add> layerCurveNodes[ i ][ curveNode.attr ] = curveNode; <ide> <del> startKnot = degree; <del> endKnot = knots.length - 1 - startKnot; <add> } <ide> <del> for ( var i = 0; i < degree; ++ i ) { <add> } <ide> <del> controlPoints.push( controlPoints[ i ] ); <add> } ); <add> <add> layersMap.set( parseInt( nodeID ), layerCurveNodes ); <ide> <ide> } <ide> <ide> } <ide> <del> var curve = new THREE.NURBSCurve( degree, knots, controlPoints, startKnot, endKnot ); <del> var vertices = curve.getPoints( controlPoints.length * 7 ); <add> return layersMap; <ide> <del> var positions = new Float32Array( vertices.length * 3 ); <add> }, <ide> <del> vertices.forEach( function ( vertex, i ) { <add> getModelAnimTransform: function ( modelNode ) { <ide> <del> vertex.toArray( positions, i * 3 ); <add> var transformData = {}; <ide> <del> } ); <add> if ( 'RotationOrder' in modelNode ) transformData.eulerOrder = parseInt( modelNode.RotationOrder.value ); <ide> <del> var geometry = new THREE.BufferGeometry(); <del> geometry.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) ); <add> if ( 'Lcl_Translation' in modelNode ) transformData.translation = modelNode.Lcl_Translation.value; <add> if ( 'RotationOffset' in modelNode ) transformData.rotationOffset = modelNode.RotationOffset.value; <ide> <del> return geometry; <add> if ( 'Lcl_Rotation' in modelNode ) transformData.rotation = modelNode.Lcl_Rotation.value; <add> if ( 'PreRotation' in modelNode ) transformData.preRotation = modelNode.PreRotation.value; <add> <add> if ( 'PostRotation' in modelNode ) transformData.postRotation = modelNode.PostRotation.value; <add> <add> if ( 'Lcl_Scaling' in modelNode ) transformData.scale = modelNode.Lcl_Scaling.value; <add> <add> return generateTransform( transformData ); <ide> <ide> }, <ide> <del> }; <add> // parse nodes in FBXTree.Objects.AnimationStack. These are the top level node in the animation <add> // hierarchy. Each Stack node will be used to create a THREE.AnimationClip <add> parseAnimStacks: function ( layersMap ) { <ide> <del> // parse animation data from FBXTree <del> function AnimationParser() {} <add> var rawStacks = FBXTree.Objects.AnimationStack; <ide> <del> AnimationParser.prototype = { <add> // connect the stacks (clips) up to the layers <add> var rawClips = {}; <ide> <del> constructor: AnimationParser, <add> for ( var nodeID in rawStacks ) { <ide> <del> parse: function () { <add> var children = connections.get( parseInt( nodeID ) ).children; <ide> <del> // since the actual transformation data is stored in FBXTree.Objects.AnimationCurve, <del> // if this is undefined we can safely assume there are no animations <del> if ( FBXTree.Objects.AnimationCurve === undefined ) return undefined; <add> if ( children.length > 1 ) { <ide> <del> var curveNodesMap = this.parseAnimationCurveNodes(); <add> // it seems like stacks will always be associated with a single layer. But just in case there are files <add> // where there are multiple layers per stack, we'll display a warning <add> console.warn( 'THREE.FBXLoader: Encountered an animation stack with multiple layers, this is currently not supported. Ignoring subsequent layers.' ); <ide> <del> this.parseAnimationCurves( curveNodesMap ); <add> } <ide> <del> var layersMap = this.parseAnimationLayers( curveNodesMap ); <del> var rawClips = this.parseAnimStacks( layersMap ); <add> var layer = layersMap.get( children[ 0 ].ID ); <add> <add> rawClips[ nodeID ] = { <add> <add> name: rawStacks[ nodeID ].attrName, <add> layer: layer, <add> <add> }; <add> <add> } <ide> <ide> return rawClips; <ide> <ide> }, <ide> <del> // parse nodes in FBXTree.Objects.AnimationCurveNode <del> // each AnimationCurveNode holds data for an animation transform for a model (e.g. left arm rotation ) <del> // and is referenced by an AnimationLayer <del> parseAnimationCurveNodes: function () { <add> addClip: function ( rawClip, sceneGraph ) { <ide> <del> var rawCurveNodes = FBXTree.Objects.AnimationCurveNode; <add> var tracks = []; <ide> <del> var curveNodesMap = new Map(); <add> var self = this; <add> rawClip.layer.forEach( function ( rawTracks ) { <ide> <del> for ( var nodeID in rawCurveNodes ) { <add> tracks = tracks.concat( self.generateTracks( rawTracks, sceneGraph ) ); <ide> <del> var rawCurveNode = rawCurveNodes[ nodeID ]; <add> } ); <ide> <del> if ( rawCurveNode.attrName.match( /S|R|T|DeformPercent/ ) !== null ) { <add> return new THREE.AnimationClip( rawClip.name, - 1, tracks ); <ide> <del> var curveNode = { <add> }, <ide> <del> id: rawCurveNode.id, <del> attr: rawCurveNode.attrName, <del> curves: {}, <add> generateTracks: function ( rawTracks, sceneGraph ) { <ide> <del> }; <add> var tracks = []; <ide> <del> curveNodesMap.set( curveNode.id, curveNode ); <add> var initialPosition = new THREE.Vector3(); <add> var initialRotation = new THREE.Quaternion(); <add> var initialScale = new THREE.Vector3(); <ide> <del> } <add> if ( rawTracks.transform ) rawTracks.transform.decompose( initialPosition, initialRotation, initialScale ); <add> <add> initialPosition = initialPosition.toArray(); <add> initialRotation = new THREE.Euler().setFromQuaternion( initialRotation ).toArray(); // todo: euler order <add> initialScale = initialScale.toArray(); <add> <add> if ( rawTracks.T !== undefined && Object.keys( rawTracks.T.curves ).length > 0 ) { <add> <add> var positionTrack = this.generateVectorTrack( rawTracks.modelName, rawTracks.T.curves, initialPosition, 'position' ); <add> if ( positionTrack !== undefined ) tracks.push( positionTrack ); <ide> <ide> } <ide> <del> return curveNodesMap; <add> if ( rawTracks.R !== undefined && Object.keys( rawTracks.R.curves ).length > 0 ) { <ide> <del> }, <add> var rotationTrack = this.generateRotationTrack( rawTracks.modelName, rawTracks.R.curves, initialRotation, rawTracks.preRotations, rawTracks.postRotations ); <add> if ( rotationTrack !== undefined ) tracks.push( rotationTrack ); <ide> <del> // parse nodes in FBXTree.Objects.AnimationCurve and connect them up to <del> // previously parsed AnimationCurveNodes. Each AnimationCurve holds data for a single animated <del> // axis ( e.g. times and values of x rotation) <del> parseAnimationCurves: function ( curveNodesMap ) { <add> } <ide> <del> var rawCurves = FBXTree.Objects.AnimationCurve; <add> if ( rawTracks.S !== undefined && Object.keys( rawTracks.S.curves ).length > 0 ) { <ide> <del> // TODO: Many values are identical up to roundoff error, but won't be optimised <del> // e.g. position times: [0, 0.4, 0. 8] <del> // position values: [7.23538335023477e-7, 93.67518615722656, -0.9982695579528809, 7.23538335023477e-7, 93.67518615722656, -0.9982695579528809, 7.235384487103147e-7, 93.67520904541016, -0.9982695579528809] <del> // clearly, this should be optimised to <del> // times: [0], positions [7.23538335023477e-7, 93.67518615722656, -0.9982695579528809] <del> // this shows up in nearly every FBX file, and generally time array is length > 100 <add> var scaleTrack = this.generateVectorTrack( rawTracks.modelName, rawTracks.S.curves, initialScale, 'scale' ); <add> if ( scaleTrack !== undefined ) tracks.push( scaleTrack ); <ide> <del> for ( var nodeID in rawCurves ) { <add> } <ide> <del> var animationCurve = { <add> if ( rawTracks.DeformPercent !== undefined ) { <ide> <del> id: rawCurves[ nodeID ].id, <del> times: rawCurves[ nodeID ].KeyTime.a.map( convertFBXTimeToSeconds ), <del> values: rawCurves[ nodeID ].KeyValueFloat.a, <add> var morphTrack = this.generateMorphTrack( rawTracks, sceneGraph ); <add> if ( morphTrack !== undefined ) tracks.push( morphTrack ); <ide> <del> }; <add> } <ide> <del> var relationships = connections.get( animationCurve.id ); <add> return tracks; <ide> <del> if ( relationships !== undefined ) { <add> }, <ide> <del> var animationCurveID = relationships.parents[ 0 ].ID; <del> var animationCurveRelationship = relationships.parents[ 0 ].relationship; <add> generateVectorTrack: function ( modelName, curves, initialValue, type ) { <ide> <del> if ( animationCurveRelationship.match( /X/ ) ) { <add> var times = this.getTimesForAllAxes( curves ); <add> var values = this.getKeyframeTrackValues( times, curves, initialValue ); <ide> <del> curveNodesMap.get( animationCurveID ).curves[ 'x' ] = animationCurve; <add> return new THREE.VectorKeyframeTrack( modelName + '.' + type, times, values ); <ide> <del> } else if ( animationCurveRelationship.match( /Y/ ) ) { <add> }, <ide> <del> curveNodesMap.get( animationCurveID ).curves[ 'y' ] = animationCurve; <add> generateRotationTrack: function ( modelName, curves, initialValue, preRotations, postRotations ) { <ide> <del> } else if ( animationCurveRelationship.match( /Z/ ) ) { <add> if ( curves.x !== undefined ) { <ide> <del> curveNodesMap.get( animationCurveID ).curves[ 'z' ] = animationCurve; <add> this.interpolateRotations( curves.x ); <add> curves.x.values = curves.x.values.map( THREE.Math.degToRad ); <ide> <del> } else if ( animationCurveRelationship.match( /d|DeformPercent/ ) && curveNodesMap.has( animationCurveID ) ) { <add> } <add> if ( curves.y !== undefined ) { <ide> <del> curveNodesMap.get( animationCurveID ).curves[ 'morph' ] = animationCurve; <add> this.interpolateRotations( curves.y ); <add> curves.y.values = curves.y.values.map( THREE.Math.degToRad ); <ide> <del> } <add> } <add> if ( curves.z !== undefined ) { <ide> <del> } <add> this.interpolateRotations( curves.z ); <add> curves.z.values = curves.z.values.map( THREE.Math.degToRad ); <ide> <ide> } <ide> <del> }, <add> var times = this.getTimesForAllAxes( curves ); <add> var values = this.getKeyframeTrackValues( times, curves, initialValue ); <ide> <del> // parse nodes in FBXTree.Objects.AnimationLayer. Each layers holds references <del> // to various AnimationCurveNodes and is referenced by an AnimationStack node <del> // note: theoretically a stack can have multiple layers, however in practice there always seems to be one per stack <del> parseAnimationLayers: function ( curveNodesMap ) { <add> if ( preRotations !== undefined ) { <ide> <del> var rawLayers = FBXTree.Objects.AnimationLayer; <add> preRotations = preRotations.map( THREE.Math.degToRad ); <add> preRotations.push( 'ZYX' ); <ide> <del> var layersMap = new Map(); <add> preRotations = new THREE.Euler().fromArray( preRotations ); <add> preRotations = new THREE.Quaternion().setFromEuler( preRotations ); <ide> <del> for ( var nodeID in rawLayers ) { <add> } <ide> <del> var layerCurveNodes = []; <add> if ( postRotations !== undefined ) { <ide> <del> var connection = connections.get( parseInt( nodeID ) ); <add> postRotations = postRotations.map( THREE.Math.degToRad ); <add> postRotations.push( 'ZYX' ); <ide> <del> if ( connection !== undefined ) { <add> postRotations = new THREE.Euler().fromArray( postRotations ); <add> postRotations = new THREE.Quaternion().setFromEuler( postRotations ).inverse(); <ide> <del> // all the animationCurveNodes used in the layer <del> var children = connection.children; <add> } <ide> <del> var self = this; <del> children.forEach( function ( child, i ) { <add> var quaternion = new THREE.Quaternion(); <add> var euler = new THREE.Euler(); <ide> <del> if ( curveNodesMap.has( child.ID ) ) { <add> var quaternionValues = []; <ide> <del> var curveNode = curveNodesMap.get( child.ID ); <add> for ( var i = 0; i < values.length; i += 3 ) { <ide> <del> // check that the curves are defined for at least one axis, otherwise ignore the curveNode <del> if ( curveNode.curves.x !== undefined || curveNode.curves.y !== undefined || curveNode.curves.z !== undefined ) { <add> euler.set( values[ i ], values[ i + 1 ], values[ i + 2 ], 'ZYX' ); <ide> <del> if ( layerCurveNodes[ i ] === undefined ) { <add> quaternion.setFromEuler( euler ); <ide> <del> var modelID; <add> if ( preRotations !== undefined ) quaternion.premultiply( preRotations ); <add> if ( postRotations !== undefined ) quaternion.multiply( postRotations ); <ide> <del> connections.get( child.ID ).parents.forEach( function ( parent ) { <add> quaternion.toArray( quaternionValues, ( i / 3 ) * 4 ); <ide> <del> if ( parent.relationship !== undefined ) modelID = parent.ID; <add> } <ide> <del> } ); <add> return new THREE.QuaternionKeyframeTrack( modelName + '.quaternion', times, quaternionValues ); <ide> <del> var rawModel = FBXTree.Objects.Model[ modelID.toString() ]; <add> }, <ide> <del> var node = { <add> generateMorphTrack: function ( rawTracks, sceneGraph ) { <ide> <del> modelName: THREE.PropertyBinding.sanitizeNodeName( rawModel.attrName ), <del> initialPosition: [ 0, 0, 0 ], <del> initialRotation: [ 0, 0, 0 ], <del> initialScale: [ 1, 1, 1 ], <del> transform: self.getModelAnimTransform( rawModel ), <add> var curves = rawTracks.DeformPercent.curves.morph; <add> var values = curves.values.map( function ( val ) { <ide> <del> }; <add> return val / 100; <ide> <del> // if the animated model is pre rotated, we'll have to apply the pre rotations to every <del> // animation value as well <del> if ( 'PreRotation' in rawModel ) node.preRotations = rawModel.PreRotation.value; <del> if ( 'PostRotation' in rawModel ) node.postRotations = rawModel.PostRotation.value; <add> } ); <ide> <del> layerCurveNodes[ i ] = node; <add> var morphNum = sceneGraph.getObjectByName( rawTracks.modelName ).morphTargetDictionary[ rawTracks.morphName ]; <ide> <del> } <add> return new THREE.NumberKeyframeTrack( rawTracks.modelName + '.morphTargetInfluences[' + morphNum + ']', curves.times, values ); <ide> <del> layerCurveNodes[ i ][ curveNode.attr ] = curveNode; <add> }, <ide> <del> } else if ( curveNode.curves.morph !== undefined ) { <add> // For all animated objects, times are defined separately for each axis <add> // Here we'll combine the times into one sorted array without duplicates <add> getTimesForAllAxes: function ( curves ) { <ide> <del> if ( layerCurveNodes[ i ] === undefined ) { <add> var times = []; <ide> <del> var deformerID; <add> // first join together the times for each axis, if defined <add> if ( curves.x !== undefined ) times = times.concat( curves.x.times ); <add> if ( curves.y !== undefined ) times = times.concat( curves.y.times ); <add> if ( curves.z !== undefined ) times = times.concat( curves.z.times ); <ide> <del> connections.get( child.ID ).parents.forEach( function ( parent ) { <add> // then sort them and remove duplicates <add> times = times.sort( function ( a, b ) { <ide> <del> if ( parent.relationship !== undefined ) deformerID = parent.ID; <add> return a - b; <ide> <del> } ); <add> } ).filter( function ( elem, index, array ) { <ide> <del> var morpherID = connections.get( deformerID ).parents[ 0 ].ID; <del> var geoID = connections.get( morpherID ).parents[ 0 ].ID; <add> return array.indexOf( elem ) == index; <ide> <del> // assuming geometry is not used in more than one model <del> var modelID = connections.get( geoID ).parents[ 0 ].ID; <add> } ); <ide> <del> var rawModel = FBXTree.Objects.Model[ modelID ]; <add> return times; <ide> <del> var node = { <add> }, <ide> <del> modelName: THREE.PropertyBinding.sanitizeNodeName( rawModel.attrName ), <del> morphName: FBXTree.Objects.Deformer[ deformerID ].attrName, <add> getKeyframeTrackValues: function ( times, curves, initialValue ) { <ide> <del> }; <add> var prevValue = initialValue; <ide> <del> layerCurveNodes[ i ] = node; <add> var values = []; <ide> <del> } <add> var xIndex = - 1; <add> var yIndex = - 1; <add> var zIndex = - 1; <ide> <del> layerCurveNodes[ i ][ curveNode.attr ] = curveNode; <add> times.forEach( function ( time ) { <ide> <del> } <add> if ( curves.x ) xIndex = curves.x.times.indexOf( time ); <add> if ( curves.y ) yIndex = curves.y.times.indexOf( time ); <add> if ( curves.z ) zIndex = curves.z.times.indexOf( time ); <ide> <del> } <add> // if there is an x value defined for this frame, use that <add> if ( xIndex !== - 1 ) { <ide> <del> } ); <add> var xValue = curves.x.values[ xIndex ]; <add> values.push( xValue ); <add> prevValue[ 0 ] = xValue; <ide> <del> layersMap.set( parseInt( nodeID ), layerCurveNodes ); <add> } else { <add> <add> // otherwise use the x value from the previous frame <add> values.push( prevValue[ 0 ] ); <ide> <ide> } <ide> <del> } <add> if ( yIndex !== - 1 ) { <ide> <del> return layersMap; <add> var yValue = curves.y.values[ yIndex ]; <add> values.push( yValue ); <add> prevValue[ 1 ] = yValue; <ide> <del> }, <add> } else { <ide> <del> getModelAnimTransform: function ( modelNode ) { <add> values.push( prevValue[ 1 ] ); <ide> <del> var transformData = {}; <add> } <ide> <del> if ( 'RotationOrder' in modelNode ) transformData.eulerOrder = parseInt( modelNode.RotationOrder.value ); <add> if ( zIndex !== - 1 ) { <ide> <del> if ( 'Lcl_Translation' in modelNode ) transformData.translation = modelNode.Lcl_Translation.value; <del> if ( 'RotationOffset' in modelNode ) transformData.rotationOffset = modelNode.RotationOffset.value; <add> var zValue = curves.z.values[ zIndex ]; <add> values.push( zValue ); <add> prevValue[ 2 ] = zValue; <ide> <del> if ( 'Lcl_Rotation' in modelNode ) transformData.rotation = modelNode.Lcl_Rotation.value; <del> if ( 'PreRotation' in modelNode ) transformData.preRotation = modelNode.PreRotation.value; <add> } else { <ide> <del> if ( 'PostRotation' in modelNode ) transformData.postRotation = modelNode.PostRotation.value; <add> values.push( prevValue[ 2 ] ); <ide> <del> if ( 'Lcl_Scaling' in modelNode ) transformData.scale = modelNode.Lcl_Scaling.value; <add> } <ide> <del> return generateTransform( transformData ); <add> } ); <add> <add> return values; <ide> <ide> }, <ide> <del> // parse nodes in FBXTree.Objects.AnimationStack. These are the top level node in the animation <del> // hierarchy. Each Stack node will be used to create a THREE.AnimationClip <del> parseAnimStacks: function ( layersMap ) { <add> // Rotations are defined as Euler angles which can have values of any size <add> // These will be converted to quaternions which don't support values greater than <add> // PI, so we'll interpolate large rotations <add> interpolateRotations: function ( curve ) { <ide> <del> var rawStacks = FBXTree.Objects.AnimationStack; <add> for ( var i = 1; i < curve.values.length; i ++ ) { <ide> <del> // connect the stacks (clips) up to the layers <del> var rawClips = {}; <add> var initialValue = curve.values[ i - 1 ]; <add> var valuesSpan = curve.values[ i ] - initialValue; <ide> <del> for ( var nodeID in rawStacks ) { <add> var absoluteSpan = Math.abs( valuesSpan ); <ide> <del> var children = connections.get( parseInt( nodeID ) ).children; <add> if ( absoluteSpan >= 180 ) { <ide> <del> if ( children.length > 1 ) { <add> var numSubIntervals = absoluteSpan / 180; <ide> <del> // it seems like stacks will always be associated with a single layer. But just in case there are files <del> // where there are multiple layers per stack, we'll display a warning <del> console.warn( 'THREE.FBXLoader: Encountered an animation stack with multiple layers, this is currently not supported. Ignoring subsequent layers.' ); <add> var step = valuesSpan / numSubIntervals; <add> var nextValue = initialValue + step; <ide> <del> } <add> var initialTime = curve.times[ i - 1 ]; <add> var timeSpan = curve.times[ i ] - initialTime; <add> var interval = timeSpan / numSubIntervals; <add> var nextTime = initialTime + interval; <ide> <del> var layer = layersMap.get( children[ 0 ].ID ); <add> var interpolatedTimes = []; <add> var interpolatedValues = []; <ide> <del> rawClips[ nodeID ] = { <add> while ( nextTime < curve.times[ i ] ) { <ide> <del> name: rawStacks[ nodeID ].attrName, <del> layer: layer, <add> interpolatedTimes.push( nextTime ); <add> nextTime += interval; <ide> <del> }; <add> interpolatedValues.push( nextValue ); <add> nextValue += step; <ide> <del> } <add> } <ide> <del> return rawClips; <add> curve.times = inject( curve.times, i, interpolatedTimes ); <add> curve.values = inject( curve.values, i, interpolatedValues ); <add> <add> } <add> <add> } <ide> <ide> }, <ide>
1
Javascript
Javascript
remove the need to rewrite chunk in reasons
7036ec488b3f5228df74ad9816262960b35c1826
<ide><path>lib/Chunk.js <ide> class Chunk { <ide> moveModule(module, otherChunk) { <ide> GraphHelpers.disconnectChunkAndModule(this, module); <ide> GraphHelpers.connectChunkAndModule(otherChunk, module); <del> module.rewriteChunkInReasons(this, [otherChunk]); <ide> } <ide> <ide> /** <ide><path>lib/Module.js <ide> class Module extends DependenciesBlock { <ide> /** @type {(string | OptimizationBailoutFunction)[]} */ <ide> this.optimizationBailout = []; <ide> <del> // delayed operations <del> /** @type {undefined | {oldChunk: Chunk, newChunks: Chunk[]}[] } */ <del> this._rewriteChunkInReasons = undefined; <del> <ide> /** @type {boolean} */ <ide> this.useSourceMap = false; <ide> <ide> class Module extends DependenciesBlock { <ide> this.renderedHash = undefined; <ide> <ide> this.reasons.length = 0; <del> this._rewriteChunkInReasons = undefined; <ide> this._chunks.clear(); <ide> <ide> this.id = null; <ide> class Module extends DependenciesBlock { <ide> return false; <ide> } <ide> <del> hasReasonForChunk(chunk) { <del> if (this._rewriteChunkInReasons) { <del> for (const operation of this._rewriteChunkInReasons) { <del> this._doRewriteChunkInReasons(operation.oldChunk, operation.newChunks); <del> } <del> this._rewriteChunkInReasons = undefined; <add> isAccessibleInChunk(chunk, ignoreChunk) { <add> // Check if module is accessible in ALL chunk groups <add> for (const chunkGroup of chunk.groupsIterable) { <add> if (!this.isAccessibleInChunkGroup(chunkGroup)) return false; <ide> } <del> for (let i = 0; i < this.reasons.length; i++) { <del> if (this.reasons[i].hasChunk(chunk)) return true; <del> } <del> return false; <add> return true; <ide> } <ide> <del> hasReasons() { <del> return this.reasons.length > 0; <del> } <add> isAccessibleInChunkGroup(chunkGroup, ignoreChunk) { <add> const queue = new Set([chunkGroup]); <ide> <del> rewriteChunkInReasons(oldChunk, newChunks) { <del> // This is expensive. Delay operation until we really need the data <del> if (this._rewriteChunkInReasons === undefined) { <del> this._rewriteChunkInReasons = []; <add> // Check if module is accessible from all items of the queue <add> queueFor: for (const cg of queue) { <add> // 1. If module is in one of the chunks of the group we can continue checking the next items <add> // because it's accessible. <add> for (const chunk of cg.chunks) { <add> if (chunk !== ignoreChunk && chunk.containsModule(this)) <add> continue queueFor; <add> } <add> // 2. If the chunk group is initial, we can break here because it's not accessible. <add> if (chunkGroup.isInitial()) return false; <add> // 3. Enqueue all parents because it must be accessible from ALL parents <add> for (const parent of chunkGroup.parentsIterable) queue.add(parent); <ide> } <del> this._rewriteChunkInReasons.push({ <del> oldChunk, <del> newChunks <del> }); <add> // When we processed through the whole list and we didn't bailout, the module is accessible <add> return true; <ide> } <ide> <del> _doRewriteChunkInReasons(oldChunk, newChunks) { <del> for (let i = 0; i < this.reasons.length; i++) { <del> this.reasons[i].rewriteChunks(oldChunk, newChunks); <add> hasReasonForChunk(chunk) { <add> // check for each reason if we need the chunk <add> for (const reason of this.reasons) { <add> const fromModule = reason.module; <add> for (const originChunk of fromModule.chunksIterable) { <add> // return true if module this is not reachable from originChunk when ignoring cunk <add> if (!this.isAccessibleInChunk(originChunk, chunk)) return true; <add> } <ide> } <add> return false; <add> } <add> <add> hasReasons() { <add> return this.reasons.length > 0; <ide> } <ide> <ide> isUsed(exportName) { <ide><path>lib/ModuleReason.js <ide> class ModuleReason { <ide> this.module = module; <ide> this.dependency = dependency; <ide> this.explanation = explanation; <del> this._chunks = null; <del> } <del> <del> hasChunk(chunk) { <del> if (this._chunks) { <del> if (this._chunks.has(chunk)) return true; <del> } else if (this.module && this.module._chunks.has(chunk)) return true; <del> return false; <del> } <del> <del> rewriteChunks(oldChunk, newChunks) { <del> if (!this._chunks) { <del> if (this.module) { <del> if (!this.module._chunks.has(oldChunk)) return; <del> this._chunks = new Set(this.module._chunks); <del> } else { <del> this._chunks = new Set(); <del> } <del> } <del> if (this._chunks.has(oldChunk)) { <del> this._chunks.delete(oldChunk); <del> for (let i = 0; i < newChunks.length; i++) { <del> this._chunks.add(newChunks[i]); <del> } <del> } <ide> } <ide> } <ide> <ide><path>lib/optimize/RemoveParentModulesPlugin.js <ide> const Queue = require("../util/Queue"); <ide> const { intersect } = require("../util/SetHelpers"); <ide> <del>const getParentChunksWithModule = (currentChunk, module) => { <del> const chunks = []; <del> const stack = new Set(currentChunk.parentsIterable); <del> <del> for (const chunk of stack) { <del> if (chunk.containsModule(module)) { <del> chunks.push(chunk); <del> } else { <del> for (const parent of chunk.parentsIterable) { <del> stack.add(parent); <del> } <del> } <del> } <del> <del> return chunks; <del>}; <del> <ide> class RemoveParentModulesPlugin { <ide> apply(compiler) { <ide> compiler.hooks.compilation.tap("RemoveParentModulesPlugin", compilation => { <ide> class RemoveParentModulesPlugin { <ide> } <ide> } <ide> for (const module of toRemove) { <del> module.rewriteChunkInReasons( <del> chunk, <del> getParentChunksWithModule(chunk, module) <del> ); <ide> chunk.removeModule(module); <ide> } <ide> } <ide><path>lib/optimize/SplitChunksPlugin.js <ide> module.exports = class SplitChunksPlugin { <ide> // Remove module from used chunks <ide> for (const chunk of usedChunks) { <ide> chunk.removeModule(module); <del> module.rewriteChunkInReasons(chunk, [newChunk]); <ide> } <ide> } <ide> } else { <ide> // Remove all modules from used chunks <ide> for (const module of item.modules) { <ide> for (const chunk of usedChunks) { <ide> chunk.removeModule(module); <del> module.rewriteChunkInReasons(chunk, [newChunk]); <ide> } <ide> } <ide> } <ide> module.exports = class SplitChunksPlugin { <ide> GraphHelpers.connectChunkAndModule(newPart, module); <ide> // Remove module from used chunks <ide> chunk.removeModule(module); <del> module.rewriteChunkInReasons(chunk, [newPart]); <ide> } <ide> } else { <ide> // change the chunk to be a part <ide><path>test/ModuleReason.unittest.js <del>"use strict"; <del> <del>const Module = require("../lib/Module"); <del>const Chunk = require("../lib/Chunk"); <del>const Dependency = require("../lib/Dependency"); <del>const ModuleReason = require("../lib/ModuleReason"); <del> <del>describe("ModuleReason", () => { <del> let myModule; <del> let myDependency; <del> let myModuleReason; <del> let myChunk; <del> let myChunk2; <del> <del> beforeEach(() => { <del> myModule = new Module(); <del> myDependency = new Dependency(); <del> myChunk = new Chunk("chunk-test", "module-test", "loc-test"); <del> myChunk2 = new Chunk("chunk-test", "module-test", "loc-test"); <del> <del> myModuleReason = new ModuleReason(myModule, myDependency); <del> }); <del> <del> describe("hasChunk", () => { <del> it("returns false when chunk is not present", () => { <del> expect(myModuleReason.hasChunk(myChunk)).toBe(false); <del> }); <del> <del> it("returns true when chunk is present", () => { <del> myModuleReason.module.addChunk(myChunk); <del> expect(myModuleReason.hasChunk(myChunk)).toBe(true); <del> }); <del> }); <del> <del> describe("rewriteChunks", () => { <del> it("if old chunk is present, it is replaced with new chunks", () => { <del> myModuleReason.module.addChunk(myChunk); <del> myModuleReason.rewriteChunks(myChunk, [myChunk2]); <del> <del> expect(myModuleReason.hasChunk(myChunk)).toBe(false); <del> expect(myModuleReason.hasChunk(myChunk2)).toBe(true); <del> }); <del> <del> it("if old chunk is not present, new chunks are not added", () => { <del> myModuleReason.rewriteChunks(myChunk, [myChunk2]); <del> <del> expect(myModuleReason.hasChunk(myChunk)).toBe(false); <del> expect(myModuleReason.hasChunk(myChunk2)).toBe(false); <del> }); <del> <del> it("if already rewritten chunk is present, it is replaced with new chunks", () => { <del> myModuleReason.module.addChunk(myChunk); <del> myModuleReason.rewriteChunks(myChunk, [myChunk2]); <del> myModuleReason.rewriteChunks(myChunk2, [myChunk]); <del> <del> expect(myModuleReason.hasChunk(myChunk)).toBe(true); <del> expect(myModuleReason.hasChunk(myChunk2)).toBe(false); <del> }); <del> }); <del>});
6
Python
Python
remove audit command
4fca38c078142744922a8c763bc1468e680a830d
<ide><path>setup.py <ide> def hello(): <ide> from setuptools import Command, setup <ide> <ide> <del>class run_audit(Command): <del> """Audits source code using PyFlakes for following issues: <del> - Names which are used but not defined or used before they are defined. <del> - Names which are redefined without having been used. <del> """ <del> description = "Audit source code with PyFlakes" <del> user_options = [] <del> <del> def initialize_options(self): <del> pass <del> <del> def finalize_options(self): <del> pass <del> <del> def run(self): <del> import os <del> import sys <del> try: <del> import pyflakes.scripts.pyflakes as flakes <del> except ImportError: <del> print("Audit requires PyFlakes installed in your system.") <del> sys.exit(-1) <del> <del> warns = 0 <del> # Define top-level directories <del> dirs = ('flask', 'examples', 'scripts') <del> for dir in dirs: <del> for root, _, files in os.walk(dir): <del> for file in files: <del> if file != '__init__.py' and file.endswith('.py'): <del> warns += flakes.checkPath(os.path.join(root, file)) <del> if warns > 0: <del> print("Audit finished with total %d warnings." % warns) <del> else: <del> print("No problems found in sourcecode.") <del> <ide> setup( <ide> name='Flask', <ide> version='0.11-dev', <ide> def run(self): <ide> entry_points=''' <ide> [console_scripts] <ide> flask=flask.cli:main <del> ''', <del> cmdclass={'audit': run_audit} <add> ''' <ide> )
1
Javascript
Javascript
remove debug message
3e0de40d3a5b033e1a188b8b896372b29e8ce502
<ide><path>vendor/browser-transforms.js <ide> function loadScripts(scripts) { <ide> dummyAnchor.href = script.src; <ide> sourceFilename = dummyAnchor.pathname.substr(1); <ide> } <del> console.log(sourceFilename); <ide> <ide> var options = { <ide> sourceMapInline: true,
1
Javascript
Javascript
use portable eol
4fedb702b221469a65f0f2bc267ae08c8159e72a
<ide><path>test/parallel/test-child-process-pipe-dataflow.js <ide> const common = require('../common'); <ide> const assert = require('assert'); <ide> const path = require('path'); <ide> const fs = require('fs'); <add>const os = require('os'); <ide> const spawn = require('child_process').spawn; <ide> const tmpdir = require('../common/tmpdir'); <ide> <ide> const MB = KB * KB; <ide> // meanings to new line - for example, line buffering. <ide> // So cut the buffer into lines at some points, forcing <ide> // data flow to be split in the stream. <del> for (let i = 0; i < KB; i++) <del> buf[i * KB] = 10; <add> for (let i = 1; i < KB; i++) <add> buf.write(os.EOL, i * KB); <ide> fs.writeFileSync(file, buf.toString()); <ide> <ide> cat = spawn('cat', [file]); <ide> const MB = KB * KB; <ide> }); <ide> <ide> wc.stdout.on('data', common.mustCall((data) => { <del> assert.strictEqual(data.toString().trim(), MB.toString()); <add> // Grep always adds one extra byte at the end. <add> assert.strictEqual(data.toString().trim(), (MB + 1).toString()); <ide> })); <ide> }
1
Java
Java
fix typo on javadoc
aa848d54ffa281165cf258ae020811b2d9b18fc7
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/support/ServletUriComponentsBuilder.java <ide> private static ServletUriComponentsBuilder initFromRequest(HttpServletRequest re <ide> * <ide> * <p>As of 4.3.15, this method replaces the contextPath with the value <ide> * of "X-Forwarded-Prefix" rather than prepending, thus aligning with <del> * {@code ForwardedHeaderFiller}. <add> * {@code ForwardedHeaderFilter}. <ide> */ <ide> public static ServletUriComponentsBuilder fromCurrentContextPath() { <ide> return fromContextPath(getCurrentRequest()); <ide> public static ServletUriComponentsBuilder fromCurrentContextPath() { <ide> * <ide> * <p>As of 4.3.15, this method replaces the contextPath with the value <ide> * of "X-Forwarded-Prefix" rather than prepending, thus aligning with <del> * {@code ForwardedHeaderFiller}. <add> * {@code ForwardedHeaderFilter}. <ide> */ <ide> public static ServletUriComponentsBuilder fromCurrentServletMapping() { <ide> return fromServletMapping(getCurrentRequest()); <ide> public static ServletUriComponentsBuilder fromCurrentServletMapping() { <ide> * <ide> * <p>As of 4.3.15, this method replaces the contextPath with the value <ide> * of "X-Forwarded-Prefix" rather than prepending, thus aligning with <del> * {@code ForwardedHeaderFiller}. <add> * {@code ForwardedHeaderFilter}. <ide> */ <ide> public static ServletUriComponentsBuilder fromCurrentRequestUri() { <ide> return fromRequestUri(getCurrentRequest()); <ide> public static ServletUriComponentsBuilder fromCurrentRequestUri() { <ide> * <ide> * <p>As of 4.3.15, this method replaces the contextPath with the value <ide> * of "X-Forwarded-Prefix" rather than prepending, thus aligning with <del> * {@code ForwardedHeaderFiller}. <add> * {@code ForwardedHeaderFilter}. <ide> */ <ide> public static ServletUriComponentsBuilder fromCurrentRequest() { <ide> return fromRequest(getCurrentRequest());
1
Javascript
Javascript
load common.js to test for global leaks
02fe8215f09ce8a89a5cd4e76cbd78a59771c96e
<ide><path>test/parallel/test-arm-math-exp-regress-1376.js <ide> // See https://github.com/nodejs/node/issues/1376 <ide> // and https://code.google.com/p/v8/issues/detail?id=4019 <ide> <add>require('../common'); <ide> Math.abs(-0.5); <ide> Math.acos(-0.5); <ide> Math.acosh(-0.5); <ide><path>test/parallel/test-bad-unicode.js <ide> 'use strict'; <add>require('../common'); <ide> var assert = require('assert'), <ide> exception = null; <ide> <ide><path>test/parallel/test-beforeexit-event-exit.js <ide> 'use strict'; <add>require('../common'); <ide> var assert = require('assert'); <ide> <ide> process.on('beforeExit', function() { <ide><path>test/parallel/test-child-process-fork-exec-argv.js <ide> 'use strict'; <add>require('../common'); <ide> var assert = require('assert'); <ide> var child_process = require('child_process'); <ide> var spawn = child_process.spawn; <ide><path>test/parallel/test-cluster-disconnect-before-exit.js <ide> 'use strict'; <add>require('../common'); <ide> var cluster = require('cluster'); <ide> <ide> if (cluster.isMaster) { <ide><path>test/parallel/test-cluster-disconnect-unshared-tcp.js <ide> 'use strict'; <add>require('../common'); <ide> process.env.NODE_CLUSTER_SCHED_POLICY = 'none'; <ide> <ide> var cluster = require('cluster'); <ide><path>test/parallel/test-cluster-disconnect-with-no-workers.js <ide> 'use strict'; <add>require('../common'); <ide> var assert = require('assert'); <ide> var cluster = require('cluster'); <ide> <ide><path>test/parallel/test-cluster-worker-events.js <ide> 'use strict'; <add>require('../common'); <ide> var assert = require('assert'); <ide> var cluster = require('cluster'); <ide> <ide><path>test/parallel/test-cluster-worker-forced-exit.js <ide> 'use strict'; <add>require('../common'); <ide> var assert = require('assert'); <ide> var cluster = require('cluster'); <ide> var net = require('net'); <ide><path>test/parallel/test-cluster-worker-isconnected.js <ide> 'use strict'; <add>require('../common'); <ide> var cluster = require('cluster'); <ide> var assert = require('assert'); <ide> var util = require('util'); <ide><path>test/parallel/test-cluster-worker-isdead.js <ide> 'use strict'; <add>require('../common'); <ide> var cluster = require('cluster'); <ide> var assert = require('assert'); <ide> var net = require('net'); <ide><path>test/parallel/test-domain-enter-exit.js <ide> 'use strict'; <ide> // Make sure the domain stack is a stack <ide> <add>require('../common'); <ide> var assert = require('assert'); <ide> var domain = require('domain'); <ide> <ide><path>test/parallel/test-domain-nested.js <ide> 'use strict'; <ide> // Make sure that the nested domains don't cause the domain stack to grow <ide> <add>require('../common'); <ide> var assert = require('assert'); <ide> var domain = require('domain'); <ide> <ide><path>test/parallel/test-domain-safe-exit.js <ide> 'use strict'; <ide> // Make sure the domain stack doesn't get clobbered by un-matched .exit() <ide> <add>require('../common'); <ide> var assert = require('assert'); <ide> var domain = require('domain'); <ide> <ide><path>test/parallel/test-event-emitter-errors.js <ide> 'use strict'; <add>require('../common'); <ide> var EventEmitter = require('events'); <ide> var assert = require('assert'); <ide> <ide><path>test/parallel/test-freelist.js <ide> <ide> // Flags: --expose-internals <ide> <add>require('../common'); <ide> const assert = require('assert'); <ide> const freelist = require('freelist'); <ide> const internalFreelist = require('internal/freelist'); <ide><path>test/parallel/test-http-client-read-in-error.js <ide> 'use strict'; <add>require('../common'); <ide> var net = require('net'); <ide> var http = require('http'); <ide> var util = require('util'); <ide><path>test/parallel/test-next-tick-doesnt-hang.js <ide> * does not hang the event loop. If this test times out it has failed. <ide> */ <ide> <add>require('../common'); <ide> process.nextTick(function() { <ide> // Nothing <ide> }); <ide><path>test/parallel/test-path-parse-format.js <ide> 'use strict'; <add>require('../common'); <ide> var assert = require('assert'); <ide> var path = require('path'); <ide> <ide><path>test/parallel/test-process-argv-0.js <ide> 'use strict'; <add>require('../common'); <ide> var path = require('path'); <ide> var assert = require('assert'); <ide> var spawn = require('child_process').spawn; <ide><path>test/parallel/test-process-binding.js <ide> 'use strict'; <add>require('../common'); <ide> var assert = require('assert'); <ide> <ide> assert.throws( <ide><path>test/parallel/test-process-exec-argv.js <ide> 'use strict'; <add>require('../common'); <ide> var assert = require('assert'); <ide> var spawn = require('child_process').spawn; <ide> <ide><path>test/parallel/test-process-exit-recursive.js <ide> 'use strict'; <add>require('../common'); <ide> var assert = require('assert'); <ide> <ide> // recursively calling .exit() should not overflow the call stack <ide><path>test/parallel/test-readline-interface.js <ide> 'use strict'; <add>require('../common'); <ide> var assert = require('assert'); <ide> var readline = require('readline'); <ide> var EventEmitter = require('events').EventEmitter; <ide><path>test/parallel/test-readline-keys.js <ide> 'use strict'; <add>require('../common'); <ide> var EventEmitter = require('events').EventEmitter; <ide> var PassThrough = require('stream').PassThrough; <ide> var assert = require('assert'); <ide><path>test/parallel/test-readline-set-raw-mode.js <ide> 'use strict'; <add>require('../common'); <ide> var assert = require('assert'); <ide> var readline = require('readline'); <ide> var Stream = require('stream'); <ide><path>test/parallel/test-readline-undefined-columns.js <ide> 'use strict'; <ide> <add>require('../common'); <ide> const assert = require('assert'); <ide> const PassThrough = require('stream').PassThrough; <ide> const readline = require('readline'); <ide><path>test/parallel/test-regress-GH-4256.js <ide> 'use strict'; <add>require('../common'); <ide> process.domain = null; <ide> var timer = setTimeout(function() { <ide> console.log('this console.log statement should not make node crash'); <ide><path>test/parallel/test-regress-GH-5927.js <ide> 'use strict'; <add>require('../common'); <ide> var assert = require('assert'); <ide> var readline = require('readline'); <ide> <ide><path>test/parallel/test-regress-GH-io-1068.js <ide> 'use strict'; <add>require('../common'); <ide> process.stdin.emit('end'); <ide><path>test/parallel/test-regress-GH-io-1811.js <ide> 'use strict'; <ide> <add>require('../common'); <ide> const assert = require('assert'); <ide> <ide> // Change kMaxLength for zlib to trigger the error without having to allocate <ide><path>test/parallel/test-regress-GH-node-9326.js <ide> 'use strict'; <add>require('../common'); <ide> var assert = require('assert'); <ide> var child_process = require('child_process'); <ide> <ide><path>test/parallel/test-repl-tab.js <ide> 'use strict'; <add>require('../common'); <ide> var assert = require('assert'); <ide> var util = require('util'); <ide> var repl = require('repl'); <ide><path>test/parallel/test-require-json.js <ide> 'use strict'; <add>require('../common'); <ide> var assert = require('assert'); <ide> <ide> try { <ide><path>test/parallel/test-require-process.js <ide> 'use strict'; <add>require('../common'); <ide> var assert = require('assert'); <ide> <ide> var nativeProcess = require('process'); <ide><path>test/parallel/test-stdin-pause-resume-sync.js <ide> 'use strict'; <add>require('../common'); <ide> console.error('before opening stdin'); <ide> process.stdin.resume(); <ide> console.error('stdin opened'); <ide><path>test/parallel/test-stdin-pause-resume.js <ide> 'use strict'; <add>require('../common'); <ide> console.error('before opening stdin'); <ide> process.stdin.resume(); <ide> console.error('stdin opened'); <ide><path>test/parallel/test-stdin-resume-pause.js <ide> 'use strict'; <add>require('../common'); <ide> process.stdin.resume(); <ide> process.stdin.pause(); <ide><path>test/parallel/test-string-decoder-end.js <ide> // the whole buffer at once, and that both match the .toString(enc) <ide> // result of the entire buffer. <ide> <add>require('../common'); <ide> var assert = require('assert'); <ide> var SD = require('string_decoder').StringDecoder; <ide> var encodings = ['base64', 'hex', 'utf8', 'utf16le', 'ucs2']; <ide><path>test/parallel/test-sync-io-option.js <ide> 'use strict'; <ide> <add>require('../common'); <ide> const assert = require('assert'); <ide> const execFile = require('child_process').execFile; <ide> <ide><path>test/parallel/test-timer-close.js <ide> 'use strict'; <add>require('../common'); <ide> var assert = require('assert'); <ide> <ide> var t = new (process.binding('timer_wrap').Timer); <ide><path>test/parallel/test-timers-non-integer-delay.js <ide> * it 100%. <ide> */ <ide> <add>require('../common'); <ide> var assert = require('assert'); <ide> <ide> var TIMEOUT_DELAY = 1.1; <ide><path>test/parallel/test-timers-this.js <ide> 'use strict'; <add>require('../common'); <ide> var assert = require('assert'); <ide> <ide> var immediateThis, intervalThis, timeoutThis, <ide><path>test/parallel/test-timers-unref-leak.js <ide> 'use strict'; <add>require('../common'); <ide> var assert = require('assert'); <ide> <ide> var called = 0; <ide><path>test/parallel/test-timers-unrefd-interval-still-fires.js <ide> /* <ide> * This test is a regression test for joyent/node#8900. <ide> */ <add>require('../common'); <ide> var assert = require('assert'); <ide> <ide> var N = 5; <ide><path>test/parallel/test-util-log.js <ide> 'use strict'; <add>require('../common'); <ide> var assert = require('assert'); <ide> var util = require('util'); <ide> <ide><path>test/sequential/test-cluster-listening-port.js <ide> 'use strict'; <add>require('../common'); <ide> var assert = require('assert'); <ide> var cluster = require('cluster'); <ide> var net = require('net'); <ide><path>test/sequential/test-vm-timeout-rethrow.js <ide> 'use strict'; <add>require('../common'); <ide> var assert = require('assert'); <ide> var vm = require('vm'); <ide> var spawn = require('child_process').spawn;
48
PHP
PHP
fix failing postgres tests
618509293da26581c4837d8665f77eeaa959129f
<ide><path>tests/TestCase/Database/QueryTest.php <ide> public function testSqlCaseStatement() { <ide> ->add(['published' => 'N']), 1, 'integer' <ide> ); <ide> <add> //Postgres requires the case statement to be cast to a integer <add> if ($this->connection->driver() instanceof \Cake\Database\Driver\Postgres) { <add> $publishedCase = $query->func()->cast([$publishedCase, 'integer' => 'literal'])->type(' AS '); <add> $notPublishedCase = $query->func()->cast([$notPublishedCase, 'integer' => 'literal'])->type(' AS '); <add> } <add> <ide> $results = $query <ide> ->select([ <ide> 'published' => $query->func()->sum($publishedCase),
1
Text
Text
add note about changing basepath config
6c282a3df4df178ea121234baa1a7868c0389b82
<ide><path>docs/api-reference/next.config.js/basepath.md <ide> module.exports = { <ide> } <ide> ``` <ide> <add>Note: this value must be set at build time and can not be changed without re-building as the value is inlined in the client-side bundles. <add> <ide> ## Links <ide> <ide> When linking to other pages using `next/link` and `next/router` the `basePath` will be automatically applied.
1
Python
Python
handle nan and inf in assert_equal
60fd0b786909db327fe4f3e925047e2c2f58f2d2
<ide><path>numpy/testing/tests/test_utils.py <ide> def test_objarray(self): <ide> a = np.array([1, 1], dtype=np.object) <ide> self._test_equal(a, 1) <ide> <del>class TestEqual(_GenericTest, unittest.TestCase): <add>class TestArrayEqual(_GenericTest, unittest.TestCase): <ide> def setUp(self): <ide> self._assert_func = assert_array_equal <ide> <ide> def test_recarrays(self): <ide> <ide> self._test_not_equal(c, b) <ide> <add>class TestEqual(TestArrayEqual): <add> def setUp(self): <add> self._assert_func = assert_equal <add> <add> def test_nan_items(self): <add> self._assert_func(np.nan, np.nan) <add> self._assert_func([np.nan], [np.nan]) <add> self._test_not_equal(np.nan, [np.nan]) <add> self._test_not_equal(np.nan, 1) <add> <add> def test_inf_items(self): <add> self._assert_func(np.inf, np.inf) <add> self._assert_func([np.inf], [np.inf]) <add> self._test_not_equal(np.inf, [np.inf]) <add> <add> def test_non_numeric(self): <add> self._assert_func('ab', 'ab') <add> self._test_not_equal('ab', 'abb') <ide> <ide> class TestArrayAlmostEqual(_GenericTest, unittest.TestCase): <ide> def setUp(self): <ide><path>numpy/testing/utils.py <ide> def assert_equal(actual,desired,err_msg='',verbose=True): <ide> for k in range(len(desired)): <ide> assert_equal(actual[k], desired[k], 'item=%r\n%s' % (k,err_msg), verbose) <ide> return <del> from numpy.core import ndarray <add> from numpy.core import ndarray, isscalar <ide> if isinstance(actual, ndarray) or isinstance(desired, ndarray): <ide> return assert_array_equal(actual, desired, err_msg, verbose) <ide> msg = build_err_msg([actual, desired], err_msg, verbose=verbose) <add> <add> try: <add> # If one of desired/actual is not finite, handle it specially here: <add> # check that both are nan if any is a nan, and test for equality <add> # otherwise <add> if not (gisfinite(desired) and gisfinite(actual)): <add> isdesnan = gisnan(desired) <add> isactnan = gisnan(actual) <add> if isdesnan or isactnan: <add> # isscalar test to check so that [np.nan] != np.nan <add> if not (isdesnan and isactnan) \ <add> or (isscalar(isdesnan) != isscalar(isactnan)): <add> raise AssertionError(msg) <add> else: <add> if not desired == actual: <add> raise AssertionError(msg) <add> return <add> # If TypeError or ValueError raised while using isnan and co, just handle <add> # as before <add> except TypeError: <add> pass <add> except ValueError: <add> pass <ide> if desired != actual : <ide> raise AssertionError(msg) <ide>
2
Javascript
Javascript
remove trailing spaces from banners
e29779957a3b2c5b71e6aa3a2d88d21bed6eec2d
<ide><path>lib/BannerPlugin.js <ide> const wrapComment = str => { <ide> return `/*!\n * ${str <ide> .replace(/\*\//g, "* /") <ide> .split("\n") <del> .join("\n * ")}\n */`; <add> .join("\n * ") <add> .replace(/\s+\n/g, "\n") <add> .trimRight()}\n */`; <ide> }; <ide> <ide> class BannerPlugin { <ide><path>test/configCases/plugins/banner-plugin/index.js <ide> it("should contain banner in bundle0 chunk", () => { <ide> expect(source).toMatch("banner is a string"); <ide> expect(source).toMatch("banner is a function"); <ide> expect(source).toMatch("/*!\n * multiline\n * banner\n * bundle0\n */"); <add> expect(source).toMatch("/*!\n * trim trailing whitespace\n *\n * trailing whitespace\n */"); <add> expect(source).toMatch("/*!\n * trim trailing whitespace\n *\n * no trailing whitespace\n */"); <ide> }); <ide> <ide> it("should not contain banner in vendors chunk", () => { <ide><path>test/configCases/plugins/banner-plugin/webpack.config.js <ide> module.exports = { <ide> }), <ide> new webpack.BannerPlugin({ <ide> banner: ({ chunk }) => `multiline\nbanner\n${chunk.name}` <del> }) <add> }), <add> new webpack.BannerPlugin( <add> "trim trailing whitespace\t \n\ntrailing whitespace " <add> ), <add> new webpack.BannerPlugin( <add> "trim trailing whitespace\t \n\nno trailing whitespace" <add> ) <ide> ] <ide> };
3
Text
Text
improve changelog [ci skip]
d65ab433ae095d99b51786c5c69be8f6cdd5e249
<ide><path>activesupport/CHANGELOG.md <del>* Fixed backward compatibility isues introduced in 326e652 <add>* Fixed backward compatibility isues introduced in 326e652. <ide> <del> Empty Hash or Array should not present in serialization result <add> Empty Hash or Array should not present in serialization result. <ide> <ide> {a: []}.to_query # => "" <ide> {a: {}}.to_query # => ""
1
Python
Python
take two on auth for beeline
19651db63f3f8584979fc82cde94e9fc753fa46f
<ide><path>airflow/hooks/hive_hooks.py <ide> class HiveCliHook(BaseHook): <ide> Note that you can also set default hive CLI parameters using the <ide> ``hive_cli_params`` to be used in your connection as in <ide> ``{"hive_cli_params": "-hiveconf mapred.job.tracker=some.jobtracker:444"}`` <add> <add> The extra connection parameter ``auth`` gets passed as in the ``jdbc`` <add> connection string as is. <add> <ide> """ <ide> <ide> def __init__( <ide> def __init__( <ide> conn = self.get_connection(hive_cli_conn_id) <ide> self.hive_cli_params = conn.extra_dejson.get('hive_cli_params', '') <ide> self.use_beeline = conn.extra_dejson.get('use_beeline', False) <del> self.auth_mechanism = db.extra_dejson.get('authMechanism', 'NOSASL') <add> self.auth = conn.extra_dejson.get('auth', 'noSasl') <ide> self.conn = conn <ide> self.run_as = run_as <ide> <ide> def run_cli(self, hql, schema=None, verbose=True): <ide> proxy_user = "hive.server2.proxy.user={0}".format(self.run_as) <ide> <ide> jdbc_url += ";principal={template};{proxy_user}" <del> elif self.auth_mechanism == "NOSASL": <del> jdbc_url += ";auth=noSasl" <add> elif self.auth: <add> jdbc_url += ";auth=" + self.auth <ide> <ide> jdbc_url = jdbc_url.format(**locals()) <ide>
1
Ruby
Ruby
remove meaningless line from adapter_test.rb
d3b3925d7d7ee53bfa1236db883924c6a3b09086
<ide><path>activerecord/test/cases/adapter_test.rb <ide> def test_create_record_with_pk_as_zero <ide> end <ide> <ide> def test_tables <del> tables = nil <ide> tables = @connection.tables <ide> assert_includes tables, "accounts" <ide> assert_includes tables, "authors"
1
Go
Go
add testcontainerorphaning integration test
c995c9bb91a2bf5b2038330d063a073d2e0c611c
<ide><path>integration/commands_test.go <ide> func TestRunCidFile(t *testing.T) { <ide> }) <ide> <ide> } <add> <add>func TestContainerOrphaning(t *testing.T) { <add> <add> // setup a temporary directory <add> tmpDir, err := ioutil.TempDir("", "project") <add> if err != nil { <add> t.Fatal(err) <add> } <add> defer os.RemoveAll(tmpDir) <add> <add> // setup a CLI and server <add> cli := docker.NewDockerCli(nil, os.Stdout, ioutil.Discard, testDaemonProto, testDaemonAddr) <add> defer cleanup(globalEngine, t) <add> srv := mkServerFromEngine(globalEngine, t) <add> <add> // closure to build something <add> buildSomething := func(template string, image string) string { <add> dockerfile := path.Join(tmpDir, "Dockerfile") <add> replacer := strings.NewReplacer("{IMAGE}", unitTestImageID) <add> contents := replacer.Replace(template) <add> ioutil.WriteFile(dockerfile, []byte(contents), 0x777) <add> if err := cli.CmdBuild("-t", image, tmpDir); err != nil { <add> t.Fatal(err) <add> } <add> img, err := srv.ImageInspect(image) <add> if err != nil { <add> t.Fatal(err) <add> } <add> return img.ID <add> } <add> <add> // build an image <add> imageName := "orphan-test" <add> template1 := ` <add> from {IMAGE} <add> cmd ["/bin/echo", "holla"] <add> ` <add> img1 := buildSomething(template1, imageName) <add> <add> // create a container using the fist image <add> if err := cli.CmdRun(imageName); err != nil { <add> t.Fatal(err) <add> } <add> <add> // build a new image that splits lineage <add> template2 := ` <add> from {IMAGE} <add> cmd ["/bin/echo", "holla"] <add> expose 22 <add> ` <add> buildSomething(template2, imageName) <add> <add> // remove the second image by name <add> resp, err := srv.ImageDelete(imageName, true) <add> <add> // see if we deleted the first image (and orphaned the container) <add> for _, i := range resp { <add> if img1 == i.Deleted { <add> t.Fatal("Orphaned image with container") <add> } <add> } <add> <add>}
1
Javascript
Javascript
name anonymous function in _stream_writable.js
caf2335a47db089a1e1b2c5a90d85cf644f6c355
<ide><path>lib/_stream_writable.js <ide> WritableState.prototype.getBuffer = function getBuffer() { <ide> }; <ide> <ide> Object.defineProperty(WritableState.prototype, 'buffer', { <del> get: internalUtil.deprecate(function() { <add> get: internalUtil.deprecate(function writableStateBufferGetter() { <ide> return this.getBuffer(); <ide> }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + <ide> 'instead.', 'DEP0003')
1
Go
Go
remove unused eventbuffer update
54d021ef8f56f90cc4f7fc604190560361dd6b0c
<ide><path>daemon/logger/awslogs/cloudwatchlogs.go <ide> func (l *logStream) collectBatch(created chan bool) { <ide> if !more { <ide> // Flush event buffer and release resources <ide> l.processEvent(batch, eventBuffer, eventBufferTimestamp) <del> eventBuffer = eventBuffer[:0] <ide> l.publishBatch(batch) <ide> batch.reset() <ide> return
1
Python
Python
fix broken static checks from
f2315bf31b513c18eb266467f6c3036351d15050
<ide><path>airflow/www/views.py <ide> def duration(self, session=None): <ide> dag = dag.partial_subset(task_ids_or_regex=root, include_upstream=True, include_downstream=False) <ide> chart_height = wwwutils.get_chart_height(dag) <ide> chart = nvd3.lineChart( <del> name="lineChart", <del> x_is_date=True, <del> height=chart_height, <del> chart_attr=self.line_chart_attr <add> name="lineChart", x_is_date=True, height=chart_height, chart_attr=self.line_chart_attr <ide> ) <ide> cum_chart = nvd3.lineChart( <del> name="cumLineChart", <del> x_is_date=True, <del> height=chart_height, <del> chart_attr=self.line_chart_attr <add> name="cumLineChart", x_is_date=True, height=chart_height, chart_attr=self.line_chart_attr <ide> ) <ide> <ide> y_points = defaultdict(list) <ide> def tries(self, session=None): <ide> x_is_date=True, <ide> y_axis_format='d', <ide> height=chart_height, <del> chart_attr=self.line_chart_attr <add> chart_attr=self.line_chart_attr, <ide> ) <ide> <ide> for task in dag.tasks: <ide> def landing_times(self, session=None): <ide> <ide> chart_height = wwwutils.get_chart_height(dag) <ide> chart = nvd3.lineChart( <del> name="lineChart", <del> x_is_date=True, <del> height=chart_height, <del> chart_attr=self.line_chart_attr <add> name="lineChart", x_is_date=True, height=chart_height, chart_attr=self.line_chart_attr <ide> ) <ide> y_points = {} <ide> x_points = {}
1
Javascript
Javascript
remove unused (local) variables in web/
d7dfa447cd696843ff178a6b85e588a8fe4633b0
<ide><path>web/debugger.js <ide> <ide> var FontInspector = (function FontInspectorClosure() { <ide> var fonts; <del> var panelWidth = 300; <ide> var active = false; <ide> var fontAttribute = 'data-font-name'; <ide> function removeSelection() { <ide> var Stepper = (function StepperClosure() { <ide> return; <ide> } <ide> <del> var self = this; <ide> var chunk = document.createDocumentFragment(); <ide> var operatorsToDisplay = Math.min(MAX_OPERATORS_COUNT, <ide> operatorList.fnArray.length); <ide><path>web/page_view.js <ide> var PageView = function pageView(container, id, scale, <ide> div.appendChild(canvasWrapper); <ide> this.canvas = canvas; <ide> <del> var scale = this.scale; <ide> var ctx = canvas.getContext('2d'); <ide> var outputScale = getOutputScale(ctx); <ide> <ide> var PageView = function pageView(container, id, scale, <ide> canvasWrapper.appendChild(canvas); <ide> printContainer.appendChild(canvasWrapper); <ide> <del> var self = this; <ide> canvas.mozPrintCallback = function(obj) { <ide> var ctx = obj.context; <ide> <ide><path>web/text_layer_builder.js <ide> var TextLayerBuilder = function textLayerBuilder(options) { <ide> var queryLen = (PDFFindController === null ? <ide> 0 : PDFFindController.state.query.length); <ide> <del> var lastDivIdx = -1; <del> var pos; <del> <ide> var ret = []; <ide> <ide> // Loop over all the matches. <ide><path>web/viewer.js <ide> var PDFView = { <ide> parseQueryString: function pdfViewParseQueryString(query) { <ide> var parts = query.split('&'); <ide> var params = {}; <del> for (var i = 0, ii = parts.length; i < parts.length; ++i) { <add> for (var i = 0, ii = parts.length; i < ii; ++i) { <ide> var param = parts[i].split('='); <ide> var key = param[0]; <ide> var value = param.length > 1 ? param[1] : null; <ide> var PDFView = { <ide> <ide> var DocumentOutlineView = function documentOutlineView(outline) { <ide> var outlineView = document.getElementById('outlineView'); <del> var outlineButton = document.getElementById('viewOutline'); <ide> while (outlineView.firstChild) { <ide> outlineView.removeChild(outlineView.firstChild); <ide> }
4
Python
Python
enable memory metrics in tests that need it
6da129cb3152d93c425aab08a92d68c99e09d252
<ide><path>tests/test_trainer.py <ide> def check_mem_metrics(self, trainer, check_func): <ide> def test_mem_metrics(self): <ide> <ide> # with mem metrics enabled <del> trainer = get_regression_trainer() <add> trainer = get_regression_trainer(skip_memory_metrics=False) <ide> self.check_mem_metrics(trainer, self.assertIn) <ide> <ide> # with mem metrics disabled <ide> def test_fp16_full_eval(self): <ide> b = torch.ones(1000, bs) - 0.001 <ide> <ide> # 1. with mem metrics enabled <del> trainer = get_regression_trainer(a=a, b=b, eval_len=16) <add> trainer = get_regression_trainer(a=a, b=b, eval_len=16, skip_memory_metrics=False) <ide> metrics = trainer.evaluate() <ide> del trainer <ide> gc.collect() <ide> def test_fp16_full_eval(self): <ide> self.assertLess(fp32_eval, 5_000) <ide> <ide> # 2. with mem metrics disabled <del> trainer = get_regression_trainer(a=a, b=b, eval_len=16, fp16_full_eval=True) <add> trainer = get_regression_trainer(a=a, b=b, eval_len=16, fp16_full_eval=True, skip_memory_metrics=False) <ide> metrics = trainer.evaluate() <ide> fp16_init = metrics["init_mem_gpu_alloc_delta"] <ide> fp16_eval = metrics["eval_mem_gpu_alloc_delta"]
1
Javascript
Javascript
use map to track handles in master
847037eaeddbb4ad493a6686f61f8b2d03266ff2
<ide><path>lib/internal/cluster/master.js <ide> function removeWorker(worker) { <ide> delete cluster.workers[worker.id]; <ide> <ide> if (keys(cluster.workers).length === 0) { <del> assert(keys(handles).length === 0, 'Resource leak detected.'); <add> assert(handles.size === 0, 'Resource leak detected.'); <ide> intercom.emit('disconnect'); <ide> } <ide> } <ide> <ide> function removeHandlesForWorker(worker) { <ide> assert(worker); <ide> <del> for (var key in handles) { <del> const handle = handles[key]; <del> <add> handles.forEach((handle, key) => { <ide> if (handle.remove(worker)) <del> delete handles[key]; <del> } <add> handles.delete(key); <add> }); <ide> } <ide> <ide> cluster.fork = function(env) { <ide> function queryServer(worker, message) { <ide> <ide> const key = `${message.address}:${message.port}:${message.addressType}:` + <ide> `${message.fd}:${message.index}`; <del> var handle = handles[key]; <add> var handle = handles.get(key); <ide> <ide> if (handle === undefined) { <ide> let address = message.address; <ide> function queryServer(worker, message) { <ide> constructor = SharedHandle; <ide> } <ide> <del> handles[key] = handle = new constructor(key, <del> address, <del> message.port, <del> message.addressType, <del> message.fd, <del> message.flags); <add> handle = new constructor(key, <add> address, <add> message.port, <add> message.addressType, <add> message.fd, <add> message.flags); <add> handles.set(key, handle); <ide> } <ide> <ide> if (!handle.data) <ide> function queryServer(worker, message) { <ide> errno: errno, <ide> key: key, <ide> ack: message.seq, <del> data: handles[key].data <add> data: handles.get(key).data <ide> }, reply); <ide> <ide> if (errno) <del> delete handles[key]; // Gives other workers a chance to retry. <add> handles.delete(key); // Gives other workers a chance to retry. <ide> <ide> send(worker, reply, handle); <ide> }); <ide> function listening(worker, message) { <ide> // removed by a prior call to removeHandlesForWorker() so guard against that. <ide> function close(worker, message) { <ide> const key = message.key; <del> const handle = handles[key]; <add> const handle = handles.get(key); <ide> <ide> if (handle && handle.remove(worker)) <del> delete handles[key]; <add> handles.delete(key); <ide> } <ide> <ide> function send(worker, message, handle, cb) { <ide><path>lib/internal/cluster/utils.js <ide> const util = require('util'); <ide> module.exports = { <ide> sendHelper, <ide> internal, <del> handles: {} // Used in tests. <add> handles: new Map() // Used in tests. <ide> }; <ide> <ide> const callbacks = new Map();
2
Javascript
Javascript
add fast path for utf8
770efeab6db5d78199d3b5bbc1bfb44a21637dc0
<ide><path>lib/internal/webstreams/adapters.js <ide> const { <ide> Uint8Array, <ide> } = primordials; <ide> <add>const { TextEncoder } = require('internal/encoding'); <add> <ide> const { <ide> ReadableStream, <ide> isReadableStream, <ide> const { <ide> const { <ide> createDeferredPromise, <ide> kEmptyObject, <add> normalizeEncoding, <ide> } = require('internal/util'); <ide> <ide> const { <ide> const finished = require('internal/streams/end-of-stream'); <ide> <ide> const { UV_EOF } = internalBinding('uv'); <ide> <add>const encoder = new TextEncoder(); <add> <ide> /** <ide> * @typedef {import('../../stream').Writable} Writable <ide> * @typedef {import('../../stream').Readable} Readable <ide> function newStreamWritableFromWritableStream(writableStream, options = kEmptyObj <ide> <ide> write(chunk, encoding, callback) { <ide> if (typeof chunk === 'string' && decodeStrings && !objectMode) { <del> chunk = Buffer.from(chunk, encoding); <del> chunk = new Uint8Array( <del> chunk.buffer, <del> chunk.byteOffset, <del> chunk.byteLength); <add> const enc = normalizeEncoding(encoding); <add> <add> if (enc === 'utf8') { <add> chunk = encoder.encode(chunk); <add> } else { <add> chunk = Buffer.from(chunk, encoding); <add> chunk = new Uint8Array( <add> chunk.buffer, <add> chunk.byteOffset, <add> chunk.byteLength); <add> } <ide> } <ide> <ide> function done(error) { <ide> function newStreamDuplexFromReadableWritablePair(pair = kEmptyObject, options = <ide> <ide> write(chunk, encoding, callback) { <ide> if (typeof chunk === 'string' && decodeStrings && !objectMode) { <del> chunk = Buffer.from(chunk, encoding); <del> chunk = new Uint8Array( <del> chunk.buffer, <del> chunk.byteOffset, <del> chunk.byteLength); <add> const enc = normalizeEncoding(encoding); <add> <add> if (enc === 'utf8') { <add> chunk = encoder.encode(chunk); <add> } else { <add> chunk = Buffer.from(chunk, encoding); <add> chunk = new Uint8Array( <add> chunk.buffer, <add> chunk.byteOffset, <add> chunk.byteLength); <add> } <ide> } <ide> <ide> function done(error) {
1
Ruby
Ruby
remove duplicated codes
30c84aababbd9411a0820e9e238f12b4c6054714
<ide><path>activerecord/test/cases/database_tasks_test.rb <ide> require 'cases/helper' <ide> <ide> module ActiveRecord <del> class DatabaseTasksCreateTest < ActiveRecord::TestCase <add> module DatabaseTasksSetupper <ide> def setup <ide> @mysql_tasks, @postgresql_tasks, @sqlite_tasks = stub, stub, stub <del> <ide> ActiveRecord::Tasks::MySQLDatabaseTasks.stubs(:new).returns @mysql_tasks <del> ActiveRecord::Tasks::PostgreSQLDatabaseTasks.stubs(:new). <del> returns @postgresql_tasks <add> ActiveRecord::Tasks::PostgreSQLDatabaseTasks.stubs(:new).returns @postgresql_tasks <ide> ActiveRecord::Tasks::SQLiteDatabaseTasks.stubs(:new).returns @sqlite_tasks <ide> end <add> end <add> <add> class DatabaseTasksCreateTest < ActiveRecord::TestCase <add> include DatabaseTasksSetupper <ide> <ide> def test_mysql_create <ide> @mysql_tasks.expects(:create) <ide> def test_establishes_connection_for_the_given_environment <ide> end <ide> <ide> class DatabaseTasksDropTest < ActiveRecord::TestCase <del> def setup <del> @mysql_tasks, @postgresql_tasks, @sqlite_tasks = stub, stub, stub <del> <del> ActiveRecord::Tasks::MySQLDatabaseTasks.stubs(:new).returns @mysql_tasks <del> ActiveRecord::Tasks::PostgreSQLDatabaseTasks.stubs(:new). <del> returns @postgresql_tasks <del> ActiveRecord::Tasks::SQLiteDatabaseTasks.stubs(:new).returns @sqlite_tasks <del> end <add> include DatabaseTasksSetupper <ide> <ide> def test_mysql_create <ide> @mysql_tasks.expects(:drop) <ide> def test_creates_test_database_when_environment_is_database <ide> end <ide> <ide> class DatabaseTasksPurgeTest < ActiveRecord::TestCase <del> def setup <del> @mysql_tasks, @postgresql_tasks, @sqlite_tasks = stub, stub, stub <del> <del> ActiveRecord::Tasks::MySQLDatabaseTasks.stubs(:new).returns @mysql_tasks <del> ActiveRecord::Tasks::PostgreSQLDatabaseTasks.stubs(:new). <del> returns @postgresql_tasks <del> ActiveRecord::Tasks::SQLiteDatabaseTasks.stubs(:new).returns @sqlite_tasks <del> end <add> include DatabaseTasksSetupper <ide> <ide> def test_mysql_create <ide> @mysql_tasks.expects(:purge) <ide> def test_sqlite_create <ide> end <ide> <ide> class DatabaseTasksCharsetTest < ActiveRecord::TestCase <del> def setup <del> @mysql_tasks, @postgresql_tasks, @sqlite_tasks = stub, stub, stub <del> ActiveRecord::Tasks::MySQLDatabaseTasks.stubs(:new).returns @mysql_tasks <del> ActiveRecord::Tasks::PostgreSQLDatabaseTasks.stubs(:new). <del> returns @postgresql_tasks <del> ActiveRecord::Tasks::SQLiteDatabaseTasks.stubs(:new).returns @sqlite_tasks <del> end <add> include DatabaseTasksSetupper <ide> <ide> def test_mysql_charset <ide> @mysql_tasks.expects(:charset) <ide> def test_sqlite_charset <ide> end <ide> <ide> class DatabaseTasksStructureDumpTest < ActiveRecord::TestCase <del> def setup <del> @mysql_tasks, @postgresql_tasks, @sqlite_tasks = stub, stub, stub <del> ActiveRecord::Tasks::MySQLDatabaseTasks.stubs(:new).returns @mysql_tasks <del> ActiveRecord::Tasks::PostgreSQLDatabaseTasks.stubs(:new). <del> returns @postgresql_tasks <del> ActiveRecord::Tasks::SQLiteDatabaseTasks.stubs(:new).returns @sqlite_tasks <del> end <add> include DatabaseTasksSetupper <ide> <ide> def test_mysql_structure_dump <ide> @mysql_tasks.expects(:structure_dump).with("awesome-file.sql") <ide> def test_sqlite_structure_dump <ide> end <ide> <ide> class DatabaseTasksStructureLoadTest < ActiveRecord::TestCase <del> def setup <del> @mysql_tasks, @postgresql_tasks, @sqlite_tasks = stub, stub, stub <del> ActiveRecord::Tasks::MySQLDatabaseTasks.stubs(:new).returns @mysql_tasks <del> ActiveRecord::Tasks::PostgreSQLDatabaseTasks.stubs(:new). <del> returns @postgresql_tasks <del> ActiveRecord::Tasks::SQLiteDatabaseTasks.stubs(:new).returns @sqlite_tasks <del> end <add> include DatabaseTasksSetupper <ide> <ide> def test_mysql_structure_load <ide> @mysql_tasks.expects(:structure_load).with("awesome-file.sql")
1
Text
Text
fix typo in readme
58fcb37760ad1d0421f15b1081fd55bdbeccd314
<ide><path>README.md <ide> # Chart.js <ide> <del>[![Build Status](https://travis-ci.org/nnnick/Chart.js.svg?branch=v2.0-dev)](https://travis-ci.org/nnnick/Chart.js) [![Code Climate](https://codeclimate.com/github/nnnick/Chart.js/badges/gpa.svg)](https://codeclimate.com/github/nnnick/Chart.js)[![Coverage Status](https://coveralls.io/repos/nnnick/Chart.js/badge.svg?branch=v2.0-dev)](https://coveralls.io/r/nnncik/Chart.js?branch=v2.0-dev) <add>[![Build Status](https://travis-ci.org/nnnick/Chart.js.svg?branch=v2.0-dev)](https://travis-ci.org/nnnick/Chart.js) [![Code Climate](https://codeclimate.com/github/nnnick/Chart.js/badges/gpa.svg)](https://codeclimate.com/github/nnnick/Chart.js)[![Coverage Status](https://coveralls.io/repos/nnnick/Chart.js/badge.svg?branch=v2.0-dev)](https://coveralls.io/r/nnnick/Chart.js?branch=v2.0-dev) <ide> <ide> <ide>
1
Javascript
Javascript
add explicit handle for errors when decrypting
31d7dd6bb9c8a555796547dd45cfb06fc8869d50
<ide><path>src/main-process/atom-application.js <ide> const getExistingSocketSecret = (atomVersion) => { <ide> const createSocketSecret = (atomVersion) => { <ide> const socketSecret = crypto.randomBytes(16).toString('hex') <ide> <del> fs.writeFileSync(getSocketSecretPath(atomVersion), socketSecret, 'utf8') <add> fs.writeFileSync(getSocketSecretPath(atomVersion), socketSecret, {encoding: 'utf8', mode: 0o600}) <ide> <ide> return socketSecret <ide> } <ide> <ide> const encryptOptions = (options, secret) => { <ide> const message = JSON.stringify(options) <ide> <del> const initVector = crypto.randomBytes(16).toString('hex') <add> const initVector = crypto.randomBytes(16) <ide> <ide> const cipher = crypto.createCipheriv('aes-256-gcm', secret, initVector) <ide> <ide> const encryptOptions = (options, secret) => { <ide> return JSON.stringify({ <ide> authTag, <ide> content, <del> initVector <add> initVector: initVector.toString('hex') <ide> }) <ide> } <ide> <ide> const decryptOptions = (optionsMessage, secret) => { <ide> const {authTag, content, initVector} = JSON.parse(optionsMessage) <ide> <del> const decipher = crypto.createDecipheriv('aes-256-gcm', secret, initVector) <add> const decipher = crypto.createDecipheriv('aes-256-gcm', secret, Buffer.from(initVector, 'hex')) <ide> decipher.setAuthTag(Buffer.from(authTag, 'hex')) <ide> <ide> let message = decipher.update(content, 'hex', 'utf8') <ide> class AtomApplication extends EventEmitter { <ide> let data = '' <ide> connection.on('data', chunk => { data += chunk }) <ide> connection.on('end', () => { <del> this.openWithOptions(decryptOptions(data, this.socketSecret)) <add> try { <add> const options = decryptOptions(data, this.socketSecret) <add> this.openWithOptions(options) <add> } catch (e) { <add> // Error while parsing/decrypting the options passed by the client. <add> // We cannot trust the client, aborting. <add> } <ide> }) <ide> }) <ide>
1
Javascript
Javascript
add disabled class to button on press
51096dc7c79b6020dec8ff4ae7ae44ae327f5ad9
<ide><path>public/js/lib/coursewares/commonFrameWork_0.0.6.js <ide> function showCompletion() { <ide> var didCompleteWith = $('#completed-with').val() || null; <ide> $('#complete-courseware-dialog').modal('show'); <ide> $('#submit-challenge').click(function(e) { <del> $('#submit-challenge').attr('disabled', 'true'); <add> <add> $('#submit-challenge') <add> .attr('disabled', 'true') <add> .addClass('disabled'); <add> <ide> e.preventDefault(); <ide> $.post( <ide> '/completed-bonfire/', {
1
Javascript
Javascript
publish validationerrorkeys as css
d34f3bc7a61056a1f4aebb49d2475414fa16d5e4
<ide><path>src/directive/form.js <ide> FormController.$inject = ['name', '$element', '$attrs']; <ide> function FormController(name, element, attrs) { <ide> var form = this, <ide> parentForm = element.parent().inheritedData('$formController') || nullFormCtrl, <add> invalidCount = 0, // used to easily determine if we are valid <ide> errors = form.$error = {}; <ide> <ide> // init state <ide> function FormController(name, element, attrs) { <ide> <ide> parentForm.$addControl(form); <ide> <add> // Setup initial state of the control <add> element.addClass(PRISTINE_CLASS); <add> toggleValidCss(true); <add> <add> // convenience method for easy toggling of classes <add> function toggleValidCss(isValid, validationErrorKey) { <add> validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : ''; <add> element. <add> removeClass((isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey). <add> addClass((isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey); <add> } <add> <add> if (parentForm) { <add> parentForm.$addControl(form); <add> } <add> <ide> form.$addControl = function(control) { <ide> if (control.$name && !form.hasOwnProperty(control.$name)) { <ide> form[control.$name] = control; <ide> } <del> } <add> }; <ide> <ide> form.$removeControl = function(control) { <ide> if (control.$name && form[control.$name] === control) { <ide> function FormController(name, element, attrs) { <ide> if (isValid) { <ide> cleanupControlErrors(errors[validationToken], validationToken, control); <ide> <del> if (equals(errors, {})) { <add> if (!invalidCount) { <add> toggleValidCss(isValid); <ide> form.$valid = true; <ide> form.$invalid = false; <ide> } <ide> } else { <add> if (!invalidCount) { <add> toggleValidCss(isValid); <add> } <ide> addControlError(validationToken, control); <ide> <ide> form.$valid = false; <ide> function FormController(name, element, attrs) { <ide> }; <ide> <ide> form.$setDirty = function() { <add> element.removeClass(PRISTINE_CLASS).addClass(DIRTY_CLASS); <ide> form.$dirty = true; <ide> form.$pristine = false; <del> } <add> }; <ide> <ide> function cleanupControlErrors(queue, validationToken, control) { <ide> if (queue) { <ide> control = control || this; // so that we can be used in forEach; <ide> arrayRemove(queue, control); <ide> if (!queue.length) { <del> delete errors[validationToken]; <add> invalidCount--; <add> errors[validationToken] = false; <add> toggleValidCss(true, validationToken); <ide> parentForm.$setValidity(validationToken, true, form); <ide> } <ide> } <ide> function FormController(name, element, attrs) { <ide> if (includes(queue, control)) return; <ide> } else { <ide> errors[validationToken] = queue = []; <add> invalidCount++; <add> toggleValidCss(false, validationToken); <ide> parentForm.$setValidity(validationToken, false, form); <ide> } <ide> queue.push(control); <ide> var formDirective = [function() { <ide> if (!attr.action) event.preventDefault(); <ide> }); <ide> <del> forEach(['valid', 'invalid', 'dirty', 'pristine'], function(name) { <del> scope.$watch(function() { <del> return controller['$' + name]; <del> }, function(value) { <del> formElement[value ? 'addClass' : 'removeClass']('ng-' + name); <del> }); <del> }); <del> <ide> var parentFormCtrl = formElement.parent().inheritedData('$formController'); <ide> if (parentFormCtrl) { <ide> formElement.bind('$destroy', function() { <ide><path>src/directive/input.js <ide> var inputDirective = [function() { <ide> }; <ide> }]; <ide> <add>var VALID_CLASS = 'ng-valid', <add> INVALID_CLASS = 'ng-invalid', <add> PRISTINE_CLASS = 'ng-pristine', <add> DIRTY_CLASS = 'ng-dirty'; <ide> <ide> /** <ide> * @ngdoc object <ide> var NgModelController = ['$scope', '$exceptionHandler', '$attrs', 'ngModel', '$e <ide> this.$parsers = []; <ide> this.$formatters = []; <ide> this.$viewChangeListeners = []; <del> this.$error = {}; <ide> this.$pristine = true; <ide> this.$dirty = false; <ide> this.$valid = true; <ide> this.$invalid = false; <ide> this.$render = noop; <ide> this.$name = $attr.name; <ide> <del> var parentForm = $element.inheritedData('$formController') || nullFormCtrl; <add> var parentForm = $element.inheritedData('$formController') || nullFormCtrl, <add> invalidCount = 0, // used to easily determine if we are valid <add> $error = this.$error = {}; // keep invalid keys here <add> <add> <add> // Setup initial state of the control <add> $element.addClass(PRISTINE_CLASS); <add> toggleValidCss(true); <add> <add> // convenience method for easy toggling of classes <add> function toggleValidCss(isValid, validationErrorKey) { <add> validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : ''; <add> $element. <add> removeClass((isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey). <add> addClass((isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey); <add> } <ide> <ide> /** <ide> * @ngdoc function <ide> var NgModelController = ['$scope', '$exceptionHandler', '$attrs', 'ngModel', '$e <ide> * <ide> * This method should be called by validators - i.e. the parser or formatter functions. <ide> * <del> * @param {string} validationErrorKey Name of the validator. <add> * @param {string} validationErrorKey Name of the validator. the `validationErrorKey` will assign <add> * to `$error[validationErrorKey]=isValid` so that it is available for data-binding. <add> * The `validationErrorKey` should be in camelCase and will get converted into dash-case <add> * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error` <add> * class and can be bound to as `{{someForm.someControl.$error.myError}}` . <ide> * @param {boolean} isValid Whether the current state is valid (true) or invalid (false). <ide> */ <ide> this.$setValidity = function(validationErrorKey, isValid) { <del> <del> if (!isValid && this.$error[validationErrorKey]) return; <del> if (isValid && !this.$error[validationErrorKey]) return; <add> if ($error[validationErrorKey] === !isValid) return; <ide> <ide> if (isValid) { <del> delete this.$error[validationErrorKey]; <del> if (equals(this.$error, {})) { <add> if ($error[validationErrorKey]) invalidCount--; <add> $error[validationErrorKey] = false; <add> toggleValidCss(isValid); <add> if (!invalidCount) { <add> toggleValidCss(isValid, validationErrorKey); <ide> this.$valid = true; <ide> this.$invalid = false; <ide> } <ide> } else { <del> this.$error[validationErrorKey] = true; <add> if (!$error[validationErrorKey]) invalidCount++; <add> $error[validationErrorKey] = true; <add> toggleValidCss(isValid) <add> toggleValidCss(isValid, validationErrorKey); <ide> this.$invalid = true; <ide> this.$valid = false; <ide> } <ide> var NgModelController = ['$scope', '$exceptionHandler', '$attrs', 'ngModel', '$e <ide> if (this.$pristine) { <ide> this.$dirty = true; <ide> this.$pristine = false; <add> $element.removeClass(PRISTINE_CLASS).addClass(DIRTY_CLASS); <ide> parentForm.$setDirty(); <ide> } <ide> <ide> var ngModelDirective = [function() { <ide> <ide> formCtrl.$addControl(modelCtrl); <ide> <del> forEach(['valid', 'invalid', 'pristine', 'dirty'], function(name) { <del> scope.$watch(function() { <del> return modelCtrl['$' + name]; <del> }, function(value) { <del> element[value ? 'addClass' : 'removeClass']('ng-' + name); <del> }); <del> }); <del> <ide> element.bind('$destroy', function() { <ide> formCtrl.$removeControl(modelCtrl); <ide> }); <ide><path>test/directive/formSpec.js <ide> describe('form', function() { <ide> expect(form.$error.required).toEqual([control]); <ide> <ide> doc.find('input').remove(); <del> expect(form.$error.required).toBeUndefined(); <add> expect(form.$error.required).toBe(false); <ide> expect(form.alias).toBeUndefined(); <ide> }); <ide> <ide> describe('form', function() { <ide> expect(scope.firstName).toBe('val1'); <ide> expect(scope.lastName).toBe('val2'); <ide> <del> expect(scope.formA.$error.required).toBeUndefined(); <del> expect(scope.formB.$error.required).toBeUndefined(); <add> expect(scope.formA.$error.required).toBe(false); <add> expect(scope.formB.$error.required).toBe(false); <ide> }); <ide> <ide> <ide> describe('form', function() { <ide> expect(child.$error.MyError).toEqual([inputB]); <ide> <ide> inputB.$setValidity('MyError', true); <del> expect(parent.$error.MyError).toBeUndefined(); <del> expect(child.$error.MyError).toBeUndefined(); <add> expect(parent.$error.MyError).toBe(false); <add> expect(child.$error.MyError).toBe(false); <ide> }); <ide> <ide> <ide> describe('form', function() { <ide> <ide> expect(parent.child).toBeUndefined(); <ide> expect(scope.child).toBeUndefined(); <del> expect(parent.$error.required).toBeUndefined(); <add> expect(parent.$error.required).toBe(false); <ide> }); <ide> <ide> <ide> describe('form', function() { <ide> expect(parent.$error.myRule).toEqual([child]); <ide> <ide> input.$setValidity('myRule', true); <del> expect(parent.$error.myRule).toBeUndefined(); <del> expect(child.$error.myRule).toBeUndefined(); <add> expect(parent.$error.myRule).toBe(false); <add> expect(child.$error.myRule).toBe(false); <ide> }); <ide> }) <ide> <ide> describe('form', function() { <ide> it('should have ng-valid/ng-invalid css class', function() { <ide> expect(doc).toBeValid(); <ide> <del> control.$setValidity('ERROR', false); <del> scope.$apply(); <add> control.$setValidity('error', false); <ide> expect(doc).toBeInvalid(); <add> expect(doc.hasClass('ng-valid-error')).toBe(false); <add> expect(doc.hasClass('ng-invalid-error')).toBe(true); <ide> <del> control.$setValidity('ANOTHER', false); <del> scope.$apply(); <add> control.$setValidity('another', false); <add> expect(doc.hasClass('ng-valid-error')).toBe(false); <add> expect(doc.hasClass('ng-invalid-error')).toBe(true); <add> expect(doc.hasClass('ng-valid-another')).toBe(false); <add> expect(doc.hasClass('ng-invalid-another')).toBe(true); <ide> <del> control.$setValidity('ERROR', true); <del> scope.$apply(); <add> control.$setValidity('error', true); <ide> expect(doc).toBeInvalid(); <add> expect(doc.hasClass('ng-valid-error')).toBe(true); <add> expect(doc.hasClass('ng-invalid-error')).toBe(false); <add> expect(doc.hasClass('ng-valid-another')).toBe(false); <add> expect(doc.hasClass('ng-invalid-another')).toBe(true); <ide> <del> control.$setValidity('ANOTHER', true); <del> scope.$apply(); <add> control.$setValidity('another', true); <ide> expect(doc).toBeValid(); <add> expect(doc.hasClass('ng-valid-error')).toBe(true); <add> expect(doc.hasClass('ng-invalid-error')).toBe(false); <add> expect(doc.hasClass('ng-valid-another')).toBe(true); <add> expect(doc.hasClass('ng-invalid-another')).toBe(false); <ide> }); <ide> <ide> <ide><path>test/directive/inputSpec.js <ide> describe('NgModelController', function() { <ide> expect(ctrl.$error.required).toBe(true); <ide> <ide> ctrl.$setValidity('required', true); <del> expect(ctrl.$error.required).toBeUndefined(); <add> expect(ctrl.$error.required).toBe(false); <ide> }); <ide> <ide> <ide> it('should set valid/invalid', function() { <del> ctrl.$setValidity('FIRST', false); <add> ctrl.$setValidity('first', false); <ide> expect(ctrl.$valid).toBe(false); <ide> expect(ctrl.$invalid).toBe(true); <ide> <del> ctrl.$setValidity('SECOND', false); <add> ctrl.$setValidity('second', false); <ide> expect(ctrl.$valid).toBe(false); <ide> expect(ctrl.$invalid).toBe(true); <ide> <del> ctrl.$setValidity('SECOND', true); <add> ctrl.$setValidity('second', true); <ide> expect(ctrl.$valid).toBe(false); <ide> expect(ctrl.$invalid).toBe(true); <ide> <del> ctrl.$setValidity('FIRST', true); <add> ctrl.$setValidity('first', true); <ide> expect(ctrl.$valid).toBe(true); <ide> expect(ctrl.$invalid).toBe(false); <ide> }); <ide> <ide> <ide> it('should emit $valid only when $invalid', function() { <del> ctrl.$setValidity('ERROR', true); <del> expect(parentFormCtrl.$setValidity).not.toHaveBeenCalled(); <add> ctrl.$setValidity('error', true); <add> expect(parentFormCtrl.$setValidity).toHaveBeenCalledOnceWith('error', true, ctrl); <add> parentFormCtrl.$setValidity.reset(); <ide> <del> ctrl.$setValidity('ERROR', false); <del> expect(parentFormCtrl.$setValidity).toHaveBeenCalledOnceWith('ERROR', false, ctrl); <add> ctrl.$setValidity('error', false); <add> expect(parentFormCtrl.$setValidity).toHaveBeenCalledOnceWith('error', false, ctrl); <ide> parentFormCtrl.$setValidity.reset(); <del> ctrl.$setValidity('ERROR', true); <del> expect(parentFormCtrl.$setValidity).toHaveBeenCalledOnceWith('ERROR', true, ctrl); <add> ctrl.$setValidity('error', true); <add> expect(parentFormCtrl.$setValidity).toHaveBeenCalledOnceWith('error', true, ctrl); <ide> }); <ide> }); <ide> <ide> describe('NgModelController', function() { <ide> ctrl.$parsers.push(function() {return undefined;}); <ide> expect(ctrl.$modelValue).toBe('aaaa'); <ide> ctrl.$setViewValue('bbbb'); <del> expect(ctrl.$modelValue).toBeUndefined; <add> expect(ctrl.$modelValue).toBeUndefined(); <ide> }); <ide> <ide> <ide> describe('ng-model', function() { <ide> $rootScope.$digest(); <ide> expect(element).toBeValid(); <ide> expect(element).toBePristine(); <add> expect(element.hasClass('ng-valid-email')).toBe(true); <add> expect(element.hasClass('ng-invalid-email')).toBe(false); <ide> <ide> $rootScope.$apply(function() { <ide> $rootScope.value = 'invalid-email'; <ide> }); <ide> expect(element).toBeInvalid(); <ide> expect(element).toBePristine(); <add> expect(element.hasClass('ng-valid-email')).toBe(false); <add> expect(element.hasClass('ng-invalid-email')).toBe(true); <ide> <ide> element.val('invalid-again'); <ide> browserTrigger(element, 'blur'); <ide> expect(element).toBeInvalid(); <ide> expect(element).toBeDirty(); <add> expect(element.hasClass('ng-valid-email')).toBe(false); <add> expect(element.hasClass('ng-invalid-email')).toBe(true); <ide> <ide> element.val('[email protected]'); <ide> browserTrigger(element, 'blur'); <ide> expect(element).toBeValid(); <ide> expect(element).toBeDirty(); <add> expect(element.hasClass('ng-valid-email')).toBe(true); <add> expect(element.hasClass('ng-invalid-email')).toBe(false); <ide> <ide> dealoc(element); <ide> })); <ide> describe('input', function() { <ide> expect(scope.form.$error.required.length).toBe(1); <ide> <ide> inputElm.remove(); <del> expect(scope.form.$error.required).toBeUndefined(); <add> expect(scope.form.$error.required).toBe(false); <ide> }); <ide> <ide> <ide> describe('input', function() { <ide> <ide> expect(scope.email).toBe('[email protected]'); <ide> expect(inputElm).toBeValid(); <del> expect(widget.$error.email).toBeUndefined(); <add> expect(widget.$error.email).toBe(false); <ide> <ide> changeInputValueTo('invalid@'); <ide> expect(scope.email).toBeUndefined(); <ide> describe('input', function() { <ide> changeInputValueTo('http://www.something.com'); <ide> expect(scope.url).toBe('http://www.something.com'); <ide> expect(inputElm).toBeValid(); <del> expect(widget.$error.url).toBeUndefined(); <add> expect(widget.$error.url).toBe(false); <ide> <ide> changeInputValueTo('invalid.com'); <ide> expect(scope.url).toBeUndefined();
4
Ruby
Ruby
optimize hash key
2e95d2ef90a32a7ed6fbb14f4e0a6764fc9e017b
<ide><path>actionview/lib/action_view/helpers/url_helper.rb <ide> def link_to(name = nil, options = nil, html_options = nil, &block) <ide> html_options = convert_options_to_data_attributes(options, html_options) <ide> <ide> url = url_for(options) <del> html_options['href'] ||= url <add> html_options["href".freeze] ||= url <ide> <ide> content_tag(:a, name || url, html_options, &block) <ide> end
1
PHP
PHP
add type support into set()
674c973d2942bb2fdb3ed23b41a36c381b59cf05
<ide><path>lib/Cake/Model/Datasource/Database/Query.php <ide> public function insert() { <ide> public function update($table) { <ide> $this->_dirty = true; <ide> $this->_type = 'update'; <del> $this->_parts['update'][] = $table; <add> $this->_parts['update'][0] = $table; <ide> return $this; <ide> } <ide> <ide> public function update($table) { <ide> * <ide> * @param string|array|QueryExpression $key The column name or array of keys <ide> * + values to set. This can also be a QueryExpression containing a SQL fragment. <del> * @param mixed $value The value to update $key to. Can be null if $key is an <del> * array or QueryExpression <add> * @param mixed $value The value to update $key to. Can be null if $key is an <add> * array or QueryExpression. When $key is an array, this parameter will be <add> * used as $types instead. <add> * @param array $types The column types to treat data as. <ide> * @return Query <ide> */ <del> public function set($key, $value = null) { <add> public function set($key, $value = null, $types = []) { <ide> if (empty($this->_parts['set'])) { <del> $this->_parts['set'] = new QueryExpression([], [], ','); <add> $this->_parts['set'] = $this->newExpr()->type(','); <ide> } <del> $set = $key; <del> if (!is_array($key) && !($key instanceof QueryExpression)) { <del> $set = [$key => $value]; <add> if (is_array($key) || $key instanceof QueryExpression) { <add> $this->_parts['set']->add($key, (array)$value); <add> } else { <add> if (is_string($types)) { <add> $types = [$key => $types]; <add> } <add> $this->_parts['set']->add([$key => $value], $types); <ide> } <del> $this->_parts['set']->add($set, []); <ide> return $this; <ide> } <ide> <ide><path>lib/Cake/Test/TestCase/Model/Datasource/Database/QueryTest.php <ide> public function testUpdateMultipleFields() { <ide> $this->_insertTwoRecords(); <ide> $query = new Query($this->connection); <ide> $query->update('articles') <del> ->set('title', 'mark') <del> ->set('body', 'some text') <add> ->set('title', 'mark', 'string') <add> ->set('body', 'some text', 'string') <ide> ->where(['id' => 1]); <ide> $result = $query->sql(false); <ide> <ide> public function testUpdateMultipleFieldsArray() { <ide> ->set([ <ide> 'title' => 'mark', <ide> 'body' => 'some text' <del> ]) <add> ], ['title' => 'string', 'body' => 'string']) <ide> ->where(['id' => 1]); <ide> $result = $query->sql(false); <ide> <ide> public function testUpdateMultipleFieldsArray() { <ide> $this->assertCount(1, $result); <ide> } <ide> <add>/** <add> * Test updates with an expression. <add> * <add> * @return void <add> */ <ide> public function testUpdateWithExpression() { <ide> $this->_insertTwoRecords(); <ide> $query = new Query($this->connection);
2
PHP
PHP
use regular function for php 7.3 compatibility
27ddf7da753290940a3a359ef7c3be37542b84d9
<ide><path>src/Illuminate/Database/Query/Grammars/SqlServerGrammar.php <ide> protected function compileAnsiOffset(Builder $query, $components) <ide> // As this moves the order statement to be part of the "select" statement, we need to <ide> // move the bindings to the right position: right after "select". <ide> $preferredBindingOrder = ['select', 'order', 'from', 'join', 'where', 'groupBy', 'having', 'union', 'unionOrder']; <del> $sortedBindings = Arr::sort($query->bindings, fn ($bindings, $key) => array_search($key, $preferredBindingOrder)); <add> $sortedBindings = Arr::sort($query->bindings, function ($bindings, $key) use ($preferredBindingOrder) { <add> return array_search($key, $preferredBindingOrder); <add> }); <ide> $query->bindings = $sortedBindings; <ide> <ide> // Next we need to calculate the constraints that should be placed on the query
1
Javascript
Javascript
hack something up that renders font right again
75884a6160ba269fd8ebed2b687fd6145eb702f3
<ide><path>fonts.js <ide> var serifFonts = { <ide> 'Wide Latin': true, 'Windsor': true, 'XITS': true <ide> }; <ide> <del>// Create the FontMeasure object only on the main thread. <del>if (!isWorker) { <del> var FontMeasure = (function FontMeasure() { <del> var kScalePrecision = 30; <del> var ctx = document.createElement('canvas').getContext('2d'); <del> ctx.scale(1 / kScalePrecision, 1); <del> <del> var current; <del> var measureCache; <del> <del> return { <del> setActive: function fonts_setActive(font, size) { <del> if (current == font) { <del> var sizes = current.sizes; <del> if (!(measureCache = sizes[size])) <del> measureCache = sizes[size] = Object.create(null); <del> } else { <del> measureCache = null; <del> } <del> <del> var name = font.loadedName; <del> var bold = font.bold ? 'bold' : 'normal'; <del> var italic = font.italic ? 'italic' : 'normal'; <del> size *= kScalePrecision; <del> var rule = italic + ' ' + bold + ' ' + size + 'px "' + name + '"'; <del> ctx.font = rule; <del> current = font; <del> }, <del> measureText: function fonts_measureText(text) { <del> var width; <del> if (measureCache && (width = measureCache[text])) <del> return width; <del> width = ctx.measureText(text).width / kScalePrecision; <del> if (measureCache) <del> measureCache[text] = width; <del> return width; <del> } <del> }; <del> })(); <del>} <del> <del>/** <del> * The FontLoader binds a fontObj to the DOM and checks if it is loaded. <del> * At the point of writing (11/9/14) there is no DOM event to detect loading <del> * of fonts. Therefore, we measure the font using a canvas before the <del> * font is attached to the DOM and later on test if the width changed. <del> * To ensure there is a change in the font size, two fallback fonts are used. <del> * The font used might look like this: <del> * ctx.font = "normal normmal 'p0_font_0', 'Arial' <del> * <del> * As long as the font 'p0_font_0' isn't loaded, the font 'Arial' is used. A <del> * second measurement is done against the font 'Courier': <del> * ctx.font = "normal normmal 'p0_font_0', 'Courier' <del> * <del> * The font sizes of Arial and Courier are quite different which ensures there <del> * gone be a change nomatter what the font looks like (e.g. you could end up <del> * with a font that looks like Arial which means you don't see any change in <del> * size, but as Courier is checked as well, there will be difference in this <del> * font). <del> * <del> * !!! The test string used for measurements is really important. Some fonts <del> * don't have definitions for characters like "a" or "b", but only for some <del> * unicode characters. Therefore, the test string have to be build using the <del> * encoding of the fontObj. <del> */ <ide> var FontLoader = { <ide> listeningForFontLoad: false, <ide> <del> /** <del> * Attach the fontObj to the DOM. <del> */ <del> bindDOM: function font_bindDom(fontObj) { <del> // The browser isn't loading a font until it's used on the page. Attaching <del> // a hidden div that uses the font 'tells' the browser to load the font. <del> var div = document.createElement('div'); <del> div.setAttribute('style', <del> 'visibility: hidden;' + <del> 'width: 10px; height: 10px;' + <del> 'position: absolute; top: 0px; left: 0px;' + <del> 'font-family: ' + fontObj.loadedName); <del> div.innerHTML = "Hi"; <del> document.body.appendChild(div); <del> <del> // Add the font-face rule to the document <del> var fontName = fontObj.loadedName; <del> var url = ('url(data:' + fontObj.mimetype + ';base64,' + <del> window.btoa(fontObj.str) + ');'); <del> var rule = "@font-face { font-family:'" + fontName + "';src:" + url + '}'; <del> var styleSheet = document.styleSheets[0]; <del> styleSheet.insertRule(rule, styleSheet.cssRules.length); <del> return rule; <del> }, <del> <del> bind: function fontLoaderBind(fonts, callback, objects) { <del> var fontsToLoad = {}; <del> // check if there are twice the same font. <del> for (var i = 0; i < fonts.length; i++) { <del> var fontName = fonts[i].loadedName; <del> if (fontsToLoad[fontName]) { <del> throw "Got twice the same font!"; <del> } else { <del> fontsToLoad[fontName] = true; <del> } <del> } <del> <add> bind: function fontLoaderBind(fonts, callback) { <ide> function checkFontsLoaded() { <ide> for (var i = 0; i < objs.length; i++) { <ide> var fontObj = objs[i]; <ide> if (fontObj.loading) { <ide> return false; <ide> } <del> objects.resolve(fontObj.loadedName); <ide> } <ide> <ide> document.documentElement.removeEventListener( <ide> var FontLoader = { <ide> for (var i = 0; i < fonts.length; i++) { <ide> var font = fonts[i]; <ide> <del> // If there is no string on the font, then the font can't get loaded / <del> // get attached to the DOM. Skip this font. <del> if (!font.str) { <del> continue; <del> } <add> var obj = new Font(font.name, font.file, font.properties); <add> objs.push(obj); <ide> <del> objs.push(font); <add> var str = ''; <add> var data = obj.data; <add> if (data) { <add> var length = data.length; <add> for (var j = 0; j < length; j++) <add> str += String.fromCharCode(data[j]); <ide> <del> rules.push(this.bindDOM(font)); <del> names.push(font.loadedName); <add> var rule = isWorker ? obj.bindWorker(str) : obj.bindDOM(str); <add> if (rule) { <add> rules.push(rule); <add> names.push(obj.loadedName); <add> } <add> } <ide> } <ide> <ide> this.listeningForFontLoad = false; <ide> var FontLoader = { <ide> <ide> return objs; <ide> }, <del> <ide> // Set things up so that at least one pdfjsFontLoad event is <ide> // dispatched when all the @font-face |rules| for |names| have been <ide> // loaded in a subdocument. It's expected that the load of |rules| <ide> function getUnicodeRangeFor(value) { <ide> return -1; <ide> } <ide> <del>/** <del> * FontShape is the minimal shape a FontObject can have to be useful during <del> * executing the IRQueue. <del> */ <del>var FontShape = (function FontShape() { <del> var constructor = function FontShape_constructor(obj) { <del> for (var name in obj) { <del> this[name] = obj[name]; <del> } <del> <del> var name = this.loadedName; <del> var bold = this.black ? (this.bold ? 'bolder' : 'bold') : <del> (this.bold ? 'bold' : 'normal'); <del> <del> var italic = this.italic ? 'italic' : 'normal'; <del> this.fontFallback = this.serif ? 'serif' : 'sans-serif'; <del> <del> this.namePart1 = italic + ' ' + bold + ' '; <del> this.namePart2 = 'px "' + name + '", "'; <del> <del> this.supported = Object.keys(this.encoding).length != 0; <del> <del> // Set the loading flag. Gets set to false in FontLoader.bind(). <del> this.loading = true; <del> }; <del> <del> function int16(bytes) { <del> return (bytes[0] << 8) + (bytes[1] & 0xff); <del> }; <del> <del> constructor.prototype = { <del> getRule: function fonts_getRule(size, fallback) { <del> fallback = fallback || this.fontFallback; <del> return this.namePart1 + size + this.namePart2 + fallback + '"'; <del> }, <del> <del> charsToUnicode: function fonts_chars2Unicode(chars) { <del> var charsCache = this.charsCache; <del> var str; <del> <del> // if we translated this string before, just grab it from the cache <del> if (charsCache) { <del> str = charsCache[chars]; <del> if (str) <del> return str; <del> } <del> <del> // lazily create the translation cache <del> if (!charsCache) <del> charsCache = this.charsCache = Object.create(null); <del> <del> // translate the string using the font's encoding <del> var encoding = this.encoding; <del> if (!encoding) <del> return chars; <del> str = ''; <del> <del> if (this.composite) { <del> // composite fonts have multi-byte strings convert the string from <del> // single-byte to multi-byte <del> // XXX assuming CIDFonts are two-byte - later need to extract the <del> // correct byte encoding according to the PDF spec <del> var length = chars.length - 1; // looping over two bytes at a time so <del> // loop should never end on the last byte <del> for (var i = 0; i < length; i++) { <del> var charcode = int16([chars.charCodeAt(i++), chars.charCodeAt(i)]); <del> var unicode = encoding[charcode]; <del> if ('undefined' == typeof(unicode)) { <del> warn('Unencoded charcode ' + charcode); <del> unicode = charcode; <del> } else { <del> unicode = unicode.unicode; <del> } <del> str += String.fromCharCode(unicode); <del> } <del> } <del> else { <del> for (var i = 0; i < chars.length; ++i) { <del> var charcode = chars.charCodeAt(i); <del> var unicode = encoding[charcode]; <del> if ('undefined' == typeof(unicode)) { <del> warn('Unencoded charcode ' + charcode); <del> unicode = charcode; <del> } else { <del> unicode = unicode.unicode; <del> } <del> <del> // Handle surrogate pairs <del> if (unicode > 0xFFFF) { <del> str += String.fromCharCode(unicode & 0xFFFF); <del> unicode >>= 16; <del> } <del> str += String.fromCharCode(unicode); <del> } <del> } <del> <del> // Enter the translated string into the cache <del> return (charsCache[chars] = str); <del> } <del> } <del> <del> return constructor; <del>})(); <del> <ide> /** <ide> * 'Font' is the class the outside world should use, it encapsulate all the font <ide> * decoding logics whatever type it is (assuming the font type is supported). <ide> var Font = (function Font() { <ide> var constructor = function font_constructor(name, file, properties) { <ide> this.name = name; <ide> this.encoding = properties.encoding; <del> <del> // Glyhps are no needed anymore? MERGE <del> // this.glyphs = properties.glyphs; <del> this.loadedName = properties.loadedName; <ide> this.coded = properties.coded; <ide> this.resources = properties.resources; <ide> this.sizes = []; <ide> var Font = (function Font() { <ide> this.black = (name.search(/Black/g) != -1); <ide> <ide> this.defaultWidth = properties.defaultWidth; <del> // MERGE <del> // this.loadedName = fontName.split('-')[0]; <add> this.loadedName = fontName.split('-')[0]; <ide> this.composite = properties.composite; <ide> this.loading = false; <ide> return; <ide> var Font = (function Font() { <ide> } <ide> <ide> this.data = data; <del> // MERGE <del> //this.textMatrix = properties.textMatrix; <ide> this.type = type; <ide> this.fontMatrix = properties.fontMatrix; <ide> this.defaultWidth = properties.defaultWidth; <del> this.loadedName = properties.loadedName; <add> this.loadedName = getUniqueName(); <ide> this.composite = properties.composite; <del> <del> // TODO: Remove this once we can be sure nothing got broken to du changes <del> // in this commit. <del> if (!this.loadedName) { <del> throw "There has to be a `loadedName`"; <del> } <del> <ide> this.loading = true; <ide> }; <ide> <add> var numFonts = 0; <add> function getUniqueName() { <add> return 'pdfFont' + numFonts++; <add> } <add> <ide> function stringToArray(str) { <ide> var array = []; <ide> for (var i = 0; i < str.length; ++i) <ide> var Font = (function Font() { <ide> } <ide> }, <ide> <add> bindWorker: function font_bindWorker(data) { <add> postMessage({ <add> action: 'font', <add> data: { <add> raw: data, <add> fontName: this.loadedName, <add> mimetype: this.mimetype <add> } <add> }); <add> }, <add> <add> bindDOM: function font_bindDom(data) { <add> var fontName = this.loadedName; <add> <add> // Add the font-face rule to the document <add> var url = ('url(data:' + this.mimetype + ';base64,' + <add> window.btoa(data) + ');'); <add> var rule = "@font-face { font-family:'" + fontName + "';src:" + url + '}'; <add> var styleSheet = document.styleSheets[0]; <add> if (!styleSheet) { <add> document.documentElement.firstChild.appendChild( <add> document.createElement('style')); <add> styleSheet = document.styleSheets[0]; <add> } <add> styleSheet.insertRule(rule, styleSheet.cssRules.length); <add> <add> return rule; <add> }, <add> <ide> charsToGlyphs: function fonts_chars2Glyphs(chars) { <ide> var charsCache = this.charsCache; <ide> var glyphs; <ide><path>pdf.js <ide> var Page = (function pagePage() { <ide> // Firefox error reporting from XHR callbacks. <ide> setTimeout(function pageSetTimeout() { <ide> var exc = null; <del> try { <add> // try { <ide> self.display(gfx, continuation); <del> } catch (e) { <del> exc = e.toString(); <del> continuation(exc); <del> throw e; <del> } <add> // } catch (e) { <add> // exc = e.toString(); <add> // continuation(exc); <add> // throw e; <add> // } <ide> }); <ide> }; <ide> <ide> var Page = (function pagePage() { <ide> ensureFonts: function(fonts, callback) { <ide> console.log('--ensureFonts--', '' + fonts); <ide> // Convert the font names to the corresponding font obj. <del> for (var i = 0; i < fonts.length; i++) { <del> // HACK FOR NOW. Access the data directly. This isn't allowed as the <del> // font object isn't resolved yet. <del> fonts[i] = this.objs.objs[fonts[i]].data; <del> } <add> // for (var i = 0; i < fonts.length; i++) { <add> // // HACK FOR NOW. Access the data directly. This isn't allowed as the <add> // // font object isn't resolved yet. <add> // fonts[i] = this.objs.objs[fonts[i]].data; <add> // } <ide> <ide> // Load all the fonts <del> FontLoader.bind( <add> var fontObjs = FontLoader.bind( <ide> fonts, <ide> function(fontObjs) { <ide> this.stats.fonts = Date.now(); <ide> var Page = (function pagePage() { <ide> }.bind(this), <ide> this.objs <ide> ); <add> <add> for (var i = 0, ii = fonts.length; i < ii; ++i) <add> fonts[i].dict.fontObj = fontObjs[i]; <ide> }, <ide> <ide> display: function(gfx, callback) { <ide> var xref = this.xref; <ide> var resources = xref.fetchIfRef(this.resources); <ide> var mediaBox = xref.fetchIfRef(this.mediaBox); <ide> assertWellFormed(isDict(resources), 'invalid page resources'); <add> <add> gfx.xref = xref; <add> gfx.res = resources; <ide> gfx.beginDrawing({ x: mediaBox[0], y: mediaBox[1], <ide> width: this.width, <ide> height: this.height, <ide> var PDFDoc = (function() { <ide> page.startRenderingFromIRQueue(data.IRQueue, fontsToLoad); <ide> } <ide> <del> checkFontData(); <add>// checkFontData(); <add> page.startRenderingFromIRQueue(data.IRQueue, data.depFonts); <ide> }, this); <ide> <ide> processorHandler.on("obj", function(data) { <ide> var PDFDoc = (function() { <ide> WorkerProcessorHandler.setup(processorHandler); <ide> } <ide> <del> processorHandler.send("doc", data); <add> processorHandler.send("doc", this.pdf); <ide> } <ide> <ide> constructor.prototype = { <ide> var PartialEvaluator = (function partialEvaluator() { <ide> } <ide> } <ide> } else if (cmd == 'Tf') { // eagerly collect all fonts <del> args[0].name = handleSetFont(args[0].name); <add> var fontRes = resources.get('Font'); <add> if (fontRes) { <add> fontRes = xref.fetchIfRef(fontRes); <add> var font = xref.fetchIfRef(fontRes.get(args[0].name)); <add> assertWellFormed(isDict(font)); <add> if (!font.translated) { <add> font.translated = this.translateFont(font, xref, resources); <add> if (font.translated) { <add> // keep track of each font we translated so the caller can <add> // load them asynchronously before calling display on a page <add> // fonts.push(font.translated); <add> dependency.push(font.translated); <add> } <add> } <add> } <add> <ide> } else if (cmd == 'EI') { <ide> buildPaintImageXObject(args[0], true); <ide> } <ide> var CanvasGraphics = (function canvasGraphics() { <ide> this.current.leading = -leading; <ide> }, <ide> setFont: function canvasGraphicsSetFont(fontRef, size) { <del> // Lookup the fontObj using fontRef only. <del> var fontRefName = fontRef.name; <del> var fontObj = this.objs.get(fontRefName); <del> <del> if (!fontObj) { <del> throw "Can't find font for " + fontRefName; <del> } <del> <del> var name = fontObj.loadedName || 'sans-serif'; <del> console.log('setFont', name); <del> <add> var font; <add> // the tf command uses a name, but graphics state uses a reference <add> if (isName(fontRef)) { <add> font = this.xref.fetchIfRef(this.res.get('Font')); <add> if (!isDict(font)) <add> return; <add> <add> font = font.get(fontRef.name); <add> } else if (isRef(fontRef)) { <add> font = fontRef; <add> } <add> font = this.xref.fetchIfRef(font); <add> if (!font) <add> error('Referenced font is not found'); <add> <add> var fontObj = font.fontObj; <ide> this.current.font = fontObj; <ide> this.current.fontSize = size; <ide> <add> var name = fontObj.loadedName || 'sans-serif'; <ide> if (this.ctx.$setFont) { <ide> this.ctx.$setFont(name, size); <ide> } else { <del> this.ctx.font = fontObj.getRule(size); <add> var bold = fontObj.black ? (fontObj.bold ? 'bolder' : 'bold') : <add> (fontObj.bold ? 'bold' : 'normal'); <add> <add> var italic = fontObj.italic ? 'italic' : 'normal'; <add> var serif = fontObj.serif ? 'serif' : 'sans-serif'; <add> var typeface = '"' + name + '", ' + serif; <add> var rule = italic + ' ' + bold + ' ' + size + 'px ' + typeface; <add> this.ctx.font = rule; <ide> } <ide> }, <ide> setTextRenderingMode: function canvasGraphicsSetTextRenderingMode(mode) { <ide> var CanvasGraphics = (function canvasGraphics() { <ide> showText: function canvasGraphicsShowText(text) { <ide> // If the current font isn't supported, we can't display the text and <ide> // bail out. <del> if (!this.current.font.supported) { <del> console.log("showText BAIL OUT"); <del> return; <del> } <add> // if (!this.current.font.supported) { <add> // console.log("showText BAIL OUT"); <add> // return; <add> // } <ide> <ide> console.log("showText", text); <ide> <ide> var CanvasGraphics = (function canvasGraphics() { <ide> <ide> // If the current font isn't supported, we can't display the text and <ide> // bail out. <del> if (!this.current.font.supported) { <del> console.log("showSpacedText BAIL OUT"); <del> return; <del> } <add> // if (!this.current.font.supported) { <add> // console.log("showSpacedText BAIL OUT"); <add> // return; <add> // } <ide> <ide> console.log("showSpacedText", arr); <ide> <ide><path>worker/processor_handler.js <ide> var WorkerProcessorHandler = { <ide> handler.on("doc", function(data) { <ide> // Create only the model of the PDFDoc, which is enough for <ide> // processing the content of the pdf. <del> pdfDoc = new PDFDocModel(new Stream(data)); <add> pdfDoc = data;//new PDFDocModel(new Stream(data)); <ide> }); <ide> <ide> handler.on("page_request", function(pageNum) { <ide> var WorkerProcessorHandler = { <ide> } <ide> <ide> // Filter the dependecies for fonts. <del> var fonts = {}; <add> // var fonts = {}; <add> // for (var i = 0; i < dependency.length; i++) { <add> // var dep = dependency[i]; <add> // if (dep.indexOf('font_') == 0) { <add> // fonts[dep] = true; <add> // } <add> // } <add> <add> var fonts = []; <ide> for (var i = 0; i < dependency.length; i++) { <ide> var dep = dependency[i]; <del> if (dep.indexOf('font_') == 0) { <del> fonts[dep] = true; <add> if (typeof dep === "object") { <add> fonts.push(dep); <ide> } <ide> } <ide> <del> <ide> handler.send("page", { <ide> pageNum: pageNum, <ide> IRQueue: IRQueue, <del> depFonts: Object.keys(fonts) <add> depFonts: fonts <ide> }); <ide> }, this); <ide>
3
Python
Python
add test utils
522201ec9e00ed2fe135a621bde1b288c59ddd25
<ide><path>keras/utils/test_utils.py <add>import numpy as np <add> <add>def get_test_data(nb_train=1000, nb_test=500, input_shape=(10,), output_shape=(2,), <add> classification=True, nb_class=2): <add> ''' <add> classification=True overrides output_shape <add> (i.e. output_shape is set to (1,)) and the output <add> consists in integers in [0, nb_class-1]. <add> <add> Otherwise: float output with shape output_shape. <add> ''' <add> nb_sample = nb_train + nb_test <add> if classification: <add> y = np.random.randint(0, nb_class, size=(nb_sample, 1)) <add> X = np.zeros((nb_sample,) + input_shape) <add> for i in range(nb_sample): <add> X[i] = np.random.normal(loc=y[i], scale=1.0, size=input_shape) <add> else: <add> y_loc = np.random.random((nb_sample,)) <add> X = np.zeros((nb_sample,) + input_shape) <add> y = np.zeros((nb_sample,) + output_shape) <add> for i in range(nb_sample): <add> X[i] = np.random.normal(loc=y_loc[i], scale=1.0, size=input_shape) <add> y[i] = np.random.normal(loc=y_loc[i], scale=1.0, size=output_shape) <add> <add> return (X[:nb_train], y[:nb_train]), (X[nb_train:], y[nb_train:])
1
PHP
PHP
remove the log statement for missing templates
3641d4485f05f6848e0f24f8bf1e57eb83af6c26
<ide><path>src/Shell/Task/TemplateTask.php <ide> public function generate($template, $vars = null) { <ide> try { <ide> return $this->View->render($template); <ide> } catch (MissingTemplateException $e) { <del> $this->log($e->getMessage()); <ide> return ''; <ide> } <ide> }
1
Ruby
Ruby
fix metadata assertions in direct upload tests
896e7477f8777a3c6f497bfa82e7ea5b9b9c89ff
<ide><path>activestorage/test/controllers/direct_uploads_controller_test.rb <ide> class ActiveStorage::S3DirectUploadsControllerTest < ActionDispatch::Integration <ide> "my_key_2": "my_value_2", <ide> "platform": "my_platform", <ide> "library_ID": "12345", <del> custom: { <add> "custom": { <ide> "my_key_3": "my_value_3" <ide> } <ide> } <ide> class ActiveStorage::S3DirectUploadsControllerTest < ActionDispatch::Integration <ide> assert_equal "hello.txt", details["filename"] <ide> assert_equal 6, details["byte_size"] <ide> assert_equal checksum, details["checksum"] <del> assert_equal metadata, details["metadata"].transform_keys(&:to_sym) <add> assert_equal metadata, details["metadata"].deep_transform_keys(&:to_sym) <ide> assert_equal "text/plain", details["content_type"] <ide> assert_match SERVICE_CONFIGURATIONS[:s3][:bucket], details["direct_upload"]["url"] <ide> assert_match(/s3(-[-a-z0-9]+)?\.(\S+)?amazonaws\.com/, details["direct_upload"]["url"]) <ide> class ActiveStorage::GCSDirectUploadsControllerTest < ActionDispatch::Integratio <ide> "my_key_2": "my_value_2", <ide> "platform": "my_platform", <ide> "library_ID": "12345", <del> custom: { <add> "custom": { <ide> "my_key_3": "my_value_3" <ide> } <ide> } <ide> class ActiveStorage::GCSDirectUploadsControllerTest < ActionDispatch::Integratio <ide> assert_equal "hello.txt", details["filename"] <ide> assert_equal 6, details["byte_size"] <ide> assert_equal checksum, details["checksum"] <del> assert_equal metadata, details["metadata"].transform_keys(&:to_sym) <add> assert_equal metadata, details["metadata"].deep_transform_keys(&:to_sym) <ide> assert_equal "text/plain", details["content_type"] <ide> assert_match %r{storage\.googleapis\.com/#{@config[:bucket]}}, details["direct_upload"]["url"] <ide> assert_equal({ "Content-MD5" => checksum, "Content-Disposition" => "inline; filename=\"hello.txt\"; filename*=UTF-8''hello.txt", "x-goog-meta-my_key_3" => "my_value_3" }, details["direct_upload"]["headers"]) <ide> class ActiveStorage::AzureStorageDirectUploadsControllerTest < ActionDispatch::I <ide> assert_equal "hello.txt", details["filename"] <ide> assert_equal 6, details["byte_size"] <ide> assert_equal checksum, details["checksum"] <del> assert_equal metadata, details["metadata"].transform_keys(&:to_sym) <add> assert_equal metadata, details["metadata"].deep_transform_keys(&:to_sym) <ide> assert_equal "text/plain", details["content_type"] <ide> assert_match %r{#{@config[:storage_account_name]}\.blob\.core\.windows\.net/#{@config[:container]}}, details["direct_upload"]["url"] <ide> assert_equal({ "Content-Type" => "text/plain", "Content-MD5" => checksum, "x-ms-blob-content-disposition" => "inline; filename=\"hello.txt\"; filename*=UTF-8''hello.txt", "x-ms-blob-type" => "BlockBlob" }, details["direct_upload"]["headers"]) <ide> class ActiveStorage::DiskDirectUploadsControllerTest < ActionDispatch::Integrati <ide> assert_equal "hello.txt", details["filename"] <ide> assert_equal 6, details["byte_size"] <ide> assert_equal checksum, details["checksum"] <del> assert_equal metadata, details["metadata"].transform_keys(&:to_sym) <add> assert_equal metadata, details["metadata"].deep_transform_keys(&:to_sym) <ide> assert_equal "text/plain", details["content_type"] <ide> assert_match(/rails\/active_storage\/disk/, details["direct_upload"]["url"]) <ide> assert_equal({ "Content-Type" => "text/plain" }, details["direct_upload"]["headers"]) <ide> class ActiveStorage::DiskDirectUploadsControllerTest < ActionDispatch::Integrati <ide> assert_equal "hello.txt", details["filename"] <ide> assert_equal 6, details["byte_size"] <ide> assert_equal checksum, details["checksum"] <del> assert_equal metadata, details["metadata"].transform_keys(&:to_sym) <add> assert_equal metadata, details["metadata"].deep_transform_keys(&:to_sym) <ide> assert_equal "text/plain", details["content_type"] <ide> assert_match(/rails\/active_storage\/disk/, details["direct_upload"]["url"]) <ide> assert_equal({ "Content-Type" => "text/plain" }, details["direct_upload"]["headers"])
1
Ruby
Ruby
pass string to factory
472b6e4fe1f4d7d8a64fde8bc66f11c990b21bc9
<ide><path>Library/Homebrew/cmd/versions.rb <ide> def version_for_sha sha <ide> # Unload the class so Formula#version returns the correct value <ide> begin <ide> Formulary.unload_formula name <del> nostdout { Formula.factory(path).version } <add> nostdout { Formula.factory(path.to_s).version } <ide> rescue *IGNORED_EXCEPTIONS => e <ide> # We rescue these so that we can skip bad versions and <ide> # continue walking the history
1
Go
Go
add more tests
5f0f0c228d438f01c3b9837eb6e8e97133d9d1f5
<ide><path>pkg/symlink/fs_test.go <ide> func TestFollowSymlinkRelativePath2(t *testing.T) { <ide> t.Fatal(err) <ide> } <ide> } <add> <add>func TestFollowSymlinkScopeLink(t *testing.T) { <add> tmpdir, err := ioutil.TempDir("", "TestFollowSymlinkScopeLink") <add> if err != nil { <add> t.Fatal(err) <add> } <add> defer os.RemoveAll(tmpdir) <add> <add> if err := makeFs(tmpdir, []dirOrLink{ <add> {path: "root2"}, <add> {path: "root", target: "root2"}, <add> {path: "root2/foo", target: "../bar"}, <add> }); err != nil { <add> t.Fatal(err) <add> } <add> if err := testSymlink(tmpdir, "root/foo", "root/bar", "root"); err != nil { <add> t.Fatal(err) <add> } <add>} <add> <add>func TestFollowSymlinkRootScope(t *testing.T) { <add> tmpdir, err := ioutil.TempDir("", "TestFollowSymlinkRootScope") <add> if err != nil { <add> t.Fatal(err) <add> } <add> defer os.RemoveAll(tmpdir) <add> <add> expected, err := filepath.EvalSymlinks(tmpdir) <add> if err != nil { <add> t.Fatal(err) <add> } <add> rewrite, err := FollowSymlinkInScope(tmpdir, "/") <add> if err != nil { <add> t.Fatal(err) <add> } <add> if rewrite != expected { <add> t.Fatalf("expected %q got %q", expected, rewrite) <add> } <add>} <add> <add>func TestFollowSymlinkEmpty(t *testing.T) { <add> res, err := FollowSymlinkInScope("", "") <add> if err != nil { <add> t.Fatal(err) <add> } <add> wd, err := os.Getwd() <add> if err != nil { <add> t.Fatal(err) <add> } <add> if res != wd { <add> t.Fatal("expected %q got %q", wd, res) <add> } <add>} <add> <add>func TestFollowSymlinkCircular(t *testing.T) { <add> tmpdir, err := ioutil.TempDir("", "TestFollowSymlinkCircular") <add> if err != nil { <add> t.Fatal(err) <add> } <add> defer os.RemoveAll(tmpdir) <add> <add> if err := makeFs(tmpdir, []dirOrLink{{path: "root/foo", target: "foo"}}); err != nil { <add> t.Fatal(err) <add> } <add> if err := testSymlink(tmpdir, "root/foo", "", "root"); err == nil { <add> t.Fatal("expected an error for foo -> foo") <add> } <add> <add> if err := makeFs(tmpdir, []dirOrLink{ <add> {path: "root/bar", target: "baz"}, <add> {path: "root/baz", target: "../bak"}, <add> {path: "root/bak", target: "/bar"}, <add> }); err != nil { <add> t.Fatal(err) <add> } <add> if err := testSymlink(tmpdir, "root/foo", "", "root"); err == nil { <add> t.Fatal("expected an error for bar -> baz -> bak -> bar") <add> } <add>} <add> <add>func TestFollowSymlinkComplexChainWithTargetPathsContainingLinks(t *testing.T) { <add> tmpdir, err := ioutil.TempDir("", "TestFollowSymlinkComplexChainWithTargetPathsContainingLinks") <add> if err != nil { <add> t.Fatal(err) <add> } <add> defer os.RemoveAll(tmpdir) <add> <add> if err := makeFs(tmpdir, []dirOrLink{ <add> {path: "root2"}, <add> {path: "root", target: "root2"}, <add> {path: "root/a", target: "r/s"}, <add> {path: "root/r", target: "../root/t"}, <add> {path: "root/root/t/s/b", target: "/../u"}, <add> {path: "root/u/c", target: "."}, <add> {path: "root/u/x/y", target: "../v"}, <add> {path: "root/u/v", target: "/../w"}, <add> }); err != nil { <add> t.Fatal(err) <add> } <add> if err := testSymlink(tmpdir, "root/a/b/c/x/y/z", "root/w/z", "root"); err != nil { <add> t.Fatal(err) <add> } <add>} <add> <add>func TestFollowSymlinkBreakoutNonExistent(t *testing.T) { <add> tmpdir, err := ioutil.TempDir("", "TestFollowSymlinkBreakoutNonExistent") <add> if err != nil { <add> t.Fatal(err) <add> } <add> defer os.RemoveAll(tmpdir) <add> <add> if err := makeFs(tmpdir, []dirOrLink{ <add> {path: "root/slash", target: "/"}, <add> {path: "root/sym", target: "/idontexist/../slash"}, <add> }); err != nil { <add> t.Fatal(err) <add> } <add> if err := testSymlink(tmpdir, "root/sym/file", "root/file", "root"); err != nil { <add> t.Fatal(err) <add> } <add>} <add> <add>func TestFollowSymlinkNoLexicalCleaning(t *testing.T) { <add> tmpdir, err := ioutil.TempDir("", "TestFollowSymlinkNoLexicalCleaning") <add> if err != nil { <add> t.Fatal(err) <add> } <add> defer os.RemoveAll(tmpdir) <add> <add> if err := makeFs(tmpdir, []dirOrLink{ <add> {path: "root/sym", target: "/foo/bar"}, <add> {path: "root/hello", target: "/sym/../baz"}, <add> }); err != nil { <add> t.Fatal(err) <add> } <add> if err := testSymlink(tmpdir, "root/hello", "root/foo/baz", "root"); err != nil { <add> t.Fatal(err) <add> } <add>}
1
PHP
PHP
add redis.connection aliases in container
fb9446f27855e6fb330cf4a65f717f32bd20a4c1
<ide><path>src/Illuminate/Foundation/Application.php <ide> public function registerCoreContainerAliases() <ide> 'queue.failer' => [\Illuminate\Queue\Failed\FailedJobProviderInterface::class], <ide> 'redirect' => [\Illuminate\Routing\Redirector::class], <ide> 'redis' => [\Illuminate\Redis\RedisManager::class, \Illuminate\Contracts\Redis\Factory::class], <add> 'redis.connection' => [\Illuminate\Redis\Connections\Connection::class, \Illuminate\Contracts\Redis\Connection::class], <ide> 'request' => [\Illuminate\Http\Request::class, \Symfony\Component\HttpFoundation\Request::class], <ide> 'router' => [\Illuminate\Routing\Router::class, \Illuminate\Contracts\Routing\Registrar::class, \Illuminate\Contracts\Routing\BindingRegistrar::class], <ide> 'session' => [\Illuminate\Session\SessionManager::class],
1
Javascript
Javascript
fix jslint warning
7b4a540422f2155f0e57d963be69960c1325474d
<ide><path>lib/url.js <ide> Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { <ide> // Back slashes before the query string get converted to forward slashes <ide> // See: https://code.google.com/p/chromium/issues/detail?id=25916 <ide> var queryIndex = url.indexOf('?'), <del> splitter = (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#', <add> splitter = <add> (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#', <ide> uSplit = url.split(splitter), <ide> slashRegex = /\\/g; <ide> uSplit[0] = uSplit[0].replace(slashRegex, '/');
1
Python
Python
fix version test
6e6dc21376e781813e4faea7264d661c2e6d67f3
<ide><path>djangorestframework/compat.py <ide> def apply_markdown(text): <ide> extensions = ['headerid(level=2)'] <ide> safe_mode = False, <ide> <del> if markdown.version < (2, 1): <add> if markdown.version_info < (2, 1): <ide> output_format = markdown.DEFAULT_OUTPUT_FORMAT <ide> <ide> md = markdown.Markdown(extensions=markdown.load_extensions(extensions),
1
Mixed
Ruby
use weak references in descendants tracker
7432c9226e67de1b9a334a097446ea8c12350dbe
<ide><path>activesupport/CHANGELOG.md <add>* Use weak references in descendants tracker to allow anonymous subclasses to <add> be garbage collected. <add> <add> *Edgars Beigarts* <add> <ide> * Update `ActiveSupport::Notifications::Instrumenter#instrument` to make <ide> passing a block optional. This will let users use <ide> `ActiveSupport::Notifications` messaging features outside of <ide><path>activesupport/lib/active_support/descendants_tracker.rb <ide> # frozen_string_literal: true <ide> <add>require "weakref" <add> <ide> module ActiveSupport <ide> # This module provides an internal implementation to track descendants <ide> # which is faster than iterating through ObjectSpace. <ide> module DescendantsTracker <ide> <ide> class << self <ide> def direct_descendants(klass) <del> @@direct_descendants[klass] || [] <add> descendants = @@direct_descendants[klass] <add> descendants ? descendants.to_a : [] <ide> end <ide> <ide> def descendants(klass) <ide> def clear <ide> # This is the only method that is not thread safe, but is only ever called <ide> # during the eager loading phase. <ide> def store_inherited(klass, descendant) <del> (@@direct_descendants[klass] ||= []) << descendant <add> (@@direct_descendants[klass] ||= DescendantsArray.new) << descendant <ide> end <ide> <ide> private <ide> <ide> def accumulate_descendants(klass, acc) <ide> if direct_descendants = @@direct_descendants[klass] <del> acc.concat(direct_descendants) <del> direct_descendants.each { |direct_descendant| accumulate_descendants(direct_descendant, acc) } <add> direct_descendants.each do |direct_descendant| <add> acc << direct_descendant <add> accumulate_descendants(direct_descendant, acc) <add> end <ide> end <ide> end <ide> end <ide> def direct_descendants <ide> def descendants <ide> DescendantsTracker.descendants(self) <ide> end <add> <add> # DescendantsArray is an array that contains weak references to classes. <add> class DescendantsArray # :nodoc: <add> include Enumerable <add> <add> def initialize <add> @refs = [] <add> end <add> <add> def initialize_copy(orig) <add> @refs = @refs.dup <add> end <add> <add> def <<(klass) <add> cleanup! <add> @refs << WeakRef.new(klass) <add> end <add> <add> def each <add> @refs.each do |ref| <add> yield ref.__getobj__ <add> rescue WeakRef::RefError <add> end <add> end <add> <add> def refs_size <add> @refs.size <add> end <add> <add> def cleanup! <add> @refs.delete_if { |ref| !ref.weakref_alive? } <add> end <add> <add> def reject! <add> @refs.reject! do |ref| <add> yield ref.__getobj__ <add> rescue WeakRef::RefError <add> true <add> end <add> end <add> end <ide> end <ide> end <ide><path>activesupport/test/descendants_tracker_test_cases.rb <ide> def test_descendants <ide> assert_equal_sets [], Child2.descendants <ide> end <ide> <add> def test_descendants_with_garbage_collected_classes <add> 1.times do <add> child_klass = Class.new(Parent) <add> assert_equal_sets [Child1, Grandchild1, Grandchild2, Child2, child_klass], Parent.descendants <add> end <add> GC.start <add> assert_equal_sets [Child1, Grandchild1, Grandchild2, Child2], Parent.descendants <add> end <add> <ide> def test_direct_descendants <ide> assert_equal_sets [Child1, Child2], Parent.direct_descendants <ide> assert_equal_sets [Grandchild1, Grandchild2], Child1.direct_descendants
3
Javascript
Javascript
improve path tests
f49bd39cdefce968793c8891774df7a02f67b5ac
<ide><path>test/parallel/test-path.js <ide> assert.strictEqual(path.win32.delimiter, ';'); <ide> assert.strictEqual(path.posix.delimiter, ':'); <ide> <ide> if (common.isWindows) <del> assert.deepStrictEqual(path, path.win32, 'should be win32 path module'); <add> assert.strictEqual(path, path.win32); <ide> else <del> assert.deepStrictEqual(path, path.posix, 'should be posix path module'); <add> assert.strictEqual(path, path.posix);
1
Python
Python
add tf prefix to tf-res test class
893122f6662acb339c7e1a014834b2670ae00e0b
<ide><path>tests/models/resnet/test_modeling_tf_resnet.py <ide> from transformers import AutoFeatureExtractor <ide> <ide> <del>class ResNetModelTester: <add>class TFResNetModelTester: <ide> def __init__( <ide> self, <ide> parent, <ide> def prepare_config_and_inputs_for_common(self): <ide> <ide> <ide> @require_tf <del>class ResNetModelTest(TFModelTesterMixin, unittest.TestCase): <add>class TFResNetModelTest(TFModelTesterMixin, unittest.TestCase): <ide> """ <ide> Here we also overwrite some of the tests of test_modeling_common.py, as ResNet does not use input_ids, inputs_embeds, <ide> attention_mask and seq_length. <ide> class ResNetModelTest(TFModelTesterMixin, unittest.TestCase): <ide> has_attentions = False <ide> <ide> def setUp(self): <del> self.model_tester = ResNetModelTester(self) <add> self.model_tester = TFResNetModelTester(self) <ide> self.config_tester = ConfigTester(self, config_class=ResNetConfig, has_text_modality=False) <ide> <ide> def test_config(self): <ide> def prepare_img(): <ide> <ide> @require_tf <ide> @require_vision <del>class ResNetModelIntegrationTest(unittest.TestCase): <add>class TFResNetModelIntegrationTest(unittest.TestCase): <ide> @cached_property <ide> def default_feature_extractor(self): <ide> return (
1
Go
Go
update imports to be consistent
40c6d00c97c737d9d3827f159518007803affcc7
<ide><path>runtime/execdriver/native/create.go <ide> package native <ide> <ide> import ( <ide> "fmt" <add> "os" <add> <ide> "github.com/dotcloud/docker/pkg/label" <ide> "github.com/dotcloud/docker/pkg/libcontainer" <ide> "github.com/dotcloud/docker/runtime/execdriver" <ide> "github.com/dotcloud/docker/runtime/execdriver/native/configuration" <ide> "github.com/dotcloud/docker/runtime/execdriver/native/template" <del> "os" <ide> ) <ide> <ide> // createContainer populates and configures the container type with the <ide><path>runtime/utils_test.go <ide> package runtime <ide> <ide> import ( <add> "testing" <add> <ide> "github.com/dotcloud/docker/runconfig" <ide> "github.com/dotcloud/docker/utils" <del> "testing" <ide> ) <ide> <ide> func TestMergeLxcConfig(t *testing.T) {
2
Python
Python
add regression test for #693
ad934a9abd973141434a12eb346a339d876b5baf
<ide><path>spacy/tests/regression/test_issue693.py <add># coding: utf8 <add>from __future__ import unicode_literals <add> <add>import pytest <add> <add> <add>@pytest.mark.xfail <add>@pytest.mark.models <add>def test_issue693(EN): <add> """Test that doc.noun_chunks parses the complete sentence.""" <add> <add> text1 = "the TopTown International Airport Board and the Goodwill Space Exploration Partnership." <add> text2 = "the Goodwill Space Exploration Partnership and the TopTown International Airport Board." <add> doc1 = EN(text1) <add> doc2 = EN(text2) <add> chunks1 = [chunk for chunk in doc1.noun_chunks] <add> chunks2 = [chunk for chunk in doc2.noun_chunks] <add> assert len(chunks1) == 2 <add> assert len(chunks2) == 2
1
Javascript
Javascript
upgrade useinsertioneffect to stable
02f411578a8e58af8ec28e385f6b0dcb768cdc41
<ide><path>packages/react-debug-tools/src/__tests__/ReactHooksInspectionIntegration-test.js <ide> describe('ReactHooksInspectionIntegration', () => { <ide> ]); <ide> }); <ide> <del> // @gate experimental || www <ide> it('should inspect the current state of all stateful hooks, including useInsertionEffect', () => { <del> const useInsertionEffect = React.unstable_useInsertionEffect; <add> const useInsertionEffect = React.useInsertionEffect; <ide> const outsideRef = React.createRef(); <ide> function effect() {} <ide> function Foo(props) { <ide><path>packages/react-dom/src/__tests__/ReactDOMServerIntegrationHooks-test.js <ide> function initModules() { <ide> useRef = React.useRef; <ide> useDebugValue = React.useDebugValue; <ide> useImperativeHandle = React.useImperativeHandle; <del> useInsertionEffect = React.unstable_useInsertionEffect; <add> useInsertionEffect = React.useInsertionEffect; <ide> useLayoutEffect = React.useLayoutEffect; <ide> useOpaqueIdentifier = React.unstable_useOpaqueIdentifier; <ide> forwardRef = React.forwardRef; <ide> describe('ReactDOMServerHooks', () => { <ide> }); <ide> }); <ide> describe('useInsertionEffect', () => { <del> // @gate experimental || www <ide> it('should warn when invoked during render', async () => { <ide> function Counter() { <ide> useInsertionEffect(() => { <ide><path>packages/react-reconciler/src/__tests__/ReactHooksWithNoopRenderer-test.js <ide> describe('ReactHooksWithNoopRenderer', () => { <ide> useState = React.useState; <ide> useReducer = React.useReducer; <ide> useEffect = React.useEffect; <del> useInsertionEffect = React.unstable_useInsertionEffect; <add> useInsertionEffect = React.useInsertionEffect; <ide> useLayoutEffect = React.useLayoutEffect; <ide> useCallback = React.useCallback; <ide> useMemo = React.useMemo; <ide> describe('ReactHooksWithNoopRenderer', () => { <ide> }); <ide> <ide> describe('useInsertionEffect', () => { <del> // @gate experimental || www <ide> it('fires insertion effects after snapshots on update', () => { <ide> function CounterA(props) { <ide> useInsertionEffect(() => { <ide> describe('ReactHooksWithNoopRenderer', () => { <ide> }); <ide> }); <ide> <del> // @gate experimental || www <ide> it('fires insertion effects before layout effects', () => { <ide> let committedText = '(empty)'; <ide> <ide> describe('ReactHooksWithNoopRenderer', () => { <ide> expect(Scheduler).toHaveYielded(['Destroy passive [current: 0]']); <ide> }); <ide> <del> // @gate experimental || www <ide> it('force flushes passive effects before firing new insertion effects', () => { <ide> let committedText = '(empty)'; <ide> <ide> describe('ReactHooksWithNoopRenderer', () => { <ide> ]); <ide> }); <ide> <del> // @gate experimental || www <ide> it('fires all insertion effects (interleaved) before firing any layout effects', () => { <ide> let committedA = '(empty)'; <ide> let committedB = '(empty)'; <ide> describe('ReactHooksWithNoopRenderer', () => { <ide> }); <ide> }); <ide> <del> // @gate experimental || www <ide> it('assumes insertion effect destroy function is either a function or undefined', () => { <ide> function App(props) { <ide> useInsertionEffect(() => { <ide><path>packages/react/index.classic.fb.js <ide> export { <ide> useEffect, <ide> useImperativeHandle, <ide> useLayoutEffect, <del> unstable_useInsertionEffect, <add> useInsertionEffect, <ide> useMemo, <ide> useMutableSource, <ide> useMutableSource as unstable_useMutableSource, <ide><path>packages/react/index.experimental.js <ide> export { <ide> useDeferredValue, <ide> useEffect, <ide> useImperativeHandle, <del> unstable_useInsertionEffect, <add> useInsertionEffect, <ide> useLayoutEffect, <ide> useMemo, <ide> useMutableSource as unstable_useMutableSource, <ide><path>packages/react/index.js <ide> export { <ide> useDeferredValue, <ide> useEffect, <ide> useImperativeHandle, <del> unstable_useInsertionEffect, <add> useInsertionEffect, <ide> useLayoutEffect, <ide> useMemo, <ide> useMutableSource, <ide><path>packages/react/index.modern.fb.js <ide> export { <ide> useDeferredValue as unstable_useDeferredValue, // TODO: Remove once call sights updated to useDeferredValue <ide> useEffect, <ide> useImperativeHandle, <del> unstable_useInsertionEffect, <add> useInsertionEffect, <ide> useLayoutEffect, <ide> useMemo, <ide> useMutableSource, <ide><path>packages/react/index.stable.js <ide> export { <ide> useDeferredValue, <ide> useEffect, <ide> useImperativeHandle, <add> useInsertionEffect, <ide> useLayoutEffect, <ide> useMemo, <ide> useMutableSource as unstable_useMutableSource, <ide><path>packages/react/src/React.js <ide> export { <ide> useEffect, <ide> useImperativeHandle, <ide> useDebugValue, <del> useInsertionEffect as unstable_useInsertionEffect, <add> useInsertionEffect, <ide> useLayoutEffect, <ide> useMemo, <ide> useMutableSource,
9
Ruby
Ruby
keep options titles consistent to "options"
ac15647bf0e6ed85714dee4e2b14b2e7e6f29320
<ide><path>actionpack/lib/action_dispatch/routing/mapper.rb <ide> def root(options = {}) <ide> # match 'photos/:id', :to => 'photos#show' <ide> # match 'photos/:id', :controller => 'photos', :action => 'show' <ide> # <del> # === Supported options <add> # === Options <ide> # <ide> # [:controller] <ide> # The route's controller. <ide> def initialize(*args) #:nodoc: <ide> # The difference here being that the routes generated are like /rails/projects/2, <ide> # rather than /accounts/rails/projects/2. <ide> # <del> # === Supported options <add> # === Options <ide> # <ide> # Takes same options as <tt>Base#match</tt> and <tt>Resources#resources</tt>. <ide> # <ide> def controller(controller, options={}) <ide> # admin_post PUT /admin/posts/:id(.:format) {:action=>"update", :controller=>"admin/posts"} <ide> # admin_post DELETE /admin/posts/:id(.:format) {:action=>"destroy", :controller=>"admin/posts"} <ide> # <del> # === Supported options <add> # === Options <ide> # <ide> # The +:path+, +:as+, +:module+, +:shallow_path+ and +:shallow_prefix+ <ide> # options all default to the name of the namespace. <ide> def resources_path_names(options) <ide> # PUT /geocoder <ide> # DELETE /geocoder <ide> # <del> # === Supported options <add> # === Options <ide> # Takes same options as +resources+. <ide> def resource(*resources, &block) <ide> options = resources.extract_options! <ide> def resource(*resources, &block) <ide> # PUT /photos/:id/comments/:id <ide> # DELETE /photos/:id/comments/:id <ide> # <del> # === Supported options <add> # === Options <ide> # Takes same options as <tt>Base#match</tt> as well as: <ide> # <ide> # [:path_names] <ide><path>activerecord/lib/active_record/associations.rb <ide> module ClassMethods <ide> # * <tt>Firm#clients.create</tt> (similar to <tt>c = Client.new("firm_id" => id); c.save; c</tt>) <ide> # The declaration can also include an options hash to specialize the behavior of the association. <ide> # <del> # === Supported options <add> # === Options <ide> # [:class_name] <ide> # Specify the class name of the association. Use it only if that name can't be inferred <ide> # from the association name. So <tt>has_many :products</tt> will by default be linked <ide><path>activerecord/lib/active_record/relation/finder_methods.rb <ide> module FinderMethods <ide> # <ide> # All approaches accept an options hash as their last parameter. <ide> # <del> # ==== Parameters <add> # ==== Options <ide> # <ide> # * <tt>:conditions</tt> - An SQL fragment like "administrator = 1", <tt>["user_name = ?", username]</tt>, <ide> # or <tt>["user_name = :user_name", { :user_name => user_name }]</tt>. See conditions in the intro.
3
Text
Text
remove badge from readme
b587aeee1c1be3633a56b945af3e7c2c303369ca
<ide><path>README.md <ide> # Keras: Deep Learning library for Theano and TensorFlow <ide> <del>![Build status](https://api.travis-ci.org/fchollet/keras.svg) <del> <ide> ## You have just found Keras. <ide> <ide> Keras is a minimalist, highly modular neural networks library, written in Python and capable of running on top of either [TensorFlow](https://github.com/tensorflow/tensorflow) or [Theano](https://github.com/Theano/Theano). It was developed with a focus on enabling fast experimentation. Being able to go from idea to result with the least possible delay is key to doing good research.
1
Go
Go
fix godoc for stockruntimename
8925f735a1940ab3fa363f58e754739a32028cb5
<ide><path>daemon/config/config_windows.go <ide> import ( <ide> ) <ide> <ide> const ( <del> // This is used by the `default-runtime` flag in dockerd as the default value. <del> // On windows we'd prefer to keep this empty so the value is auto-detected based on other options. <add> // StockRuntimeName is used by the 'default-runtime' flag in dockerd as the <add> // default value. On Windows keep this empty so the value is auto-detected <add> // based on other options. <ide> StockRuntimeName = "" <ide> ) <ide>
1
Javascript
Javascript
expand hash in stats
513a1f1c8008117e8c2c7a5833ac2ca77b7737ed
<ide><path>lib/webpack.js <ide> function webpack(context, moduleName, options, callback) { <ide> function writeFiles() { <ide> var remFiles = fileWrites.length; <ide> fileWrites.forEach(function(writeAction) { <del> options.events.emit("task", "write " + writeAction[0]); <del> fileSizeMap[path.basename(writeAction[0])] = writeAction[1].length; <del> fs.writeFile(writeAction[0].replace(HASH_REGEXP, hash), writeAction[1], "utf-8", function(err) { <del> options.events.emit("task-end", "write " + writeAction[0]); <add> var writeActionFileName = writeAction[0].replace(HASH_REGEXP, hash) <add> options.events.emit("task", "write " + writeActionFileName); <add> fileSizeMap[path.basename(writeActionFileName)] = writeAction[1].length; <add> fs.writeFile(writeActionFileName, writeAction[1], "utf-8", function(err) { <add> options.events.emit("task-end", "write " + writeActionFileName); <ide> if(err) throw err; <ide> remFiles--; <ide> if(remFiles === 0)
1
Python
Python
add unit test for azurecosmosdocumentsensor
3c3342f1fd0662401c09bdc2f7de277b53ac1d43
<ide><path>tests/providers/microsoft/azure/sensors/test_azure_cosmos.py <add># Licensed to the Apache Software Foundation (ASF) under one <add># or more contributor license agreements. See the NOTICE file <add># distributed with this work for additional information <add># regarding copyright ownership. The ASF licenses this file <add># to you under the Apache License, Version 2.0 (the <add># "License"); you may not use this file except in compliance <add># with the License. You may obtain a copy of the License at <add># <add># http://www.apache.org/licenses/LICENSE-2.0 <add># <add># Unless required by applicable law or agreed to in writing, <add># software distributed under the License is distributed on an <add># "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY <add># KIND, either express or implied. See the License for the <add># specific language governing permissions and limitations <add># under the License. <add> <add>import unittest <add>from unittest import mock <add> <add>from airflow.providers.microsoft.azure.sensors.azure_cosmos import AzureCosmosDocumentSensor <add> <add>DB_NAME = 'test-db-name' <add>COLLECTION_NAME = 'test-db-collection-name' <add>DOCUMENT_ID = 'test-document-id' <add> <add> <add>class TestAzureCosmosSensor(unittest.TestCase): <add> @mock.patch('airflow.providers.microsoft.azure.sensors.azure_cosmos.AzureCosmosDBHook') <add> def test_should_call_hook_with_args(self, mock_hook): <add> mock_instance = mock_hook.return_value <add> mock_instance.get_document.return_value = True # Indicate document returned <add> sensor = AzureCosmosDocumentSensor( <add> task_id="test-task-1", <add> database_name=DB_NAME, <add> collection_name=COLLECTION_NAME, <add> document_id=DOCUMENT_ID, <add> ) <add> result = sensor.poke(None) <add> mock_instance.get_document.assert_called_once_with(DOCUMENT_ID, DB_NAME, COLLECTION_NAME) <add> self.assertEqual(result, True) <add> <add> @mock.patch('airflow.providers.microsoft.azure.sensors.azure_cosmos.AzureCosmosDBHook') <add> def test_should_return_false_on_no_document(self, mock_hook): <add> mock_instance = mock_hook.return_value <add> mock_instance.get_document.return_value = None # Indicate document not returned <add> sensor = AzureCosmosDocumentSensor( <add> task_id="test-task-2", <add> database_name=DB_NAME, <add> collection_name=COLLECTION_NAME, <add> document_id=DOCUMENT_ID, <add> ) <add> result = sensor.poke(None) <add> mock_instance.get_document.assert_called_once_with(DOCUMENT_ID, DB_NAME, COLLECTION_NAME) <add> self.assertEqual(result, False) <ide><path>tests/test_project_structure.py <ide> import mmap <ide> import os <ide> import unittest <add>from typing import Set <ide> <ide> from parameterized import parameterized <ide> <ide> ROOT_FOLDER = os.path.realpath( <ide> os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir) <ide> ) <ide> <del>MISSING_TEST_FILES = { <del> 'tests/providers/microsoft/azure/sensors/test_azure_cosmos.py', <del>} <add>MISSING_TEST_FILES: Set[str] = set() # add missing test files in providers package here. <ide> <ide> <ide> class TestProjectStructure(unittest.TestCase):
2
PHP
PHP
add comment with the value of the hashed password
c3d3dc14031c44510b948ad17b4c395906603cc6
<ide><path>database/factories/UserFactory.php <ide> return [ <ide> 'name' => $faker->name, <ide> 'email' => $faker->unique()->safeEmail, <del> 'password' => '$2y$10$TKh8H1.PfQx37YgCzwiKb.KjNyWgaHb9cbcoQgdIVFlYg7B77UdFm', <add> 'password' => '$2y$10$TKh8H1.PfQx37YgCzwiKb.KjNyWgaHb9cbcoQgdIVFlYg7B77UdFm', // secret <ide> 'remember_token' => str_random(10), <ide> ]; <ide> });
1
PHP
PHP
improve key generation
b9f6d162e64ab0be170db2ae476bf3dcdfb99563
<ide><path>application/config/database.php <ide> 'host' => 'localhost', <ide> 'database' => 'database', <ide> 'username' => 'root', <del> 'password' => 'password', <add> 'password' => '', <ide> 'charset' => 'utf8', <ide> ), <ide> <ide> 'host' => 'localhost', <ide> 'database' => 'database', <ide> 'username' => 'root', <del> 'password' => 'password', <add> 'password' => '', <ide> 'charset' => 'utf8', <ide> ), <ide> <ide> 'host' => 'localhost', <ide> 'database' => 'database', <ide> 'username' => 'root', <del> 'password' => 'password', <add> 'password' => '', <ide> ), <ide> <ide> ), <ide><path>laravel/cli/tasks/key.php <ide> public function generate($arguments = array()) <ide> { <ide> echo "An application key already exists!"; <ide> } <add> <add> echo PHP_EOL; <ide> } <ide> <ide> } <ide>\ No newline at end of file
2
Python
Python
add test for serializermethodfield
a6901ea36de19a35fa82783c984841b4c3ca0dad
<ide><path>rest_framework/tests/test_fields.py <ide> class BooleanRequiredSerializer(serializers.Serializer): <ide> bool_field = serializers.BooleanField(required=True) <ide> <ide> self.assertFalse(BooleanRequiredSerializer(data={}).is_valid()) <add> <add> <add>class SerializerMethodFieldTest(TestCase): <add> """ <add> Tests for the SerializerMethodField field_to_native() behavior <add> """ <add> class SerializerTest(serializers.Serializer): <add> def get_my_test(self, obj): <add> return obj.my_test[0:5] <add> <add> class Example(): <add> my_test = 'Hey, this is a test !' <add> <add> def test_field_to_native(self): <add> s = serializers.SerializerMethodField('get_my_test') <add> s.initialize(self.SerializerTest(), 'name') <add> result = s.field_to_native(self.Example(), None) <add> self.assertEqual(result, 'Hey, ')
1
Ruby
Ruby
add regression test
5db56a513286814991c27000af2c0243cc19d1e2
<ide><path>test/test_insert_manager.rb <ide> module Arel <ide> INSERT INTO "users" VALUES (1) <ide> } <ide> end <add> <add> it "accepts sql literals" do <add> table = Table.new :users <add> manager = Arel::InsertManager.new <add> manager.into table <add> <add> manager.values = Arel.sql("DEFAULT VALUES") <add> manager.to_sql.must_be_like %{ <add> INSERT INTO "users" DEFAULT VALUES <add> } <add> end <ide> end <ide> <ide> describe "combo" do
1
Javascript
Javascript
add playerreset event
0e5442f98e1bb3c258b807ca9bf171ca638d4e11
<ide><path>src/js/mixins/evented.js <ide> const isEvented = (object) => <ide> !!object.eventBusEl_ && <ide> ['on', 'one', 'off', 'trigger'].every(k => typeof object[k] === 'function'); <ide> <add>/** <add> * Adds a callback to run after the evented mixin applied. <add> * <add> * @param {Object} object <add> * An object to Add <add> * @param {Function} callback <add> * The callback to run. <add> */ <add>const addEventedCallback = (target, callback) => { <add> if (isEvented(target)) { <add> callback(); <add> } else { <add> if (!target.eventedCallbacks) { <add> target.eventedCallbacks = []; <add> } <add> target.eventedCallbacks.push(callback); <add> } <add>}; <add> <ide> /** <ide> * Whether a value is a valid event type - non-empty string or array. <ide> * <ide> function evented(target, options = {}) { <ide> <ide> Obj.assign(target, EventedMixin); <ide> <add> if (target.eventedCallbacks) { <add> target.eventedCallbacks.forEach((callback) => { <add> callback(); <add> }); <add> } <add> <ide> // When any evented object is disposed, it removes all its listeners. <ide> target.on('dispose', () => { <ide> target.off(); <ide> function evented(target, options = {}) { <ide> <ide> export default evented; <ide> export {isEvented}; <add>export {addEventedCallback}; <ide><path>src/js/player.js <ide> import document from 'global/document'; <ide> import window from 'global/window'; <ide> import tsml from 'tsml'; <ide> import evented from './mixins/evented'; <add>import {isEvented, addEventedCallback} from './mixins/evented'; <ide> import * as Events from './utils/events.js'; <ide> import * as Dom from './utils/dom.js'; <ide> import * as Fn from './utils/fn.js'; <ide> class Player extends Component { <ide> // Make this an evented object and use `el_` as its event bus. <ide> evented(this, {eventBusKey: 'el_'}); <ide> <add> if (this.fluid_) { <add> this.on('playerreset', this.updateStyleEl_); <add> } <ide> // We also want to pass the original player options to each component and plugin <ide> // as well so they don't need to reach back into the player for options later. <ide> // We also need to do another copy of this.options_ so we don't end up with <ide> class Player extends Component { <ide> <ide> this.fluid_ = !!bool; <ide> <add> if (isEvented(this)) { <add> this.off('playerreset', this.updateStyleEl_); <add> } <ide> if (bool) { <ide> this.addClass('vjs-fluid'); <ide> this.fill(false); <add> addEventedCallback(function() { <add> this.on('playerreset', this.updateStyleEl_); <add> }); <ide> } else { <ide> this.removeClass('vjs-fluid'); <ide> } <ide> class Player extends Component { <ide> } <ide> this.loadTech_(this.options_.techOrder[0], null); <ide> this.techCall_('reset'); <add> if (isEvented(this)) { <add> this.trigger('playerreset'); <add> } <ide> } <ide> <ide> /**
2
Javascript
Javascript
add tests for iswindow
65a44dd49cf594008ce4d21de4b57abeab7fe52c
<ide><path>test/AngularSpec.js <ide> describe('angular', function() { <ide> }); <ide> <ide> <add> describe('isWindow', function () { <add> it('should return true for the Window object', function() { <add> expect(isWindow(window)).toBe(true); <add> }); <add> <add> it('should return false for any object that is not a Window', function() { <add> expect(isWindow([])).toBe(false); <add> expect(isWindow('')).toBeFalsy(); <add> expect(isWindow(23)).toBe(false); <add> expect(isWindow({})).toBe(false); <add> expect(isWindow(new Date())).toBe(false); <add> expect(isWindow(document)).toBe(false); <add> }); <add> }); <add> <add> <ide> describe('compile', function() { <ide> it('should link to existing node and create scope', inject(function($rootScope, $compile) { <ide> var template = angular.element('<div>{{greeting = "hello world"}}</div>');
1
PHP
PHP
remove queue responses. no longer needed
6c22d54f89d1021306b6dfab1604a06d4c9cc53e
<ide><path>src/Illuminate/Queue/Worker.php <ide> public function runNextJob($connectionName, $queue = null, $delay = 0, $sleep = <ide> } <ide> <ide> $this->sleep($sleep); <del> <del> return ['job' => null, 'failed' => false]; <ide> } <ide> <ide> /** <ide> public function process($connection, Job $job, $maxTries = 0, $delay = 0) <ide> $job->fire(); <ide> <ide> $this->raiseAfterJobEvent($connection, $job); <del> <del> return ['job' => $job, 'failed' => false]; <ide> } catch (Exception $e) { <ide> $this->handleJobException($connection, $job, $delay, $e); <ide> } catch (Throwable $e) { <ide> protected function raiseExceptionOccurredJobEvent($connection, Job $job, $except <ide> */ <ide> protected function logFailedJob($connection, Job $job) <ide> { <del> if ($this->failer) { <del> $this->failer->log($connection, $job->getQueue(), $job->getRawBody()); <add> if (! $this->failer) { <add> return; <add> } <ide> <del> $job->delete(); <add> $this->failer->log($connection, $job->getQueue(), $job->getRawBody()); <ide> <del> $job->failed(); <add> $job->delete(); <ide> <del> $this->raiseFailedJobEvent($connection, $job); <del> } <add> $job->failed(); <ide> <del> return ['job' => $job, 'failed' => true]; <add> $this->raiseFailedJobEvent($connection, $job); <ide> } <ide> <ide> /**
1
PHP
PHP
allow bc for nullish db values as strings
960d3dfbe0db71cf63a761d58532b31b07331369
<ide><path>src/Database/Type/DateTimeType.php <ide> public function toDatabase($value, Driver $driver) <ide> */ <ide> public function toPHP($value, Driver $driver) <ide> { <del> if ($value === null) { <add> if ($value === null || (int)$value === 0) { <ide> return null; <ide> } <ide> <ide><path>tests/TestCase/Database/Type/DateTimeTypeTest.php <ide> public function tearDown() <ide> public function testToPHP() <ide> { <ide> $this->assertNull($this->type->toPHP(null, $this->driver)); <add> $this->assertNull($this->type->toPHP('0000-00-00 00:00:00', $this->driver)); <ide> <ide> $result = $this->type->toPHP('2001-01-04 12:13:14', $this->driver); <ide> $this->assertInstanceOf('Cake\I18n\Time', $result); <ide><path>tests/TestCase/Database/Type/DateTypeTest.php <ide> public function setUp() <ide> public function testToPHP() <ide> { <ide> $this->assertNull($this->type->toPHP(null, $this->driver)); <add> $this->assertNull($this->type->toPHP('0000-00-00', $this->driver)); <ide> <ide> $result = $this->type->toPHP('2001-01-04', $this->driver); <ide> $this->assertInstanceOf('DateTime', $result);
3
Javascript
Javascript
add string.prototype.trim to polyfill check
2b0e51bdbaa0f0e589c8a24e358a7739e70f38dc
<ide><path>src/browser/ui/React.js <ide> if (__DEV__) { <ide> Function.prototype.bind, <ide> Object.keys, <ide> String.prototype.split, <add> String.prototype.trim, <ide> <ide> // shams <ide> Object.create, <ide> if (__DEV__) { <ide> if (!expectedFeatures[i]) { <ide> console.error( <ide> 'One or more ES5 shim/shams expected by React are not available: ' + <del> 'http://facebook.github.io/react/docs/working-with-the-browser.html' + <del> '#polyfills-needed-to-support-older-browsers' <add> 'http://fb.me/react-warning-polyfills' <ide> ); <ide> break; <ide> }
1
PHP
PHP
add docs for runcommand + container
923446ec557f4e069f097c1233a68febb0443e0c
<ide><path>src/Console/BaseCommand.php <ide> public function abort(int $code = self::CODE_ERROR): void <ide> /** <ide> * Execute another command with the provided set of arguments. <ide> * <add> * If you are using a string command name, that command's dependencies <add> * will not be resolved with the application container. Instead you will <add> * need to pass the command as an object with all of its dependencies. <add> * <ide> * @param string|\Cake\Console\CommandInterface $command The command class name or command instance. <ide> * @param array $args The arguments to invoke the command with. <ide> * @param \Cake\Console\ConsoleIo $io The ConsoleIo instance to use for the executed command.
1
Text
Text
update template.md too
ef2ec255dd30e216ca6f6f88084229d6b6289410
<ide><path>examples/dll-app-and-vendor/0-vendor/template.md <ide> This is the vendor build part. <ide> <del>It's built separately from the app part. The vendors dll is only built when vendors has changed and not while the normal development cycle. <add>It's built separately from the app part. The vendors dll is only built when the array of vendors has changed and not during the normal development cycle. <ide> <ide> The DllPlugin in combination with the `output.library` option exposes the internal require function as global variable in the target environment. <ide> <del>A manifest is creates which includes mappings from module names to internal ids. <add>A manifest is created which includes mappings from module names to internal ids. <ide> <ide> ### webpack.config.js <ide>
1
Ruby
Ruby
recommend adoptopenjdk as per
c9a75db27d36dcf3a8fa85590e7e3c0b61de3862
<ide><path>Library/Homebrew/cask/dsl/caveats.rb <ide> def eval_caveats(&block) <ide> if java_version == :any <ide> <<~EOS <ide> #{@cask} requires Java. You can install the latest version with: <del> brew cask install java <add> brew cask install adoptopenjdk <ide> EOS <ide> elsif java_version.include?("11") || java_version.include?("+") <ide> <<~EOS <ide> #{@cask} requires Java #{java_version}. You can install the latest version with: <del> brew cask install java <add> brew cask install adoptopenjdk <ide> EOS <ide> else <ide> <<~EOS <ide> #{@cask} requires Java #{java_version}. You can install it with: <del> brew cask install homebrew/cask-versions/java#{java_version} <add> brew cask install homebrew/cask-versions/adoptopenjdk#{java_version} <ide> EOS <ide> end <ide> end
1
Ruby
Ruby
pass `verbose` to unpack strategies
81939dc496f54f5f1ce390578c17797ce95de4f5
<ide><path>Library/Homebrew/download_strategy.rb <ide> def _fetch <ide> class NoUnzipCurlDownloadStrategy < CurlDownloadStrategy <ide> def stage <ide> UnpackStrategy::Uncompressed.new(cached_location) <del> .extract(basename: basename_without_params) <add> .extract(basename: basename_without_params, <add> verbose: ARGV.verbose? && !shutup) <ide> end <ide> end <ide> <ide><path>Library/Homebrew/system_command.rb <ide> def run! <ide> result <ide> end <ide> <del> def initialize(executable, args: [], sudo: false, input: [], print_stdout: false, print_stderr: true, verbose: false, must_succeed: false, env: {}, **options) <add> def initialize(executable, args: [], sudo: false, env: {}, input: [], must_succeed: false, <add> print_stdout: false, print_stderr: true, verbose: false, **options) <add> <ide> @executable = executable <ide> @args = args <ide> @sudo = sudo <ide><path>Library/Homebrew/unpack_strategy/air.rb <add># frozen_string_literal: true <add> <ide> module UnpackStrategy <ide> class Air <ide> include UnpackStrategy <ide> def dependencies <ide> @dependencies ||= [Hbc::CaskLoader.load("adobe-air")] <ide> end <ide> <add> AIR_APPLICATION_INSTALLER = <add> "/Applications/Utilities/Adobe AIR Application Installer.app/Contents/MacOS/Adobe AIR Application Installer" <add> <add> private_constant :AIR_APPLICATION_INSTALLER <add> <ide> private <ide> <ide> def extract_to_dir(unpack_dir, basename:, verbose:) <del> system_command!( <del> "/Applications/Utilities/Adobe AIR Application Installer.app/Contents/MacOS/Adobe AIR Application Installer", <del> args: ["-silent", "-location", unpack_dir, path], <del> ) <add> system_command! AIR_APPLICATION_INSTALLER, <add> args: ["-silent", "-location", unpack_dir, path], <add> verbose: verbose <ide> end <ide> end <ide> end <ide><path>Library/Homebrew/unpack_strategy/bzip2.rb <ide> def self.can_extract?(path) <ide> def extract_to_dir(unpack_dir, basename:, verbose:) <ide> FileUtils.cp path, unpack_dir/basename, preserve: true <ide> quiet_flags = verbose ? [] : ["-q"] <del> system_command! "bunzip2", args: [*quiet_flags, unpack_dir/basename] <add> system_command! "bunzip2", <add> args: [*quiet_flags, unpack_dir/basename], <add> verbose: verbose <ide> end <ide> end <ide> end <ide><path>Library/Homebrew/unpack_strategy/cab.rb <ide> def self.can_extract?(path) <ide> def extract_to_dir(unpack_dir, basename:, verbose:) <ide> system_command! "cabextract", <ide> args: ["-d", unpack_dir, "--", path], <del> env: { "PATH" => PATH.new(Formula["cabextract"].opt_bin, ENV["PATH"]) } <add> env: { "PATH" => PATH.new(Formula["cabextract"].opt_bin, ENV["PATH"]) }, <add> verbose: verbose <ide> end <ide> <ide> def dependencies <ide><path>Library/Homebrew/unpack_strategy/dmg.rb <ide> module UnpackStrategy <ide> class Dmg <ide> include UnpackStrategy <ide> <del> using Magic <del> <ide> module Bom <ide> DMG_METADATA = Set.new %w[ <ide> .background <ide> def bom <ide> class Mount <ide> include UnpackStrategy <ide> <del> def eject <add> def eject(verbose: false) <ide> tries ||= 3 <ide> <ide> return unless path.exist? <ide> <ide> if tries > 1 <ide> system_command! "diskutil", <ide> args: ["eject", path], <del> print_stderr: false <add> print_stderr: false, <add> verbose: verbose <ide> else <ide> system_command! "diskutil", <ide> args: ["unmount", "force", path], <del> print_stderr: false <add> print_stderr: false, <add> verbose: verbose <ide> end <ide> rescue ErrorDuringExecution => e <ide> raise e if (tries -= 1).zero? <ide> def extract_to_dir(unpack_dir, basename:, verbose:) <ide> filelist.puts(path.bom) <ide> filelist.close <ide> <del> system_command! "mkbom", args: ["-s", "-i", filelist.path, "--", bomfile.path] <add> system_command! "mkbom", <add> args: ["-s", "-i", filelist.path, "--", bomfile.path], <add> verbose: verbose <ide> end <ide> <del> system_command! "ditto", args: ["--bom", bomfile.path, "--", path, unpack_dir] <add> system_command! "ditto", <add> args: ["--bom", bomfile.path, "--", path, unpack_dir], <add> verbose: verbose <ide> <ide> FileUtils.chmod "u+w", Pathname.glob(unpack_dir/"**/*").reject(&:symlink?) <ide> end <ide> def extract_to_dir(unpack_dir, basename:, verbose:) <ide> raise "No mounts found in '#{path}'; perhaps it is a bad disk image?" if mounts.empty? <ide> <ide> mounts.each do |mount| <del> mount.extract(to: unpack_dir) <add> mount.extract(to: unpack_dir, verbose: verbose) <ide> end <ide> end <ide> end <ide> def mount(verbose: false) <ide> Dir.mktmpdir do |mount_dir| <ide> mount_dir = Pathname(mount_dir) <ide> <del> without_eula = system_command("hdiutil", <add> without_eula = system_command "hdiutil", <ide> args: ["attach", "-plist", "-nobrowse", "-readonly", "-noidme", "-mountrandom", mount_dir, path], <ide> input: "qn\n", <del> print_stderr: false) <add> print_stderr: false, <add> verbose: verbose <ide> <ide> # If mounting without agreeing to EULA succeeded, there is none. <ide> plist = if without_eula.success? <ide> without_eula.plist <ide> else <ide> cdr_path = mount_dir/path.basename.sub_ext(".cdr") <ide> <del> system_command!("hdiutil", args: ["convert", "-quiet", "-format", "UDTO", "-o", cdr_path, path]) <add> system_command! "hdiutil", <add> args: ["convert", "-quiet", "-format", "UDTO", "-o", cdr_path, path], <add> verbose: verbose <ide> <del> with_eula = system_command!( <del> "/usr/bin/hdiutil", <del> args: ["attach", "-plist", "-nobrowse", "-readonly", "-noidme", "-mountrandom", mount_dir, cdr_path], <del> ) <add> with_eula = system_command! "hdiutil", <add> args: ["attach", "-plist", "-nobrowse", "-readonly", "-noidme", "-mountrandom", mount_dir, cdr_path], <add> verbose: verbose <ide> <ide> if verbose && !(eula_text = without_eula.stdout).empty? <ide> ohai "Software License Agreement for '#{path}':" <ide> def mount(verbose: false) <ide> begin <ide> yield mounts <ide> ensure <del> mounts.each(&:eject) <add> mounts.each do |mount| <add> mount.eject(verbose: verbose) <add> end <ide> end <ide> end <ide> end <ide><path>Library/Homebrew/unpack_strategy/fossil.rb <ide> def extract_to_dir(unpack_dir, basename:, verbose:) <ide> system_command! "fossil", <ide> args: ["open", path, *args], <ide> chdir: unpack_dir, <del> env: { "PATH" => PATH.new(Formula["fossil"].opt_bin, ENV["PATH"]) } <add> env: { "PATH" => PATH.new(Formula["fossil"].opt_bin, ENV["PATH"]) }, <add> verbose: verbose <ide> end <ide> end <ide> end <ide><path>Library/Homebrew/unpack_strategy/generic_unar.rb <ide> def dependencies <ide> def extract_to_dir(unpack_dir, basename:, verbose:) <ide> system_command! "unar", <ide> args: ["-force-overwrite", "-quiet", "-no-directory", "-output-directory", unpack_dir, "--", path], <del> env: { "PATH" => PATH.new(Formula["unar"].opt_bin, ENV["PATH"]) } <add> env: { "PATH" => PATH.new(Formula["unar"].opt_bin, ENV["PATH"]) }, <add> verbose: verbose <ide> end <ide> end <ide> end <ide><path>Library/Homebrew/unpack_strategy/gzip.rb <ide> def extract_to_dir(unpack_dir, basename:, verbose:) <ide> FileUtils.cp path, unpack_dir/basename, preserve: true <ide> quiet_flags = verbose ? [] : ["-q"] <ide> system_command! "gunzip", <del> args: [*quiet_flags, "-N", "--", unpack_dir/basename] <add> args: [*quiet_flags, "-N", "--", unpack_dir/basename], <add> verbose: verbose <ide> end <ide> end <ide> end <ide><path>Library/Homebrew/unpack_strategy/lha.rb <ide> def dependencies <ide> def extract_to_dir(unpack_dir, basename:, verbose:) <ide> system_command! "lha", <ide> args: ["xq2w=#{unpack_dir}", path], <del> env: { "PATH" => PATH.new(Formula["lha"].opt_bin, ENV["PATH"]) } <add> env: { "PATH" => PATH.new(Formula["lha"].opt_bin, ENV["PATH"]) }, <add> verbose: verbose <ide> end <ide> end <ide> end <ide><path>Library/Homebrew/unpack_strategy/lzip.rb <ide> def extract_to_dir(unpack_dir, basename:, verbose:) <ide> quiet_flags = verbose ? [] : ["-q"] <ide> system_command! "lzip", <ide> args: ["-d", *quiet_flags, unpack_dir/basename], <del> env: { "PATH" => PATH.new(Formula["lzip"].opt_bin, ENV["PATH"]) } <add> env: { "PATH" => PATH.new(Formula["lzip"].opt_bin, ENV["PATH"]) }, <add> verbose: verbose <ide> end <ide> end <ide> end <ide><path>Library/Homebrew/unpack_strategy/lzma.rb <ide> def extract_to_dir(unpack_dir, basename:, verbose:) <ide> quiet_flags = verbose ? [] : ["-q"] <ide> system_command! "unlzma", <ide> args: [*quiet_flags, "--", unpack_dir/basename], <del> env: { "PATH" => PATH.new(Formula["xz"].opt_bin, ENV["PATH"]) } <add> env: { "PATH" => PATH.new(Formula["xz"].opt_bin, ENV["PATH"]) }, <add> verbose: verbose <ide> end <ide> <ide> def dependencies <ide><path>Library/Homebrew/unpack_strategy/mercurial.rb <ide> def self.can_extract?(path) <ide> def extract_to_dir(unpack_dir, basename:, verbose:) <ide> system_command! "hg", <ide> args: ["--cwd", path, "archive", "--subrepos", "-y", "-t", "files", unpack_dir], <del> env: { "PATH" => PATH.new(Formula["mercurial"].opt_bin, ENV["PATH"]) } <add> env: { "PATH" => PATH.new(Formula["mercurial"].opt_bin, ENV["PATH"]) }, <add> verbose: verbose <ide> end <ide> end <ide> end <ide><path>Library/Homebrew/unpack_strategy/p7zip.rb <ide> def dependencies <ide> def extract_to_dir(unpack_dir, basename:, verbose:) <ide> system_command! "7zr", <ide> args: ["x", "-y", "-bd", "-bso0", path, "-o#{unpack_dir}"], <del> env: { "PATH" => PATH.new(Formula["p7zip"].opt_bin, ENV["PATH"]) } <add> env: { "PATH" => PATH.new(Formula["p7zip"].opt_bin, ENV["PATH"]) }, <add> verbose: verbose <ide> end <ide> end <ide> end <ide><path>Library/Homebrew/unpack_strategy/rar.rb <ide> def dependencies <ide> def extract_to_dir(unpack_dir, basename:, verbose:) <ide> system_command! "unrar", <ide> args: ["x", "-inul", path, unpack_dir], <del> env: { "PATH" => PATH.new(Formula["unrar"].opt_bin, ENV["PATH"]) } <add> env: { "PATH" => PATH.new(Formula["unrar"].opt_bin, ENV["PATH"]) }, <add> verbose: verbose <ide> end <ide> end <ide> end <ide><path>Library/Homebrew/unpack_strategy/subversion.rb <ide> def self.can_extract?(path) <ide> def extract_to_dir(unpack_dir, basename:, verbose:) <ide> system_command! "svn", <ide> args: ["export", "--force", ".", unpack_dir], <del> chdir: path.to_s <add> chdir: path.to_s, <add> verbose: verbose <ide> end <ide> end <ide> end <ide><path>Library/Homebrew/unpack_strategy/tar.rb <ide> def extract_to_dir(unpack_dir, basename:, verbose:) <ide> <ide> if DependencyCollector.tar_needs_xz_dependency? && Xz.can_extract?(path) <ide> tmpdir = Pathname(tmpdir) <del> Xz.new(path).extract(to: tmpdir) <add> Xz.new(path).extract(to: tmpdir, verbose: verbose) <ide> tar_path = tmpdir.children.first <ide> end <ide> <del> system_command! "tar", args: ["xf", tar_path, "-C", unpack_dir] <add> system_command! "tar", <add> args: ["xf", tar_path, "-C", unpack_dir], <add> verbose: verbose <ide> end <ide> end <ide> end <ide><path>Library/Homebrew/unpack_strategy/xar.rb <ide> def self.can_extract?(path) <ide> private <ide> <ide> def extract_to_dir(unpack_dir, basename:, verbose:) <del> system_command! "xar", args: ["-x", "-f", path, "-C", unpack_dir] <add> system_command! "xar", <add> args: ["-x", "-f", path, "-C", unpack_dir], <add> verbose: verbose <ide> end <ide> end <ide> end <ide><path>Library/Homebrew/unpack_strategy/xz.rb <ide> def extract_to_dir(unpack_dir, basename:, verbose:) <ide> quiet_flags = verbose ? [] : ["-q"] <ide> system_command! "unxz", <ide> args: [*quiet_flags, "-T0", "--", unpack_dir/basename], <del> env: { "PATH" => PATH.new(Formula["xz"].opt_bin, ENV["PATH"]) } <add> env: { "PATH" => PATH.new(Formula["xz"].opt_bin, ENV["PATH"]) }, <add> verbose: verbose <ide> end <ide> end <ide> end <ide><path>Library/Homebrew/unpack_strategy/zip.rb <ide> def self.can_extract?(path) <ide> <ide> def extract_to_dir(unpack_dir, basename:, verbose:) <ide> quiet_flags = verbose ? [] : ["-qq"] <del> system_command! "unzip", args: [*quiet_flags, path, "-d", unpack_dir] <add> system_command! "unzip", <add> args: [*quiet_flags, path, "-d", unpack_dir], <add> verbose: verbose <ide> end <ide> end <ide> end
20
PHP
PHP
fix cs errors
06fb49d1974bf46715bc99b04163376633e74609
<ide><path>src/Database/Schema/MysqlSchema.php <ide> protected function _convertColumn(string $column): array <ide> } <ide> if (strpos($col, 'blob') !== false || $col === 'binary') { <ide> $lengthName = substr($col, 0, -4); <del> $length = isset(TableSchema::$columnLengths[$lengthName]) ? TableSchema::$columnLengths[$lengthName] : $length; <add> $length = TableSchema::$columnLengths[$lengthName] ?? $length; <ide> <ide> return ['type' => TableSchema::TYPE_BINARY, 'length' => $length]; <ide> } <ide><path>tests/TestCase/Database/Schema/MysqlSchemaTest.php <ide> public static function convertColumnProvider() <ide> ], <ide> [ <ide> 'BINARY(1)', <del> ['type' => 'binary', 'length' => 1] <add> ['type' => 'binary', 'length' => 1], <ide> ], <ide> [ <ide> 'TEXT', <ide><path>tests/TestCase/Database/Schema/SqliteSchemaTest.php <ide> public static function convertColumnProvider() <ide> ], <ide> [ <ide> 'BINARY(1)', <del> ['type' => 'binary', 'length' => 1] <add> ['type' => 'binary', 'length' => 1], <ide> ], <ide> [ <ide> 'BLOB',
3
Javascript
Javascript
add test case like html-plugin
ed742e071b69c8cab6b60ed9d7ac1731a42aa02a
<ide><path>lib/optimize/RealContentHashPlugin.js <ide> const toCachedSource = source => { <ide> * @property {AssetInfo} info <ide> * @property {Source} source <ide> * @property {RawSource | undefined} newSource <add> * @property {RawSource | undefined} newSourceWithoutOwn <ide> * @property {string} content <del> * @property {boolean} hasOwnHash <add> * @property {Set<string>} ownHashes <ide> * @property {Promise} contentComputePromise <add> * @property {Promise} contentComputeWithoutOwnPromise <ide> * @property {Set<string>} referencedHashes <ide> * @property {Set<string>} hashes <ide> */ <ide> class RealContentHashPlugin { <ide> source: cachedSource, <ide> /** @type {RawSource | undefined} */ <ide> newSource: undefined, <add> /** @type {RawSource | undefined} */ <add> newSourceWithoutOwn: undefined, <ide> content, <del> hasOwnHash: false, <add> /** @type {Set<string>} */ <add> ownHashes: undefined, <ide> contentComputePromise: undefined, <add> contentComputeWithoutOwnPromise: undefined, <ide> /** @type {Set<string>} */ <ide> referencedHashes: undefined, <ide> hashes <ide> class RealContentHashPlugin { <ide> const { name, source, content, hashes } = asset; <ide> if (Buffer.isBuffer(content)) { <ide> asset.referencedHashes = EMPTY_SET; <add> asset.ownHashes = EMPTY_SET; <ide> return; <ide> } <ide> const etag = cacheAnalyse.mergeEtags( <ide> class RealContentHashPlugin { <ide> ); <ide> [ <ide> asset.referencedHashes, <del> asset.hasOwnHash <add> asset.ownHashes <ide> ] = await cacheAnalyse.providePromise(name, etag, () => { <ide> const referencedHashes = new Set(); <del> let hasOwnHash = false; <add> let ownHashes = new Set(); <ide> const inContent = content.match(hashRegExp); <ide> if (inContent) { <ide> for (const hash of inContent) { <ide> if (hashes.has(hash)) { <del> hasOwnHash = true; <add> ownHashes.add(hash); <ide> continue; <ide> } <ide> referencedHashes.add(hash); <ide> } <ide> } <del> return [referencedHashes, hasOwnHash]; <add> return [referencedHashes, ownHashes]; <ide> }); <ide> }) <ide> ); <ide> ${referencingAssets <ide> return undefined; <ide> } <ide> const hashes = new Set(); <del> for (const { referencedHashes } of assets) { <add> for (const { referencedHashes, ownHashes } of assets) { <add> if (!ownHashes.has(hash)) { <add> for (const hash of ownHashes) { <add> hashes.add(hash); <add> } <add> } <ide> for (const hash of referencedHashes) { <ide> hashes.add(hash); <ide> } <ide> ${referencingAssets <ide> add(hash, new Set()); <ide> } <ide> const hashToNewHash = new Map(); <del> const computeNewContent = (asset, includeOwn) => { <add> const getEtag = asset => <add> cacheGenerate.mergeEtags( <add> cacheGenerate.getLazyHashedEtag(asset.source), <add> Array.from(asset.referencedHashes, hash => <add> hashToNewHash.get(hash) <add> ).join("|") <add> ); <add> const computeNewContent = asset => { <ide> if (asset.contentComputePromise) return asset.contentComputePromise; <ide> return (asset.contentComputePromise = (async () => { <ide> if ( <del> asset.hasOwnHash || <add> asset.ownHashes.size > 0 || <ide> Array.from(asset.referencedHashes).some( <ide> hash => hashToNewHash.get(hash) !== hash <ide> ) <ide> ) { <del> const identifier = <del> asset.name + <del> (includeOwn && asset.hasOwnHash ? "|with-own" : ""); <del> const etag = cacheGenerate.mergeEtags( <del> cacheGenerate.getLazyHashedEtag(asset.source), <del> Array.from(asset.referencedHashes, hash => <del> hashToNewHash.get(hash) <del> ).join("|") <del> ); <add> const identifier = asset.name; <add> const etag = getEtag(asset); <ide> asset.newSource = await cacheGenerate.providePromise( <add> identifier, <add> etag, <add> () => { <add> const newContent = asset.content.replace(hashRegExp, hash => <add> hashToNewHash.get(hash) <add> ); <add> return new RawSource(newContent); <add> } <add> ); <add> } <add> })()); <add> }; <add> const computeNewContentWithoutOwn = asset => { <add> if (asset.contentComputeWithoutOwnPromise) <add> return asset.contentComputeWithoutOwnPromise; <add> return (asset.contentComputeWithoutOwnPromise = (async () => { <add> if ( <add> asset.ownHashes.size > 0 || <add> Array.from(asset.referencedHashes).some( <add> hash => hashToNewHash.get(hash) !== hash <add> ) <add> ) { <add> const identifier = asset.name + "|without-own"; <add> const etag = getEtag(asset); <add> asset.newSourceWithoutOwn = await cacheGenerate.providePromise( <ide> identifier, <ide> etag, <ide> () => { <ide> const newContent = asset.content.replace( <ide> hashRegExp, <ide> hash => { <del> if (!includeOwn && asset.hashes.has(hash)) { <add> if (asset.ownHashes.has(hash)) { <ide> return ""; <ide> } <ide> return hashToNewHash.get(hash); <ide> ${referencingAssets <ide> const assets = hashToAssets.get(oldHash); <ide> assets.sort(comparator); <ide> const hash = createHash(this._hashFunction); <del> await Promise.all(assets.map(computeNewContent)); <del> const assetsContent = assets.map(asset => <del> asset.newSource ? asset.newSource.buffer() : asset.source.buffer() <add> await Promise.all( <add> assets.map(asset => <add> asset.ownHashes.has(oldHash) <add> ? computeNewContentWithoutOwn(asset) <add> : computeNewContent(asset) <add> ) <ide> ); <add> const assetsContent = assets.map(asset => { <add> if (asset.ownHashes.has(oldHash)) { <add> return asset.newSourceWithoutOwn <add> ? asset.newSourceWithoutOwn.buffer() <add> : asset.source.buffer(); <add> } else { <add> return asset.newSource <add> ? asset.newSource.buffer() <add> : asset.source.buffer(); <add> } <add> }); <ide> let newHash = hooks.updateHash.call(assetsContent, oldHash); <ide> if (!newHash) { <ide> for (const content of assetsContent) { <ide> ${referencingAssets <ide> } <ide> await Promise.all( <ide> assetsWithInfo.map(async asset => { <del> // recomputed content with it's own hash <del> if (asset.hasOwnHash) { <del> asset.contentComputePromise = undefined; <del> } <del> await computeNewContent(asset, true); <add> await computeNewContent(asset); <ide> const newName = asset.name.replace(hashRegExp, hash => <ide> hashToNewHash.get(hash) <ide> ); <ide><path>test/configCases/process-assets/html-plugin/index.js <add>const crypto = require("crypto"); <add>const fs = require("fs"); <add>const path = require("path"); <add> <add>it("should result in the correct HTML", () => { <add> const content = fs.readFileSync( <add> path.resolve(__dirname, "index.html"), <add> "utf-8" <add> ); <add> <add> // check minimized <add> expect(content).toMatch(/<\/script> <script/); <add> <add> // check inlined js is minimized <add> expect(content).toMatch(/For license information please see inline-/); <add> <add> // contains references to normal-[contenthash].js <add> expect(content).toMatch(/normal-.{20}\.js/); <add> <add> const [filename] = /normal-.{20}\.js/.exec(content); <add> const normalJs = fs.readFileSync(path.resolve(__dirname, filename)); <add> const hash = crypto.createHash("sha512"); <add> hash.update(normalJs); <add> const digest = hash.digest("base64"); <add> <add> // SRI has been updated and matched content <add> expect(content).toContain(digest); <add>}); <ide><path>test/configCases/process-assets/html-plugin/inline.js <add>console.log("inline"); <ide><path>test/configCases/process-assets/html-plugin/normal.js <add>console.log("normal"); <ide><path>test/configCases/process-assets/html-plugin/test.config.js <add>module.exports = { <add> findBundle: function () { <add> return "./test.js"; <add> } <add>}; <ide><path>test/configCases/process-assets/html-plugin/webpack.config.js <add>const { <add> sources: { RawSource, OriginalSource, ReplaceSource }, <add> Compilation, <add> util: { createHash }, <add> optimize: { RealContentHashPlugin } <add>} = require("../../../../"); <add> <add>class HtmlPlugin { <add> constructor(entrypoints) { <add> this.entrypoints = entrypoints; <add> } <add> <add> apply(compiler) { <add> compiler.hooks.compilation.tap("html-plugin", compilation => { <add> compilation.hooks.processAssets.tap( <add> { <add> name: "html-plugin", <add> stage: Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL <add> }, <add> () => { <add> const publicPath = compilation.outputOptions.publicPath; <add> const files = []; <add> for (const name of this.entrypoints) { <add> for (const file of compilation.entrypoints.get(name).getFiles()) <add> files.push(file); <add> } <add> const toScriptTag = (file, extra) => { <add> const asset = compilation.getAsset(file); <add> const hash = createHash("sha512"); <add> hash.update(asset.source.source()); <add> const integrity = `sha512-${hash.digest("base64")}`; <add> compilation.updateAsset( <add> file, <add> x => x, <add> assetInfo => ({ <add> ...assetInfo, <add> contenthash: Array.isArray(assetInfo.contenthash) <add> ? [...new Set([...assetInfo.contenthash, integrity])] <add> : assetInfo.contenthash <add> ? [assetInfo.contenthash, integrity] <add> : integrity <add> }) <add> ); <add> return `<script src="${ <add> publicPath === "auto" ? "" : publicPath <add> }${file}" integrity="${integrity}"></script>`; <add> }; <add> compilation.emitAsset( <add> "index.html", <add> new OriginalSource(`<html> <add> <body> <add>${files.map(file => ` ${toScriptTag(file)}`).join("\n")} <add> </body> <add></html>`) <add> ); <add> } <add> ); <add> }); <add> } <add>} <add> <add>class HtmlInlinePlugin { <add> constructor(inline) { <add> this.inline = inline; <add> } <add> <add> apply(compiler) { <add> compiler.hooks.compilation.tap("html-inline-plugin", compilation => { <add> compilation.hooks.processAssets.tap( <add> { <add> name: "html-inline-plugin", <add> stage: Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_INLINE, <add> additionalAssets: true <add> }, <add> assets => { <add> const publicPath = compilation.outputOptions.publicPath; <add> for (const name of Object.keys(assets)) { <add> if (/\.html$/.test(name)) { <add> const asset = compilation.getAsset(name); <add> const content = asset.source.source(); <add> const matches = []; <add> const regExp = /<script\s+src\s*=\s*"([^"]+)"(?:\s+[^"=\s]+(?:\s*=\s*(?:"[^"]*"|[^\s]+))?)*\s*><\/script>/g; <add> let match = regExp.exec(content); <add> while (match) { <add> let url = match[1]; <add> if (url.startsWith(publicPath)) <add> url = url.slice(publicPath.length); <add> if (this.inline.test(url)) { <add> const asset = compilation.getAsset(url); <add> matches.push({ <add> start: match.index, <add> length: match[0].length, <add> asset <add> }); <add> } <add> match = regExp.exec(content); <add> } <add> if (matches.length > 0) { <add> const newSource = new ReplaceSource(asset.source, name); <add> for (const { start, length, asset } of matches) { <add> newSource.replace( <add> start, <add> start + length - 1, <add> `<script>${asset.source.source()}</script>` <add> ); <add> } <add> compilation.updateAsset(name, newSource); <add> } <add> } <add> } <add> } <add> ); <add> }); <add> } <add>} <add> <add>class SriHashSupportPlugin { <add> apply(compiler) { <add> compiler.hooks.compilation.tap("sri-hash-support-plugin", compilation => { <add> RealContentHashPlugin.getCompilationHooks(compilation).updateHash.tap( <add> "sri-hash-support-plugin", <add> (input, oldHash) => { <add> if (/^sha512-.{88}$/.test(oldHash) && input.length === 1) { <add> const hash = createHash("sha512"); <add> hash.update(input[0]); <add> return `sha512-${hash.digest("base64")}`; <add> } <add> } <add> ); <add> }); <add> } <add>} <add> <add>class HtmlMinimizePlugin { <add> apply(compiler) { <add> compiler.hooks.compilation.tap("html-minimize-plugin", compilation => { <add> compilation.hooks.processAssets.tap( <add> { <add> name: "html-minimize-plugin", <add> stage: Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE, <add> additionalAssets: true <add> }, <add> assets => { <add> for (const name of Object.keys(assets)) { <add> if (/\.html$/.test(name)) { <add> compilation.updateAsset( <add> name, <add> source => new RawSource(source.source().replace(/\s+/g, " ")), <add> assetInfo => ({ <add> ...assetInfo, <add> minimized: true <add> }) <add> ); <add> } <add> } <add> } <add> ); <add> }); <add> } <add>} <add> <add>/** @type {import("../../../../").Configuration} */ <add>module.exports = { <add> mode: "production", <add> entry: { <add> test: { import: "./index.js", filename: "test.js" }, <add> inline: "./inline.js", <add> normal: "./normal.js" <add> }, <add> output: { <add> filename: "[name]-[contenthash].js" <add> }, <add> optimization: { <add> minimize: true, <add> minimizer: ["...", new HtmlMinimizePlugin()] <add> }, <add> node: { <add> __dirname: false, <add> __filename: false <add> }, <add> plugins: [ <add> new HtmlPlugin(["inline", "normal"]), <add> new HtmlInlinePlugin(/inline/), <add> new SriHashSupportPlugin() <add> ] <add>};
6
Ruby
Ruby
extract the transaction class to a local variable
f5cec76ea8de1b9d076d0b1138ab8c2cabc0390d
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/transaction.rb <ide> def initialize(connection) <ide> end <ide> <ide> def begin_transaction(options = {}) <del> transaction = <del> if @stack.empty? <del> RealTransaction.new(@connection, current_transaction, options) <del> else <del> SavepointTransaction.new(@connection, current_transaction, options) <del> end <add> transaction_class = @stack.empty? ? RealTransaction : SavepointTransaction <add> transaction = transaction_class.new(@connection, current_transaction, options) <ide> <ide> @stack.push(transaction) <ide> transaction
1
Python
Python
fix missing rowvar in cov call in corrcoeff
b1c994b77d851e49a1c62248b09aeaea5645fbdf
<ide><path>numpy/lib/function_base.py <ide> def corrcoef(x, y=None, rowvar=1, bias=0, ddof=None): <ide> cov : Covariance matrix <ide> <ide> """ <del> c = cov(x, y, bias=bias, ddof=ddof) <add> c = cov(x, y, rowvar, bias, ddof) <ide> try: <ide> d = diag(c) <ide> except ValueError: # scalar covariance
1
Python
Python
make _compatloggeradapter work on python 2.4
eec93b23fa568c485e6be59e1b7d31a3c1d54e80
<ide><path>celery/utils/compat.py <ide> def critical(self, msg, *args, **kwargs): <ide> self.log(logging.CRITICAL, msg, args, **kwargs) <ide> fatal = critical <ide> <del> def log(self, level, msg, args, **kwargs): <add> def log(self, level, msg, *args, **kwargs): <ide> if self.logger.isEnabledFor(level): <ide> msg, kwargs = self.process(msg, kwargs) <ide> self._log(level, msg, args, **kwargs) <ide> def addHandler(self, hdlr): <ide> def removeHandler(self, hdlr): <ide> self.logger.removeHandler(hdlr) <ide> <add> @property <add> def level(self): <add> return self.logger.level <add> <ide> <ide> try: <ide> from logging import LoggerAdapter
1
Javascript
Javascript
fix ssr crash on a hasownproperty attribute
f60a7f722cfd0083ca43387798dde7cd95b2fe26
<ide><path>packages/react-dom/src/__tests__/ReactServerRendering-test.js <ide> describe('ReactDOMServer', () => { <ide> (__DEV__ ? '\n in iframe (at **)' : ''), <ide> ); <ide> }); <add> <add> it('should not crash on poisoned hasOwnProperty', () => { <add> let html; <add> expect( <add> () => <add> (html = ReactDOMServer.renderToString( <add> <div hasOwnProperty="poison"> <add> <span unknown="test" /> <add> </div>, <add> )), <add> ).toWarnDev(['React does not recognize the `hasOwnProperty` prop']); <add> expect(html).toContain('<span unknown="test">'); <add> }); <ide> }); <ide> <ide> describe('renderToStaticMarkup', () => { <ide><path>packages/react-dom/src/server/ReactPartialRenderer.js <ide> function processContext(type, context) { <ide> return maskedContext; <ide> } <ide> <add>const hasOwnProperty = Object.prototype.hasOwnProperty; <ide> const STYLE = 'style'; <ide> const RESERVED_PROPS = { <ide> children: null, <ide> function createOpenTagMarkup( <ide> let ret = '<' + tagVerbatim; <ide> <ide> for (const propKey in props) { <del> if (!props.hasOwnProperty(propKey)) { <add> if (!hasOwnProperty.call(props, propKey)) { <ide> continue; <ide> } <ide> let propValue = props[propKey]; <ide><path>packages/react-dom/src/shared/DOMProperty.js <ide> export const VALID_ATTRIBUTE_NAME_REGEX = new RegExp( <ide> '^[' + ATTRIBUTE_NAME_START_CHAR + '][' + ATTRIBUTE_NAME_CHAR + ']*$', <ide> ); <ide> <add>const hasOwnProperty = Object.prototype.hasOwnProperty; <ide> const illegalAttributeNameCache = {}; <ide> const validatedAttributeNameCache = {}; <ide> <ide> export function isAttributeNameSafe(attributeName: string): boolean { <del> if (validatedAttributeNameCache.hasOwnProperty(attributeName)) { <add> if (hasOwnProperty.call(validatedAttributeNameCache, attributeName)) { <ide> return true; <ide> } <del> if (illegalAttributeNameCache.hasOwnProperty(attributeName)) { <add> if (hasOwnProperty.call(illegalAttributeNameCache, attributeName)) { <ide> return false; <ide> } <ide> if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) {
3
Ruby
Ruby
fix make_relative_symlink when names differ
527c841f1cdcf1352187d63058acd7fdb304363f
<ide><path>Library/Homebrew/extend/pathname.rb <ide> def make_relative_symlink src <ide> Dir.chdir self.dirname do <ide> # TODO use Ruby function so we get exceptions <ide> # NOTE Ruby functions may work, but I had a lot of problems <del> rv = system 'ln', '-sf', src.relative_path_from(self.dirname) <add> rv = system 'ln', '-sf', src.relative_path_from(self.dirname), self.basename <ide> unless rv and $? == 0 <ide> raise <<-EOS.undent <ide> Could not create symlink #{to_s}.
1
Javascript
Javascript
add known issue for vm module
9e5d0e3d76a9ae23a43e1849e37e945a6326a0c6
<ide><path>test/known_issues/test-vm-strict-mode.js <add>'use strict'; <add>// https://github.com/nodejs/node/issues/12300 <add> <add>require('../common'); <add>const assert = require('assert'); <add>const vm = require('vm'); <add> <add>const ctx = vm.createContext({ x: 42 }); <add> <add>// The following line wrongly throws an <add>// error because GlobalPropertySetterCallback() <add>// does not check if the property exists <add>// on the sandbox. It should just set x to 1 <add>// instead of throwing an error. <add>vm.runInContext('"use strict"; x = 1', ctx); <add> <add>assert.strictEqual(ctx.x, 1);
1
Javascript
Javascript
reset elements for donut charts
a6c712323f86ed9d12256f824287202c9d641dd4
<ide><path>src/Chart.Doughnut.js <ide> _options: this.options, <ide> }, this); <ide> <add> this.resetElements(); <add> <ide> // Update the chart with the latest data. <ide> this.update(); <ide> <ide> return 0; <ide> } <ide> }, <add> resetElements: function() { <add> this.outerRadius = (helpers.min([this.chart.width, this.chart.height]) - this.options.elements.slice.borderWidth / 2) / 2; <add> this.innerRadius = this.options.cutoutPercentage ? (this.outerRadius / 100) * (this.options.cutoutPercentage) : 1; <add> this.radiusLength = (this.outerRadius - this.innerRadius) / this.data.datasets.length; <add> <add> // Update the points <add> helpers.each(this.data.datasets, function(dataset, datasetIndex) { <add> // So that calculateCircumference works <add> dataset.total = 0; <add> helpers.each(dataset.data, function(value) { <add> dataset.total += Math.abs(value); <add> }, this); <add> <add> dataset.outerRadius = this.outerRadius - (this.radiusLength * datasetIndex); <add> dataset.innerRadius = dataset.outerRadius - this.radiusLength; <add> <add> helpers.each(dataset.metaData, function(slice, index) { <add> helpers.extend(slice, { <add> _model: { <add> x: this.chart.width / 2, <add> y: this.chart.height / 2, <add> startAngle: Math.PI * -0.5, // use - PI / 2 instead of 3PI / 2 to make animations better. It means that we never deal with overflow during the transition function <add> circumference: (this.options.animation.animateRotate) ? 0 : this.calculateCircumference(metaSlice.value), <add> outerRadius: (this.options.animation.animateScale) ? 0 : dataset.outerRadius, <add> innerRadius: (this.options.animation.animateScale) ? 0 : dataset.innerRadius, <add> <add> backgroundColor: slice.custom && slice.custom.backgroundColor ? slice.custom.backgroundColor : helpers.getValueAtIndexOrDefault(dataset.backgroundColor, index, this.options.elements.slice.backgroundColor), <add> hoverBackgroundColor: slice.custom && slice.custom.hoverBackgroundColor ? slice.custom.hoverBackgroundColor : helpers.getValueAtIndexOrDefault(dataset.hoverBackgroundColor, index, this.options.elements.slice.hoverBackgroundColor), <add> borderWidth: slice.custom && slice.custom.borderWidth ? slice.custom.borderWidth : helpers.getValueAtIndexOrDefault(dataset.borderWidth, index, this.options.elements.slice.borderWidth), <add> borderColor: slice.custom && slice.custom.borderColor ? slice.custom.borderColor : helpers.getValueAtIndexOrDefault(dataset.borderColor, index, this.options.elements.slice.borderColor), <add> <add> label: helpers.getValueAtIndexOrDefault(dataset.label, index, this.data.labels[index]) <add> }, <add> }); <add> <add> slice.pivot(); <add> }, this); <add> <add> }, this); <add> }, <ide> update: function() { <ide> <ide> this.outerRadius = (helpers.min([this.chart.width, this.chart.height]) - this.options.elements.slice.borderWidth / 2) / 2; <ide> }); <ide> <ide> if (index === 0) { <del> slice._model.startAngle = Math.PI * 1.5; <add> slice._model.startAngle = Math.PI * -0.5; // use - PI / 2 instead of 3PI / 2 to make animations better. It means that we never deal with overflow during the transition function <ide> } else { <ide> slice._model.startAngle = dataset.metaData[index - 1]._model.endAngle; <ide> }
1
PHP
PHP
add `@since` annotations
96dd7a2c8adc36bfb405dd232ce00bd9a2d29628
<ide><path>src/Validation/Validator.php <ide> public function allowEmpty($field, $when = true, $message = null) <ide> * Valid values are true (always), 'create', 'update'. If a callable is passed then <ide> * the field will allowed to be empty only when the callback returns true. <ide> * @param string|null $message The message to show if the field is not <add> * @since 3.7.0 <ide> * @return $this <ide> */ <ide> public function allowEmptyFor($field, $flags, $when = true, $message = null) <ide> public function allowEmptyFor($field, $flags, $when = true, $message = null) <ide> * the field will allowed to be empty only when the callback returns true. <ide> * @param string|null $message The message to show if the field is not <ide> * @return $this <add> * @since 3.7.0 <ide> * @see \Cake\Validation\Validator::allowEmptyFor() For detail usage <ide> */ <ide> public function allowEmptyString($field, $when = true, $message = null) <ide> public function allowEmptyString($field, $when = true, $message = null) <ide> * the field will allowed to be empty only when the callback returns true. <ide> * @param string|null $message The message to show if the field is not <ide> * @return $this <add> * @since 3.7.0 <ide> * @see \Cake\Validation\Validator::allowEmptyFor() For detail usage <ide> */ <ide> public function allowEmptyArray($field, $when = true, $message = null) <ide> public function allowEmptyArray($field, $when = true, $message = null) <ide> * the field will allowed to be empty only when the callback returns true. <ide> * @param string|null $message The message to show if the field is not <ide> * @return $this <add> * @since 3.7.0 <ide> * @see \Cake\Validation\Validator::allowEmptyFor() For detail usage <ide> */ <ide> public function allowEmptyFile($field, $when = true, $message = null) <ide> public function allowEmptyFile($field, $when = true, $message = null) <ide> * the field will allowed to be empty only when the callback returns true. <ide> * @param string|null $message The message to show if the field is not <ide> * @return $this <add> * @since 3.7.0 <ide> * @see \Cake\Validation\Validator::allowEmptyFor() For detail usage <ide> */ <ide> public function allowEmptyDate($field, $when = true, $message = null) <ide> public function allowEmptyDate($field, $when = true, $message = null) <ide> * the field will allowed to be empty only when the callback returns true. <ide> * @param string|null $message The message to show if the field is not <ide> * @return $this <add> * @since 3.7.0 <ide> * @see \Cake\Validation\Validator::allowEmptyFor() For detail usage <ide> */ <ide> public function allowEmptyTime($field, $when = true, $message = null) <ide> public function allowEmptyTime($field, $when = true, $message = null) <ide> * the field will allowed to be empty only when the callback returns true. <ide> * @param string|null $message The message to show if the field is not <ide> * @return $this <add> * @since 3.7.0 <ide> * @see \Cake\Validation\Validator::allowEmptyFor() For detail usage <ide> */ <ide> public function allowEmptyDateTime($field, $when = true, $message = null)
1
Ruby
Ruby
remove trailing whitespace
81d467abbaa6410fc3734314b8a7605163d6c64f
<ide><path>Library/Homebrew/test/support/fixtures/cask/Casks/with-languages.rb <ide> cask 'with-languages' do <ide> version '1.2.3' <del> <add> <ide> language "zh" do <ide> sha256 "abc123" <ide> "zh-CN" <ide> <ide> url "file://#{TEST_FIXTURE_DIR}/cask/caffeine.zip" <ide> homepage 'http://example.com/local-caffeine' <del> <add> <ide> app 'Caffeine.app' <ide> end
1
Javascript
Javascript
use new uniform() instead of object literals
66bdaf5a00e4346a2e5e3a735ce913432cba4c28
<ide><path>examples/js/Mirror.js <ide> THREE.ShaderLib[ 'mirror' ] = { <ide> <ide> uniforms: { <del> "mirrorColor": { value: new THREE.Color( 0x7F7F7F ) }, <del> "mirrorSampler": { value: null }, <del> "textureMatrix" : { value: new THREE.Matrix4() } <add> "mirrorColor": new THREE.Uniform( new THREE.Color( 0x7F7F7F ) ), <add> "mirrorSampler": new THREE.Uniform( null ), <add> "textureMatrix" : new THREE.Uniform( new THREE.Matrix4() ) <ide> }, <ide> <ide> vertexShader: [
1
Text
Text
add gitter link to readme
e52740f09ad610dbd73dff405989258fa2a9fb4b
<ide><path>README.md <ide> By default, Keras will use TensorFlow as its tensor manipulation library. [Follo <ide> <ide> ## Support <ide> <del>You can ask questions and join the development discussion on the [Keras Google group](https://groups.google.com/forum/#!forum/keras-users). <add>You can ask questions and join the development discussion: <add> <add>- On the [Keras Google group](https://groups.google.com/forum/#!forum/keras-users). <add>- On the [Keras Gitter channel](https://gitter.im/Keras-io/Lobby). <ide> <ide> You can also post bug reports and feature requests in [Github issues](https://github.com/fchollet/keras/issues). Make sure to read [our guidelines](https://github.com/fchollet/keras/blob/master/CONTRIBUTING.md) first. <ide> <ide><path>docs/templates/index.md <ide> By default, Keras will use TensorFlow as its tensor manipulation library. [Follo <ide> <ide> ## Support <ide> <del>You can ask questions and join the development discussion on the [Keras Google group](https://groups.google.com/forum/#!forum/keras-users). <add>You can ask questions and join the development discussion: <add> <add>- On the [Keras Google group](https://groups.google.com/forum/#!forum/keras-users). <add>- On the [Keras Gitter channel](https://gitter.im/Keras-io/Lobby). <ide> <ide> You can also post bug reports and feature requests in [Github issues](https://github.com/fchollet/keras/issues). Make sure to read [our guidelines](https://github.com/fchollet/keras/blob/master/CONTRIBUTING.md) first. <ide>
2
Text
Text
correct apm command
bd9681457610955d13b3e3647f70ac66ce209543
<ide><path>docs/private-beta/tasks.md <ide> package authors about breaking API changes. <ide> <ide> * Finish APM backend (integrate with GitHub Releases) <ide> * Streamline Dev workflow <del> * `api create` - create package scaffolding <add> * `apm create` - create package scaffolding <ide> * `apm test` - so users can run focused package tests <ide> * `apm publish` - should integrate release best practices (ie npm version) <ide> * Determine which classes and methods should be included in the public API
1
Python
Python
eliminate slow check for pypy during numpy import
acdd0e3ffff0db9f45951c6b51887937ca31935e
<ide><path>numpy/core/_internal.py <ide> import ast <ide> import re <ide> import sys <del>import platform <ide> import warnings <ide> <ide> from .multiarray import dtype, array, ndarray, promote_types <ide> except ImportError: <ide> ctypes = None <ide> <del>IS_PYPY = platform.python_implementation() == 'PyPy' <add>IS_PYPY = sys.implementation.name == 'pypy' <ide> <ide> if sys.byteorder == 'little': <ide> _nbo = '<' <ide><path>numpy/testing/_private/utils.py <ide> class KnownFailureException(Exception): <ide> KnownFailureTest = KnownFailureException # backwards compat <ide> verbose = 0 <ide> <del>IS_PYPY = platform.python_implementation() == 'PyPy' <add>IS_PYPY = sys.implementation.name == 'pypy' <ide> IS_PYSTON = hasattr(sys, "pyston_version_info") <ide> HAS_REFCOUNT = getattr(sys, 'getrefcount', None) is not None and not IS_PYSTON <ide> HAS_LAPACK64 = numpy.linalg.lapack_lite._ilp64
2
Python
Python
add two tests for different arr_ndims
ffa6cf66b03dab41ae843f3b8117a279fb2ef5c2
<ide><path>numpy/core/tests/test_shape_base.py <ide> def test_tuple(self): <ide> assert_raises_regex(TypeError, 'tuple', np.block, ([1, 2], [3, 4])) <ide> assert_raises_regex(TypeError, 'tuple', np.block, [(1, 2), (3, 4)]) <ide> <add> def test_different_ndims(self): <add> a = 1. <add> b = 2 * np.ones((1, 2)) <add> c = 3 * np.ones((1, 1, 3)) <add> <add> result = np.block([a, b, c]) <add> expected = np.array([[[1., 2., 2., 3., 3., 3.]]]) <add> <add> assert_equal(result, expected) <add> <add> def test_different_ndims_depths(self): <add> a = 1. <add> b = 2 * np.ones((1, 2)) <add> c = 3 * np.ones((1, 2, 3)) <add> <add> result = np.block([[a, b], [c]]) <add> expected = np.array([[[1., 2., 2.], <add> [3., 3., 3.], <add> [3., 3., 3.]]]) <add> <add> assert_equal(result, expected) <add> <ide> <ide> if __name__ == "__main__": <ide> run_module_suite()
1
Python
Python
use image_connection in v2 os update_image
2321d34f7d095d98470c3bc1aaeb1d77b0d94bd6
<ide><path>libcloud/compute/drivers/openstack.py <ide> def ex_update_image(self, image_id, data): <ide> """ <ide> Patch a NodeImage. Can be used to set visibility <ide> :param image_id: ID of the image which should be used <add> <ide> :type image_id: ``str`` <ide> :param data: The data to PATCH, either a dict or a list <add> for example: [ <add> {'op': 'replace', 'path': '/visibility', 'value': 'shared'} <add> ] <add> <ide> :type data: ``dict|list`` <ide> :rtype: :class:`NodeImage` <ide> """ <del> response = self.connection.request( <add> response = self.image_connection.request( <ide> '/v2/images/%s' % (image_id,), <ide> headers={'Content-type': 'application/' <ide> 'openstack-images-'
1
Javascript
Javascript
add a comma for better reading flow
0c9480de8c122dd2da10ed745dade02e0479aba8
<ide><path>src/ng/directive/ngTransclude.js <ide> * You can specify that you want to insert a named transclusion slot, instead of the default slot, by providing the slot name <ide> * as the value of the `ng-transclude` or `ng-transclude-slot` attribute. <ide> * <del> * Any existing content of the element that this directive is placed on will be removed before the transcluded content is inserted. <add> * Any existing content of the element that this directive is placed on, will be removed before the transcluded content is inserted. <ide> * <ide> * @element ANY <ide> *
1
Python
Python
enhance ipex integration in trainer
b7d8bd378caa170b54c3a07949d9f85b73c29333
<ide><path>src/transformers/testing_utils.py <ide> def require_intel_extension_for_pytorch(test_case): <ide> """ <ide> Decorator marking a test that requires Intel Extension for PyTorch. <ide> <del> These tests are skipped when Intel Extension for PyTorch isn't installed. <add> These tests are skipped when Intel Extension for PyTorch isn't installed or it does not match current PyTorch <add> version. <ide> <ide> """ <del> return unittest.skipUnless(is_ipex_available(), "test requires Intel Extension for PyTorch")(test_case) <add> return unittest.skipUnless( <add> is_ipex_available(), <add> "test requires Intel Extension for PyTorch to be installed and match current PyTorch version, see" <add> " https://github.com/intel/intel-extension-for-pytorch", <add> )(test_case) <ide> <ide> <ide> def require_torch_scatter(test_case): <ide><path>src/transformers/trainer.py <ide> def torch_jit_model_eval(self, model, dataloader, training=False): <ide> def ipex_optimize_model(self, model, training=False, dtype=torch.float32): <ide> if not is_ipex_available(): <ide> raise ImportError( <del> "Using IPEX but IPEX is not installed, please refer to" <del> " https://github.com/intel/intel-extension-for-pytorch." <add> "Using IPEX but IPEX is not installed or IPEX's version does not match current PyTorch, please refer" <add> " to https://github.com/intel/intel-extension-for-pytorch." <ide> ) <ide> <ide> import intel_extension_for_pytorch as ipex <ide> def ipex_optimize_model(self, model, training=False, dtype=torch.float32): <ide> else: <ide> if not model.training: <ide> model.train() <del> model, self.optimizer = ipex.optimize(model, dtype=dtype, optimizer=self.optimizer, level="O1") <add> model, self.optimizer = ipex.optimize( <add> model, dtype=dtype, optimizer=self.optimizer, inplace=True, level="O1" <add> ) <ide> <ide> return model <ide> <ide><path>src/transformers/utils/import_utils.py <ide> def is_apex_available(): <ide> <ide> <ide> def is_ipex_available(): <del> return importlib.util.find_spec("intel_extension_for_pytorch") is not None <add> def get_major_and_minor_from_version(full_version): <add> return str(version.parse(full_version).major) + "." + str(version.parse(full_version).minor) <add> <add> if not is_torch_available() or importlib.util.find_spec("intel_extension_for_pytorch") is None: <add> return False <add> _ipex_version = "N/A" <add> try: <add> _ipex_version = importlib_metadata.version("intel_extension_for_pytorch") <add> except importlib_metadata.PackageNotFoundError: <add> return False <add> torch_major_and_minor = get_major_and_minor_from_version(_torch_version) <add> ipex_major_and_minor = get_major_and_minor_from_version(_ipex_version) <add> if torch_major_and_minor != ipex_major_and_minor: <add> logger.warning( <add> f"Intel Extension for PyTorch {ipex_major_and_minor} needs to work with PyTorch {ipex_major_and_minor}.*," <add> f" but PyTorch {_torch_version} is found. Please switch to the matching version and run again." <add> ) <add> return False <add> return True <ide> <ide> <ide> def is_bitsandbytes_available(): <ide><path>tests/trainer/test_trainer.py <ide> def test_number_of_steps_in_training(self): <ide> train_output = trainer.train() <ide> self.assertEqual(train_output.global_step, 10) <ide> <del> @unittest.skip(reason="skip temporarily until intel_extension_for_pytorch works with torch 1.12") <ide> @require_torch_bf16_cpu <ide> @require_intel_extension_for_pytorch <ide> def test_number_of_steps_in_training_with_ipex(self): <ide> def test_evaluate_with_jit(self): <ide> expected_acc = AlmostAccuracy()((pred + 1, y))["accuracy"] <ide> self.assertAlmostEqual(results["eval_accuracy"], expected_acc) <ide> <del> @unittest.skip(reason="skip temporarily until intel_extension_for_pytorch works with torch 1.12") <ide> @require_torch_bf16_cpu <ide> @require_intel_extension_for_pytorch <ide> def test_evaluate_with_ipex(self): <ide> def test_predict_with_jit(self): <ide> self.assertTrue(np.array_equal(labels[0], trainer.eval_dataset.ys[0])) <ide> self.assertTrue(np.array_equal(labels[1], trainer.eval_dataset.ys[1])) <ide> <del> @unittest.skip(reason="skip temporarily until intel_extension_for_pytorch works with torch 1.12") <ide> @require_torch_bf16_cpu <ide> @require_intel_extension_for_pytorch <ide> def test_predict_with_ipex(self):
4
Ruby
Ruby
simplify build options api
3f9e88ae69b1ce7c854008b8cbebc38df11b8701
<ide><path>Library/Homebrew/cmd/options.rb <ide> def options <ide> ff.each do |f| <ide> next if f.build.empty? <ide> if ARGV.include? '--compact' <del> puts f.build.collect {|k,v| "--"+k} * " " <add> puts f.build.as_flags * " " <ide> else <ide> puts f.name if ff.length > 1 <ide> dump_options_for_formula f <ide> def options <ide> end <ide> <ide> def dump_options_for_formula f <del> f.build.each do |k,v| <del> puts "--"+k <del> puts "\t"+v <add> f.build.each do |opt| <add> puts opt.flag <add> puts "\t"+opt.description <ide> end <ide> end <ide> end <ide><path>Library/Homebrew/formula_support.rb <ide> def to_s <ide> end <ide> <ide> <add># Represents a build-time option for a formula <add>class Option <add> attr_reader :name, :description, :flag <add> <add> def initialize name, description=nil <add> @name = name.to_s <add> @description = description.to_s <add> @flag = '--'+name.to_s <add> end <add> <add> def eql?(other) <add> @name == other.name <add> end <add> <add> def hash <add> @name.hash <add> end <add>end <add> <add> <ide> # This class holds the build-time options defined for a Formula, <ide> # and provides named access to those options during install. <ide> class BuildOptions <ide> def add name, description=nil <ide> end <ide> end <ide> <del> @options << [name, description] <add> @options << Option.new(name, description) <ide> end <ide> <ide> def has_option? name <del> @options.any? { |opt, _| opt == name } <add> any? { |opt| opt.name == name } <ide> end <ide> <ide> def empty? <ide> @options.empty? <ide> end <ide> <del> def each <del> @options.each { |opt, desc| yield opt, desc } <add> def each(&blk) <add> @options.each(&blk) <add> end <add> <add> def as_flags <add> map { |opt| opt.flag } <ide> end <ide> <ide> def include? name <ide><path>Library/Homebrew/tab.rb <ide> def self.for_install f, args <ide> arg_options = args.options_only <ide> # Pick off the option flags from the formula's `options` array by <ide> # discarding the descriptions. <del> formula_options = f.build.map { |opt, _| "--#{opt}" } <add> formula_options = f.build.as_flags <ide> <ide> Tab.new :used_options => formula_options & arg_options, <ide> :unused_options => formula_options - arg_options, <ide> def self.for_formula f <ide> <ide> def self.dummy_tab f <ide> Tab.new :used_options => [], <del> :unused_options => f.build.map { |opt, _| "--#{opt}" }, <add> :unused_options => f.build.as_flags, <ide> :built_bottle => false, <ide> :tapped_from => "" <ide> end
3
PHP
PHP
add array dependencies to translator functions
d9a3d99ce657d5a9bde485a4027f08f5a1b7ab70
<ide><path>src/Illuminate/Translation/Translator.php <ide> public function has($key, $locale = null) <ide> * @param string $locale <ide> * @return string <ide> */ <del> public function get($key, $replace = array(), $locale = null) <add> public function get($key, array $replace = array(), $locale = null) <ide> { <ide> list($namespace, $group, $item) = $this->parseKey($key); <ide> <ide> public function get($key, $replace = array(), $locale = null) <ide> * @param array $replace <ide> * @return string|null <ide> */ <del> protected function getLine($namespace, $group, $locale, $item, $replace) <add> protected function getLine($namespace, $group, $locale, $item, array $replace) <ide> { <ide> $line = array_get($this->loaded[$namespace][$group][$locale], $item); <ide> <ide> protected function getLine($namespace, $group, $locale, $item, $replace) <ide> * @param array $replace <ide> * @return string <ide> */ <del> protected function makeReplacements($line, $replace) <add> protected function makeReplacements($line, array $replace) <ide> { <ide> $replace = $this->sortReplacements($replace); <ide> <ide> protected function makeReplacements($line, $replace) <ide> * @param array $replace <ide> * @return array <ide> */ <del> protected function sortReplacements($replace) <add> protected function sortReplacements(array $replace) <ide> { <ide> return with(new Collection($replace))->sortBy(function($r) <ide> { <ide> protected function sortReplacements($replace) <ide> * @param string $locale <ide> * @return string <ide> */ <del> public function choice($key, $number, $replace = array(), $locale = null) <add> public function choice($key, $number, array $replace = array(), $locale = null) <ide> { <ide> $line = $this->get($key, $replace, $locale = $locale ?: $this->locale); <ide>
1
PHP
PHP
improve code readibility
7630f2ea0dddc7ab6f114b46998d4f9a6223d81c
<ide><path>src/Database/QueryCompiler.php <ide> public function compile(Query $query, ValueBinder $generator): string <ide> */ <ide> protected function _sqlCompiler(string &$sql, Query $query, ValueBinder $generator): Closure <ide> { <del> return function ($parts, $name) use (&$sql, $query, $generator): ?string { <add> return function ($part, $partName) use (&$sql, $query, $generator) { <ide> if ( <del> !isset($parts) || <del> ( <del> ( <del> is_array($parts) || <del> $parts instanceof Countable <del> ) && <del> !count($parts) <del> ) <add> $part === null || <add> (is_array($part) && empty($part)) || <add> ($part instanceof Countable && count($part) === 0) <ide> ) { <del> return null; <add> return; <ide> } <del> if ($parts instanceof ExpressionInterface) { <del> $parts = [$parts->sql($generator)]; <add> <add> if ($part instanceof ExpressionInterface) { <add> $part = [$part->sql($generator)]; <ide> } <del> if (isset($this->_templates[$name])) { <del> $parts = $this->_stringifyExpressions((array)$parts, $generator); <add> if (isset($this->_templates[$partName])) { <add> $part = $this->_stringifyExpressions((array)$part, $generator); <add> $sql .= sprintf($this->_templates[$partName], implode(', ', $part)); <ide> <del> return $sql .= sprintf($this->_templates[$name], implode(', ', $parts)); <add> return; <ide> } <ide> <del> return $sql .= $this->{'_build' . ucfirst($name) . 'Part'}($parts, $query, $generator); <add> $sql .= $this->{'_build' . ucfirst($partName) . 'Part'}($part, $query, $generator); <ide> }; <ide> } <ide>
1