text:
package org.typemeta.funcj.functions;

import org.typemeta.funcj.tuples.*;

import java.util.Objects;

/**
 * Interfaces for composable functions which throw a specific exception type.
 */
public abstract class FunctionsGenEx {

    /**
     * Function of arity 0.
     * @param <R>       the function return type
     * @param <X>       the exception type
     */
    @FunctionalInterface
    public interface F0<R, X extends Exception> {
        /**
         * Static constructor.
         * @param f         the function
         * @param <R>       the function return type
         * @param <X>       the exception type
         * @return          the function
         */
        static <R, X extends Exception> F0<R, X> of(F0<R, X> f) {
            return f;
        }

        /**
         * Return a zero-argument constant function that always returns the same value.
         * @param r         the value the function always returns
         * @param <R>       the value type
         * @param <X>       the exception type
         * @return          a zero-argument constant function that always returns the same value
         */
        static <R, X extends Exception> F0<R, X> konst(R r) {
            return () -> r;
        }

        /**
         * Apply this function
         * @return          the result of applying this function
         * @throws          X the exception
         */
        R apply() throws X;

        /**
         * Compose this function with another,
         * to create a function that first applies {@code f}
         * and then applies this function to the result.
         * @param f         the function to compose with
         * @param <T>       the argument type to {@code f}
         * @return          a function that first applies {@code f} and then applies this function to the result.
         */
        default <T> F<T, R, X> compose(SideEffectGenEx.F<? super T, X> f) {
            return t -> {
                f.apply(t);
                return this.apply();
            };
        }

        /**
         * Compose this function with another,
         * to create a function that first applies this function
         * and then applies {@code f} to the result.
         * @param f         the function to compose with
         * @param <T>       the argument type to {@code f}
         * @return          a function that first applies this function and then applies {@code f} to the result.
         */
        default <T> F0<T, X> andThen(F<? super R, ? extends T, X> f) {
            return () -> f.apply(this.apply());
        }
    }

    /**
     * Function of arity 1.
     * Note: if the input type to {@code F} is fixed to type T then the result is a monad,
     * where pure = {@code konst} and bind = {@code flatMap}.
     * @param <A>       the function argument type
     * @param <R>       the function return type
     * @param <X>       the exception type
     */
    @FunctionalInterface
    public interface F<A, R, X extends Exception> {
        /**
         * Static constructor.
         * @param f         the function
         * @param <A>       the function argument type
         * @param <R>       the function return type
         * @param <X>       the exception type
         * @return          the function
         */
        static <A, R, X extends Exception> F<A, R, X> of(F<A, R, X> f) {
            return f;
        }

        /**
         * The identity function, that simply returns its argument.
         * @param <A>       input and output type of function
         * @param <X>       the exception type
         * @return          the identity function
         */
        static <A, X extends Exception> F<A, A, X> id() {
            return x -> x;
        }

        /**
         * The constant function, that always returns the same value, regardless of its argument
         * @param r         the value the constant function will return
         * @param <A>       the input type of the function
         * @param <R>       the type of the constant value {@code r}
         * @param <X>       the exception type
         * @return          the constant function
         */
        static <A, R, X extends Exception> F<A, R, X> konst(R r) {
            return a -> r;
        }

        /**
         * Convert a curried function by reversing the order of its arguments
         * @param f         the function to be flipped
         * @param <A>       the function's first argument type
         * @param <B>       the function's second argument type
         * @param <R>       the function's return type
         * @param <X>       the exception type
         * @return          the flipped function
         */
        static <A, B, R, X extends Exception> F<B, F<A, R, X>, X> flip(F<A, F<B, R, X>, X> f) {
            return b -> a -> f.apply(a).apply(b);
        }

        /**
         * Apply this function
         * @param a         the function argument
         * @return          the result of applying this function
         * @throws          X the exception
         */
        R apply(A a) throws X;

        /**
         * Compose this function with another,
         * to create a function that first applies {@code f}
         * and then applies this function to the result.
         * @param f         the function to compose with
         * @param <T>       the argument type to {@code f}
         * @return          a function that first applies {@code f} and then applies this function to the result.
         */
        default <T> F<T, R, X> compose(F<? super T, ? extends A, X> f) {
            return t -> this.apply(f.apply(t));
        }

        /**
         * Compose this function with another,
         * to create a function that first applies this function
         * and then applies {@code f} to the result.
         * @param f         the function to compose with
         * @param <T>       the argument type to {@code f}
         * @return          a function that first applies this function and then applies {@code f} to the result.
         */
        default <T> F<A, T, X> andThen(F<? super R, ? extends T, X> f) {
            return a -> f.apply(this.apply(a));
        }

        /**
         * Map a function over this oemn.
         * Essentially {@link F#compose} without the wildcard generic types.
         * @param f         the function to compose with
         * @param <T>       the argument type to {@code f}
         * @return          a function that first applies {@code f} and then applies this function to the result.
         */
        default <T> F<A, T, X> map(F<R, T, X> f) {
            return f.compose(this);
        }

        /**
         * Applicative function composition.
         * @param f         the function to compose with
         * @param <B>       the return type of the function returned by {@code f}
         * @return          the composed function
         */
        default <B> F<A, B, X> app(F<A, F<R, B, X>, X> f) {
            return a -> f.apply(a).apply(apply(a));
        }

        /**
         * Monadic function composition.
         * @param f         the function to compose with
         * @param <B>       the return type of the function returned by {@code f}
         * @return          the composed function
         */
        default <B> F<A, B, X> flatMap(F<R, F<A, B, X>, X> f) {
            return a -> f.apply(apply(a)).apply(a);
        }
    }

    /**
     * Function of arity 2.
     * @param <A>       the function's first argument type
     * @param <B>       the function's second argument type
     * @param <R>       the function return type
     * @param <X>       the exception type
     */
    @FunctionalInterface
    public interface F2<A, B, R, X extends Exception> {
        /**
         * Static constructor.
         * @param f         the function
         * @param <A>       the function's first argument type
         * @param <B>       the function's second argument type
         * @param <R>       the function return type
         * @param <X>       the exception type
         * @return          the function
         */
        static <A, B, R, X extends Exception> F2<A, B, R, X> of(F2<A, B, R, X> f) {
            return f;
        }

        /**
         * Convert an curried function to its uncurried equivalent.
         * @param f         the curried function
         * @param <A>       the function's first argument type
         * @param <B>       the function's second argument type
         * @param <R>       the function return type
         * @param <X>       the exception type
         * @return          the uncurried function
         */
        static <A, B, R, X extends Exception> F2<A, B, R, X> uncurry(F<A, F<B, R, X>, X> f) {
            return (a, b) -> f.apply(a).apply(b);
        }

        /**
         * A function that always returns its first argument.
         * @param <A>       the function's first argument type
         * @param <B>       the function's second argument type
         * @param <X>       the exception type
         * @return          a function that always returns its first argument.
         */
        static <A, B, X extends Exception> F2<A, B, A, X> first() {
            return (a, b) -> a;
        }

        /**
         * A function that always returns its second argument.
         * @param <A>       the function's first argument type
         * @param <B>       the function's second argument type
         * @param <X>       the exception type
         * @return          a function that always returns its second argument.
         */
        static <A, B, X extends Exception> F2<A, B, B, X> second() {
            return (a, b) -> b;
        }

        /**
         * Apply this function.
         * @param a         the function's first argument
         * @param b         the function's second argument
         * @return          the result of applying this function
         * @throws          X the exception
         */
        R apply(A a, B b) throws X;

        /**
         * Partially apply this function.
         * @param a         the value to partially apply this function to
         * @return          the partially applied function
         */
        default F<B, R, X> partial(A a) {
            return b -> apply(a, b);
        }

        /**
         * Convert this function to its curried equivalent.
         * @return          the curried equivalent of this function
         */
        default F<A, F<B, R, X>, X> curry() {
            return a -> b -> apply(a, b);
        }

        /**
         * Flip this function by reversing the order of its arguments.
         * @return          the flipped function
         */
        default F2<B, A, R, X> flip() {
            return (b, a) -> apply(a, b);
        }

        /**
         * Convert this function to one that operates on a {@link Tuple2}.
         * @return          a function that operates on a {@link Tuple2}
         * @throws          X the exception
         */
        default F<Tuple2<A, B>, R, X> tupled() throws X {
            return t2 -> apply(t2._1, t2._2);
        }
    }

    /**
     * Function of arity 3.
     * @param <A>       the function's first argument type
     * @param <B>       the function's second argument type
     * @param <C>       the function's third argument type
     * @param <R>       the function's return type
     * @param <X>       the exception type
     */
    @FunctionalInterface
    public interface F3<A, B, C, R, X extends Exception> {
        /**
         * Static constructor.
         * @param f         the function
         * @param <A>       the function's first argument type
         * @param <B>       the function's second argument type
         * @param <C>       the function's third argument type
         * @param <R>       the function's return type
         * @param <X>       the exception type
         * @return          the function
         */
        static <A, B, C, R, X extends Exception> F3<A, B, C, R, X> of(F3<A, B, C, R, X> f) {
            return f;
        }

        /**
         * Convert an curried function to its uncurried equivalent.
         * @param f         the curried function
         * @param <A>       the function's first argument type
         * @param <B>       the function's second argument type
         * @param <C>       the function's third argument type
         * @param <R>       the function's return type
         * @param <X>       the exception type
         * @return          the uncurried function
         */
        static <A, B, C, R, X extends Exception> F3<A, B, C, R, X> uncurry(F<A, F<B, F<C, R, X>, X>, X> f) {
            return (a, b, c) -> f.apply(a).apply(b).apply(c);
        }

        /**
         * Apply this function.
         * @param a         the function's first argument
         * @param b         the function's second argument
         * @param c         the function's third argument
         * @return          the result of applying this function
         * @throws          X the exception
         */
        R apply(A a, B b, C c) throws X;

        /**
         * Partially apply this function to one value.
         * @param a         the value
         * @return          the partially applied function
         */
        default F2<B, C, R, X> partial(A a) {
            return (b, c) -> apply(a, b, c);
        }

        /**
         * Partially apply this function to two values.
         * @param a         the first value
         * @param b         the second value
         * @return          the partially applied function
         */
        default F<C, R, X> partial(A a, B b) {
            return c -> apply(a, b, c);
        }

        /**
         * Convert this function to its curried equivalent.
         * @return          the curried equivalent of this function
         */
        default F<A, F<B, F<C, R, X>, X>, X> curry() {
            return a -> b -> c -> apply(a, b, c);
        }

        /**
         * Convert this function to one that operates on a {@link Tuple3}.
         * @return          a function that operates on a {@link Tuple3}
         * @throws          X the exception
         */
        default F<Tuple3<A, B, C>, R, X> tupled() throws X {
            return t3 -> apply(t3._1, t3._2, t3._3);
        }
    }

