text:
package com.linecorp.armeria.server;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.Sets.toImmutableEnumSet;
import static com.linecorp.armeria.internal.ArmeriaHttpUtil.concatPaths;
import static com.linecorp.armeria.server.AbstractPathMapping.ensureAbsolutePath;
import static com.linecorp.armeria.server.AnnotatedValueResolver.toRequestObjectResolvers;
import static java.util.Objects.requireNonNull;

import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Function;
import java.util.stream.Collectors;

import javax.annotation.Nullable;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.MoreObjects;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableList.Builder;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Sets;

import com.linecorp.armeria.common.HttpMethod;
import com.linecorp.armeria.common.HttpRequest;
import com.linecorp.armeria.common.HttpResponse;
import com.linecorp.armeria.common.HttpStatus;
import com.linecorp.armeria.common.MediaType;
import com.linecorp.armeria.common.RequestContext;
import com.linecorp.armeria.internal.DefaultValues;
import com.linecorp.armeria.server.AnnotatedValueResolver.NoParameterException;
import com.linecorp.armeria.server.annotation.ByteArrayResponseConverterFunction;
import com.linecorp.armeria.server.annotation.ConsumeType;
import com.linecorp.armeria.server.annotation.ConsumeTypes;
import com.linecorp.armeria.server.annotation.Consumes;
import com.linecorp.armeria.server.annotation.ConsumesGroup;
import com.linecorp.armeria.server.annotation.Decorator;
import com.linecorp.armeria.server.annotation.DecoratorFactory;
import com.linecorp.armeria.server.annotation.DecoratorFactoryFunction;
import com.linecorp.armeria.server.annotation.Decorators;
import com.linecorp.armeria.server.annotation.Delete;
import com.linecorp.armeria.server.annotation.ExceptionHandler;
import com.linecorp.armeria.server.annotation.ExceptionHandlerFunction;
import com.linecorp.armeria.server.annotation.Get;
import com.linecorp.armeria.server.annotation.Head;
import com.linecorp.armeria.server.annotation.JacksonResponseConverterFunction;
import com.linecorp.armeria.server.annotation.Options;
import com.linecorp.armeria.server.annotation.Order;
import com.linecorp.armeria.server.annotation.Patch;
import com.linecorp.armeria.server.annotation.Path;
import com.linecorp.armeria.server.annotation.Post;
import com.linecorp.armeria.server.annotation.ProduceType;
import com.linecorp.armeria.server.annotation.ProduceTypes;
import com.linecorp.armeria.server.annotation.Produces;
import com.linecorp.armeria.server.annotation.ProducesGroup;
import com.linecorp.armeria.server.annotation.Put;
import com.linecorp.armeria.server.annotation.RequestConverter;
import com.linecorp.armeria.server.annotation.RequestConverterFunction;
import com.linecorp.armeria.server.annotation.RequestObject;
import com.linecorp.armeria.server.annotation.ResponseConverter;
import com.linecorp.armeria.server.annotation.ResponseConverterFunction;
import com.linecorp.armeria.server.annotation.StringResponseConverterFunction;
import com.linecorp.armeria.server.annotation.Trace;

/**
 * Builds a list of {@link AnnotatedHttpService}s from a Java object.
 */
final class AnnotatedHttpServiceFactory {
    private static final Logger logger = LoggerFactory.getLogger(AnnotatedHttpServiceFactory.class);

    /**
     * An instance map for reusing converters, exception handlers and decorators.
     */
    private static final ConcurrentMap<Class<?>, Object> instanceCache = new ConcurrentHashMap<>();

    /**
     * A default {@link ExceptionHandlerFunction}.
     */
    private static final ExceptionHandlerFunction defaultExceptionHandler = new DefaultExceptionHandler();

    /**
     * A default {@link ResponseConverterFunction}s.
     */
    private static final List<ResponseConverterFunction> defaultResponseConverters =
            ImmutableList.of(new JacksonResponseConverterFunction(),
                             new StringResponseConverterFunction(),
                             new ByteArrayResponseConverterFunction());

    /**
     * Mapping from HTTP method annotation to {@link HttpMethod}, like following.
     * <ul>
     *   <li>{@link Options} -> {@link HttpMethod#OPTIONS}
     *   <li>{@link Get} -> {@link HttpMethod#GET}
     *   <li>{@link Head} -> {@link HttpMethod#HEAD}
     *   <li>{@link Post} -> {@link HttpMethod#POST}
     *   <li>{@link Put} -> {@link HttpMethod#PUT}
     *   <li>{@link Patch} -> {@link HttpMethod#PATCH}
     *   <li>{@link Delete} -> {@link HttpMethod#DELETE}
     *   <li>{@link Trace} -> {@link HttpMethod#TRACE}
     * </ul>
     */
    private static final Map<Class<?>, HttpMethod> HTTP_METHOD_MAP =
            ImmutableMap.<Class<?>, HttpMethod>builder()
                    .put(Options.class, HttpMethod.OPTIONS)
                    .put(Get.class, HttpMethod.GET)
                    .put(Head.class, HttpMethod.HEAD)
                    .put(Post.class, HttpMethod.POST)
                    .put(Put.class, HttpMethod.PUT)
                    .put(Patch.class, HttpMethod.PATCH)
                    .put(Delete.class, HttpMethod.DELETE)
                    .put(Trace.class, HttpMethod.TRACE)
                    .build();

    /**
     * Returns the list of {@link AnnotatedHttpService} defined by {@link Path} and HTTP method annotations
     * from the specified {@code object}.
     */
    static List<AnnotatedHttpServiceElement> find(String pathPrefix, Object object,
                                                  Iterable<?> exceptionHandlersAndConverters) {
        Builder<ExceptionHandlerFunction> exceptionHandlers = null;
        Builder<RequestConverterFunction> requestConverters = null;
        Builder<ResponseConverterFunction> responseConverters = null;

        for (final Object o : exceptionHandlersAndConverters) {
            boolean added = false;
            if (o instanceof ExceptionHandlerFunction) {
                if (exceptionHandlers == null) {
                    exceptionHandlers = ImmutableList.builder();
                }
                exceptionHandlers.add((ExceptionHandlerFunction) o);
                added = true;
            }
            if (o instanceof RequestConverterFunction) {
                if (requestConverters == null) {
                    requestConverters = ImmutableList.builder();
                }
                requestConverters.add((RequestConverterFunction) o);
                added = true;
            }
            if (o instanceof ResponseConverterFunction) {
                if (responseConverters == null) {
                    responseConverters = ImmutableList.builder();
                }
                responseConverters.add((ResponseConverterFunction) o);
                added = true;
            }
            if (!added) {
                throw new IllegalArgumentException(o.getClass().getName() +
                                                   " is neither an exception handler nor a converter.");
            }
        }

        final List<ExceptionHandlerFunction> exceptionHandlerFunctions =
                exceptionHandlers != null ? exceptionHandlers.build() : ImmutableList.of();
        final List<RequestConverterFunction> requestConverterFunctions =
                requestConverters != null ? requestConverters.build() : ImmutableList.of();
        final List<ResponseConverterFunction> responseConverterFunctions =
                responseConverters != null ? responseConverters.build() : ImmutableList.of();

        final List<Method> methods = requestMappingMethods(object);
        return methods.stream()
                      .map((Method method) -> create(pathPrefix, object, method, exceptionHandlerFunctions,
                                                     requestConverterFunctions, responseConverterFunctions))
                      .collect(toImmutableList());
    }

    /**
     * Returns an {@link AnnotatedHttpService} instance defined to {@code method} of {@code object} using
     * {@link Path} annotation.
     */
    private static AnnotatedHttpServiceElement create(String pathPrefix, Object object, Method method,
                                                      List<ExceptionHandlerFunction> baseExceptionHandlers,
                                                      List<RequestConverterFunction> baseRequestConverters,
                                                      List<ResponseConverterFunction> baseResponseConverters) {

        final Set<Annotation> methodAnnotations = httpMethodAnnotations(method);
        if (methodAnnotations.isEmpty()) {
            throw new IllegalArgumentException("HTTP Method specification is missing: " + method.getName());
        }

        final Set<HttpMethod> methods = toHttpMethods(methodAnnotations);
        if (methods.isEmpty()) {
            throw new IllegalArgumentException(method.getDeclaringClass().getName() + '#' + method.getName() +
                                               " must have an HTTP method annotation.");
        }

        final Class<?> clazz = object.getClass();
        final HttpHeaderPathMapping pathMapping =
                new HttpHeaderPathMapping(pathStringMapping(pathPrefix, method, methodAnnotations),
                                          methods, consumableMediaTypes(method, clazz),
                                          producibleMediaTypes(method, clazz));

        final List<ExceptionHandlerFunction> eh =
                exceptionHandlers(method, clazz).addAll(baseExceptionHandlers)
                                                .add(defaultExceptionHandler).build();
        final List<RequestConverterFunction> req =
                requestConverters(method, clazz).addAll(baseRequestConverters).build();
        final List<ResponseConverterFunction> res =
                responseConverters(method, clazz).addAll(baseResponseConverters)
                                                 .addAll(defaultResponseConverters).build();

        List<AnnotatedValueResolver> resolvers;
        try {
            resolvers = AnnotatedValueResolver.of(method, pathMapping.paramNames(),
                                                  toRequestObjectResolvers(req));
        } catch (NoParameterException ignored) {
            // Allow no parameter like below:
            //
            // @Get("/")
            // public String method1() { ... }
            //
            resolvers = ImmutableList.of();
        }

        final Set<String> expectedParamNames = pathMapping.paramNames();
        final Set<String> requiredParamNames =
                resolvers.stream()
                         .filter(AnnotatedValueResolver::isPathVariable)
                         .map(AnnotatedValueResolver::httpElementName)
                         .collect(Collectors.toSet());

        if (!expectedParamNames.containsAll(requiredParamNames)) {
            final Set<String> missing = Sets.difference(requiredParamNames, expectedParamNames);
            throw new IllegalArgumentException("cannot find path variables: " + missing);
        }

        // Warn unused path variables only if there's no '@RequestObject' annotation.
        if (resolvers.stream().noneMatch(r -> r.isAnnotationType(RequestObject.class)) &&
            !requiredParamNames.containsAll(expectedParamNames)) {
            final Set<String> missing = Sets.difference(expectedParamNames, requiredParamNames);
            logger.warn("Some path variables of the method '" + method.getName() +
                        "' of the class '" + clazz.getName() +
                        "' do not have their corresponding parameters annotated with @Param. " +
                        "They would not be automatically injected: " + missing);
        }
        return new AnnotatedHttpServiceElement(pathMapping,
                                               new AnnotatedHttpService(object, method, resolvers, eh, res),
                                               decorator(method, clazz));
    }