    /**
     * Function of arity 4.
     * @param <A>       the function's first argument type
     * @param <B>       the function's second argument type
     * @param <C>       the function's third argument type
     * @param <D>       the function's fourth argument type
     * @param <R>       the function's return type
     * @param <X>       the exception type
     */
    @FunctionalInterface
    public interface F4<A, B, C, D, R, X extends Exception> {
        /**
         * Static constructor.
         * @param f         the function
         * @param <A>       the function's first argument type
         * @param <B>       the function's second argument type
         * @param <C>       the function's third argument type
         * @param <D>       the function's fourth argument type
         * @param <R>       the function's return type
         * @param <X>       the exception type
         * @return          the function
         */
        static <A, B, C, D, R, X extends Exception> F4<A, B, C, D, R, X> of(F4<A, B, C, D, R, X> f) {
            return f;
        }

        /**
         * Convert an curried function to its uncurried equivalent.
         * @param f         the curried function
         * @param <A>       the function's first argument type
         * @param <B>       the function's second argument type
         * @param <C>       the function's third argument type
         * @param <D>       the function's fourth argument type
         * @param <R>       the function's return type
         * @param <X>       the exception type
         * @return          the uncurried function
         */
        static <A, B, C, D, R, X extends Exception> F4<A, B, C, D, R, X> uncurry(F<A, F<B, F<C, F<D, R, X>, X>, X>, X> f) {
            return (a, b, c, d) -> f.apply(a).apply(b).apply(c).apply(d);
        }

        /**
         * Apply this function.
         * @param a         the function's first argument
         * @param b         the function's second argument
         * @param c         the function's third argument
         * @param d         the function's fourth argument
         * @return          the result of applying this function
         * @throws          X the exception
         */
        R apply(A a, B b, C c, D d) throws X;

        /**
         * Partially apply this function to one value.
         * @param a         the first value
         * @return          the partially applied function
         */
        default F3<B, C, D, R, X> partial(A a) {
            return (b, c, d) -> apply(a, b, c, d);
        }

        /**
         * Partially apply this function to two values.
         * @param a         the first value
         * @param b         the second value
         * @return          the partially applied function
         */
        default F2<C, D, R, X> partial(A a, B b) {
            return (c, d) -> apply(a, b, c, d);
        }

        /**
         * Partially apply this function to three values.
         * @param a         the first value
         * @param b         the second value
         * @param c         the third value
         * @return          the partially applied function
         */
        default F<D, R, X> partial(A a, B b, C c) {
            return d -> apply(a, b, c, d);
        }

        /**
         * Convert this function to its curried equivalent.
         * @return          the curried equivalent of this function
         */
        default F<A, F<B, F<C, F<D, R, X>, X>, X>, X> curry() {
            return a -> b -> c -> d -> apply(a, b, c, d);
        }
    }

    /**
     * Function of arity 5.
     * @param <A>       the function's first argument type
     * @param <B>       the function's second argument type
     * @param <C>       the function's third argument type
     * @param <D>       the function's fourth argument type
     * @param <E>       the function's fifth argument type
     * @param <R>       the function's return type
     * @param <X>       the exception type
     */
    @FunctionalInterface
    public interface F5<A, B, C, D, E, R, X extends Exception> {
        /**
         * Static constructor.
         * @param f         the function
         * @param <A>       the function's first argument type
         * @param <B>       the function's second argument type
         * @param <C>       the function's third argument type
         * @param <D>       the function's fourth argument type
         * @param <E>       the function's fifth argument type
         * @param <R>       the function's return type
         * @param <X>       the exception type
         * @return          the function
         */
        static <A, B, C, D, E, R, X extends Exception> F5<A, B, C, D, E, R, X> of(
                F5<A, B, C, D, E, R, X> f) {
            return f;
        }

        /**
         * Convert an curried function to its uncurried equivalent.
         * @param f         the curried function
         * @param <A>       the function's first argument type
         * @param <B>       the function's second argument type
         * @param <C>       the function's third argument type
         * @param <D>       the function's fourth argument type
         * @param <E>       the function's fifth argument type
         * @param <R>       the function's return type
         * @param <X>       the exception type
         * @return          the uncurried function
         */
        static <A, B, C, D, E, R, X extends Exception> F5<A, B, C, D, E, R, X> uncurry(
                F<A, F<B, F<C, F<D, F<E, R, X>, X>, X>, X>, X> f) {
            return (a, b, c, d, e) -> f.apply(a).apply(b).apply(c).apply(d).apply(e);
        }

        /**
         * Apply this function.
         * @param a         the function's first argument
         * @param b         the function's second argument
         * @param c         the function's third argument
         * @param d         the function's fourth argument
         * @param e         the function's fifth argument
         * @return          the result of applying this function
         * @throws X         exception
         */
        R apply(A a, B b, C c, D d, E e) throws X;

        /**
         * Partially apply this function to one value.
         * @param a         the first value
         * @return          the partially applied function
         */
        default F4<B, C, D, E, R, X> partial(A a) {
            return (b, c, d, e) -> apply(a, b, c, d, e);
        }

        /**
         * Partially apply this function to two values.
         * @param a         the first value
         * @param b         the second value
         * @return          the partially applied function
         */
        default F3<C, D, E, R, X> partial(A a, B b) {
            return (c, d, e) -> apply(a, b, c, d, e);
        }

        /**
         * Partially apply this function to three values.
         * @param a         the first value
         * @param b         the second value
         * @param c         the third value
         * @return          the partially applied function
         */
        default F2<D, E, R, X> partial(A a, B b, C c) {
            return (d, e) -> apply(a, b, c, d, e);
        }

        /**
         * Partially apply this function to four values.
         * @param a         the first value
         * @param b         the second value
         * @param c         the third value
         * @param d         the fourth value
         * @return          the partially applied function
         */
        default F<E, R, X> partial(A a, B b, C c, D d) {
            return e -> apply(a, b, c, d, e);
        }

        /**
         * Convert this function to its curried equivalent.
         * @return          the curried equivalent of this function
         */
        default F<A, F<B, F<C, F<D, F<E, R, X>, X>, X>, X>, X> curry() {
            return a -> b -> c -> d -> e -> apply(a, b, c, d, e);
        }
    }

    /**
     * Function of arity 6.
     * @param <A>       the function's first argument type
     * @param <B>       the function's second argument type
     * @param <C>       the function's third argument type
     * @param <D>       the function's fourth argument type
     * @param <E>       the function's fifth argument type
     * @param <G>       the function's sixth argument type
     * @param <R>       the function's return type
     * @param <X>       the exception type
     */
    @FunctionalInterface
    public interface F6<A, B, C, D, E, G, R, X extends Exception> {
        /**
         * Static constructor.
         * @param f         the function
         * @param <A>       the function's first argument type
         * @param <B>       the function's second argument type
         * @param <C>       the function's third argument type
         * @param <D>       the function's fourth argument type
         * @param <E>       the function's fifth argument type
         * @param <G>       the function's sixth argument type
         * @param <R>       the function's return type
         * @param <X>       the exception type
         * @return          the function
         */
        static <A, B, C, D, E, G, R, X extends Exception> F6<A, B, C, D, E, G, R, X> of(
                F6<A, B, C, D, E, G, R, X> f) {
            return f;
        }

        /**
         * Convert an curried function to its uncurried equivalent.
         * @param f         the curried function
         * @param <A>       the function's first argument type
         * @param <B>       the function's second argument type
         * @param <C>       the function's third argument type
         * @param <D>       the function's fourth argument type
         * @param <E>       the function's fifth argument type
         * @param <G>       the function's sixth argument type
         * @param <R>       the function's return type
         * @param <X>       the exception type
         * @return          the uncurried function
         */
        static <A, B, C, D, E, G, R, X extends Exception> F6<A, B, C, D, E, G, R, X> uncurry(
                F<A, F<B, F<C, F<D, F<E, F<G, R, X>, X>, X>, X>, X>, X> f) {
            return (a, b, c, d, e, g) -> f.apply(a).apply(b).apply(c).apply(d).apply(e).apply(g);
        }

        /**
         * Apply this function.
         * @param a         the function's first argument
         * @param b         the function's second argument
         * @param c         the function's third argument
         * @param d         the function's fourth argument
         * @param e         the function's fifth argument
         * @param g         the function's sixth argument
         * @return          the result of applying this function
         * @throws          X the exception
         */
        R apply(A a, B b, C c, D d, E e, G g) throws X;

        /**
         * Partially apply this function to one value.
         * @param a         the first value
         * @return          the partially applied function
         */
        default F5<B, C, D, E, G, R, X> partial(A a) {
            return (b, c, d, e, g) -> apply(a, b, c, d, e, g);
        }

        /**
         * Partially apply this function to two values.
         * @param a         the first value
         * @param b         the second value
         * @return          the partially applied function
         */
        default F4<C, D, E, G, R, X> partial(A a, B b) {
            return (c, d, e, g) -> apply(a, b, c, d, e, g);
        }

        /**
         * Partially apply this function to three values.
         * @param a         the first value
         * @param b         the second value
         * @param c         the third value
         * @return          the partially applied function
         */
        default F3<D, E, G, R, X> partial(A a, B b, C c) {
            return (d, e, g) -> apply(a, b, c, d, e, g);
        }

        /**
         * Partially apply this function to four values.
         * @param a         the first value
         * @param b         the second value
         * @param c         the third value
         * @param d         the fourth value
         * @return          the partially applied function
         */
        default F2<E, G, R, X> partial(A a, B b, C c, D d) {
            return (e, g) -> apply(a, b, c, d, e, g);
        }

        /**
         * Partially apply this function to five values.
         * @param a         the first value
         * @param b         the second value
         * @param c         the third value
         * @param d         the fourth value
         * @param e         the fifth value
         * @return          the partially applied function
         */
        default F<G, R, X> partial(A a, B b, C c, D d, E e) {
            return g -> apply(a, b, c, d, e, g);
        }

        /**
         * Convert this function to its curried equivalent.
         * @return          the curried equivalent of this function
         */
        default F<A, F<B, F<C, F<D, F<E, F<G, R, X>, X>, X>, X>, X>, X> curry() {
            return a -> b -> c -> d -> e -> g -> apply(a, b, c, d, e, g);
        }
    }

    /**
     * Function of arity 7.
     * @param <A>       the function's first argument type
     * @param <B>       the function's second argument type
     * @param <C>       the function's third argument type
     * @param <D>       the function's fourth argument type
     * @param <E>       the function's fifth argument type
     * @param <G>       the function's sixth argument type
     * @param <H>       the function's seventh argument type
     * @param <R>       the function's return type
     * @param <X>       the exception type
     */
    @FunctionalInterface
    public interface F7<A, B, C, D, E, G, H, R, X extends Exception> {
        /**
         * Static constructor.
         * @param f         the function
         * @param <A>       the function's first argument type
         * @param <B>       the function's second argument type
         * @param <C>       the function's third argument type
         * @param <D>       the function's fourth argument type
         * @param <E>       the function's fifth argument type
         * @param <G>       the function's sixth argument type
         * @param <H>       the function's seventh argument type
         * @param <R>       the function's return type
         * @param <X>       the exception type
         * @return          the function
         */
        static <A, B, C, D, E, G, H, R, X extends Exception> F7<A, B, C, D, E, G, H, R, X> of(
                F7<A, B, C, D, E, G, H, R, X> f) {
            return f;
        }

        /**
         * Convert an curried function to its uncurried equivalent.
         * @param f         the curried function
         * @param <A>       the function's first argument type
         * @param <B>       the function's second argument type
         * @param <C>       the function's third argument type
         * @param <D>       the function's fourth argument type
         * @param <E>       the function's fifth argument type
         * @param <G>       the function's sixth argument type
         * @param <H>       the function's seventh argument type
         * @param <R>       the function's return type
         * @param <X>       the exception type
         * @return          the uncurried function
         */
        static <A, B, C, D, E, G, H, R, X extends Exception> F7<A, B, C, D, E, G, H, R, X> uncurry(
                F<A, F<B, F<C, F<D, F<E, F<G, F<H, R, X>, X>, X>, X>, X>, X>, X> f) {
            return (a, b, c, d, e, g, h) -> f.apply(a).apply(b).apply(c).apply(d).apply(e).apply(g).apply(h);
        }

        /**
         * Apply this function.
         * @param a         the function's first argument
         * @param b         the function's second argument
         * @param c         the function's third argument
         * @param d         the function's fourth argument
         * @param e         the function's fifth argument
         * @param g         the function's sixth argument
         * @param h         the function's seventh argument
         * @return          the result of applying this function
         * @throws          X the exception
         */
        R apply(A a, B b, C c, D d, E e, G g, H h) throws X;

        /**
         * Partially apply this function to one value.
         * @param a         the first value
         * @return          the partially applied function
         */
        default F6<B, C, D, E, G, H, R, X> partial(A a) {
            return (b, c, d, e, g, h) -> apply(a, b, c, d, e, g, h);
        }

        /**
         * Partially apply this function to two value.
         * @param a         the first value
         * @param b         the second value
         * @return          the partially applied function
         */
        default F5<C, D, E, G, H, R, X> partial(A a, B b) {
            return (c, d, e, g, h) -> apply(a, b, c, d, e, g, h);
        }

        /**
         * Partially apply this function to three values.
         * @param a         the first value
         * @param b         the second value
         * @param c         the third value
         * @return          the partially applied function
         */
        default F4<D, E, G, H, R, X> partial(A a, B b, C c) {
            return (d, e, g, h) -> apply(a, b, c, d, e, g, h);
        }

        /**
         * Partially apply this function to four values.
         * @param a         the first value
         * @param b         the second value
         * @param c         the third value
         * @param d         the fourth value
         * @return          the partially applied function
         */
        default F3<E, G, H, R, X> partial(A a, B b, C c, D d) {
            return (e, g, h) -> apply(a, b, c, d, e, g, h);
        }

        /**
         * Partially apply this function to five values.
         * @param a         the first value
         * @param b         the second value
         * @param c         the third value
         * @param d         the fourth value
         * @param e         the fifth value
         * @return          the partially applied function
         */
        default F2<G, H, R, X> partial(A a, B b, C c, D d, E e) {
            return (g, h) -> apply(a, b, c, d, e, g, h);
        }

        /**
         * Partially apply this function to six values.
         * @param a         the first value
         * @param b         the second value
         * @param c         the third value
         * @param d         the fourth value
         * @param e         the fifth value
         * @param g         the sixth value
         * @return          the partially applied function
         */
        default F<H, R, X> partial(A a, B b, C c, D d, E e, G g) {
            return h -> apply(a, b, c, d, e, g, h);
        }

        /**
         * Convert this function to its curried equivalent.
         * @return          the curried equivalent of this function
         */
        default F<A, F<B, F<C, F<D, F<E, F<G, F<H, R, X>, X>, X>, X>, X>, X>, X> curry() {
            return a -> b -> c -> d -> e -> g -> h -> apply(a, b, c, d, e, g, h);
        }
    }

    /**
     * Function of arity 8.
     * @param <A>       the function's first argument type
     * @param <B>       the function's second argument type
     * @param <C>       the function's third argument type
     * @param <D>       the function's fourth argument type
     * @param <E>       the function's fifth argument type
     * @param <G>       the function's sixth argument type
     * @param <H>       the function's seventh argument type
     * @param <I>       the function's eighth argument type
     * @param <R>       the function's return type
     * @param <X>       the exception type
     */
    @FunctionalInterface
    public interface F8<A, B, C, D, E, G, H, I, R, X extends Exception> {
        /**
         * Static constructor.
         * @param f         the function
         * @param <A>       the function's first argument type
         * @param <B>       the function's second argument type
         * @param <C>       the function's third argument type
         * @param <D>       the function's fourth argument type
         * @param <E>       the function's fifth argument type
         * @param <G>       the function's sixth argument type
         * @param <H>       the function's seventh argument type
         * @param <I>       the function's eighth argument type
         * @param <R>       the function's return type
         * @param <X>       the exception type
         * @return          the function
         */
        static <A, B, C, D, E, G, H, I, R, X extends Exception> F8<A, B, C, D, E, G, H, I, R, X> of(
                F8<A, B, C, D, E, G, H, I, R, X> f) {
            return f;
        }

        /**
         * Convert an curried function to its uncurried equivalent.
         * @param f         the curried function
         * @param <A>       the function's first argument type
         * @param <B>       the function's second argument type
         * @param <C>       the function's third argument type
         * @param <D>       the function's fourth argument type
         * @param <E>       the function's fifth argument type
         * @param <G>       the function's sixth argument type
         * @param <H>       the function's seventh argument type
         * @param <I>       the function's eighth argument type
         * @param <R>       the function's return type
         * @param <X>       the exception type
         * @return          the uncurried function
         */
        static <A, B, C, D, E, G, H, I, R, X extends Exception> F8<A, B, C, D, E, G, H, I, R, X> uncurry(
                F<A, F<B, F<C, F<D, F<E, F<G, F<H, F<I, R, X>, X>, X>, X>, X>, X>, X>, X> f) {
            return (a, b, c, d, e, g, h, i) ->
                    f.apply(a).apply(b).apply(c).apply(d).apply(e).apply(g).apply(h).apply(i);
        }

        /**
         * Apply this function.
         * @param a         the function's first argument
         * @param b         the function's second argument
         * @param c         the function's third argument
         * @param d         the function's fourth argument
         * @param e         the function's fifth argument
         * @param g         the function's sixth argument
         * @param h         the function's seventh argument
         * @param i         the function's eighth argument
         * @return          the result of applying this function
         * @throws          X the exception
         */
        R apply(A a, B b, C c, D d, E e, G g, H h, I i) throws X;

        /**
         * Partially apply this function to one value.
         * @param a         the first value
         * @return          the partially applied function
         */
        default F7<B, C, D, E, G, H, I, R, X> partial(A a) {
            return (b, c, d, e, g, h, i) -> apply(a, b, c, d, e, g, h, i);
        }

        /**
         * Partially apply this function to two value.
         * @param a         the first value
         * @param b         the second value
         * @return          the partially applied function
         */
        default F6<C, D, E, G, H, I, R, X> partial(A a, B b) {
            return (c, d, e, g, h, i) -> apply(a, b, c, d, e, g, h, i);
        }

        /**
         * Partially apply this function to three values.
         * @param a         the first value
         * @param b         the second value
         * @param c         the third value
         * @return          the partially applied function
         */
        default F5<D, E, G, H, I, R, X> partial(A a, B b, C c) {
            return (d, e, g, h, i) -> apply(a, b, c, d, e, g, h, i);
        }

        /**
         * Partially apply this function to four values.
         * @param a         the first value
         * @param b         the second value
         * @param c         the third value
         * @param d         the fourth value
         * @return          the partially applied function
         */
        default F4<E, G, H, I, R, X> partial(A a, B b, C c, D d) {
            return (e, g, h, i) -> apply(a, b, c, d, e, g, h, i);
        }

        /**
         * Partially apply this function to five values.
         * @param a         the first value
         * @param b         the second value
         * @param c         the third value
         * @param d         the fourth value
         * @param e         the fifth value
         * @return          the partially applied function
         */
        default F3<G, H, I, R, X> partial(A a, B b, C c, D d, E e) {
            return (g, h, i) -> apply(a, b, c, d, e, g, h, i);
        }

        /**
         * Partially apply this function to six values.
         * @param a         the first value
         * @param b         the second value
         * @param c         the third value
         * @param d         the fourth value
         * @param e         the fifth value
         * @param g         the sixth value
         * @return          the partially applied function
         */
        default F2<H, I, R, X> partial(A a, B b, C c, D d, E e, G g) {
            return (h, i) -> apply(a, b, c, d, e, g, h, i);
        }

        /**
         * Partially apply this function to seven values.
         * @param a         the first value
         * @param b         the second value
         * @param c         the third value
         * @param d         the fourth value
         * @param e         the fifth value
         * @param g         the sixth value
         * @param h         the seventh value
         * @return          the partially applied function
         */
        default F<I, R, X> partial(A a, B b, C c, D d, E e, G g, H h) {
            return i -> apply(a, b, c, d, e, g, h, i);
        }

        /**
         * Convert this function to its curried equivalent.
         * @return          the curried equivalent of this function
         */
        default F<A, F<B, F<C, F<D, F<E, F<G, F<H, F<I, R, X>, X>, X>, X>, X>, X>, X>, X> curry() {
            return a -> b -> c -> d -> e -> g -> h -> i -> apply(a, b, c, d, e, g, h, i);
        }
    }

    /**
     * Unary operator function.
     * @param <T>       the operand type
     * @param <X>       the exception type
     */
    @FunctionalInterface
    public interface Op<T, X extends Exception> extends F<T, T, X> {
        /**
         * Static constructor
         * @param op        the operator function
         * @param <T>       the operand type
         * @param <X>       the exception type
         * @return          the operator function
         */
        static <T, X extends Exception> Op<T, X> of(Op<T, X> op) {
            return op;
        }
    }

    /**
     * Binary operator function.
     * @param <T>       the operand type
     * @param <X>       the exception type
     */
    @FunctionalInterface
    public interface Op2<T, X extends Exception> extends F2<T, T, T, X> {
        /**
         * Static constructor
         * @param op        the operator function
         * @param <T>       the operand type
         * @param <X>       the exception type
         * @return          the operator function
         */
        static <T, X extends Exception> Op2<T, X> of(Op2<T, X> op) {
            return op;
        }

        /**
         * Flip this function by reversing the order of its arguments.
         * @return          the flipped function
         */
        default Op2<T, X> flip() {
            return (b, a) -> apply(a, b);
        }
    }

    /**
     * Predicate function
     * @param <T>       the operand type
     * @param <X>       the exception type
     */
    @FunctionalInterface
    public interface Predicate<T, X extends Exception> extends F<T, Boolean, X> {
        /**
         * Static constructor
         * @param pr        the predicate function
         * @param <T>       the operand type
         * @param <X>       the exception type
         * @return          the predicate function
         */
        static <T, X extends Exception> Predicate<T, X> of(Predicate<T, X> pr) {
            return pr;
        }