    /**
     * Returns the list of {@link Path} annotated methods.
     */
    private static List<Method> requestMappingMethods(Object object) {
        return Arrays.stream(object.getClass().getMethods())
                     .filter(m -> m.getAnnotation(Path.class) != null ||
                                  !httpMethodAnnotations(m).isEmpty())
                     .sorted(Comparator.comparingInt(AnnotatedHttpServiceFactory::order))
                     .collect(toImmutableList());
    }

    /**
     * Returns the value of the order of the {@link Method}. The order could be retrieved from {@link Order}
     * annotation. 0 would be returned if there is no specified {@link Order} annotation.
     */
    private static int order(Method method) {
        final Order order = method.getAnnotation(Order.class);
        return order != null ? order.value() : 0;
    }

    /**
     * Returns {@link Set} of HTTP method annotations of a given method.
     * The annotations are as follows.
     *
     * @see Options
     * @see Get
     * @see Head
     * @see Post
     * @see Put
     * @see Patch
     * @see Delete
     * @see Trace
     */
    private static Set<Annotation> httpMethodAnnotations(Method method) {
        return Arrays.stream(method.getAnnotations())
                     .filter(annotation -> HTTP_METHOD_MAP.containsKey(annotation.annotationType()))
                     .collect(Collectors.toSet());
    }

    /**
     * Returns {@link Set} of {@link HttpMethod}s mapped to HTTP method annotations.
     *
     * @see Options
     * @see Get
     * @see Head
     * @see Post
     * @see Put
     * @see Patch
     * @see Delete
     * @see Trace
     */
    private static Set<HttpMethod> toHttpMethods(Set<Annotation> annotations) {
        return annotations.stream()
                          .map(annotation -> HTTP_METHOD_MAP.get(annotation.annotationType()))
                          .filter(Objects::nonNull)
                          .collect(toImmutableEnumSet());
    }

    /**
     * Returns the list of {@link MediaType}s specified by {@link Consumes} annotation.
     */
    private static List<MediaType> consumableMediaTypes(Method method, Class<?> clazz) {
        final List<MediaType> mediaTypes = consumableMediaTypes(method);
        return mediaTypes.isEmpty() ? consumableMediaTypes(clazz) : mediaTypes;
    }

    private static List<MediaType> consumableMediaTypes(AnnotatedElement element) {
        final List<MediaType> mediaTypes = new ArrayList<>();

        for (final Annotation annotation : element.getAnnotations()) {
            if (annotation instanceof ConsumesGroup) {
                Arrays.stream(((ConsumesGroup) annotation).value())
                      .forEach(e -> addConsumableMediaType(mediaTypes, MediaType.parse(e.value())));
            } else if (annotation instanceof Consumes) {
                addConsumableMediaType(mediaTypes, MediaType.parse(((Consumes) annotation).value()));
            } else if (annotation instanceof ConsumeTypes) {
                Arrays.stream(((ConsumeTypes) annotation).value())
                      .forEach(e -> addConsumableMediaType(mediaTypes, MediaType.parse(e.value())));
            } else if (annotation instanceof ConsumeType) {
                addConsumableMediaType(mediaTypes, MediaType.parse(((ConsumeType) annotation).value()));
            } else {
                Arrays.stream(annotation.annotationType().getAnnotationsByType(Consumes.class))
                      .forEach(e -> addConsumableMediaType(mediaTypes, MediaType.parse(e.value())));
            }
        }
        return mediaTypes;
    }

    private static void addConsumableMediaType(List<MediaType> mediaTypes, MediaType newMediaType) {
        addMediaType(mediaTypes, newMediaType, Consumes.class, true);
    }

    /**
     * Returns the list of {@link MediaType}s specified by {@link Produces} annotation.
     */
    private static List<MediaType> producibleMediaTypes(Method method, Class<?> clazz) {
        final List<MediaType> mediaTypes = producibleMediaTypes(method);
        return mediaTypes.isEmpty() ? producibleMediaTypes(clazz) : mediaTypes;
    }

    private static List<MediaType> producibleMediaTypes(AnnotatedElement element) {
        final List<MediaType> mediaTypes = new ArrayList<>();

        for (final Annotation annotation : element.getAnnotations()) {
            if (annotation instanceof ProducesGroup) {
                Arrays.stream(((ProducesGroup) annotation).value())
                      .forEach(e -> addProducibleMediaType(mediaTypes, MediaType.parse(e.value())));
            } else if (annotation instanceof Produces) {
                addProducibleMediaType(mediaTypes, MediaType.parse(((Produces) annotation).value()));
            } else if (annotation instanceof ProduceTypes) {
                Arrays.stream(((ProduceTypes) annotation).value())
                      .forEach(e -> addProducibleMediaType(mediaTypes, MediaType.parse(e.value())));
            } else if (annotation instanceof ProduceType) {
                addProducibleMediaType(mediaTypes, MediaType.parse(((ProduceType) annotation).value()));
            } else {
                Arrays.stream(annotation.annotationType().getAnnotationsByType(Produces.class))
                      .forEach(e -> addProducibleMediaType(mediaTypes, MediaType.parse(e.value())));
            }
        }
        return mediaTypes;
    }

    private static void addProducibleMediaType(List<MediaType> mediaTypes, MediaType newMediaType) {
        addMediaType(mediaTypes, newMediaType, Produces.class, false);
    }

    private static void addMediaType(List<MediaType> mediaTypes, MediaType newMediaType,
                                     Class<?> clazz, boolean allowWildcard) {
        if (!allowWildcard && newMediaType.hasWildcard()) {
            throw new IllegalArgumentException('@' + clazz.getSimpleName() + " must not have a wildcard: " +
                                               newMediaType);
        }
        if (mediaTypes.stream().anyMatch(e -> e.equals(newMediaType))) {
            throw new IllegalArgumentException("Duplicated media type for @" + clazz.getSimpleName() + ": " +
                                               newMediaType);
        }
        mediaTypes.add(newMediaType);
    }

    /**
     * Returns the {@link PathMapping} instance mapped to {@code method}.
     */
    private static PathMapping pathStringMapping(String pathPrefix, Method method,
                                                 Set<Annotation> methodAnnotations) {
        pathPrefix = ensureAbsolutePath(pathPrefix, "pathPrefix");
        if (!pathPrefix.endsWith("/")) {
            pathPrefix += '/';
        }

        final String pattern = findPattern(method, methodAnnotations);
        final PathMapping mapping = PathMapping.of(pattern);
        if ("/".equals(pathPrefix)) {
            // pathPrefix is not specified or "/".
            return mapping;
        }

        if (pattern.startsWith(ExactPathMapping.PREFIX)) {
            return PathMapping.ofExact(concatPaths(
                    pathPrefix, pattern.substring(ExactPathMapping.PREFIX_LEN)));
        }

        if (pattern.startsWith(PrefixPathMapping.PREFIX)) {
            return PathMapping.ofPrefix(concatPaths(
                    pathPrefix, pattern.substring(PrefixPathMapping.PREFIX_LEN)));
        }

        if (pattern.startsWith(GlobPathMapping.PREFIX)) {
            final String glob = pattern.substring(GlobPathMapping.PREFIX_LEN);
            if (glob.startsWith("/")) {
                return PathMapping.ofGlob(concatPaths(pathPrefix, glob));
            } else {
                // NB: We cannot use PathMapping.ofGlob(pathPrefix + "/**/" + glob) here
                //     because that will extract '/**/' as a path parameter, which a user never specified.
                return new PrefixAddingPathMapping(pathPrefix, mapping);
            }
        }

        if (pattern.startsWith(RegexPathMapping.PREFIX)) {
            return new PrefixAddingPathMapping(pathPrefix, mapping);
        }

        if (pattern.startsWith("/")) {
            // Default pattern
            return PathMapping.of(concatPaths(pathPrefix, pattern));
        }

        // Should never reach here because we validated the path pattern.
        throw new Error();
    }