        /**
         * Return a {@code Predicate} that checks if a value is null
         * @param <T>       the operand type
         * @param <X>       the exception type
         * @return          a {@code Predicate} that checks if a value is null
         */
        static <T, X extends Exception> Predicate<T, X> isNull() {
            return Objects::isNull;
        }

        /**
         * Return a {@code Predicate} that checks if a value is equal to the given value
         * @param lhs       the value to compare against
         * @param <T>       the operand type
         * @param <X>       the exception type
         * @return          a {@code Predicate} that checks if a value is equal to the given value
         */
        static <T, X extends Exception> Predicate<T, X> isEqual(Object lhs) {
            return (lhs == null)
                    ? isNull()
                    : lhs::equals;
        }

        /**
         * Invert this {@code Predicate}
         * @return          a {@code Predicate} that logically inverts this {@code Predicate}
         */
        default Predicate<T, X> negate() {
            return t -> !apply(t);
        }

        /**
         * Compose this {@code Predicate} with another by logically and'ing them.
         * @param rhs       other {@code Predicate}
         * @return          a {@code Predicate} that returns true iff both {@code Predicate}s return true
         */
        default Predicate<T, X> and(Predicate<? super T, X> rhs) {
            Objects.requireNonNull(rhs);
            return t -> apply(t) && rhs.apply(t);
        }

        /**
         * Compose this {@code Predicate} with another by logically or'ing them.
         * @param rhs       other {@code Predicate}
         * @return          a {@code Predicate} that returns true if either {@code Predicate}s return true
         */
        default Predicate<T, X> or(Predicate<? super T, X> rhs) {
            Objects.requireNonNull(rhs);
            return t -> apply(t) ||  rhs.apply(t);
        }
    }
}


text:
class AlembicWriteJob;

class AlembicObject
{
private:
   XSI::CRefArray mRefs;
   AlembicWriteJob * mJob;
   Abc::OObject mMyParent;
protected:

   int mNumSamples;

  enum refType{
     REF_NODE,
     REF_PRIMITIVE,
     REF_GLOBAL_TRANS,
     REF_PARENT_GLOBAL_TRANS
  };

public:

   SceneNodePtr mExoSceneNode;

   AlembicObject(SceneNodePtr eNode, AlembicWriteJob * in_Job, Abc::OObject oParent);
   ~AlembicObject();

   AlembicWriteJob * GetJob() { return mJob; }
   const XSI::CRef & GetRef(ULONG index = 0) { return mRefs[index]; }
   ULONG GetRefCount() { return mRefs.GetCount(); }
   void AddRef(const XSI::CRef & in_Ref) { mRefs.Add(in_Ref); }
   Abc::OObject GetMyParent() { return mMyParent; }
   virtual Abc::OCompoundProperty GetCompound() = 0;
   int GetNumSamples() { return mNumSamples; }

   //std::string GetXfoName();

   virtual XSI::CStatus Save(double time) = 0;
};

typedef boost::shared_ptr < AlembicObject > AlembicObjectPtr;

class alembic_UD
{
public:
   alembic_UD(ULONG in_id);
   ~alembic_UD();

   double lastTime;

   std::vector<double> times;
   std::map<size_t,Abc::M44d> indexToMatrices;

   static void clearAll();

private:
   ULONG id;
   static std::map<ULONG,alembic_UD*> gAlembicUDs;

};

#include "AlembicWriteJob.h"

#endif

redpajama_set_name: RedPajamaGithub


text:
@class DBFILESSearchMode;

#pragma mark - API Object

///
/// The `SearchMode` union.
///
/// This class implements the `DBSerializable` protocol (serialize and
/// deserialize instance methods), which is required for all Obj-C SDK API route
/// objects.
///
@interface DBFILESSearchMode : NSObject <DBSerializable, NSCopying>

#pragma mark - Instance fields

/// The `DBFILESSearchModeTag` enum type represents the possible tag states with
/// which the `DBFILESSearchMode` union can exist.
typedef NS_ENUM(NSInteger, DBFILESSearchModeTag) {
  /// Search file and folder names.
  DBFILESSearchModeFilename,

  /// Search file and folder names as well as file contents.
  DBFILESSearchModeFilenameAndContent,

  /// Search for deleted file and folder names.
  DBFILESSearchModeDeletedFilename,

};

/// Represents the union's current tag state.
@property (nonatomic, readonly) DBFILESSearchModeTag tag;

#pragma mark - Constructors

///
/// Initializes union class with tag state of "filename".
///
/// Description of the "filename" tag state: Search file and folder names.
///
/// @return An initialized instance.
///
- (nonnull instancetype)initWithFilename;

///
/// Initializes union class with tag state of "filename_and_content".
///
/// Description of the "filename_and_content" tag state: Search file and folder
/// names as well as file contents.
///
/// @return An initialized instance.
///
- (nonnull instancetype)initWithFilenameAndContent;

///
/// Initializes union class with tag state of "deleted_filename".
///
/// Description of the "deleted_filename" tag state: Search for deleted file and
/// folder names.
///
/// @return An initialized instance.
///
- (nonnull instancetype)initWithDeletedFilename;

- (nonnull instancetype)init NS_UNAVAILABLE;

#pragma mark - Tag state methods

///
/// Retrieves whether the union's current tag state has value "filename".
///
/// @return Whether the union's current tag state has value "filename".
///
- (BOOL)isFilename;

///
/// Retrieves whether the union's current tag state has value
/// "filename_and_content".
///
/// @return Whether the union's current tag state has value
/// "filename_and_content".
///
- (BOOL)isFilenameAndContent;

///
/// Retrieves whether the union's current tag state has value
/// "deleted_filename".
///
/// @return Whether the union's current tag state has value "deleted_filename".
///
- (BOOL)isDeletedFilename;

///
/// Retrieves string value of union's current tag state.
///
/// @return A human-readable string representing the union's current tag state.
///
- (NSString * _Nonnull)tagName;

@end

#pragma mark - Serializer Object

///
/// The serialization class for the `DBFILESSearchMode` union.
///
@interface DBFILESSearchModeSerializer : NSObject

///
/// Serializes `DBFILESSearchMode` instances.
///
/// @param instance An instance of the `DBFILESSearchMode` API object.
///
/// @return A json-compatible dictionary representation of the
/// `DBFILESSearchMode` API object.
///
+ (NSDictionary * _Nonnull)serialize:(DBFILESSearchMode * _Nonnull)instance;

///
/// Deserializes `DBFILESSearchMode` instances.
///
/// @param dict A json-compatible dictionary representation of the
/// `DBFILESSearchMode` API object.
///
/// @return An instantiation of the `DBFILESSearchMode` object.
///
+ (DBFILESSearchMode * _Nonnull)deserialize:(NSDictionary * _Nonnull)dict;

@end


text:
\chapter{Spezielle Anforderungen an die Entwicklungs-Umgebung}

	\section{Software}

		Für die Entwicklung ist das vorgegebene GitLab-Repository zu verwenden.

	\section{Hardware}

		Das Produkt muss auf den Rechnern des SCI entwickelt werden oder zumindest dort lauffähig sein.


text:
package org.remoteui.demo.apps.calculator;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.sourceforge.jeval.EvaluationException;
import net.sourceforge.jeval.Evaluator;

import org.remoteui.annotation.Activity;
import org.remoteui.webapp.WebActivity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Example "app" - a scientific calculator.
 *
 * @author Daniel Thommes
 */
@Activity(id = "scientificCalc", layout = "calculator.layout.mv")
public class ScientificCalculatorActivity extends WebActivity {

	/**
	 * SLF4J Logger
	 */
	private static final Logger logger = LoggerFactory
			.getLogger(ScientificCalculatorActivity.class);

	private Evaluator evaluator = new Evaluator();

	private String calculation = "";

	private String ans = "";

	private static Map<Pattern, String> patterns = new LinkedHashMap<Pattern, String>();

	static {
		patterns.put(Pattern.compile("e"), "2.718281828459045");
		patterns.put(Pattern.compile("π"), "(2*asin(1))");
		patterns.put(Pattern.compile("√(-?\\d+\\.?\\d*)"), "sqrt($1)");
		patterns.put(Pattern.compile("sin(-?\\d+\\.?\\d*)"), "sin($1)");
		patterns.put(Pattern.compile("asin(-?\\d+\\.?\\d*)"), "asin($1)");
		patterns.put(Pattern.compile("cos(-?\\d+\\.?\\d*)"), "cos($1)");
		patterns.put(Pattern.compile("acos(-?\\d+\\.?\\d*)"), "acos($1)");
		patterns.put(Pattern.compile("tan(-?\\d+\\.?\\d*)"), "tan($1)");
		patterns.put(Pattern.compile("atan(-?\\d+\\.?\\d*)"), "atan($1)");
		// log y = ln y / ln 10
		patterns.put(Pattern.compile("log(-?\\d+\\.?\\d*)"), "log($1)/log(10)");
		patterns.put(Pattern.compile("ld(-?\\d+\\.?\\d*)"), "log($1)/log(2)");
		patterns.put(Pattern.compile("ln(-?\\d+\\.?\\d*)"), "log($1)");
		patterns.put(Pattern.compile("E(-?\\d+\\.?\\d*)"), "*10^$1");
		patterns.put(Pattern.compile("²"), "^2");
		patterns.put(Pattern.compile("³"), "^3");
		patterns.put(Pattern.compile("(-?\\d+\\.?\\d*)\\^(-?\\d+\\.?\\d*)"), "pow($1,$2)");
		patterns.put(Pattern.compile("x"), "*");
	}

	public String getCalculation() {
		return calculation;
	}

	public void append(String text) {
		calculation += text;
		firePropertyChanged("calculation");
	}

	public void onAcClicked() {
		calculation = "";
		firePropertyChanged("calculation");
	}

	public void onBackSpace() {
		if (calculation.length() > 0) {
			calculation = calculation.substring(0, calculation.length() - 1);
			firePropertyChanged("calculation");
		}
	}

	public void onAnsClicked() {
		calculation += ans;
		firePropertyChanged("calculation");
	}

	public void onEvaluate() {
		try {
			for (Entry<Pattern, String> replacement : patterns.entrySet()) {
				Matcher matcher = replacement.getKey().matcher(calculation);
				if (matcher.find()) {
					calculation = matcher.replaceAll(replacement.getValue());
				}
			}
			logger.debug("{}", calculation);
			calculation = evaluator.evaluate(calculation);
			ans = calculation;
		} catch (EvaluationException e) {
			calculation = e.getMessage();
		}
		firePropertyChanged("calculation");
	}
}


text:
@interface UNWebView : UIViewController
@property(nonatomic,strong)NSString *html;
//@property(nonatomic,strong)UIColor *UNNavColor;
@end


text:
<?php
	// Quick Reference
	// HTML Tidy Configuration Options
	// http://tidy.sourceforge.net/docs/quickref.html
	$config = array(
		"show-body-only"		=> true,
		"wrap"					=> 0,
		"tab-size" 				=> 2,
		"indent-spaces" 		=> 2,
		"indent"         		=> "auto",
		"logical-emphasis"		=> true,
		"fix-uri"				=> true,
		"quote-ampersand"		=> true,
		"enclose-block-text"	=> true,
		"drop-empty-paras"		=> true,
		"output-xhtml"   		=> true,
		"vertical-space"		=> true
	);

	$excludedWarnings = array(
		"missing <!DOCTYPE> declaration",
		"inserting missing 'title' element",
		"inserting implicit <body>",
		"plain text isn't allowed in <head> elements"
	);
?>


text:
<?php

/**
 * Log Online visitors collection
 *
 * @category    Mage
 * @package     Mage_Log
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Mage_Log_Model_Mysql4_Visitor_Online_Collection extends Mage_Log_Model_Resource_Visitor_Online_Collection
{
}


text:
By following this guide, you'll set up a development environment, deploy an app locally and on Bluemix, and integrate a Bluemix database service in your app.

## Prerequisites

You'll need a [Bluemix account](https://console.ng.bluemix.net/registration/), [Git](https://git-scm.com/downloads) [Cloud Foundry CLI](https://github.com/cloudfoundry/cli#downloads) and [Node](https://nodejs.org/en/)

## 1. Clone the sample app

Now you're ready to start working with the simple Node.js *hello world* app. Clone the repository and change to the directory to where the sample app is located.
  ```
  git clone https://github.com/IBM-Bluemix/get-started-node
  ```

  ```
  cd get-started-node
  ```

  Peruse the files in the *get-started-node* directory to familiarize yourself with the contents.

## 2. Run the app locally

Install the dependencies listed in the [package.json](https://docs.npmjs.com/files/package.json) file to run the app locally.
  ```
  npm install
  ```

Run the app.
  ```
  npm start
  ```

View your app at: http://localhost:3000

## 3. Prepare the app for deployment

To deploy to Bluemix, it can be helpful to set up a manifest.yml file. One is provided for you with the sample. Take a moment to look at it.

The manifest.yml includes basic information about your app, such as the name, how much memory to allocate for each instance and the route. In this manifest.yml **random-route: true** generates a random route for your app to prevent your route from colliding with others.  You can replace **random-route: true** with **host: myChosenHostName**, supplying a host name of your choice. [Learn more...](https://console.bluemix.net/docs/manageapps/depapps.html#appmanifest)
 ```
 applications:
 - name: nodejs-helloworld
   random-route: true
   memory: 128M
 ```

## 4. Deploy the app

You can use the Cloud Foundry CLI to deploy apps.

Choose your API endpoint
   ```
   cf api <API-endpoint>
   ```

Replace the *API-endpoint* in the command with an API endpoint from the following list.
  ```
  https://api.ng.bluemix.net # US South
  https://api.eu-gb.bluemix.net # United Kingdom
  https://api.au-syd.bluemix.net # Sydney
  ```

Login to your Bluemix account

  ```
  cf login
  ```

From within the *nodejs-helloworld* directory push your app to Bluemix
  ```
  cf push
  ```

This can take a minute. If there is an error in the deployment process you can use the command `cf logs <Your-App-Name> --recent` to troubleshoot.

View your app at the URL listed in the output of the push command, for example, *myUrl.mybluemix.net*.  You can issue the
```
cf apps
```
command to view your apps status and see the URL.

## 5. Add a database

Next, we'll add a NoSQL database to this application and set up the application so that it can run locally and on Bluemix.

1. Log in to Bluemix in your Browser. Select your application and click on `Connect new` under `Connections`.
2. Select `Cloudant NoSQL DB` and Create the service.
3. Select `Restage` when prompted. Bluemix will restart your application and provide the database credentials to your application using the `VCAP_SERVICES` environment variable. This environment variable is only available to the application when it is running on Bluemix.

## 6. Use the database

We're now going to update your local code to point to this database. We'll create a json file that will store the credentials for the services the application will use. This file will get used ONLY when the application is running locally. When running in Bluemix, the credentials will be read from the VCAP_SERVICES environment variable.

1. Create a file called `vcap-local.json` in the `nodejs-helloworld` directory with the following content:
  ```
  {
    "services": {
      "cloudantNoSQLDB": [
        {
          "credentials": {
            "url":"CLOUDANT_DATABASE_URL"
          },
          "label": "cloudantNoSQLDB"
        }
      ]
    }
  }
  ```

2. Back in the Bluemix UI, select your App -> Connections -> Cloudant -> View Credentials

3. Copy and paste just the `url` from the credentials to the `url` field of the `vcap-local.json` file.

4. Run your application locally.
  ```
  npm start
  ```

  View your app at: http://localhost:3000. Any names you enter into the app will now get added to the database.

  Tip: Use [nodemon](https://nodemon.io/) to automatically restart the application when you update code.

5. Make any changes you want and re-deploy to Bluemix!
  ```
  cf push
  ```


text:
package com.vasilkoff.android.Sync.model;

import android.content.ContentResolver;
import android.net.Uri;

import com.vasilkoff.android.Sync.provider.DataContract;

/**
 * Created by maxim.vasilkov@gmail.com on 24/08/15.
 */
public class UserObject  extends ModelObject {

    public String username;
    public String picture_path;

    /**
     * MIME type for lists of entries.
     */
    public static final String getCONTENT_TYPE() {
        return ContentResolver.CURSOR_DIR_BASE_TYPE + "/vnd.jsonsyncadapter.users";
    }
    /**
     * MIME type for individual entries.
     */
    public static final String getCONTENT_ITEM_TYPE() {
        return ContentResolver.CURSOR_ITEM_BASE_TYPE + "/vnd.jsonsyncadapter.user";
    }

    /**
     * Fully qualified URI for "entry" resources.
     */
    public static final Uri getCONTENT_URI() {
        return DataContract.BASE_CONTENT_URI.buildUpon().appendPath("users").build();
    }

    public static String[] getProjection() {
        return getProjection(UserObject.class);
    }
}


text:
using System;
using System.Collections;
using Server.Targeting;
using Server.Network;

namespace Server.Spells.Second
{
	public class ProtectionSpell : MagerySpell
	{
		private static Hashtable m_Registry = new Hashtable();
		public static Hashtable Registry { get { return m_Registry; } }

		private static SpellInfo m_Info = new SpellInfo(
				"Protection", "Uus Sanct",
				236,
				9011,
				Reagent.Garlic,
				Reagent.Ginseng,
				Reagent.SulfurousAsh
			);

		public override SpellCircle Circle { get { return SpellCircle.Second; } }

		public ProtectionSpell( Mobile caster, Item scroll ) : base( caster, scroll, m_Info )
		{
		}

		public override bool CheckCast()
		{
			if ( Core.AOS )
				return true;

			if ( m_Registry.ContainsKey( Caster ) )
			{
				Caster.SendLocalizedMessage( 1005559 ); // This spell is already in effect.
				return false;
			}
			else if ( !Caster.CanBeginAction( typeof( DefensiveSpell ) ) )
			{
				Caster.SendLocalizedMessage( 1005385 ); // The spell will not adhere to you at this time.
				return false;
			}

			return true;
		}

		private static Hashtable m_Table = new Hashtable();

		public static void Toggle( Mobile caster, Mobile target )
		{
			/* Players under the protection spell effect can no longer have their spells "disrupted" when hit.
			 * Players under the protection spell have decreased physical resistance stat value (-15 + (Inscription/20),
			 * a decreased "resisting spells" skill value by -35 + (Inscription/20),
			 * and a slower casting speed modifier (technically, a negative "faster cast speed") of 2 points.
			 * The protection spell has an indefinite duration, becoming active when cast, and deactivated when re-cast.
			 * Reactive Armor, Protection, and Magic Reflection will stay on—even after logging out,
			 * even after dying—until you "turn them off" by casting them again.
			 */

			object[] mods = (object[])m_Table[target];

			if ( mods == null )
			{
				target.PlaySound( 0x1E9 );
				target.FixedParticles( 0x375A, 9, 20, 5016, EffectLayer.Waist );

				mods = new object[2]
					{
						new ResistanceMod( ResistanceType.Physical, -15 + Math.Min( (int)(caster.Skills[SkillName.Inscribe].Value / 20), 15 ) ),
						new DefaultSkillMod( SkillName.MagicResist, true, -35 + Math.Min( (int)(caster.Skills[SkillName.Inscribe].Value / 20), 35 ) )
					};

				m_Table[target] = mods;
				Registry[target] = 100.0;

				target.AddResistanceMod( (ResistanceMod)mods[0] );
				target.AddSkillMod( (SkillMod)mods[1] );

				int physloss = -15 + (int) (caster.Skills[SkillName.Inscribe].Value / 20);
				int resistloss = -35 + (int) (caster.Skills[SkillName.Inscribe].Value / 20);
				string args = String.Format("{0}\t{1}", physloss, resistloss);
				BuffInfo.AddBuff(target, new BuffInfo(BuffIcon.Protection, 1075814, 1075815, args.ToString()));
			}
			else
			{
				target.PlaySound( 0x1ED );
				target.FixedParticles( 0x375A, 9, 20, 5016, EffectLayer.Waist );

				m_Table.Remove( target );
				Registry.Remove( target );

				target.RemoveResistanceMod( (ResistanceMod)mods[0] );
				target.RemoveSkillMod( (SkillMod)mods[1] );

				BuffInfo.RemoveBuff(target, BuffIcon.Protection);
			}
		}

        public static void EndProtection(Mobile m)
        {
            if (m_Table.Contains(m))
            {
                object[] mods = (object[])m_Table[m];

                m_Table.Remove(m);
                Registry.Remove(m);

                m.RemoveResistanceMod((ResistanceMod)mods[0]);
                m.RemoveSkillMod((SkillMod)mods[1]);

                BuffInfo.RemoveBuff(m, BuffIcon.Protection);
            }
        }

		public override void OnCast()
		{
			if ( Core.AOS )
			{
				if ( CheckSequence() )
					Toggle( Caster, Caster );

				FinishSequence();
			}
			else
			{
				if ( m_Registry.ContainsKey( Caster ) )
				{
					Caster.SendLocalizedMessage( 1005559 ); // This spell is already in effect.
				}
				else if ( !Caster.CanBeginAction( typeof( DefensiveSpell ) ) )
				{
					Caster.SendLocalizedMessage( 1005385 ); // The spell will not adhere to you at this time.
				}
				else if ( CheckSequence() )
				{
					if ( Caster.BeginAction( typeof( DefensiveSpell ) ) )
					{
						double value = (int)(Caster.Skills[SkillName.EvalInt].Value + Caster.Skills[SkillName.Meditation].Value + Caster.Skills[SkillName.Inscribe].Value);
						value /= 4;

						if ( value < 0 )
							value = 0;
						else if ( value > 75 )
							value = 75.0;

						Registry.Add( Caster, value );
						new InternalTimer( Caster ).Start();

						Caster.FixedParticles( 0x375A, 9, 20, 5016, EffectLayer.Waist );
						Caster.PlaySound( 0x1ED );
					}
					else
					{
						Caster.SendLocalizedMessage( 1005385 ); // The spell will not adhere to you at this time.
					}
				}

				FinishSequence();
			}
		}