    /**
     * Returns a specified path pattern. The path pattern might be specified by {@link Path} or
     * HTTP method annotations such as {@link Get} and {@link Post}.
     */
    private static String findPattern(Method method, Set<Annotation> methodAnnotations) {
        String pattern = null;

        final Path path = method.getAnnotation(Path.class);
        if (path != null) {
            pattern = method.getAnnotation(Path.class).value();
        }
        for (Annotation a : methodAnnotations) {
            final String p = (String) invokeValueMethod(a);
            if (DefaultValues.isUnspecified(p)) {
                continue;
            }
            checkArgument(pattern == null,
                          "Only one path can be specified. (" + pattern + ", " + p + ')');
            pattern = p;
        }
        if (pattern == null || pattern.isEmpty()) {
            throw new IllegalArgumentException(
                    "A path pattern should be specified by @Path or HTTP method annotations.");
        }
        return pattern;
    }

    /**
     * Returns a decorator chain which is specified by {@link Decorator} annotations and user-defined
     * decorator annotations.
     */
    private static Function<Service<HttpRequest, HttpResponse>,
            ? extends Service<HttpRequest, HttpResponse>> decorator(Method method, Class<?> clazz) {

        final List<DecoratorAndOrder> decorators = collectDecorators(clazz, method);

        Function<Service<HttpRequest, HttpResponse>,
                ? extends Service<HttpRequest, HttpResponse>> decorator = null;
        for (int i = decorators.size() - 1; i >= 0; i--) {
            final DecoratorAndOrder d = decorators.get(i);
            decorator = decorator == null ? d.decorator()
                                          : decorator.andThen(d.decorator());
        }
        return decorator == null ? Function.identity() : decorator;
    }

    /**
     * Returns a decorator list which is specified by {@link Decorator} annotations and user-defined
     * decorator annotations.
     */
    @VisibleForTesting
    static List<DecoratorAndOrder> collectDecorators(Class<?> clazz, Method method) {
        final List<DecoratorAndOrder> decorators = new ArrayList<>();

        // Class-level decorators are applied before method-level decorators.
        collectDecorators(decorators, clazz.getAnnotations());
        collectDecorators(decorators, method.getAnnotations());

        // Sort decorators by "order" attribute values.
        decorators.sort(Comparator.comparing(DecoratorAndOrder::order));

        return decorators;
    }

    /**
     * Adds decorators to the specified {@code list}. Decorators which are annotated with {@link Decorator}
     * and user-defined decorators will be collected.
     */
    private static void collectDecorators(List<DecoratorAndOrder> list, Annotation[] annotations) {
        if (annotations.length == 0) {
            return;
        }

        // Respect the order of decorators which is specified by a user. The first one is first applied
        // for most of the cases. But if @Decorator and user-defined decorators are specified in a mixed order,
        // the specified order and the applied order can be different. To overcome this problem, we introduce
        // "order" attribute to @Decorator annotation to sort decorators. If a user-defined decorator
        // annotation has "order" attribute, it will be also used for sorting.
        for (final Annotation annotation : annotations) {
            if (annotation instanceof Decorator) {
                final Decorator d = (Decorator) annotation;
                list.add(new DecoratorAndOrder(d, newDecorator(d), d.order()));
                continue;
            }

            if (annotation instanceof Decorators) {
                final Decorator[] decorators = ((Decorators) annotation).value();
                for (final Decorator d : decorators) {
                    list.add(new DecoratorAndOrder(d, newDecorator(d), d.order()));
                }
                continue;
            }

            DecoratorAndOrder udd = userDefinedDecorator(annotation);
            if (udd != null) {
                list.add(udd);
                continue;
            }

            // If user-defined decorators are repeatable and they are specified more than once.
            try {
                final Annotation[] decorators = (Annotation[]) annotation.annotationType()
                                                                         .getMethod("value")
                                                                         .invoke(annotation);
                for (final Annotation decorator : decorators) {
                    udd = userDefinedDecorator(decorator);
                    if (udd == null) {
                        break;
                    }
                    list.add(udd);
                }
            } catch (Throwable ignore) {
                // The annotation may be a container of a decorator or may be not, so we just ignore
                // any exception from this clause.
            }
        }
    }

    /**
     * Returns a decorator with its order if the specified {@code annotation} is one of the user-defined
     * decorator annotation.
     */
    @Nullable
    private static DecoratorAndOrder userDefinedDecorator(Annotation annotation) {
        // User-defined decorator MUST be annotated with @DecoratorFactory annotation.
        final DecoratorFactory d = annotation.annotationType().getAnnotation(DecoratorFactory.class);
        if (d == null) {
            return null;
        }

        // In case of user-defined decorator, we need to create a new decorator from its factory.
        @SuppressWarnings("unchecked")
        final DecoratorFactoryFunction<Annotation> factory = getInstance(d, DecoratorFactoryFunction.class);

        // If the annotation has "order" attribute, we can use it when sorting decorators.
        int order = 0;
        try {
            final Object value = annotation.annotationType().getMethod("order").invoke(annotation);
            if (value instanceof Integer) {
                order = (Integer) value;
            }
        } catch (Throwable ignore) {
            // A user-defined decorator may not have an 'order' attribute.
            // If it does not exist, '0' is used by default.
        }
        return new DecoratorAndOrder(annotation, factory.newDecorator(annotation), order);
    }

    /**
     * Returns a new decorator which decorates a {@link Service} by {@link FunctionalDecoratingService}
     * and the specified {@link DecoratingServiceFunction}.
     */
    @SuppressWarnings("unchecked")
    private static Function<Service<HttpRequest, HttpResponse>,
            ? extends Service<HttpRequest, HttpResponse>> newDecorator(Decorator decorator) {
        return service -> new FunctionalDecoratingService<>(
                service, getInstance(decorator, DecoratingServiceFunction.class));
    }

    /**
     * Returns an exception handler list which is specified by {@link ExceptionHandler} annotations.
     */
    private static Builder<ExceptionHandlerFunction> exceptionHandlers(Method targetMethod,
                                                                       Class<?> targetClass) {
        return annotationValues(targetMethod, targetClass, ExceptionHandler.class,
                                ExceptionHandlerFunction.class);
    }

    /**
     * Returns a request converter list which is specified by {@link RequestConverter} annotations.
     */
    private static Builder<RequestConverterFunction> requestConverters(Method targetMethod,
                                                                       Class<?> targetClass) {
        return annotationValues(targetMethod, targetClass, RequestConverter.class,
                                RequestConverterFunction.class);
    }

    /**
     * Returns a response converter list which is specified by {@link ResponseConverter} annotations.
     */
    private static Builder<ResponseConverterFunction> responseConverters(Method targetMethod,
                                                                         Class<?> targetClass) {
        return annotationValues(targetMethod, targetClass, ResponseConverter.class,
                                ResponseConverterFunction.class);
    }

    /**
     * Returns an immutable list builder of objects which are specified as the {@code value} of annotation
     * {@code T}.
     */
    private static <T extends Annotation, R> Builder<R> annotationValues(
            Method targetMethod, Class<?> targetClass, Class<T> annotationClass, Class<R> expectedType) {

        requireNonNull(annotationClass, "annotationClass");
        requireNonNull(targetMethod, "targetMethod");
        requireNonNull(targetClass, "targetClass");

        final Builder<R> builder = new Builder<>();
        for (final T annotation : targetMethod.getAnnotationsByType(annotationClass)) {
            builder.add(getInstance(annotation, expectedType));
        }
        for (final T annotation : targetClass.getAnnotationsByType(annotationClass)) {
            builder.add(getInstance(annotation, expectedType));
        }
        return builder;
    }

    /**
     * Returns a cached instance of the specified {@link Class}.
     */
    @SuppressWarnings("unchecked")
    static <T> T getInstance(Annotation annotation, Class<T> expectedType) {
        try {
            final Class<? extends T> clazz = (Class<? extends T>) invokeValueMethod(annotation);
            return expectedType.cast(instanceCache.computeIfAbsent(clazz, type -> {
                try {
                    final Constructor<? extends T> constructor = clazz.getDeclaredConstructor();
                    constructor.setAccessible(true);
                    return constructor.newInstance();
                } catch (Exception e) {
                    throw new IllegalStateException(
                            "A class specified in @" + annotation.getClass().getSimpleName() +
                            " annotation must have an accessible default constructor: " + clazz.getName(), e);
                }
            }));
        } catch (ClassCastException e) {
            throw new IllegalArgumentException(
                    "A class specified in @" + annotation.getClass().getSimpleName() +
                    " annotation cannot be cast to " + expectedType, e);
        }
    }

    /**
     * Returns an object which is returned by {@code value()} method of the specified annotation {@code a}.
     */
    private static Object invokeValueMethod(Annotation a) {
        try {
            return a.getClass().getMethod("value").invoke(a);
        } catch (Exception e) {
            throw new IllegalStateException("An annotation @" + a.getClass().getSimpleName() +
                                            " must have a 'value' method", e);
        }
    }

    private AnnotatedHttpServiceFactory() {}

    /**
     * A {@link PathMapping} implementation that combines path prefix and another {@link PathMapping}.
     */
    @VisibleForTesting
    static final class PrefixAddingPathMapping extends AbstractPathMapping {

        private final String pathPrefix;
        private final PathMapping mapping;
        private final String loggerName;
        private final String meterTag;

        PrefixAddingPathMapping(String pathPrefix, PathMapping mapping) {
            assert mapping instanceof GlobPathMapping || mapping instanceof RegexPathMapping
                    : "unexpected mapping type: " + mapping.getClass().getName();

            this.pathPrefix = pathPrefix;
            this.mapping = mapping;
            loggerName = loggerName(pathPrefix) + '.' + mapping.loggerName();
            meterTag = PrefixPathMapping.PREFIX + pathPrefix + ',' + mapping.meterTag();
        }