		private class InternalTimer : Timer
		{
			private Mobile m_Caster;

			public InternalTimer( Mobile caster ) : base( TimeSpan.FromSeconds( 0 ) )
			{
				double val = caster.Skills[SkillName.Magery].Value * 2.0;
				if ( val < 15 )
					val = 15;
				else if ( val > 240 )
					val = 240;

				m_Caster = caster;
				Delay = TimeSpan.FromSeconds( val );
				Priority = TimerPriority.OneSecond;
			}

			protected override void OnTick()
			{
				ProtectionSpell.Registry.Remove( m_Caster );
				DefensiveSpell.Nullify( m_Caster );
			}
		}
	}
}


text:
require "spec_helper"

describe Mongoid::Persistable::Settable do

  describe "#set" do

    context "when the document is a root document" do

      shared_examples_for "a settable root document" do

        it "sets the normal field to the new value" do
          expect(person.title).to eq("kaiser")
        end

        it "properly sets aliased fields" do
          expect(person.test).to eq("alias-test")
        end

        it "casts fields that need typecasting" do
          expect(person.dob).to eq(date)
        end

        it "returns self object" do
          expect(set).to eq(person)
        end

        it "persists the normal field set" do
          expect(person.reload.title).to eq("kaiser")
        end

        it "persists sets on aliased fields" do
          expect(person.reload.test).to eq("alias-test")
        end

        it "persists fields that need typecasting" do
          expect(person.reload.dob).to eq(date)
        end

        it "resets the dirty attributes for the sets" do
          expect(person).to_not be_changed
        end
      end

      let(:person) do
        Person.create
      end

      let(:date) do
        Date.new(1976, 11, 19)
      end

      context "when provided string fields" do

        let!(:set) do
          person.set("title" => "kaiser", "test" => "alias-test", "dob" => date)
        end

        it_behaves_like "a settable root document"
      end

      context "when provided symbol fields" do

        let!(:set) do
          person.set(title: "kaiser", test: "alias-test", dob: date)
        end

        it_behaves_like "a settable root document"
      end
    end

    context "when the document is embedded" do

      shared_examples_for "a settable embedded document" do

        it "sets the normal field to the new value" do
          expect(address.number).to eq(44)
        end

        it "properly sets aliased fields" do
          expect(address.suite).to eq("400")
        end

        it "casts fields that need typecasting" do
          expect(address.end_date).to eq(date)
        end

        it "returns self object" do
          expect(set).to eq(address)
        end

        it "persists the normal field set" do
          expect(address.reload.number).to eq(44)
        end

        it "persists the aliased field set" do
          expect(address.reload.suite).to eq("400")
        end

        it "persists the fields that need typecasting" do
          expect(address.reload.end_date).to eq(date)
        end

        it "resets the dirty attributes for the sets" do
          expect(address).to_not be_changed
        end
      end

      let(:person) do
        Person.create
      end

      let(:address) do
        person.addresses.create(street: "t")
      end

      let(:date) do
        Date.new(1976, 11, 19)
      end

      context "when provided string fields" do

        let!(:set) do
          address.set("number" => 44, "suite" => "400", "end_date" => date)
        end

        it_behaves_like "a settable embedded document"
      end

      context "when provided symbol fields" do

        let!(:set) do
          address.set(number: 44, suite: "400", end_date: date)
        end

        it_behaves_like "a settable embedded document"
      end
    end
  end
end


text:
'use strict';

let score = 0;

// Greet and meet
const username = prompt('Welcome! What\'s your name?');
console.log('User name: ' + username);

alert('Hello, ' + username + '! I\'m going to ask you a series of yes/no questions to see how well you know me.');

// Question one: do I have sibs? Correct answer: no
function askSibs(){
    const siblings = prompt ('First, do I have any siblings?').toLowerCase();
    console.log('Siblings? Answer: ' + siblings);
    if(siblings === 'yes' || siblings   === 'y') {
        alert('Actually, ' + username + ', I\'m an only child and I was raised by a single mom. But I do have a lot of close friends that feel like siblings to me. Next question!');
    }
    else if(siblings    === 'no' || siblings   === 'n') {
        alert('Great job, ' + username + '! I do have a few step-siblings but we don\'t know each other very well. Next question!');
        score = score + 1;
    }
}

askSibs();
console.log('score:' + score);

//Question two: do I have children? Correct answer: yes
function askChildren(){
    const children = prompt ('Do I have any children of my own?' ).toLowerCase();
    console.log('Children? Answer: ' + children);
    if(children === 'yes' || children === 'y') {
        alert('That\'s right, ' + username + '! I have the sweetest, kindest, and funniest 7-year-old on the planet. His name is Oliver.');
        score = score + 1;
    }
    else if(children === 'no' || children === 'n') {
        alert('You didn\'t know, ' + username + '?! I have the sweetest, kindest, and funniest 7-year-old on the planet. His name is Oliver.');
    }
}

askChildren();
console.log('score:' + score);

//Question three: Do I like arts and crafts? Correct answer: yes
function askCrafts(){
    const crafts = prompt ('Okay, you\'re doing great. Next question: Do I enjoy making art and crafting?' ).toLowerCase();
    console.log('Do I enjoy crafts? Answer: ' + crafts);
    // change to " 'yes' || 'y' "
    if(crafts === 'yes' || crafts === 'y') {
        alert('Darn tootin\' ' + username + '! I especially love wood burning and wool felting, but I\'m always into learning new crafty skills.');
        score = score + 1;
    }
    else if(crafts === 'no' || crafts === 'n') {
        alert('Well, ' + username + ', looks like I\'ll have to make you a little something soon. I especially love wood burning and wool felting, but I\'m always into learning new crafty skills.');
    }
}

askCrafts();
console.log('score:' + score);

//Question four: Do I enjoy southern food? Correct answer: yes
function askFood(){
    const food = prompt ('Alright, here\'s a tough one for you: Do I like southern food?').toLowerCase();
    console.log('Like southern food? Answer: ' + food);
    if(food === 'yes' || food === 'y') {
        alert('Zing! You are so smart, ' + username + '. I love southern food. In fact, I love pretty much ALL food!');
        score = score + 1;
    }
    else if(food === 'no' || food === 'n') {
        alert(username + '. Seriously? Who doesn\'t love southern food?!');
    }
}

askFood();
console.log('score:' + score);

//Question five: Have I traveled overseas? Correct answer: no
function askTravel(){
    const travel = prompt ('You\'re doing a bang-up job here ' + username + '. So, tell me, have I ever traveled overseas?').toLowerCase();
    console.log('Overseas travel? Answer: ' + travel);
    if(travel === 'yes' || travel === 'y') {
        alert('Nice try, ' + username + ', but I have never left the country. Well, I went to Toronto once.');
    }
    else if(travel === 'no' || travel === 'n') {
        alert('Spot on, ' + username + '! I haven\'t been outside the country except one quick trip to Toronto back before you needed a passport to cross the border in a car!');
        score = score + 1;
    }
}

askTravel();
console.log('score:' + score);

//Q6 with 4 guesses, tells too high or too low, how many guesses left, when correct gives 1 point and exits loop

function askDog() {
    for (let i = 0; i < 4; i++){
        const numDogs = prompt('How many dogs do I have?');
        console.log('Dog guess: ' + numDogs);
        if(numDogs == '2'){
            alert('Yes! I have a Catahoula mix and a white lab/Sharpei mix, and they are both a little crazy.');
            score = score + 1;
            i = 4;  //break;
        }
        else if(numDogs > 2){
            alert('That\'s too many dogs! You have ' + (3 - i) + ' guesses left!');
        }
        else if(numDogs < 2){
            alert('That\'s not enough dogs for me. You have ' + (3 - i) + ' guesses left!');
        }
        else(alert(username + ', that isn\'t even a number. You have ' + (3 - i) + ' guesses left!')
        );
    }
}

askDog();
console.log('score:' + score);

//Q7 uses an array of possible answers, if correct gives 1 pt.

const jobs = [' waitress', ' painter', ' electrician', ' teacher', ' carpenter', ' dishwasher', ' wrestler', ' driver', ' fire-breather', ' landscaper', ' nanny'];

function askJob(){
    for(let i = 0; i < 6; i++){
        const oneJob = ( ' ' + prompt('Last one, ' + username + '!! I\'ve done a lot of things to make money in my lifetime. Can you guess one position I\'ve had?').toLowerCase());

        console.log('Job guess: ' + oneJob);

        if(jobs.includes(oneJob)){
            alert('YES! I have totally been a ' + oneJob + '. Here are just a few job titles I\'ve had: ' + jobs + '. Whew!');
            score = score + 1;
            i = 6;
        }

        else if(!jobs.includes(oneJob)){
            alert('Nope, I have not been a ' + oneJob + ', but it\'s certainly never too late! Try again! You have ' + (5 - i) + ' attempts remaining.');
        }

        if(!jobs.includes(oneJob) && (5 - i) === 0){
            alert( 'Sorry, ' + username + ', you\'re out of tries. Here are just a few job titles I\'ve had: ' + jobs + '. Whew!');
        }
    }
}

askJob();
console.log('Final Score: ' + score);

alert('Great job, ' + username + '! Your final score is ' + score + '/7. You were really a good sport. Have a wonderful day!');


text:
#include BOSS_WEBRTC_U_modules__desktop_capture__desktop_frame_h //original-code:"modules/desktop_capture/desktop_frame.h"

#include <utility>

#include <string.h>

#include BOSS_ABSEILCPP_U_absl__memory__memory_h //original-code:"absl/memory/memory.h"
#include BOSS_WEBRTC_U_modules__desktop_capture__desktop_geometry_h //original-code:"modules/desktop_capture/desktop_geometry.h"
#include BOSS_WEBRTC_U_rtc_base__checks_h //original-code:"rtc_base/checks.h"