        @Override
        protected PathMappingResult doApply(PathMappingContext mappingCtx) {
            final String path = mappingCtx.path();
            if (!path.startsWith(pathPrefix)) {
                return PathMappingResult.empty();
            }

            final PathMappingResult result =
                    mapping.apply(mappingCtx.overridePath(path.substring(pathPrefix.length() - 1)));
            if (result.isPresent()) {
                return PathMappingResult.of(path, mappingCtx.query(), result.pathParams());
            } else {
                return PathMappingResult.empty();
            }
        }

        @Override
        public Set<String> paramNames() {
            return mapping.paramNames();
        }

        @Override
        public String loggerName() {
            return loggerName;
        }

        @Override
        public String meterTag() {
            return meterTag;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) {
                return true;
            }
            if (!(o instanceof PrefixAddingPathMapping)) {
                return false;
            }

            final PrefixAddingPathMapping that = (PrefixAddingPathMapping) o;
            return pathPrefix.equals(that.pathPrefix) && mapping.equals(that.mapping);
        }

        @Override
        public int hashCode() {
            return 31 * pathPrefix.hashCode() + mapping.hashCode();
        }

        @Override
        public String toString() {
            return '[' + PrefixPathMapping.PREFIX + pathPrefix + ", " + mapping + ']';
        }
    }

    /**
     * A default exception handler is used when a user does not specify exception handlers
     * by {@link ExceptionHandler} annotation.
     */
    private static class DefaultExceptionHandler implements ExceptionHandlerFunction {
        @Override
        public HttpResponse handleException(RequestContext ctx, HttpRequest req, Throwable cause) {
            if (cause instanceof IllegalArgumentException) {
                return HttpResponse.of(HttpStatus.BAD_REQUEST);
            }

            if (cause instanceof HttpStatusException) {
                return HttpResponse.of(((HttpStatusException) cause).httpStatus());
            }

            if (cause instanceof HttpResponseException) {
                return ((HttpResponseException) cause).httpResponse();
            }

            return ExceptionHandlerFunction.DEFAULT.handleException(ctx, req, cause);
        }
    }

    /**
     * An internal class to hold a decorator with its order.
     */
    @VisibleForTesting
    static final class DecoratorAndOrder {
        // Keep the specified annotation for testing purpose.
        private final Annotation annotation;
        private final Function<Service<HttpRequest, HttpResponse>,
                ? extends Service<HttpRequest, HttpResponse>> decorator;
        private final int order;

        private DecoratorAndOrder(Annotation annotation,
                                  Function<Service<HttpRequest, HttpResponse>,
                                          ? extends Service<HttpRequest, HttpResponse>> decorator,
                                  int order) {
            this.annotation = annotation;
            this.decorator = decorator;
            this.order = order;
        }

        Annotation annotation() {
            return annotation;
        }

        Function<Service<HttpRequest, HttpResponse>,
                ? extends Service<HttpRequest, HttpResponse>> decorator() {
            return decorator;
        }

        int order() {
            return order;
        }

        @Override
        public String toString() {
            return MoreObjects.toStringHelper(this)
                              .add("annotation", annotation())
                              .add("decorator", decorator())
                              .add("order", order())
                              .toString();
        }
    }

    /**
     * Details of an annotated HTTP service method.
     */
    static final class AnnotatedHttpServiceElement {
        /**
         * Path param extractor with placeholders, e.g., "/const1/{var1}/{var2}/const2"
         */
        private final HttpHeaderPathMapping pathMapping;

        /**
         * The {@link AnnotatedHttpService} that will handle the request actually.
         */
        private final AnnotatedHttpService service;

        /**
         * A decorator of the {@link AnnotatedHttpService} which will be evaluated at service registration time.
         */
        private final Function<Service<HttpRequest, HttpResponse>,
                ? extends Service<HttpRequest, HttpResponse>> decorator;

        private AnnotatedHttpServiceElement(HttpHeaderPathMapping pathMapping,
                                            AnnotatedHttpService service,
                                            Function<Service<HttpRequest, HttpResponse>,
                                                    ? extends Service<HttpRequest, HttpResponse>> decorator) {
            this.pathMapping = requireNonNull(pathMapping, "pathMapping");
            this.service = requireNonNull(service, "service");
            this.decorator = requireNonNull(decorator, "decorator");
        }

        HttpHeaderPathMapping pathMapping() {
            return pathMapping;
        }

        AnnotatedHttpService service() {
            return service;
        }

        Function<Service<HttpRequest, HttpResponse>,
                ? extends Service<HttpRequest, HttpResponse>> decorator() {
            return decorator;
        }

        @Override
        public String toString() {
            return MoreObjects.toStringHelper(this)
                              .add("pathMapping", pathMapping())
                              .add("service", service())
                              .add("decorator", decorator())
                              .toString();
        }
    }
}


text:
using System;
using System.Linq;
using AnalysesEngine.Core.Helpers;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace ApplicationTests
{
    [TestClass]
    public class TimeStampsGeneratorTests
    {
        [TestMethod]
        public void TestTimeStampsGeneration()
        {
            // testing that we get 6 timestamps
            var st = DateTime.Today.AddDays(-5);
            var et = DateTime.Today;
            var tsList = TimeStampsGenerator.Get(TimeSpan.FromDays(1),st,et );

            Assert.IsTrue(tsList.Count == 6, "has 6 timestamps");
            Assert.IsTrue(tsList[0]==st,"st is there");
            Assert.IsTrue(tsList[5]==et,"et is there");

        }

        [TestMethod]
        public void TestTimeStampsGenerationSingleDay()
        {
            // testing that we get st et
            var st = DateTime.Today;
            var et = DateTime.Now;
            var tsList = TimeStampsGenerator.Get(TimeSpan.FromDays(1), st, et);

            Assert.IsTrue(tsList.Count == 2, "has 2 timestamps");
            Assert.IsTrue(tsList[0] == st, "st is there");
            Assert.IsTrue(tsList[1] == et, "et is there");

        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.qubole.quark.fatjdbc.test;

import com.qubole.quark.catalog.db.encryption.AESEncrypt;
import com.qubole.quark.fatjdbc.test.utility.SelectTest;
import org.flywaydb.core.Flyway;
import org.junit.BeforeClass;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.Properties;

/**
 * Created by adeshr on 2/18/16.
 */
public class DbSelectTest extends SelectTest {
  private static final String dbSchemaUrl = "jdbc:h2:mem:DbSelectTest;DB_CLOSE_DELAY=-1";
  private static Connection dbConnection;
  static {
    dbUrl = "jdbc:h2:mem:SelectTest2;DB_CLOSE_DELAY=-1";
    props = new Properties();
    props.put("url", dbSchemaUrl);
    props.put("user", "sa");
    props.put("password", "");
    props.put("encryptionKey", "easy");
  }

  @BeforeClass
  public static void setUpDb() throws Exception {
    SelectTest.setUpClass(dbUrl);
    Flyway flyway = new Flyway();
    flyway.setDataSource(dbSchemaUrl, "sa", "");
    flyway.migrate();

    Properties connInfo = new Properties();
    connInfo.setProperty("url", dbSchemaUrl);
    connInfo.setProperty("user", "sa");
    connInfo.setProperty("password", "");

    dbConnection = DriverManager.getConnection(dbSchemaUrl, connInfo);

    Statement stmt = dbConnection.createStatement();
    String sql = "insert into data_sources(name, type, url, ds_set_id, datasource_type) values "
        + "('H2', 'H2', '" + dbUrl + "', 1, 'JDBC'); insert into jdbc_sources (id, "
        + "username, password) values(1, 'sa', '');" +
        "update ds_sets set default_datasource_id = 1 where id = 1;";

    stmt.execute(sql);
    stmt.close();
  }

  protected String getConnectionUrl() {
    return "jdbc:quark:fat:db:";
  }
}


text:
package com.infinityraider.agricraft.impl.v1;

import com.infinityraider.agricraft.AgriCraft;
import com.infinityraider.agricraft.api.v1.content.IAgriContent;
import com.infinityraider.agricraft.content.AgriTabs;

public final class AgriContent implements IAgriContent {
    private static final AgriContent INSTANCE = new AgriContent();

    public static AgriContent getInstance() {
        return INSTANCE;
    }

    private AgriContent() {}

    @Override
    public Blocks getBlocks() {
        return AgriCraft.instance.getModBlockRegistry();
    }

    @Override
    public Enchantments getEnchantments() {
        return AgriCraft.instance.getModEnchantmentRegistry();
    }

    @Override
    public Fluids getFluids() {
        return AgriCraft.instance.getModFluidRegistry();
    }

    @Override
    public Items getItems() {
        return AgriCraft.instance.getModItemRegistry();
    }

    @Override
    public Sounds getSounds() {
        return AgriCraft.instance.getModSoundRegistry();
    }

    @Override
    public Tabs getTabs() {
        return AgriTabs.TABS;
    }
}


text:
#ifndef MEGA_TREEPROC_H
#define MEGA_TREEPROC_H 1

#include "sharenodekeys.h"
#include "node.h"
#include "transfer.h"
#include "sync.h"

namespace mega {
// node tree processor
class MEGA_API TreeProc
{
public:
    virtual void proc(MegaClient*, Node*) = 0;

    virtual ~TreeProc() { }
};

class MEGA_API TreeProcDel : public TreeProc
{
public:
    void proc(MegaClient*, Node*);
};

class MEGA_API TreeProcApplyKey : public TreeProc
{
public:
    void proc(MegaClient*, Node*);
};

class MEGA_API TreeProcCopy : public TreeProc
{
public:
    vector<NewNode> nn;
    unsigned nc = 0;
    bool allocated = false;

    void allocnodes(void);

    void proc(MegaClient*, Node*);
};

class MEGA_API TreeProcDU : public TreeProc
{
public:
    m_off_t numbytes;
    int numfiles;
    int numfolders;

    void proc(MegaClient*, Node*);
    TreeProcDU();
};

class MEGA_API TreeProcShareKeys : public TreeProc
{
    ShareNodeKeys snk;
    Node* sn;

public:
    void proc(MegaClient*, Node*);
    void get(Command*);

    TreeProcShareKeys(Node* = NULL);
};

class MEGA_API TreeProcForeignKeys : public TreeProc
{
public:
    void proc(MegaClient*, Node*);
};

#ifdef ENABLE_SYNC
class MEGA_API TreeProcDelSyncGet : public TreeProc
{
public:
    void proc(MegaClient*, Node*);
};

class MEGA_API LocalTreeProc
{
public:
    virtual void proc(MegaClient*, LocalNode*) = 0;

    virtual ~LocalTreeProc() { }
};

class MEGA_API LocalTreeProcMove : public LocalTreeProc
{
    Sync *newsync;
    bool recreate;

public:
    LocalTreeProcMove(Sync*, bool);
    void proc(MegaClient*, LocalNode*);
    int nc;
};

class MEGA_API LocalTreeProcUpdateTransfers : public LocalTreeProc
{
public:
    void proc(MegaClient*, LocalNode*);
};

class MEGA_API LocalTreeProcUnlinkNodes : public LocalTreeProc
{
public:
    void proc(MegaClient*, LocalNode*);
};

#endif
} // namespace

#endif


text:
namespace ql {
	namespace effects {
		struct effect;
	}

	//! A basic AI, suitable for most NPCs.
	struct basic_ai {
		basic_ai(reg& reg, id id);

		auto act() -> std::future<void>;

		auto perceive(effects::effect const& effect) -> void;

	private:
		reg_ptr _reg;
		id _id;

		struct idle_state {};
		struct walk_state {};
		struct attack_state {
			ql::id target_id;
		};

		std::variant<idle_state, walk_state, attack_state> _state = idle_state{};
	};
}


text:
#include <linux/kernel.h>
#include <linux/oprofile.h>
#include <linux/errno.h>
#include <linux/init.h>

int __init oprofile_arch_init(struct oprofile_operations *ops)
{
	return -ENODEV;
}

void oprofile_arch_exit(void)
{
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GymFitnessOlympic.Models.entity
{
    public class KhachLe
    {
        public DateTime ThoiGian { get; set; }
        public int SoTien { get; set; }
        public NhanVien NhanVien { get; set; }
        public bool IsGYM { get; set; }
        public GiamGia GiamGia { get; set; }
        public KhachLe()
        {
            IsGYM = true;
        }

        public String LoaiVe {
            get {
                return IsGYM ? "GYM" : "Sauna";
            }
        }

        public string TenPhong {
            get {
                return NhanVien.PhongTap.TenPhongTap;

            }
        }
    }
}


text: module.exports = require("npm:fizzy-ui-utils@1.0.1/utils");


text:
Getting started with `typepad`
==============================

.. toctree::

   start
   auth


text:
package org.gradle.language.base.internal.compile;

import org.gradle.api.NonNullApi;
import org.gradle.language.base.compile.CompilerVersion;
import org.gradle.util.internal.VersionNumber;

@NonNullApi
public class DefaultCompilerVersion implements CompilerVersion {

    private final String type;
    private final String vendor;
    private final VersionNumber version;

    public DefaultCompilerVersion(String type, String vendor, VersionNumber version) {
        this.type = type;
        this.vendor = vendor;
        this.version = version;
    }

    @Override
    public String getType() {
        return type;
    }

    @Override
    public String getVendor() {
        return vendor;
    }

    @Override
    public String getVersion() {
        return version.toString();
    }

    @Override
    public String toString() {
        return "CompilerVersion{" + "type='" + type + '\'' + ", vendor='" + vendor + '\'' + ", version=" + version + '}';
    }
}


text:
package quasar.physical.marklogic.cts

import slamdata.Predef._

import quasar.{NonTerminal, Terminal, RenderTree}, RenderTree.ops._
import quasar.physical.marklogic.xquery._
import quasar.physical.marklogic.xquery.syntax._

import eu.timepit.refined.scalaz._
import matryoshka._
import scalaz._, Scalaz._
import xml.name._

/** cts:query AST
  *
  * NB: Currently can only support literal conditions.
  *
  * @tparam V the type of literal values
  * @tparam A recursive position
  */
sealed abstract class Query[V, A]

object Query extends QueryInstances {
  final case class AndNot[V, A](positive: A, negative: A) extends Query[V, A]

  // TODO: Options
  final case class And[V, A](queries: IList[A]) extends Query[V, A]

  final case class Collection[V, A](uris: IList[Uri]) extends Query[V, A]

  final case class Directory[V, A](uris: IList[Uri], depth: MatchDepth) extends Query[V, A]

  final case class DocumentFragment[V, A](query: A) extends Query[V, A]

  final case class Document[V, A](uris: IList[Uri]) extends Query[V, A]

  // TODO: Options
  final case class ElementAttributeRange[V, A](
    elements: IList[QName],
    attributes: IList[QName],
    op: ComparisonOp,
    values: IList[V]
  ) extends Query[V, A]

  // TODO: Options
  final case class ElementAttributeValue[V, A](
    elements: IList[QName],
    attributes: IList[QName],
    values: IList[String]
  ) extends Query[V, A]

  // TODO: Options
  final case class ElementAttributeWord[V, A](
    elements: IList[QName],
    attributes: IList[QName],
    words: IList[String]
  ) extends Query[V, A]

  final case class Element[V, A](
    elements: IList[QName],
    query: A
  ) extends Query[V, A]

  // TODO: Options
  final case class ElementRange[V, A](
    elements: IList[QName],
    op: ComparisonOp,
    values: IList[V]
  ) extends Query[V, A]

  // TODO: Options
  final case class ElementValue[V, A](
    elements: IList[QName],
    values: IList[String]
  ) extends Query[V, A]

  // TODO: Options
  final case class ElementWord[V, A](
    elements: IList[QName],
    words: IList[String]
  ) extends Query[V, A]

  final case class False[V, A]() extends Query[V, A]

  // TODO: Field queries?

  // TODO: Options
  final case class JsonPropertyRange[V, A](
    properties: IList[String],
    op: ComparisonOp,
    values: IList[V]
  ) extends Query[V, A]

  final case class JsonPropertyScope[V, A](
    properties: IList[String],
    query: A
  ) extends Query[V, A]

  // TODO: Options
  final case class JsonPropertyValue[V, A](
    properties: IList[String],
    values: IList[V]
  ) extends Query[V, A]

  // TODO: Options
  final case class JsonPropertyWord[V, A](
    properties: IList[String],
    words: IList[String]
  ) extends Query[V, A]

  // TODO: Options
  // NB: http://blog.davidcassel.net/2012/08/a-trick-with-ctsnear-query/
  final case class Near[V, A](queries: IList[A], weight: Double) extends Query[V, A]

  final case class Not[V, A](query: A) extends Query[V, A]

  // TODO: Options
  final case class Or[V, A](queries: IList[A]) extends Query[V, A]

  // TODO: Options
  final case class PathRange[V, A](
    paths: IList[String],
    op: ComparisonOp,
    values: IList[V]
  ) extends Query[V, A]

  final case class True[V, A]() extends Query[V, A]

  // TODO: Options
  final case class Word[V, A](words: IList[String]) extends Query[V, A]

  private def mkSeqF[F[_]: Foldable: Functor, A](fa: F[A])(f: A => XQuery): XQuery =
    mkSeq(fa map f)

  private def strSeq[F[_]: Foldable: Functor, A](fa: F[String]): XQuery =
    mkSeqF(fa)(_.xs)

  private def qnameSeq[F[_]: Foldable: Functor, A](fa: F[QName]): XQuery =
    mkSeqF(fa)(_.xqy)

  def toXQuery[V, F[_]: Monad](f: V => F[XQuery]): AlgebraM[F, Query[V, ?], XQuery] = {
    case AndNot(positive, negative) =>
      cts.andNotQuery(positive, negative).point[F]
    case And(queries) =>
      cts.andQuery(mkSeq(queries)).point[F]
    case Not(query) =>
      cts.notQuery(query).point[F]
    case Or(queries) =>
      cts.orQuery(mkSeq(queries)).point[F]
    case Collection(uris) =>
      cts.collectionQuery(mkSeq(uris map (_.value.xs))).point[F]
    case Directory(uris, depth) =>
      cts.directoryQuery(mkSeq(uris map (_.value.xs)), MatchDepth toXQuery depth).point[F]
    case DocumentFragment(query) =>
      cts.documentFragmentQuery(query).point[F]
    case Document(uris) =>
      cts.documentQuery(mkSeq(uris map (_.value.xs))).point[F]
    case ElementAttributeRange(elements, attributes, op, values) =>
      values.traverse(f).map(mkSeq(_))
        .map(cts.elementAttributeRangeQuery(qnameSeq(elements), qnameSeq(attributes), ComparisonOp toXQuery op, _))
    case ElementAttributeValue(elements, attributes, values) =>
      cts.elementAttributeValueQuery(qnameSeq(elements), qnameSeq(attributes), strSeq(values)).point[F]
    case ElementAttributeWord(elements, attributes, words) =>
      cts.elementAttributeWordQuery(qnameSeq(elements), qnameSeq(attributes), strSeq(words)).point[F]
    case Element(elements, query) =>
      cts.elementQuery(qnameSeq(elements), query).point[F]
    case ElementRange(elements, op, values) =>
      values.traverse(f).map(mkSeq(_))
        .map(cts.elementRangeQuery(qnameSeq(elements), ComparisonOp toXQuery op, _))
    case ElementValue(elements, values) =>
      cts.elementValueQuery(qnameSeq(elements), strSeq(values)).point[F]
    case ElementWord(elements, words) =>
      cts.elementWordQuery(qnameSeq(elements), strSeq(words)).point[F]
    case JsonPropertyRange(properties, op, values) =>
      values.traverse(f).map(mkSeq(_))
        .map(cts.jsonPropertyRangeQuery(strSeq(properties), ComparisonOp toXQuery op, _))
    case JsonPropertyScope(properties, query) =>
      cts.jsonPropertyScopeQuery(strSeq(properties), query).point[F]
    case JsonPropertyValue(properties, values) =>
      values.traverse(f).map(mkSeq(_))
        .map(cts.jsonPropertyValueQuery(strSeq(properties), _))
    case JsonPropertyWord(properties, words) =>
      cts.jsonPropertyWordQuery(strSeq(properties), strSeq(words)).point[F]
    case Near(queries, weight) =>
      cts.nearQuery(mkSeq(queries), weight).point[F]
    case Word(words) =>
      cts.wordQuery(strSeq(words)).point[F]
    case PathRange(paths, op, values) =>
      values.traverse(f).map(mkSeq(_))
        .map(cts.pathRangeQuery(strSeq(paths), ComparisonOp toXQuery op, _))
    case True() =>
      cts.True.point[F]
    case False() =>
      cts.False.point[F]
  }
}

sealed abstract class QueryInstances {
  import Query._

  implicit def traverse[V]: Traverse[Query[V, ?]] =
    new Traverse[Query[V, ?]] {
      def traverseImpl[F[_]: Applicative, A, B](qa: Query[V, A])(f: A => F[B]): F[Query[V, B]] = {
        def F(qb: Query[V, B]): F[Query[V, B]] = qb.point[F]

        qa match {
          case AndNot(positive, negative) => (f(positive) |@| f(negative))(AndNot(_, _))
          case And(queries) => (queries traverse f) map (And(_))
          case Collection(uris) => F(Collection(uris))
          case Directory(uris, depth) => F(Directory(uris, depth))
          case DocumentFragment(query) => f(query) map (DocumentFragment(_))
          case Document(uris) => F(Document(uris))
          case ElementAttributeRange(elements, attributes, op, values) => F(ElementAttributeRange(elements, attributes, op, values))
          case ElementAttributeValue(elements, attributes, values) => F(ElementAttributeValue(elements, attributes, values))
          case ElementAttributeWord(elements, attributes, words) => F(ElementAttributeWord(elements, attributes, words))
          case Element(elements, query) => f(query) map (Element(elements, _))
          case ElementRange(elements, op, values) => F(ElementRange(elements, op, values))
          case ElementValue(elements, values) => F(ElementValue(elements, values))
          case ElementWord(elements, words) => F(ElementWord(elements, words))
          case False() => F(False())
          case JsonPropertyRange(properties, op, values) => F(JsonPropertyRange(properties, op, values))
          case JsonPropertyScope(properties, query) => f(query) map (JsonPropertyScope(properties, _))
          case JsonPropertyValue(properties, values) => F(JsonPropertyValue(properties, values))
          case JsonPropertyWord(properties, words) => F(JsonPropertyWord(properties, words))
          case Near(queries, weight) => (queries traverse f) map (Near(_, weight))
          case Not(query) => f(query) map (Not(_))
          case Or(queries) => (queries traverse f) map (Or(_))
          case PathRange(paths, op, values) => F(PathRange(paths, op, values))
          case True() => F(True())
          case Word(words) => F(Word(words))
        }
      }
    }

  implicit def equal[V: Equal]: Delay[Equal, Query[V, ?]] =
    new Delay[Equal, Query[V, ?]] {
      def apply[A](eql: Equal[A]): Equal[Query[V, A]] = {
        implicit val eqlA = eql

        Equal.equal {
          case (AndNot(p1, n1), AndNot(p2, n2)) =>
            p1 === p2 && n1 === n2
          case (And(q1), And(q2)) =>
            q1 === q2
          case (Collection(u1), Collection(u2)) =>
            u1 === u2
          case (Directory(u1, d1), Directory(u2, d2)) =>
            u1 === u2 && d1 === d2
          case (DocumentFragment(q1), DocumentFragment(q2)) =>
            q1 === q2
          case (Document(u1), Document(u2)) =>
            u1 === u2
          case (ElementAttributeRange(e1, a1, o1, v1), ElementAttributeRange(e2, a2, o2, v2)) =>
            e1 === e2 && a1 === a2 && o1 === o2 && v1 === v2
          case (ElementAttributeValue(e1, a1, v1), ElementAttributeValue(e2, a2, v2)) =>
            e1 === e2 && a1 === a2 && v1 === v2
          case (ElementAttributeWord(e1, a1, w1), ElementAttributeWord(e2, a2, w2)) =>
            e1 === e2 && a1 === a2 && w1 === w2
          case (Element(e1, q1), Element(e2, q2)) =>
            e1 === e2 && q1 === q2
          case (ElementRange(e1, o1, v1), ElementRange(e2, o2, v2)) =>
            e1 === e2 && o1 === o2 && v1 === v2
          case (ElementValue(e1, v1), ElementValue(e2, v2)) =>
            e1 === e2 && v1 === v2
          case (ElementWord(e1, w1), ElementWord(e2, w2)) =>
            e1 === e2 && w1 === w2
          case (False(), False()) =>
            true
          case (JsonPropertyRange(p1, o1, v1), JsonPropertyRange(p2, o2, v2)) =>
            p1 === p2 && o1 === o2 && v1 === v2
          case (JsonPropertyScope(p1, q1), JsonPropertyScope(p2, q2)) =>
            p1 === p2 && q1 === q2
          case (JsonPropertyValue(p1, v1), JsonPropertyValue(p2, v2)) =>
            p1 === p2 && v1 === v2
          case (JsonPropertyWord(p1, w1), JsonPropertyWord(p2, w2)) =>
            p1 === p2 && w1 === w2
          case (Near(q1, w1), Near(q2, w2)) =>
            q1 === q2 && w1 === w2
          case (Not(q1), Not(q2)) =>
            q1 === q2
          case (Or(q1), Or(q2)) =>
            q1 === q2
          case (PathRange(p1, o1, v1), PathRange(p2, o2, v2)) =>
            p1 === p2 && o1 === o2 && v1 === v2
          case (True(), True()) =>
            true
          case (Word(w1), Word(w2)) =>
            w1 === w2

          case (_, _) =>
            false
        }
      }
    }

    implicit def renderTree[V: RenderTree]: Delay[RenderTree, Query[V, ?]] =
      new Delay[RenderTree, Query[V, ?]] {
        def apply[A](rt: RenderTree[A]) = {
          implicit val rta = rt

          val nt = List("cts:query")

          def leaf(t: String, l: Option[String]) =
            Terminal(t :: nt, l)

          def node[X: RenderTree](t: String, xs: X*) =
            NonTerminal(t :: nt, none, xs.map(_.render).toList)

          def nodeL[X: RenderTree](t: String, xs: IList[X]) =
            node(t, xs.toList: _*)

          def us(xs: IList[Uri]) = nodeL("Uris", xs)
          def es(xs: IList[QName]) = nodeL("Elements", xs)
          def as(xs: IList[QName]) = nodeL("Attributes", xs)
          def vs(xs: IList[V]) = nodeL("Values", xs)
          def ws(xs: IList[String]) = nodeL("Words", xs)
          def ps(xs: IList[String]) = nodeL("Properties", xs)

          RenderTree.make[Query[V, A]] {
            case AndNot(positive, negative) =>
              node("cts:and-not-query", positive, negative)
            case And(queries) =>
              nodeL("cts:and-query", queries)
            case Collection(uris) =>
              node("cts:collection-query", us(uris))
            case Directory(uris, depth) =>
              node("cts:directory-query", us(uris), depth.render)
            case DocumentFragment(query) =>
              node("cts:document-fragment-query", query)
            case Document(uris) =>
              node("cts:document-query", us(uris))
            case ElementAttributeRange(elements, attributes, op, values) =>
              node(
                "cts:element-attribute-range-query",
                es(elements),
                as(attributes),
                op.render,
                vs(values))
            case ElementAttributeValue(elements, attributes, values) =>
              node(
                "cts:element-attribute-value-query",
                es(elements),
                as(attributes),
                nodeL("Values", values))
            case ElementAttributeWord(elements, attributes, words) =>
              node(
                "cts:element-attribute-word-query",
                es(elements),
                as(attributes),
                ws(words))
            case Element(elements, query) =>
              node("cts:element-query", es(elements), query.render)
            case ElementRange(elements, op, values) =>
              node(
                "cts:element-range-query",
                es(elements),
                op.render,
                vs(values))
            case ElementValue(elements, values) =>
              node(
                "cts:element-value-query",
                es(elements),
                nodeL("Values", values))
            case ElementWord(elements, words) =>
              node(
                "cts:element-word-query",
                es(elements),
                ws(words))
            case False() =>
              leaf("cts:false-query", none)
            case JsonPropertyRange(properties, op, values) =>
              node(
                "cts:json-property-range-query",
                ps(properties),
                op.render,
                vs(values))
            case JsonPropertyScope(properties, query) =>
              node(
                "cts:json-property-scope-query",
                ps(properties),
                query.render)
            case JsonPropertyValue(properties, values) =>
              node(
                "cts:json-property-value-query",
                ps(properties),
                vs(values))
            case JsonPropertyWord(properties, words) =>
              node(
                "cts:json-property-word-query",
                ps(properties),
                ws(words))
            case Near(queries, weight) =>
              nodeL(
                "cts:near-query",
                queries.map(_.render) ::: IList(leaf("Weight", weight.shows.some)))
            case Not(query) =>
              node("cts:not-query", query)
            case Or(queries) =>
              nodeL("cts:or-query", queries)
            case PathRange(paths, op, values) =>
              node(
                "cts:path-range-query",
                nodeL("Paths", paths),
                op.render,
                vs(values))
            case True() =>
              leaf("cts:true-query", none)
            case Word(words) =>
              node("cts:word-query", ws(words))
          }
        }
      }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ChangeListManager">
    <list default="true" id="5ee37101-91fb-4287-b90d-a2a399046d01" name="Default" comment="">
      <change type="MODIFICATION" beforePath="$PROJECT_DIR$/app/Http/Kernel.php" afterPath="$PROJECT_DIR$/app/Http/Kernel.php" />
      <change type="MODIFICATION" beforePath="$PROJECT_DIR$/app/Http/routes.php" afterPath="$PROJECT_DIR$/app/Http/routes.php" />
    </list>
    <ignored path="struct-api-laravel.iws" />
    <ignored path=".idea/workspace.xml" />
    <ignored path=".idea/dataSources.local.xml" />
    <option name="EXCLUDED_CONVERTED_TO_IGNORED" value="true" />
    <option name="TRACKING_ENABLED" value="true" />
    <option name="SHOW_DIALOG" value="false" />
    <option name="HIGHLIGHT_CONFLICTS" value="true" />
    <option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
    <option name="LAST_RESOLUTION" value="IGNORE" />
  </component>
  <component name="ChangesViewManager" flattened_view="true" show_ignored="false" />
  <component name="CreatePatchCommitExecutor">
    <option name="PATCH_PATH" value="" />
  </component>
  <component name="DaemonCodeAnalyzer">
    <disable_hints />
  </component>
  <component name="ExecutionTargetManager" SELECTED_TARGET="default_target" />
  <component name="FavoritesManager">
    <favorites_list name="struct-api-laravel" />
  </component>
  <component name="FileEditorManager">
    <leaf>
      <file leaf-file-name="routes.php" pinned="false" current-in-tab="false">
        <entry file="file://$PROJECT_DIR$/app/Http/routes.php">
          <provider selected="true" editor-type-id="text-editor">
            <state vertical-scroll-proportion="-6.875" vertical-offset="0" max-vertical-offset="315">
              <caret line="20" column="41" selection-start-line="20" selection-start-column="41" selection-end-line="20" selection-end-column="41" />
              <folding />
            </state>
          </provider>
        </entry>
      </file>
      <file leaf-file-name="ClientController.php" pinned="false" current-in-tab="true">
        <entry file="file://$PROJECT_DIR$/app/Http/Controllers/ClientController.php">
          <provider selected="true" editor-type-id="text-editor">
            <state vertical-scroll-proportion="0.28229666" vertical-offset="229" max-vertical-offset="1125">
              <caret line="31" column="15" selection-start-line="31" selection-start-column="15" selection-end-line="31" selection-end-column="15" />
              <folding>
                <element signature="e#48#71#0#PHP" expanded="true" />
              </folding>
            </state>
          </provider>
        </entry>
      </file>
    </leaf>
  </component>
  <component name="Git.Settings">
    <option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" />
  </component>
  <component name="IdeDocumentHistory">
    <option name="CHANGED_PATHS">
      <list>
        <option value="$PROJECT_DIR$/.env" />
        <option value="$PROJECT_DIR$/app/Http/Kernel.php" />
        <option value="$PROJECT_DIR$/app/Http/routes.php" />
        <option value="$PROJECT_DIR$/app/Http/Controllers/ClientController.php" />
      </list>
    </option>
  </component>
  <component name="JsGulpfileManager">
    <detection-done>true</detection-done>
    <gulpfiles>
      <GulpfileState>
        <gulpfile-path>$PROJECT_DIR$/gulpfile.js</gulpfile-path>
      </GulpfileState>
    </gulpfiles>
  </component>
  <component name="PhpWorkspaceProjectConfiguration" backward_compatibility_performed="true" />
  <component name="ProjectFrameBounds">
    <option name="y" value="23" />
    <option name="width" value="1680" />
    <option name="height" value="957" />
  </component>
  <component name="ProjectLevelVcsManager" settingsEditedManually="false">
    <OptionsSetting value="true" id="Add" />
    <OptionsSetting value="true" id="Remove" />
    <OptionsSetting value="true" id="Checkout" />
    <OptionsSetting value="true" id="Update" />
    <OptionsSetting value="true" id="Status" />
    <OptionsSetting value="true" id="Edit" />
    <ConfirmationsSetting value="0" id="Add" />
    <ConfirmationsSetting value="0" id="Remove" />
  </component>
  <component name="ProjectView">
    <navigator currentView="ProjectPane" proportions="" version="1">
      <flattenPackages />
      <showMembers />
      <showModules />
      <showLibraryContents />
      <hideEmptyPackages />
      <abbreviatePackageNames />
      <autoscrollToSource />
      <autoscrollFromSource />
      <sortByType />
    </navigator>
    <panes>
      <pane id="ProjectPane">
        <subPane>
          <PATH>
            <PATH_ELEMENT>
              <option name="myItemId" value="struct-api-laravel" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
            </PATH_ELEMENT>
          </PATH>
          <PATH>
            <PATH_ELEMENT>
              <option name="myItemId" value="struct-api-laravel" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
            </PATH_ELEMENT>
            <PATH_ELEMENT>
              <option name="myItemId" value="struct-api-laravel" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
            </PATH_ELEMENT>
          </PATH>
          <PATH>
            <PATH_ELEMENT>
              <option name="myItemId" value="struct-api-laravel" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
            </PATH_ELEMENT>
            <PATH_ELEMENT>
              <option name="myItemId" value="struct-api-laravel" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
            </PATH_ELEMENT>
            <PATH_ELEMENT>
              <option name="myItemId" value="app" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
            </PATH_ELEMENT>
          </PATH>
          <PATH>
            <PATH_ELEMENT>
              <option name="myItemId" value="struct-api-laravel" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
            </PATH_ELEMENT>
            <PATH_ELEMENT>
              <option name="myItemId" value="struct-api-laravel" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
            </PATH_ELEMENT>
            <PATH_ELEMENT>
              <option name="myItemId" value="app" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
            </PATH_ELEMENT>
            <PATH_ELEMENT>
              <option name="myItemId" value="Http" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
            </PATH_ELEMENT>
          </PATH>
          <PATH>
            <PATH_ELEMENT>
              <option name="myItemId" value="struct-api-laravel" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
            </PATH_ELEMENT>
            <PATH_ELEMENT>
              <option name="myItemId" value="struct-api-laravel" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
            </PATH_ELEMENT>
            <PATH_ELEMENT>
              <option name="myItemId" value="app" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
            </PATH_ELEMENT>
            <PATH_ELEMENT>
              <option name="myItemId" value="Http" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
            </PATH_ELEMENT>
            <PATH_ELEMENT>
              <option name="myItemId" value="Controllers" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
            </PATH_ELEMENT>
          </PATH>
        </subPane>
      </pane>
      <pane id="Scope" />
    </panes>
  </component>
  <component name="PropertiesComponent">
    <property name="options.lastSelected" value="preferences.lookFeel" />
    <property name="options.splitter.main.proportions" value="0.3" />
    <property name="options.splitter.details.proportions" value="0.2" />
    <property name="WebServerToolWindowFactoryState" value="false" />
    <property name="SearchEverywhereHistoryKey" value="	FILE	file:///Users/Admin/Projetos/struct-api-laravel/app/Http/routes.php" />
  </component>
  <component name="RunManager">
    <list size="0" />
  </component>
  <component name="ShelveChangesManager" show_recycled="false" />
  <component name="TaskManager">
    <task active="true" id="Default" summary="Default task">
      <changelist id="5ee37101-91fb-4287-b90d-a2a399046d01" name="Default" comment="" />
      <created>1437185303752</created>
      <option name="number" value="Default" />
      <updated>1437185303752</updated>
    </task>
    <servers />
  </component>
  <component name="ToolWindowManager">
    <frame x="0" y="23" width="1680" height="957" extended-state="6" />
    <editor active="true" />
    <layout>
      <window_info id="Gulp" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="-1" side_tool="true" content_ui="tabs" />
      <window_info id="Changes" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="-1" side_tool="false" content_ui="tabs" />
      <window_info id="Terminal" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="-1" side_tool="false" content_ui="tabs" />
      <window_info id="TODO" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="6" side_tool="false" content_ui="tabs" />
      <window_info id="Database" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="-1" side_tool="false" content_ui="tabs" />
      <window_info id="Structure" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
      <window_info id="Application Servers" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="-1" side_tool="false" content_ui="tabs" />
      <window_info id="Project" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" weight="0.15952381" sideWeight="0.5" order="0" side_tool="false" content_ui="combo" />
      <window_info id="Favorites" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="-1" side_tool="true" content_ui="tabs" />
      <window_info id="Event Log" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="-1" side_tool="true" content_ui="tabs" />
      <window_info id="Version Control" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="-1" side_tool="false" content_ui="tabs" />
      <window_info id="Cvs" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="4" side_tool="false" content_ui="tabs" />
      <window_info id="Message" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" />
      <window_info id="Find" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
      <window_info id="Ant Build" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
      <window_info id="Commander" active="false" anchor="right" auto_hide="false" internal_type="SLIDING" type="SLIDING" visible="false" weight="0.4" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" />
      <window_info id="Debug" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.4" sideWeight="0.5" order="3" side_tool="false" content_ui="tabs" />
      <window_info id="Run" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="2" side_tool="false" content_ui="tabs" />
      <window_info id="Inspection" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.4" sideWeight="0.5" order="5" side_tool="false" content_ui="tabs" />
      <window_info id="Hierarchy" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="2" side_tool="false" content_ui="combo" />
    </layout>
  </component>
  <component name="Vcs.Log.UiProperties">
    <option name="RECENTLY_FILTERED_USER_GROUPS">
      <collection />
    </option>
    <option name="RECENTLY_FILTERED_BRANCH_GROUPS">
      <collection />
    </option>
  </component>
  <component name="VcsContentAnnotationSettings">
    <option name="myLimit" value="2678400000" />
  </component>
  <component name="VcsManagerConfiguration">
    <option name="myTodoPanelSettings">
      <TodoPanelSettings />
    </option>
  </component>
  <component name="XDebuggerManager">
    <breakpoint-manager />
    <watches-manager />
  </component>
  <component name="editorHistoryManager">
    <entry file="file://$PROJECT_DIR$/config/database.php">
      <provider selected="true" editor-type-id="text-editor">
        <state vertical-scroll-proportion="-0.32296652" vertical-offset="270" max-vertical-offset="1980">
          <caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
          <folding />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/config/app.php">
      <provider selected="true" editor-type-id="text-editor">
        <state vertical-scroll-proportion="0.0" vertical-offset="0" max-vertical-offset="3045">
          <caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
          <folding />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/.env">
      <provider selected="true" editor-type-id="text-editor">
        <state vertical-scroll-proportion="0.069767445" vertical-offset="0" max-vertical-offset="860">
          <caret line="4" column="17" selection-start-line="4" selection-start-column="17" selection-end-line="4" selection-end-column="17" />
          <folding />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/database/migrations/2015_07_17_193406_create_clients_table.php">
      <provider selected="true" editor-type-id="text-editor">
        <state vertical-scroll-proportion="0.0" vertical-offset="0" max-vertical-offset="860">
          <caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
          <folding />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/app/Http/Kernel.php">
      <provider selected="true" editor-type-id="text-editor">
        <state vertical-scroll-proportion="0.5562201" vertical-offset="0" max-vertical-offset="836">
          <caret line="31" column="71" selection-start-line="31" selection-start-column="71" selection-end-line="31" selection-end-column="71" />
          <folding />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php">
      <provider selected="true" editor-type-id="text-editor">
        <state vertical-scroll-proportion="-3.820574" vertical-offset="20609" max-vertical-offset="50580">
          <caret line="1187" column="27" selection-start-line="1187" selection-start-column="27" selection-end-line="1187" selection-end-column="27" />
          <folding />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/app/Http/routes.php">
      <provider selected="true" editor-type-id="text-editor">
        <state vertical-scroll-proportion="-6.875" vertical-offset="0" max-vertical-offset="315">
          <caret line="20" column="41" selection-start-line="20" selection-start-column="41" selection-end-line="20" selection-end-column="41" />
          <folding />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/app/Http/Controllers/ClientController.php">
      <provider selected="true" editor-type-id="text-editor">
        <state vertical-scroll-proportion="0.28229666" vertical-offset="229" max-vertical-offset="1125">
          <caret line="31" column="15" selection-start-line="31" selection-start-column="15" selection-end-line="31" selection-end-column="15" />
          <folding>
            <element signature="e#48#71#0#PHP" expanded="true" />
          </folding>
        </state>
      </provider>
    </entry>
  </component>
</project>


text:
var Message = require('../message');

/**
 * Sends events to the embedded VR view IFrame via postMessage. Also handles
 * messages sent back from the IFrame:
 *
 *    click: When a hotspot was clicked.
 *    modechange: When the user changes viewing mode (VR|Fullscreen|etc).
 */
function IFrameMessageSender(iframe) {
  if (!iframe) {
    console.error('No iframe specified');
    return;
  }
  this.iframe = iframe;

  // On iOS, if the iframe is across domains, also send DeviceMotion data.
  if (this.isIOS_()) {
    window.addEventListener('devicemotion', this.onDeviceMotion_.bind(this), false);
  }
}

/**
 * Sends a message to the associated VR View IFrame.
 */
IFrameMessageSender.prototype.send = function(message) {
  var iframeWindow = this.iframe.contentWindow;
  iframeWindow.postMessage(message, '*');
};

IFrameMessageSender.prototype.onDeviceMotion_ = function(e) {
  var message = {
    type: Message.DEVICE_MOTION,
    deviceMotionEvent: this.cloneDeviceMotionEvent_(e)
  };

  this.send(message);
};

IFrameMessageSender.prototype.cloneDeviceMotionEvent_ = function(e) {
  return {
    acceleration: {
      x: e.acceleration.x,
      y: e.acceleration.y,
      z: e.acceleration.z,
    },
    accelerationIncludingGravity: {
      x: e.accelerationIncludingGravity.x,
      y: e.accelerationIncludingGravity.y,
      z: e.accelerationIncludingGravity.z,
    },
    rotationRate: {
      alpha: e.rotationRate.alpha,
      beta: e.rotationRate.beta,
      gamma: e.rotationRate.gamma,
    },
    interval: e.interval,
    timeStamp: e.timeStamp
  };
};

IFrameMessageSender.prototype.isIOS_ = function() {
  return /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
};

module.exports = IFrameMessageSender;


text:
package fi.csc.chipster.scheduler.offer;

import java.time.Instant;
import java.time.temporal.ChronoUnit;

public class OfferJob {

	private Instant lastScheduleTimestamp;
	private Instant heartbeatTimestamp;
	private Instant runnableTimestamp;

	public OfferJob() {
		this.lastScheduleTimestamp = Instant.now();
	}

	public Instant getLastScheduleTimestamp() {
		return lastScheduleTimestamp;
	}

	public Instant getHeartbeatTimestamp() {
		return heartbeatTimestamp;
	}

	public void setHeartbeatTimestamp() {
		this.heartbeatTimestamp = Instant.now();
	}

	/**
	 * Check if the job is in SCHEDULED state, i.e. doesn't have heartbeat yet
	 *
	 * @return
	 */
	public boolean isScheduled() {
		return heartbeatTimestamp == null;
	}

	public boolean hasHeartbeat() {
		return heartbeatTimestamp != null;
	}

	public long getTimeSinceLastScheduled() {
		return lastScheduleTimestamp.until(Instant.now(), ChronoUnit.SECONDS);
	}

	public long getTimeSinceLastHeartbeat() {
		return heartbeatTimestamp.until(Instant.now(), ChronoUnit.SECONDS);
	}

	public void setRunnableTimestamp() {
		runnableTimestamp = Instant.now();
	}

	public boolean isRunnable() {
		return runnableTimestamp != null;
	}
}


text:
set -e

if [ ! $(env | grep TRAVIS_JOB_ID ) ] ; then
  echo "This script is supposed to run on Travis CI"
  exit 1
fi

RECIPE="${1}"
DOCKER=$(echo "${RECIPE}" | cut -d "-" -f 1) # Allow e.g., a recipe called "inkscape-standalone" to use the "inkscape" Docker image

mkdir -p ./out/

if [ -f recipes/$RECIPE/Dockerfile ] && [ -f recipes/$RECIPE/Recipe ] ; then
  # There is a Dockerfile, hence build using Docker
  mv recipes/$RECIPE/Recipe ./out/Recipe
  sed -i -e 's|sudo ||g' ./out/Recipe # For subsurface recipe
  docker run -i -v ${PWD}/out:/out probonopd/appimages:$DOCKER /bin/bash -ex /out/Recipe
elif [ -f recipes/$RECIPE.yml ] ; then
  # There is no Dockerfile but a YAML file for the meta Recipe
  bash -ex pkg2appimage recipes/$RECIPE.yml
elif [ -f recipes/$RECIPE/Recipe ] ; then
  # There is no Dockerfile but a Recipe, hence build without Docker
  bash -ex recipes/$RECIPE/Recipe
else
  # There is no Recipe
  echo "Recipe not found, is RECIPE missing?"
  exit 1
fi

ls -lh out/*.AppImage