namespace webrtc {

DesktopFrame::DesktopFrame(DesktopSize size,
                           int stride,
                           uint8_t* data,
                           SharedMemory* shared_memory)
    : data_(data),
      shared_memory_(shared_memory),
      size_(size),
      stride_(stride),
      capture_time_ms_(0),
      capturer_id_(DesktopCapturerId::kUnknown) {
  RTC_DCHECK(size_.width() >= 0);
  RTC_DCHECK(size_.height() >= 0);
}

DesktopFrame::~DesktopFrame() = default;

void DesktopFrame::CopyPixelsFrom(const uint8_t* src_buffer,
                                  int src_stride,
                                  const DesktopRect& dest_rect) {
  RTC_CHECK(DesktopRect::MakeSize(size()).ContainsRect(dest_rect));

  uint8_t* dest = GetFrameDataAtPos(dest_rect.top_left());
  for (int y = 0; y < dest_rect.height(); ++y) {
    memcpy(dest, src_buffer, DesktopFrame::kBytesPerPixel * dest_rect.width());
    src_buffer += src_stride;
    dest += stride();
  }
}

void DesktopFrame::CopyPixelsFrom(const DesktopFrame& src_frame,
                                  const DesktopVector& src_pos,
                                  const DesktopRect& dest_rect) {
  RTC_CHECK(DesktopRect::MakeSize(src_frame.size())
                .ContainsRect(
                    DesktopRect::MakeOriginSize(src_pos, dest_rect.size())));

  CopyPixelsFrom(src_frame.GetFrameDataAtPos(src_pos), src_frame.stride(),
                 dest_rect);
}

DesktopRect DesktopFrame::rect() const {
  const float scale = scale_factor();
  // Only scale the size.
  return DesktopRect::MakeXYWH(top_left().x(), top_left().y(),
                               size().width() / scale, size().height() / scale);
}

float DesktopFrame::scale_factor() const {
  float scale = 1.0f;
  if (!dpi().is_zero() && dpi().x() == dpi().y())
    scale = dpi().x() / kStandardDPI;

  return scale;
}

uint8_t* DesktopFrame::GetFrameDataAtPos(const DesktopVector& pos) const {
  return data() + stride() * pos.y() + DesktopFrame::kBytesPerPixel * pos.x();
}

void DesktopFrame::CopyFrameInfoFrom(const DesktopFrame& other) {
  set_dpi(other.dpi());
  set_capture_time_ms(other.capture_time_ms());
  set_capturer_id(other.capturer_id());
  *mutable_updated_region() = other.updated_region();
  set_top_left(other.top_left());
}

void DesktopFrame::MoveFrameInfoFrom(DesktopFrame* other) {
  set_dpi(other->dpi());
  set_capture_time_ms(other->capture_time_ms());
  set_capturer_id(other->capturer_id());
  mutable_updated_region()->Swap(other->mutable_updated_region());
  set_top_left(other->top_left());
}

BasicDesktopFrame::BasicDesktopFrame(DesktopSize size)
    : DesktopFrame(size,
                   kBytesPerPixel * size.width(),
                   new uint8_t[kBytesPerPixel * size.width() * size.height()],
                   nullptr) {}

BasicDesktopFrame::~BasicDesktopFrame() {
  delete[] data_;
}

// static
DesktopFrame* BasicDesktopFrame::CopyOf(const DesktopFrame& frame) {
  DesktopFrame* result = new BasicDesktopFrame(frame.size());
  for (int y = 0; y < frame.size().height(); ++y) {
    memcpy(result->data() + y * result->stride(),
           frame.data() + y * frame.stride(),
           frame.size().width() * kBytesPerPixel);
  }
  result->CopyFrameInfoFrom(frame);
  return result;
}

// static
std::unique_ptr<DesktopFrame> SharedMemoryDesktopFrame::Create(
    DesktopSize size,
    SharedMemoryFactory* shared_memory_factory) {
  RTC_DCHECK(shared_memory_factory);

  size_t buffer_size = size.height() * size.width() * kBytesPerPixel;
  std::unique_ptr<SharedMemory> shared_memory =
      shared_memory_factory->CreateSharedMemory(buffer_size);
  if (!shared_memory)
    return nullptr;

  return absl::make_unique<SharedMemoryDesktopFrame>(
      size, size.width() * kBytesPerPixel, std::move(shared_memory));
}

SharedMemoryDesktopFrame::SharedMemoryDesktopFrame(DesktopSize size,
                                                   int stride,
                                                   SharedMemory* shared_memory)
    : DesktopFrame(size,
                   stride,
                   reinterpret_cast<uint8_t*>(shared_memory->data()),
                   shared_memory) {}

SharedMemoryDesktopFrame::SharedMemoryDesktopFrame(
    DesktopSize size,
    int stride,
    std::unique_ptr<SharedMemory> shared_memory)
    : SharedMemoryDesktopFrame(size, stride, shared_memory.release()) {}

SharedMemoryDesktopFrame::~SharedMemoryDesktopFrame() {
  delete shared_memory_;
}

}  // namespace webrtc


text:
@class JKImage;

@interface JKImageFilter : JKPatch

@property(nonatomic, strong) JKImage *inputImage;
@property(nonatomic, readonly) JKImage *outputImage;

@end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>org.springframework.aop.framework.autoproxy.target (Spring Framework 5.1.18.RELEASE API)</title>
<meta name="date" content="2020-09-15">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Spring Framework

Prev Package

Next Package

Frames

No Frames

All Classes

Package org.springframework.aop.framework.autoproxy.target

Class Summary

Class
Description

AbstractBeanFactoryBasedTargetSourceCreator

Convenient superclass for
 TargetSourceCreator
 implementations that require creating multiple instances of a prototype bean.

LazyInitTargetSourceCreator

TargetSourceCreator that enforces a LazyInitTargetSource for each bean
 that is defined as "lazy-init".

QuickTargetSourceCreator

Convenient TargetSourceCreator using bean name prefixes to create one of three
 well-known TargetSource types:
 : CommonsPool2TargetSource
 % ThreadLocalTargetSource
 ! PrototypeTargetSource

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Spring Framework

Prev Package

Next Package

Frames

No Frames

All Classes


text:
package jetbrains.buildServer.nuget.tests.integration.http;

import jetbrains.buildServer.NetworkUtil;
import jetbrains.buildServer.log.Loggers;
import jetbrains.buildServer.util.FileUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Eugene Petrenko
 *         Created: 27.07.2009 16:25:49
 */
public abstract class SimpleHttpServerBase {
  public static final String STATUS_LINE_200 = "HTTP/1.0 200 Ok";
  public static final String STATUS_LINE_201 = "HTTP/1.0 201 Created";
  public static final String STATUS_LINE_301 = "HTTP/1.0 301 Moved Permanently";
  public static final String STATUS_LINE_401 = "HTTP/1.1 401 Authorization Required";
  public static final String STATUS_LINE_404 = "HTTP/1.0 404 Not Found";
  public static final String STATUS_LINE_500 = "HTTP/1.0 500 Error";

  private volatile boolean myStopped;

  private ServerSocket mySocket;
  private int myPort;
  private int myWaitAfterAccept = -1;
  private final Semaphore myWaitAfterAcceptHandle = new Semaphore(1){{acquireUninterruptibly();}};
  private Thread myProcessingThread;
  protected Pattern requestParser = Pattern.compile(".*GET\\s+(\\S+)\\s.*", Pattern.DOTALL);

  public SimpleHttpServerBase() {
    myPort = NetworkUtil.getFreePort(1025);
  }

  public static Response getFileResponse(@NotNull final File file, @NotNull List<String> headers) {
    List<String> fileHeaders = new ArrayList<String>();
    fileHeaders.addAll(headers);
    Date lastModified = new Date(file.lastModified());
    SimpleDateFormat format = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss");
    fileHeaders.add("Last-Modfied: " + format.format(lastModified));
    fileHeaders.add("ETag: " + file.hashCode());

    try {
      final Response fileResponse = getFileResponse(new FileInputStream(file), fileHeaders);
      return new Response(fileResponse.getStatusLine(), fileResponse.getHeaders()) {
        @Override
        public void printContent(PrintStream ps) throws IOException {
          fileResponse.printContent(ps);
        }

        @Override
        public Integer getLength() {
          return (int)file.length();
        }
      };
    } catch (FileNotFoundException e) {
      return createStringResponse(STATUS_LINE_404, fileHeaders, "");
    }
  }

  protected static Response getFileResponse(@NotNull final InputStream content, @NotNull List<String> headers) {
    return createStreamResponse(STATUS_LINE_200, headers, content);
  }

  public int getPort() {
    return myPort;
  }

  public void start() throws IOException {
    myStopped = false;

    createSocket();

    myProcessingThread = new Thread(new Runnable() {
      public void run() {
        try {
          while (!myStopped) {
            processRequest(mySocket.accept());
          }
        } catch (IOException e) {
          if (!myStopped) {
            e.printStackTrace();
          }
        }
      }
    }, "simple server");
    myProcessingThread.start();
  }

  protected void postProcessSocketData(String httpHeader, @NotNull final InputStream is) throws IOException {

  }

  protected void processRequest(@NotNull final Socket connection) {
    waitBeforeResponse();
    try {
      final InputStream is = /*new BufferedInputStream*/(connection.getInputStream());
      final OutputStream os = new BufferedOutputStream(connection.getOutputStream());

      final PrintStream ps = new PrintStream(os, false, "utf-8");
      final StringBuilder sb = new StringBuilder();
      while (true) {
        final int c = is.read();
        if (c == -1) break;
        //System.out.print((char)c);
        sb.append((char) c);

        if (sb.length() > 4) {
          final String last4 = sb.substring(sb.length() - 4);
          if ("\r\n\r\n".equals(last4)) {
            break;
          }
        }
      }
      final String httpHeader = sb.toString();
      postProcessSocketData(httpHeader, is);

      Response response = null;
      try {
        try {
          response = this.getResponse(httpHeader);
        } catch (Throwable t) {
          Loggers.TEST.error("Failed to get response. " + t.getMessage(), t);
          response = createStringResponse(STATUS_LINE_500, Collections.<String>emptyList(), "");
        }
        writeResponse(ps, response);
      } finally {
        if (response != null) response.dispose();
      }

      ps.close();
    } catch (IOException e) {
      // NOP
    } finally {
      try {
        connection.close();
      } catch(IOException e) {
        // NOP
      }
    }
  }

  private void waitBeforeResponse() {
    if (myWaitAfterAccept > 0) {
      try {
        if (myWaitAfterAcceptHandle.tryAcquire(myWaitAfterAccept, TimeUnit.SECONDS)) {
          myWaitAfterAcceptHandle.release();
        }
      } catch (InterruptedException e) {
        //NOP
      }
    }
  }

  private void writeResponse(final PrintStream ps, final Response response) throws IOException {
    ps.println(response.getStatusLine());
    for (String h : response.getHeaders()) {
      ps.print(h);
      ps.print("\r\n");
    }
    if (response.getLength() != null) {
      ps.print("Content-Length: " + response.getLength() + "\r\n");
    }
    //close headers section
    ps.print("\r\n");
    ps.flush();

    response.printContent(ps);
    ps.flush();
  }

  private void createSocket() throws IOException {
    while (true) {
      try {
        mySocket = new ServerSocket(myPort, 50, null);
        break;
      } catch (IOException e) {
        myPort++;
      }
    }
    mySocket.setSoTimeout(32 * 4096);
  }

  public void stop() {
    if (myStopped) return;
    myWaitAfterAcceptHandle.release();

    myStopped = true;
    try {
      mySocket.close();
      mySocket = null;
    } catch (IOException e) {
      //
    }

    try {
      myProcessingThread.join(60*1000);
    } catch (InterruptedException e) {
      //
    }
  }

  public void setWaitAfterAccept(int seconds) {
    myWaitAfterAccept = seconds;
  }

  protected abstract Response getResponse(String httpHeader) throws IOException;

  @Nullable
  protected String getRequestPath(@NotNull final String request) {
    Matcher matcher = requestParser.matcher(request);
    if (matcher.matches()) {
      return matcher.group(1);
    }
    return null;
  }

  @Nullable
  protected String getHeaderLine(@NotNull final String request, @NotNull final String header) {
    for (String line : request.split("[\r\n]+")) {
      if (line.startsWith(header)) {
        return line.substring(header.length()).trim();
      }
    }
    return null;
  }

  public abstract static class Response {
    private final String myStatusLine;
    private final List<String> myHeaders;

    public Response(final String statusLine, final Collection<String> headers) {
      myStatusLine = statusLine;
      myHeaders = new ArrayList<String>(headers);
    }

    public String getStatusLine() {
      return myStatusLine;
    }

    public List<String> getHeaders() {
      return myHeaders;
    }

    public abstract void printContent(PrintStream ps) throws IOException;

    public abstract Integer getLength();

    public void dispose() {}
  }

  public static Response createStringResponse(final String statusLine,
                                              final Collection<String> headers,
                                              final String content) {
    return new Response(statusLine, headers) {
      @Override
      public void printContent(PrintStream ps) {
        ps.print(content);
      }

      @Override
      public Integer getLength() {
        return content.length();
      }
    };
  }

  public static Response createStreamResponse(final String statusLine,
                                              final Collection<String> headers,
                                              final byte[] content) {
    return new Response(statusLine, headers) {
      @Override
      public void printContent(PrintStream ps) throws IOException {
        ps.write(content);
      }

      @Override
      public Integer getLength() {
        return content.length;
      }
    };
  }

  public static Response createStreamResponse(final String statusLine,
                                              final List<String> headers,
                                              final InputStream content) {
    return new Response(statusLine, headers) {
      @Override
      public void printContent(PrintStream ps) throws IOException {
        final BufferedInputStream bis = new BufferedInputStream(content);
        int data;
        while ((data = bis.read()) != -1) {
          ps.write(data);
        }
        ps.write("                              ".getBytes("utf-8"));
      }

      @Override
      public Integer getLength() {
        return null;
      }

      @Override
      public void dispose() {
        FileUtil.close(content);
      }
    };
  }

}


text:
layout: post
published: true
categories:
    - Subscriptions
    - Coupons
title: Five Four Club Free Aviator Sunglasses Coupon!
featured: false
comments: true
type: photo
imagefeature: FiveFourClubTopgun.png
headline: Five Four Club Free Aviator Sunglasses Coupon!
tags: [Five Four Club, Subscriptions, Coupons]
date: 2015-09-20 12:32:39 -08:00
---

Five Four Club has a new deal! Get a free pair of aviator sunglasses worth $75 with your first delivery! Use coupon code TOPGUN at checkout.

Plus, if you click here to join, you'll receive $30 off your first package (that's 50% off!) AND get the Aviator Sunglasses too, how awesome is that!

My husband absolutely LOVES Five Four Club! The clothes are of high quality and the style on trend. When you join, you complete a style profile to input your size and style preference (Classic, Casual, Fashion Forward or a Mix of all). Checkout my past review on the blog.

If you're interested in joining, now is a better time than ever to take advantage of this amazing deal! 50% off PLUS get the free sunglasses worth $75, amazing.

Visit their website for more info and to join, I totally recommend them to any guy who's looking to bump up their wardrobe or is just too busy to shop.

What's Five Four Club?

Subscription: Five Four Club

Cost: $60/monthly + Free Shipping

What do you get: Five Four Club is a monthly men's clothing subscription. Each month you'll receive an apparel package (2-3 items) valued at $120 or more that's selected according to your style profile and preferences.

Coupon: Click here to get 50% off and use coupon code TOPGUN to get a free aviator sunglasses worth $75 with your first package!


text:
Editor.UI.idtree = (() => {
  'use strict';

  function _getLastChildRecursively ( itemEL ) {
    if ( itemEL.foldable && !itemEL.folded ) {
      return _getLastChildRecursively ( Polymer.dom(itemEL).lastElementChild );
    }
    return itemEL;
  }

  function _checkFoldable ( el ) {
    return Polymer.dom(el).childNodes.length > 0;
  }

  let idtree = {
    'ui-idtree': true,

    created () {
      this._id2el = {};
      this._activeElement = null;
    },

    addItem ( parentEL, itemEL, options ) {
      options = options || {};
      for ( var p in options ) {
        itemEL[p] = options[p];
      }

      let id = options.id;
      if ( id === null || id === undefined ) {
        throw new Error( 'The id you provide is invalid: ' + id );
      }

      //
      if ( this._id2el[id] ) {
        throw new Error( 'The id already added in the tree: ' + id );
      }

      //
      let name = options.name || '';
      let folded = options.folded;
      if ( folded === null || folded === undefined ) {
        folded = true;
      }

      // init item element
      itemEL._userId = id;
      itemEL.name = name;
      itemEL.folded = folded;
      if ( itemEL.foldable === undefined ) {
        itemEL.foldable = false;
      }

      // append to parent
      if ( parentEL.insertItem ) {
        parentEL.insertItem(itemEL);
      } else {
        Polymer.dom(parentEL).appendChild(itemEL);
      }

      if ( parentEL !== this ) {
        parentEL.foldable = true;
      }

      // add to id table
      this._id2el[id] = itemEL;
    },

    updateItemID ( itemEL, newID ) {
      delete this._id2el[itemEL._userId];
      itemEL._userId = newID;
      this._id2el[newID] = itemEL;
    },

    removeItem ( itemEL ) {
      let parentEL = Polymer.dom(itemEL).parentNode;
      Polymer.dom(parentEL).removeChild(itemEL);

      if ( parentEL !== this ) {
        parentEL.foldable = _checkFoldable(parentEL);
      }

      let self = this;
      function deleteRecursively (itemEL) {
        delete self._id2el[itemEL._userId];

        // children
        let children = Polymer.dom(itemEL).children;
        for ( let i = 0; i < children.length; ++i ) {
          deleteRecursively(children[i]);
        }
      }
      deleteRecursively(itemEL);
    },

    removeItemById (id) {
      let el = this._id2el[id];
      if ( el ) {
        this.removeItem(el);
      }
    },

    setItemParent ( itemEL, parentEL ) {
      if ( Editor.UI.PolymerUtils.isSelfOrAncient( parentEL, itemEL ) ) {
        throw new Error('Failed to set item parent to its child');
      }

      let oldParentEL = Polymer.dom(itemEL).parentNode;

      //
      if ( parentEL.insertItem ) {
        parentEL.insertItem(itemEL);
      } else {
        Polymer.dom(parentEL).appendChild(itemEL);
      }
      parentEL.foldable = _checkFoldable(parentEL);

      //
      if ( oldParentEL !== this ) {
        oldParentEL.foldable = _checkFoldable(oldParentEL);
      }
    },

    setItemParentById (id, parentId) {
      let itemEL = this._id2el[id];
      if ( !itemEL ) {
        return;
      }

      let parentEL = parentId ? this._id2el[parentId] : this;
      if ( !parentEL ) {
        return;
      }
      this.setItemParent(itemEL, parentEL);
    },

    renameItemById (id, newName) {
      let itemEL = this._id2el[id];
      if ( !itemEL ) {
        return;
      }
      itemEL.name = newName;
    },

    nextItem ( curItem, skipChildren ) {
      let curItemDOM = Polymer.dom(curItem);
      if ( !skipChildren && curItem.foldable && !curItem.folded ) {
        return curItemDOM.firstElementChild;
      }

      if ( curItemDOM.nextElementSibling ) {
        return curItemDOM.nextElementSibling;
      }

      let parentEL = curItemDOM.parentNode;
      if ( parentEL === this ) {
        return null;
      }

      return this.nextItem(parentEL, true);
    },

    prevItem ( curItem ) {
      let curItemDOM = Polymer.dom(curItem);

      let prevSiblingEL = curItemDOM.previousSibling;
      if ( prevSiblingEL ) {
        if ( prevSiblingEL.foldable && !prevSiblingEL.folded ) {
          return _getLastChildRecursively (prevSiblingEL);
        }

        return prevSiblingEL;
      }

      let parentEL = curItemDOM.parentNode;
      if ( parentEL === this ) {
        return null;
      }

      return parentEL;
    },

    lastItem () {
      let lastChildEL = Polymer.dom(this).lastElementChild;
      if ( lastChildEL && lastChildEL.foldable && !lastChildEL.folded ) {
        return _getLastChildRecursively (lastChildEL);
      }
      return lastChildEL;
    },

    clear () {
      let thisDOM = Polymer.dom(this);
      while (thisDOM.firstChild) {
        thisDOM.removeChild(thisDOM.firstChild);
      }
      this._id2el = {};
    },

    expand ( id, expand ) {
      let itemEL = this._id2el[id];
      let parentEL = Polymer.dom(itemEL).parentNode;
      while ( parentEL ) {
        if ( parentEL === this ) {
          break;
        }

        parentEL.folded = !expand;
        parentEL = Polymer.dom(parentEL).parentNode;
      }
    },

    scrollToItem ( el ) {
      window.requestAnimationFrame(() => {
        this.$.content.scrollTop = el.offsetTop + 16 - this.offsetHeight/2;
      });
    },

    selectItemById ( id ) {
      let itemEL = this._id2el[id];
      if ( itemEL ) {
        itemEL.selected = true;
      }
    },

    unselectItemById ( id ) {
      let itemEL = this._id2el[id];
      if ( itemEL ) {
        itemEL.selected = false;
      }
    },

    activeItemById ( id ) {
      let itemEL = this._id2el[id];
      if ( itemEL ) {
        this._activeElement = itemEL;
      }
    },

    deactiveItemById ( id ) {
      if ( this._activeElement && this._activeElement._userId === id ) {
        this._activeElement = null;
      }
    },

    activeItem ( itemEL ) {
      this._activeElement = itemEL;
    },

    deactiveItem ( itemEL ) {
      if ( itemEL && this._activeElement === itemEL ) {
        this._activeElement = null;
      }
    },

    dumpItemStates () {
      let states = [];

      for ( let id in this._id2el ) {
        if ( this._id2el[id].foldable ) {
          states.push({
            id: this._id2el[id]._userId,
            folded: this._id2el[id].folded
          });
        }
      }

      return states;
    },

    restoreItemStates (states) {
      if ( !states ) {
        return;
      }

      states.forEach(state => {
        let itemEL = this._id2el[state.id];
        if ( itemEL ) {
          itemEL.folded = state.folded;
        }
      });
    },

    getToplevelElements ( ids ) {
      let elements = new Array(ids.length);
      for ( let i = 0; i < ids.length; ++i ) {
        elements[i] = this._id2el[ids[i]];
      }

      let resultELs = Editor.Utils.arrayCmpFilter ( elements, ( elA, elB ) => {
        if ( elA.contains(elB) ) {
          return 1;
        }

        if ( elB.contains(elA) ) {
          return -1;
        }

        return 0;
      });
      return resultELs;
    },
  };

  return idtree;
})();