text:
package nl.talsmasoftware.enumerables.jackson2.bug25;

import java.util.Arrays;
import java.util.List;

/**
 * Created by kroon.r on 28-06-2017.
 */
public class TypeWithEnumerableList {

    public List<Team> teammembers;
    public String stringValue;

    @Override
    public int hashCode() {
        return Arrays.hashCode(new Object[] {teammembers, stringValue});
    }

    @Override
    public boolean equals(Object other) {
        return this == other || (other instanceof TypeWithEnumerableList
                && TypeWithEnumerable.equals(teammembers, ((TypeWithEnumerableList) other).teammembers)
                && TypeWithEnumerable.equals(stringValue, ((TypeWithEnumerableList) other).stringValue)
        );
    }

}


text:
"""
Copyright (c) 2006-2016 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission
"""

import copy
import types

from lib.core.exception import SqlmapDataException

class AttribDict(dict):
    """
    This class defines the sqlmap object, inheriting from Python data
    type dictionary.

    >>> foo = AttribDict()
    >>> foo.bar = 1
    >>> foo.bar
    1
    """

    def __init__(self, indict=None, attribute=None):
        if indict is None:
            indict = {}

        # Set any attributes here - before initialisation
        # these remain as normal attributes
        self.attribute = attribute
        dict.__init__(self, indict)
        self.__initialised = True

        # After initialisation, setting attributes
        # is the same as setting an item

    def __getattr__(self, item):
        """
        Maps values to attributes
        Only called if there *is NOT* an attribute with this name
        """

        try:
            return self.__getitem__(item)
        except KeyError:
            raise SqlmapDataException("unable to access item '%s'" % item)

    def __setattr__(self, item, value):
        """
        Maps attributes to values
        Only if we are initialised
        """

        # This test allows attributes to be set in the __init__ method
        if "_AttribDict__initialised" not in self.__dict__:
            return dict.__setattr__(self, item, value)

        # Any normal attributes are handled normally
        elif item in self.__dict__:
            dict.__setattr__(self, item, value)

        else:
            self.__setitem__(item, value)

    def __getstate__(self):
        return self.__dict__

    def __setstate__(self, dict):
        self.__dict__ = dict

    def __deepcopy__(self, memo):
        retVal = self.__class__()
        memo[id(self)] = retVal

        for attr in dir(self):
            if not attr.startswith('_'):
                value = getattr(self, attr)
                if not isinstance(value, (types.BuiltinFunctionType, types.FunctionType, types.MethodType)):
                    setattr(retVal, attr, copy.deepcopy(value, memo))

        for key, value in self.items():
            retVal.__setitem__(key, copy.deepcopy(value, memo))

        return retVal

class InjectionDict(AttribDict):
    def __init__(self):
        AttribDict.__init__(self)

        self.place = None
        self.parameter = None
        self.ptype = None
        self.prefix = None
        self.suffix = None
        self.clause = None
        self.notes = set()

        # data is a dict with various stype, each which is a dict with
        # all the information specific for that stype
        self.data = AttribDict()

        # conf is a dict which stores current snapshot of important
        # options used during detection
        self.conf = AttribDict()

        self.dbms = None
        self.dbms_version = None
        self.os = None

redpajama_set_name: RedPajamaGithub


text:
package org.apache.cassandra.utils.concurrent;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.Consumer;
import java.util.function.Function;

import javax.annotation.Nullable;

import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.Uninterruptibles;
import org.junit.Assert;

import io.netty.util.concurrent.GenericFutureListener;
import org.apache.cassandra.config.DatabaseDescriptor;

public abstract class AbstractTestAsyncPromise extends AbstractTestPromise
{
    static
    {
        DatabaseDescriptor.clientInitialization();
    }

    public static <V> Promise<V> cancelSuccess(Promise<V> promise)
    {
        success(promise, Promise::isCancellable, true);
        return cancelShared(promise);
    }

    public static <V> Promise<V> cancelExclusiveSuccess(Promise<V> promise)
    {
        success(promise, Promise::isCancellable, true);
        success(promise, Promise::setUncancellableExclusive, true);
        return cancelShared(promise);
    }

    private static <V> Promise<V> cancelShared(Promise<V> promise)
    {
        success(promise, Promise::setUncancellable, true);
        success(promise, Promise::setUncancellable, true);
        success(promise, Promise::setUncancellableExclusive, false);
        success(promise, p -> p.cancel(true), false);
        success(promise, p -> p.cancel(false), false);
        success(promise, Promise::isCancellable, false);
        success(promise, Promise::isCancelled, false);
        return promise;
    }

    public static <V> Promise<V> cancelFailure(Promise<V> promise)
    {
        success(promise, Promise::isCancellable, false);
        return cancelShared(promise);
    }

    protected <V> void testOneSuccess(Promise<V> promise, boolean tryOrSet, V value, V otherValue)
    {
        List<V> results = new ArrayList<>();
        List<Integer> order = new ArrayList<>();
        class ListenerFactory
        {
            int count = 0;

            public GenericFutureListener<Future<V>> get()
            {
                int id = count++;
                return p -> { results.add(p.getNow()); order.add(id); };
            }
            public GenericFutureListener<Future<V>> getListenerToFailure(Promise<V> promise)
            {
                int id = count++;
                return p -> { Assert.assertTrue(p.cause() instanceof RuntimeException); results.add(promise.getNow()); order.add(id); };
            }
            public GenericFutureListener<Future<V>> getRecursive()
            {
                int id = count++;
                return p -> { promise.addListener(get()); results.add(p.getNow()); order.add(id); };
            }
            public Runnable getRunnable(Future<V> p)
            {
                int id = count++;
                return () -> { results.add(p.getNow()); order.add(id); };
            }
            public Runnable getRecursiveRunnable(Future<V> p)
            {
                int id = count++;
                return () -> { promise.addListener(getRunnable(p)); results.add(p.getNow()); order.add(id); };
            }
            public Consumer<V> getConsumer()
            {
                int id = count++;
                return result -> { results.add(result); order.add(id); };
            }
            public Consumer<V> getRecursiveConsumer()
            {
                int id = count++;
                return result -> { promise.addCallback(getConsumer(), fail -> Assert.fail()); results.add(result); order.add(id); };
            }
            public Function<V, Future<V>> getAsyncFunction()
            {
                int id = count++;
                return result -> { results.add(result); order.add(id); return ImmediateFuture.success(result); };
            }
            public Function<V, V> getFunction()
            {
                int id = count++;
                return result -> { results.add(result); order.add(id); return result; };
            }
            public Function<V, Future<V>> getRecursiveAsyncFunction(Promise<V> promise)
            {
                int id = count++;
                return result -> { promise.flatMap(getAsyncFunction()); results.add(result); order.add(id); return ImmediateFuture.success(result); };
            }
            public Function<V, Future<V>> getAsyncFailingFunction()
            {
                int id = count++;
                return result -> { results.add(result); order.add(id); return ImmediateFuture.failure(new RuntimeException()); };
            }
            public Function<V, V> getFailingFunction()
            {
                int id = count++;
                return result -> { results.add(result); order.add(id); throw new RuntimeException(); };
            }
            public Function<V, Future<V>> getRecursiveAsyncFailingFunction(Promise<V> promise)
            {
                int id = count++;
                return result -> { promise.flatMap(getAsyncFailingFunction()); results.add(result); order.add(id); return ImmediateFuture.failure(new RuntimeException()); };
            }
            public FutureCallback<V> getCallback(Future<V> p)
            {
                int id = count++;
                return new FutureCallback<V>()
                {
                    @Override
                    public void onSuccess(@Nullable Object o)
                    {
                        results.add(p.getNow());
                        order.add(id);
                    }

                    @Override
                    public void onFailure(Throwable throwable)
                    {
                        Assert.fail();
                    }
                };
            }
            public FutureCallback<V> getRecursiveCallback(Future<V> p)
            {
                int id = count++;
                return new FutureCallback<V>()
                {
                    @Override
                    public void onSuccess(@Nullable Object o)
                    {
                        promise.addCallback(getCallback(p));
                        results.add(p.getNow());
                        order.add(id);
                    }

                    @Override
                    public void onFailure(Throwable throwable)
                    {
                        Assert.fail();
                    }
                };
            }
        }
        ListenerFactory listeners = new ListenerFactory();
        Async async = new Async();
        promise.addListener(listeners.get());
        promise.addListener(listeners.getRunnable(promise));
        promise.addListener(listeners.getRunnable(promise), MoreExecutors.directExecutor());
        promise.addListeners(listeners.getRecursive(), listeners.get());
        promise.addListener(listeners.getRecursiveRunnable(promise), MoreExecutors.directExecutor());
        promise.addListener(listeners.getRecursive());
        promise.addCallback(listeners.getCallback(promise));
        promise.addCallback(listeners.getCallback(promise), MoreExecutors.directExecutor());
        promise.addCallback(listeners.getRecursiveCallback(promise));
        promise.addCallback(listeners.getRecursiveCallback(promise), MoreExecutors.directExecutor());
        promise.addCallback(listeners.getConsumer(), fail -> Assert.fail());
        promise.addCallback(listeners.getConsumer(), fail -> Assert.fail(), MoreExecutors.directExecutor());
        promise.addCallback(listeners.getRecursiveConsumer(), fail -> Assert.fail());
        promise.addCallback(listeners.getRecursiveConsumer(), fail -> Assert.fail(), MoreExecutors.directExecutor());
        promise.map(listeners.getFunction()).addListener(listeners.get());
        promise.map(listeners.getFunction(), MoreExecutors.directExecutor()).addListener(listeners.get());
        promise.map(listeners.getFailingFunction()).addListener(listeners.getListenerToFailure(promise));
        promise.map(listeners.getFailingFunction(), MoreExecutors.directExecutor()).addListener(listeners.getListenerToFailure(promise));
        promise.flatMap(listeners.getAsyncFunction()).addListener(listeners.get());
        promise.flatMap(listeners.getAsyncFunction(), MoreExecutors.directExecutor()).addListener(listeners.get());
        promise.flatMap(listeners.getRecursiveAsyncFunction(promise)).addListener(listeners.get());
        promise.flatMap(listeners.getRecursiveAsyncFunction(promise), MoreExecutors.directExecutor()).addListener(listeners.get());
        promise.flatMap(listeners.getAsyncFailingFunction()).addListener(listeners.getListenerToFailure(promise));
        promise.flatMap(listeners.getAsyncFailingFunction(), MoreExecutors.directExecutor()).addListener(listeners.getListenerToFailure(promise));
        promise.flatMap(listeners.getRecursiveAsyncFailingFunction(promise)).addListener(listeners.getListenerToFailure(promise));
        promise.flatMap(listeners.getRecursiveAsyncFailingFunction(promise), MoreExecutors.directExecutor()).addListener(listeners.getListenerToFailure(promise));

        success(promise, Promise::getNow, null);
        success(promise, Promise::isSuccess, false);
        success(promise, Promise::isDone, false);
        success(promise, Promise::isCancelled, false);
        async.success(promise, Promise::get, value);
        async.success(promise, p -> p.get(1L, TimeUnit.SECONDS), value);
        async.success(promise, Promise::await, promise);
        async.success(promise, Promise::awaitUninterruptibly, promise);
        async.success(promise, p -> p.await(1L, TimeUnit.SECONDS), true);
        async.success(promise, p -> p.await(1000L), true);
        async.success(promise, p -> p.awaitUninterruptibly(1L, TimeUnit.SECONDS), true);
        async.success(promise, p -> p.awaitUninterruptibly(1000L), true);
        async.success(promise, Promise::sync, promise);
        async.success(promise, Promise::syncUninterruptibly, promise);
        if (tryOrSet) promise.trySuccess(value);
        else promise.setSuccess(value);
        success(promise, p -> p.cancel(true), false);
        success(promise, p -> p.cancel(false), false);
        failure(promise, p -> p.setSuccess(null), IllegalStateException.class);
        failure(promise, p -> p.setFailure(new NullPointerException()), IllegalStateException.class);
        success(promise, Promise::getNow, value);
        success(promise, p -> p.trySuccess(otherValue), false);
        success(promise, p -> p.tryFailure(new NullPointerException()), false);
        success(promise, Promise::getNow, value);
        success(promise, Promise::cause, null);
        promise.addListener(listeners.get());
        promise.addListener(listeners.getRunnable(promise));
        promise.addListener(listeners.getRunnable(promise), MoreExecutors.directExecutor());
        promise.addListeners(listeners.getRecursive(), listeners.get());
        promise.addListener(listeners.getRecursiveRunnable(promise), MoreExecutors.directExecutor());
        promise.addListener(listeners.getRecursive());
        promise.addCallback(listeners.getCallback(promise));
        promise.addCallback(listeners.getCallback(promise), MoreExecutors.directExecutor());
        promise.addCallback(listeners.getRecursiveCallback(promise));
        promise.addCallback(listeners.getRecursiveCallback(promise), MoreExecutors.directExecutor());
        promise.addCallback(listeners.getConsumer(), fail -> Assert.fail());
        promise.addCallback(listeners.getConsumer(), fail -> Assert.fail(), MoreExecutors.directExecutor());
        promise.addCallback(listeners.getRecursiveConsumer(), fail -> Assert.fail());
        promise.addCallback(listeners.getRecursiveConsumer(), fail -> Assert.fail(), MoreExecutors.directExecutor());
        promise.map(listeners.getFunction()).addListener(listeners.get());
        promise.map(listeners.getFunction(), MoreExecutors.directExecutor()).addListener(listeners.get());
        promise.map(listeners.getFailingFunction()).addListener(listeners.getListenerToFailure(promise));
        promise.map(listeners.getFailingFunction(), MoreExecutors.directExecutor()).addListener(listeners.getListenerToFailure(promise));
        promise.flatMap(listeners.getAsyncFunction()).addListener(listeners.get());
        promise.flatMap(listeners.getAsyncFunction(), MoreExecutors.directExecutor()).addListener(listeners.get());
        promise.flatMap(listeners.getRecursiveAsyncFunction(promise)).addListener(listeners.get());
        promise.flatMap(listeners.getRecursiveAsyncFunction(promise), MoreExecutors.directExecutor()).addListener(listeners.get());
        promise.flatMap(listeners.getAsyncFailingFunction()).addListener(listeners.getListenerToFailure(promise));
        promise.flatMap(listeners.getAsyncFailingFunction(), MoreExecutors.directExecutor()).addListener(listeners.getListenerToFailure(promise));
        promise.flatMap(listeners.getRecursiveAsyncFailingFunction(promise)).addListener(listeners.getListenerToFailure(promise));
        promise.flatMap(listeners.getRecursiveAsyncFailingFunction(promise), MoreExecutors.directExecutor()).addListener(listeners.getListenerToFailure(promise));
        success(promise, Promise::isSuccess, true);
        success(promise, Promise::isDone, true);
        success(promise, Promise::isCancelled, false);
        async.verify();
        Assert.assertEquals(listeners.count, results.size());
        Assert.assertEquals(listeners.count, order.size());
        for (V result : results)
            Assert.assertEquals(value, result);
        for (int i = 0 ; i < order.size() ; ++i)
            Assert.assertEquals(i, order.get(i).intValue());
    }

    protected <V> void testOneFailure(Promise<V> promise, boolean tryOrSet, Throwable cause, V otherValue)
    {
        List<Throwable> results = new ArrayList<>();
        List<Integer> order = new ArrayList<>();
        Async async = new Async();
        class ListenerFactory
        {
            int count = 0;

            public GenericFutureListener<Future<V>> get()
            {
                int id = count++;
                return p -> { results.add(p.cause()); order.add(id); };
            }
            public GenericFutureListener<Future<V>> getRecursive()
            {
                int id = count++;
                return p -> { promise.addListener(get()); results.add(p.cause()); order.add(id); };
            }
            public Runnable getRunnable(Future<V> p)
            {
                int id = count++;
                return () -> { results.add(p.cause()); order.add(id); };
            }
            public Runnable getRecursiveRunnable(Future<V> p)
            {
                int id = count++;
                return () -> { promise.addListener(getRunnable(p)); results.add(p.cause()); order.add(id); };
            }
            public Consumer<Throwable> getConsumer()
            {
                int id = count++;
                return result -> { results.add(result); order.add(id); };
            }
            public Consumer<Throwable> getRecursiveConsumer()
            {
                int id = count++;
                return result -> { promise.addCallback(fail -> Assert.fail(), getConsumer()); results.add(result); order.add(id); };
            }
            public Function<V, Future<V>> getAsyncFunction()
            {
                return result -> { Assert.fail(); return ImmediateFuture.success(result); };
            }
            public Function<V, Future<V>> getRecursiveAsyncFunction()
            {
                return result -> { promise.flatMap(getAsyncFunction()); return ImmediateFuture.success(result); };
            }
            public FutureCallback<V> getCallback(Future<V> p)
            {
                int id = count++;
                return new FutureCallback<V>()
                {
                    @Override
                    public void onSuccess(@Nullable Object o)
                    {
                        Assert.fail();
                    }

                    @Override
                    public void onFailure(Throwable throwable)
                    {
                        results.add(p.cause());
                        order.add(id);
                    }
                };
            }
            public FutureCallback<V> getRecursiveCallback(Future<V> p)
            {
                int id = count++;
                return new FutureCallback<V>()
                {
                    @Override
                    public void onSuccess(@Nullable Object o)
                    {
                        Assert.fail();
                    }

                    @Override
                    public void onFailure(Throwable throwable)
                    {
                        promise.addCallback(getCallback(p));
                        results.add(p.cause());
                        order.add(id);
                    }
                };
            }
        }
        ListenerFactory listeners = new ListenerFactory();
        promise.addListener(listeners.get());
        promise.addListeners(listeners.getRecursive(), listeners.get());
        promise.addListener(listeners.getRecursive());
        promise.addListener(listeners.getRunnable(promise));
        promise.addListener(listeners.getRunnable(promise), MoreExecutors.directExecutor());
        promise.addListener(listeners.getRecursiveRunnable(promise), MoreExecutors.directExecutor());
        promise.addListener(listeners.getRecursive());
        promise.addCallback(listeners.getCallback(promise));
        promise.addCallback(listeners.getRecursiveCallback(promise));
        promise.addCallback(fail -> Assert.fail(), listeners.getConsumer());
        promise.addCallback(fail -> Assert.fail(), listeners.getRecursiveConsumer());
        promise.flatMap(listeners.getAsyncFunction()).addListener(listeners.get());
        promise.flatMap(listeners.getAsyncFunction(), MoreExecutors.directExecutor()).addListener(listeners.get());
        promise.flatMap(listeners.getRecursiveAsyncFunction()).addListener(listeners.get());
        promise.flatMap(listeners.getRecursiveAsyncFunction(), MoreExecutors.directExecutor()).addListener(listeners.get());
        success(promise, Promise::isSuccess, false);
        success(promise, Promise::isDone, false);
        success(promise, Promise::isCancelled, false);
        success(promise, Promise::getNow, null);
        success(promise, Promise::cause, null);
        async.failure(promise, p -> p.get(), ExecutionException.class);
        async.failure(promise, p -> p.get(1L, TimeUnit.SECONDS), ExecutionException.class);
        async.success(promise, Promise::await, promise);
        async.success(promise, Promise::awaitThrowUncheckedOnInterrupt, promise);
        async.success(promise, Promise::awaitUninterruptibly, promise);
        async.success(promise, p -> p.await(1L, TimeUnit.SECONDS), true);
        async.success(promise, p -> p.await(1000L), true);
        async.success(promise, p -> p.awaitUninterruptibly(1L, TimeUnit.SECONDS), true);
        async.success(promise, p -> p.awaitThrowUncheckedOnInterrupt(1L, TimeUnit.SECONDS), true);
        async.success(promise, p -> p.awaitUninterruptibly(1000L), true);
        async.success(promise, p -> p.awaitUntil(System.nanoTime() + TimeUnit.SECONDS.toNanos(1L)), true);
        async.success(promise, p -> p.awaitUntilUninterruptibly(System.nanoTime() + TimeUnit.SECONDS.toNanos(1L)), true);
        async.success(promise, p -> p.awaitUntilThrowUncheckedOnInterrupt(System.nanoTime() + TimeUnit.SECONDS.toNanos(1L)), true);
        async.failure(promise, p -> p.sync(), cause);
        async.failure(promise, p -> p.syncUninterruptibly(), cause);
        if (tryOrSet) promise.tryFailure(cause);
        else promise.setFailure(cause);
        success(promise, p -> p.cancel(true), false);
        success(promise, p -> p.cancel(false), false);
        failure(promise, p -> p.setSuccess(null), IllegalStateException.class);
        failure(promise, p -> p.setFailure(new NullPointerException()), IllegalStateException.class);
        success(promise, Promise::cause, cause);
        success(promise, Promise::getNow, null);
        success(promise, p -> p.trySuccess(otherValue), false);
        success(promise, p -> p.tryFailure(new NullPointerException()), false);
        success(promise, Promise::getNow, null);
        success(promise, Promise::cause, cause);
        promise.addListener(listeners.get());
        promise.addListeners(listeners.getRecursive(), listeners.get());
        promise.addListener(listeners.getRecursive());
        promise.addListener(listeners.getRunnable(promise));
        promise.addListener(listeners.getRunnable(promise), MoreExecutors.directExecutor());
        promise.addListener(listeners.getRecursiveRunnable(promise), MoreExecutors.directExecutor());
        promise.addListener(listeners.getRecursive());
        promise.addCallback(listeners.getCallback(promise));
        promise.addCallback(listeners.getRecursiveCallback(promise));
        promise.addCallback(fail -> Assert.fail(), listeners.getConsumer());
        promise.addCallback(fail -> Assert.fail(), listeners.getRecursiveConsumer());
        promise.flatMap(listeners.getAsyncFunction()).addListener(listeners.get());
        promise.flatMap(listeners.getAsyncFunction(), MoreExecutors.directExecutor()).addListener(listeners.get());
        success(promise, Promise::isSuccess, false);
        success(promise, Promise::isDone, true);
        success(promise, Promise::isCancelled, false);
        success(promise, Promise::isCancellable, false);
        async.verify();
        Assert.assertEquals(listeners.count, results.size());
        Assert.assertEquals(listeners.count, order.size());
        for (Throwable result : results)
            Assert.assertEquals(cause, result);
        for (int i = 0 ; i < order.size() ; ++i)
            Assert.assertEquals(i, order.get(i).intValue());
    }

    // TODO: test listeners?
    public <V> void testOneCancellation(Promise<V> promise, boolean interruptIfRunning, V otherValue)
    {
        Async async = new Async();
        success(promise, Promise::isCancellable, true);
        success(promise, Promise::getNow, null);
        success(promise, Promise::cause, null);
        async.failure(promise, p -> p.get(), CancellationException.class);
        async.failure(promise, p -> p.get(1L, TimeUnit.SECONDS), CancellationException.class);
        async.success(promise, Promise::await, promise);
        async.success(promise, Promise::awaitThrowUncheckedOnInterrupt, promise);
        async.success(promise, Promise::awaitUninterruptibly, promise);
        async.success(promise, p -> p.await(1L, TimeUnit.SECONDS), true);
        async.success(promise, p -> p.await(1000L), true);
        async.success(promise, p -> p.awaitUninterruptibly(1L, TimeUnit.SECONDS), true);
        async.success(promise, p -> p.awaitThrowUncheckedOnInterrupt(1L, TimeUnit.SECONDS), true);
        async.success(promise, p -> p.awaitUninterruptibly(1000L), true);
        async.success(promise, p -> p.awaitUntil(System.nanoTime() + TimeUnit.SECONDS.toNanos(1L)), true);
        async.success(promise, p -> p.awaitUntilUninterruptibly(System.nanoTime() + TimeUnit.SECONDS.toNanos(1L)), true);
        async.success(promise, p -> p.awaitUntilThrowUncheckedOnInterrupt(System.nanoTime() + TimeUnit.SECONDS.toNanos(1L)), true);
        async.failure(promise, p -> p.sync(), CancellationException.class);
        async.failure(promise, p -> p.syncUninterruptibly(), CancellationException.class);
        promise.cancel(interruptIfRunning);
        failure(promise, p -> p.setFailure(null), IllegalStateException.class);
        failure(promise, p -> p.setFailure(null), IllegalStateException.class);
        Assert.assertTrue(promise.cause() instanceof CancellationException);
        success(promise, Promise::getNow, null);
        success(promise, p -> p.trySuccess(otherValue), false);
        success(promise, Promise::getNow, null);
        Assert.assertTrue(promise.cause() instanceof CancellationException);
        success(promise, Promise::isSuccess, false);
        success(promise, Promise::isDone, true);
        success(promise, Promise::isCancelled, true);
        success(promise, Promise::isCancellable, false);
        async.verify();
    }

    public <V> void testOneTimeout(Promise<V> promise)
    {
        Async async = new Async();
        async.failure(promise, p -> p.get(1L, TimeUnit.MILLISECONDS), TimeoutException.class);
        async.success(promise, p -> p.await(1L, TimeUnit.MILLISECONDS), false);
        async.success(promise, p -> p.awaitThrowUncheckedOnInterrupt(1L, TimeUnit.MILLISECONDS), false);
        async.success(promise, p -> p.await(1L), false);
        async.success(promise, p -> p.awaitUninterruptibly(1L, TimeUnit.MILLISECONDS), false);
        async.success(promise, p -> p.awaitThrowUncheckedOnInterrupt(1L, TimeUnit.MILLISECONDS), false);
        async.success(promise, p -> p.awaitUninterruptibly(1L), false);
        async.success(promise, p -> p.awaitUntil(System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(1L)), false);
        async.success(promise, p -> p.awaitUntilUninterruptibly(System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(1L)), false);
        async.success(promise, p -> p.awaitUntilThrowUncheckedOnInterrupt(System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(1L)), false);
        Uninterruptibles.sleepUninterruptibly(10L, TimeUnit.MILLISECONDS);
        async.verify();
    }

}


text: Determine if a binary tree is balanced.


text:
package proxmox

import "github.com/LunaNode/cloug/service/compute"

import "crypto/tls"
import "encoding/json"
import "net/http"

type ProxmoxJSONConfig struct {
	URL      string `json:"url"`
	Username string `json:"username"`
	Password string `json:"password"`
	Insecure bool   `json:"insecure"`
}

func ProxmoxFromJSON(jsonData []byte) (compute.Provider, error) {
	var cfg ProxmoxJSONConfig
	err := json.Unmarshal(jsonData, &cfg)
	if err != nil {
		return nil, err
	}
	proxmox, err := MakeProxmox(cfg.URL, cfg.Username, cfg.Password), nil
	if err != nil {
		return nil, err
	}

	if cfg.Insecure {
		proxmox.Client.Client = &http.Client{
			Transport: &http.Transport{
				TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
			},
		}
	}

	return proxmox, nil
}


text:
//$Id: CollectionAction.java 9673 2006-03-22 14:57:59Z steve.ebersole@jboss.com $
package org.hibernate.action;

import org.hibernate.cache.CacheConcurrencyStrategy.SoftLock;
import org.hibernate.cache.CacheException;
import org.hibernate.cache.CacheKey;
import org.hibernate.collection.PersistentCollection;
import org.hibernate.engine.SessionImplementor;
import org.hibernate.persister.collection.CollectionPersister;
import org.hibernate.pretty.MessageHelper;
import org.hibernate.util.StringHelper;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;

/**
 * Any action relating to insert/update/delete of a collection
 * @author Gavin King
 */
public abstract class CollectionAction implements Executable, Serializable, Comparable {

	private transient CollectionPersister persister;
	private final Serializable key;
	private Serializable finalKey;
	private final SessionImplementor session;
	private SoftLock lock;
	private final String collectionRole;
	private final PersistentCollection collection;

	public CollectionAction(
			final CollectionPersister persister,
			final PersistentCollection collection,
			final Serializable key,
			final SessionImplementor session)
	throws CacheException {
		this.persister = persister;
		this.session = session;
		this.key = key;
		this.collectionRole = persister.getRole();
		this.collection = collection;
	}

	protected PersistentCollection getCollection() {
		return collection;
	}

	private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
		ois.defaultReadObject();
		persister = session.getFactory().getCollectionPersister( collectionRole );
	}

	public void afterTransactionCompletion(boolean success) throws CacheException {
		if ( persister.hasCache() ) {
			final CacheKey ck = new CacheKey(
					key,
					persister.getKeyType(),
					persister.getRole(),
					session.getEntityMode(),
					session.getFactory()
				);
			persister.getCache().release(ck, lock);
		}
	}

	public boolean hasAfterTransactionCompletion() {
		return persister.hasCache();
	}

	public Serializable[] getPropertySpaces() {
		return persister.getCollectionSpaces();
	}

	protected final CollectionPersister getPersister() {
		return persister;
	}

	protected final Serializable getKey() {
		finalKey = key;
		if ( key instanceof DelayedPostInsertIdentifier ) {
			// need to look it up from the persistence-context
			finalKey = session.getPersistenceContext().getEntry( collection.getOwner() ).getId();
			if ( finalKey == key ) {
				// we may be screwed here since the collection action is about to execute
				// and we do not know the final owner key value
			}
		}
		return finalKey;
	}

	protected final SessionImplementor getSession() {
		return session;
	}

	public final void beforeExecutions() throws CacheException {
		// we need to obtain the lock before any actions are
		// executed, since this may be an inverse="true"
		// bidirectional association and it is one of the
		// earlier entity actions which actually updates
		// the database (this action is resposible for
		// second-level cache invalidation only)
		if ( persister.hasCache() ) {
			final CacheKey ck = new CacheKey(
					key,
					persister.getKeyType(),
					persister.getRole(),
					session.getEntityMode(),
					session.getFactory()
				);
			lock = persister.getCache().lock(ck, null);
		}
	}

	protected final void evict() throws CacheException {
		if ( persister.hasCache() ) {
			CacheKey ck = new CacheKey(
					key,
					persister.getKeyType(),
					persister.getRole(),
					session.getEntityMode(),
					session.getFactory()
				);
			persister.getCache().evict(ck);
		}
	}

	public String toString() {
		return StringHelper.unqualify( getClass().getName() ) +
				MessageHelper.infoString( collectionRole, key );
	}

	public int compareTo(Object other) {
		CollectionAction action = ( CollectionAction ) other;
		//sort first by role name
		int roleComparison = collectionRole.compareTo( action.collectionRole );
		if ( roleComparison != 0 ) {
			return roleComparison;
		}
		else {
			//then by fk
			return persister.getKeyType()
					.compare( key, action.key, session.getEntityMode() );
		}
	}
}


text:
import {isBlank, isPresent} from 'angular2/src/core/facade/lang';
import {CONST_EXPR} from 'angular2/src/core/facade/lang';
import {ListWrapper, StringMapWrapper} from 'angular2/src/core/facade/collection';
import {OpaqueToken} from 'angular2/src/core/di';

import * as modelModule from './model';

export const NG_VALIDATORS: OpaqueToken = CONST_EXPR(new OpaqueToken("NgValidators"));

/**
 * Provides a set of validators used by form controls.
 *
 * # Example
 *
 * ```
 * var loginControl = new Control("", Validators.required)
 * ```
 */
export class Validators {
  static required(control: modelModule.Control): {[key: string]: boolean} {
    return isBlank(control.value) || control.value == "" ? {"required": true} : null;
  }

  static nullValidator(c: any): {[key: string]: boolean} { return null; }

  static compose(validators: Function[]): Function {
    if (isBlank(validators)) return Validators.nullValidator;

    return function(control: modelModule.Control) {
      var res = ListWrapper.reduce(validators, (res, validator) => {
        var errors = validator(control);
        return isPresent(errors) ? StringMapWrapper.merge(<any>res, <any>errors) : res;
      }, {});
      return StringMapWrapper.isEmpty(res) ? null : res;
    };
  }

  static group(group: modelModule.ControlGroup): {[key: string]: any[]} {
    var res: {[key: string]: any[]} = {};
    StringMapWrapper.forEach(group.controls, (control, name) => {
      if (group.contains(name) && isPresent(control.errors)) {
        Validators._mergeErrors(control, res);
      }
    });
    return StringMapWrapper.isEmpty(res) ? null : res;
  }

  static array(array: modelModule.ControlArray): {[key: string]: any[]} {
    var res: {[key: string]: any[]} = {};
    array.controls.forEach((control) => {
      if (isPresent(control.errors)) {
        Validators._mergeErrors(control, res);
      }
    });
    return StringMapWrapper.isEmpty(res) ? null : res;
  }

  static _mergeErrors(control: modelModule.AbstractControl, res: {[key: string]: any[]}): void {
    StringMapWrapper.forEach(control.errors, (value, error) => {
      if (!StringMapWrapper.contains(res, error)) {
        res[error] = [];
      }
      var current: any[] = res[error];
      current.push(control);
    });
  }
}


text:
<?php

final class AlmanacDeviceViewController
  extends AlmanacDeviceController {

  public function shouldAllowPublic() {
    return true;
  }

  public function handleRequest(AphrontRequest $request) {
    $viewer = $request->getViewer();

    $name = $request->getURIData('name');

    $device = id(new AlmanacDeviceQuery())
      ->setViewer($viewer)
      ->withNames(array($name))
      ->needProperties(true)
      ->executeOne();
    if (!$device) {
      return new Aphront404Response();
    }

    $title = pht('Device %s', $device->getName());

    $curtain = $this->buildCurtain($device);

    $header = id(new PHUIHeaderView())
      ->setUser($viewer)
      ->setHeader($device->getName())
      ->setPolicyObject($device)
      ->setHeaderIcon('fa-server');

    $issue = null;
    if ($device->isClusterDevice()) {
      $issue = $this->addClusterMessage(
        pht('This device is bound to a cluster service.'),
        pht(
          'This device is bound to a cluster service. You do not have '.
          'permission to manage cluster services, so the device can not '.
          'be edited.'));
    }

    $interfaces = $this->buildInterfaceList($device);

    $crumbs = $this->buildApplicationCrumbs();
    $crumbs->addTextCrumb($device->getName());
    $crumbs->setBorder(true);

    $timeline = $this->buildTransactionTimeline(
      $device,
      new AlmanacDeviceTransactionQuery());
    $timeline->setShouldTerminate(true);

    $view = id(new PHUITwoColumnView())
      ->setHeader($header)
      ->setCurtain($curtain)
      ->setMainColumn(array(
          $issue,
          $interfaces,
          $this->buildAlmanacPropertiesTable($device),
          $this->buildSSHKeysTable($device),
          $this->buildServicesTable($device),
          $timeline,
        ));

    return $this->newPage()
      ->setTitle($title)
      ->setCrumbs($crumbs)
      ->appendChild(
        array(
          $view,
        ));
  }

  private function buildCurtain(AlmanacDevice $device) {
    $viewer = $this->getViewer();

    $can_edit = PhabricatorPolicyFilter::hasCapability(
      $viewer,
      $device,
      PhabricatorPolicyCapability::CAN_EDIT);

    $id = $device->getID();
    $edit_uri = $this->getApplicationURI("device/edit/{$id}/");

    $curtain = $this->newCurtainView($device);

    $curtain->addAction(
      id(new PhabricatorActionView())
        ->setIcon('fa-pencil')
        ->setName(pht('Edit Device'))
        ->setHref($edit_uri)
        ->setWorkflow(!$can_edit)
        ->setDisabled(!$can_edit));

    return $curtain;
  }

  private function buildInterfaceList(AlmanacDevice $device) {
    $viewer = $this->getViewer();
    $id = $device->getID();

    $can_edit = PhabricatorPolicyFilter::hasCapability(
      $viewer,
      $device,
      PhabricatorPolicyCapability::CAN_EDIT);

    $interfaces = id(new AlmanacInterfaceQuery())
      ->setViewer($viewer)
      ->withDevicePHIDs(array($device->getPHID()))
      ->execute();

    $table = id(new AlmanacInterfaceTableView())
      ->setUser($viewer)
      ->setInterfaces($interfaces)
      ->setCanEdit($can_edit);

    $header = id(new PHUIHeaderView())
      ->setHeader(pht('Device Interfaces'))
      ->addActionLink(
        id(new PHUIButtonView())
          ->setTag('a')
          ->setHref($this->getApplicationURI("interface/edit/?deviceID={$id}"))
          ->setWorkflow(!$can_edit)
          ->setDisabled(!$can_edit)
          ->setText(pht('Add Interface'))
          ->setIcon('fa-plus'));

    return id(new PHUIObjectBoxView())
      ->setHeader($header)
      ->setBackground(PHUIObjectBoxView::BLUE_PROPERTY)
      ->setTable($table);
  }

  private function buildSSHKeysTable(AlmanacDevice $device) {
    $viewer = $this->getViewer();
    $id = $device->getID();
    $device_phid = $device->getPHID();

    $can_edit = PhabricatorPolicyFilter::hasCapability(
      $viewer,
      $device,
      PhabricatorPolicyCapability::CAN_EDIT);

    $keys = id(new PhabricatorAuthSSHKeyQuery())
      ->setViewer($viewer)
      ->withObjectPHIDs(array($device_phid))
      ->withIsActive(true)
      ->execute();

    $table = id(new PhabricatorAuthSSHKeyTableView())
      ->setUser($viewer)
      ->setKeys($keys)
      ->setCanEdit($can_edit)
      ->setShowID(true)
      ->setShowTrusted(true)
      ->setNoDataString(pht('This device has no associated SSH public keys.'));

    $menu_button = PhabricatorAuthSSHKeyTableView::newKeyActionsMenu(
      $viewer,
      $device);

    $header = id(new PHUIHeaderView())
      ->setHeader(pht('SSH Public Keys'))
      ->addActionLink($menu_button);

    return id(new PHUIObjectBoxView())
      ->setHeader($header)
      ->setBackground(PHUIObjectBoxView::BLUE_PROPERTY)
      ->setTable($table);
  }

  private function buildServicesTable(AlmanacDevice $device) {
    $viewer = $this->getViewer();

    // NOTE: We're loading all services so we can show hidden, locked services.
    // In general, we let you know about all the things the device is bound to,
    // even if you don't have permission to see their details. This is similar
    // to exposing the existence of edges in other applications, with the
    // addition of always letting you see that locks exist.

    $services = id(new AlmanacServiceQuery())
      ->setViewer(PhabricatorUser::getOmnipotentUser())
      ->withDevicePHIDs(array($device->getPHID()))
      ->execute();

    $handles = $viewer->loadHandles(mpull($services, 'getPHID'));

    $icon_cluster = id(new PHUIIconView())
      ->setIcon('fa-sitemap');

    $rows = array();
    foreach ($services as $service) {
      $rows[] = array(
        ($service->isClusterService()
          ? $icon_cluster
          : null),
        $handles->renderHandle($service->getPHID()),
      );
    }

    $table = id(new AphrontTableView($rows))
      ->setNoDataString(pht('No services are bound to this device.'))
      ->setHeaders(
        array(
          null,
          pht('Service'),
        ))
      ->setColumnClasses(
        array(
          null,
          'wide pri',
        ));

    return id(new PHUIObjectBoxView())
      ->setHeaderText(pht('Bound Services'))
      ->setBackground(PHUIObjectBoxView::BLUE_PROPERTY)
      ->setTable($table);
  }

}


text:
cordova.define('cordova/plugin_list', function(require, exports, module) {
module.exports = [
    {
        "file": "plugins/cordova-plugin-whitelist/whitelist.js",
        "id": "cordova-plugin-whitelist.whitelist",
        "runs": true
    },
    {
        "file": "plugins/cordova-plugin-device/www/device.js",
        "id": "cordova-plugin-device.device",
        "clobbers": [
            "device"
        ]
    },
    {
        "file": "plugins/de.appplant.cordova.plugin.local-notification/www/local-notification.js",
        "id": "de.appplant.cordova.plugin.local-notification.LocalNotification",
        "clobbers": [
            "cordova.plugins.notification.local",
            "plugin.notification.local"
        ]
    },
    {
        "file": "plugins/de.appplant.cordova.plugin.local-notification/www/local-notification-core.js",
        "id": "de.appplant.cordova.plugin.local-notification.LocalNotification.Core",
        "clobbers": [
            "cordova.plugins.notification.local.core",
            "plugin.notification.local.core"
        ]
    },
    {
        "file": "plugins/de.appplant.cordova.plugin.local-notification/www/local-notification-util.js",
        "id": "de.appplant.cordova.plugin.local-notification.LocalNotification.Util",
        "merges": [
            "cordova.plugins.notification.local.core",
            "plugin.notification.local.core"
        ]
    }
];
module.exports.metadata =
// TOP OF METADATA
{}
// BOTTOM OF METADATA
});


text:
package net.maritimecloud.identityregistry.command.user;

import net.maritimecloud.common.domain.DomainIdentifier;

/**
 *
 * @author Christoffer Børrild
 */
public class UserId extends DomainIdentifier<UserId> {

    public UserId(String anId) {
        super(anId);
    }

    public UserId(UserId aUserId) {
        this(aUserId.identifier());
    }

    protected UserId() {
        super();
    }

}


text:
Overview
============

The dropavatar-rails gem aims to provide a way for images to be manipulated (resized and cropped) client side and then uploaded via XHR post request as base64 data.
Primarily this is done to reduce load on a Rails server by centralling processing images with things like Carrierwave or Paperclip.

Usage
============

### Gem install

Include the Gem in your gemfile

    gem 'dropavatar-rails'

Then include the css and js in your application.{js,css} in your Rails application

application.css:

    *= require dropavatar

application.js:

    //= require dropavatar

after a `bundle install` you should be good to start changing views

### Views

Adding the class "dropavater" to a file input (as below) will mean the following:
* a new hidden field is added to the parent form which will contain the Base64 version of the image
* the actual file input will be moved out of the form so it doesn't get submitted as part of the form (causing the remote ajax call not to work anymore)
* when an image is dropped onto the body of the page it will put the image as a string in the hidden field

```haml
  = semantic_form_for user, :remote=>true do |f|
    = f.input :photo, :as=>"file", :class=>"dropavatar"
    #...
```

Adding an image with the class "dropavater-preview" will add an image next to the

```haml
  = semantic_form_for user, :remote=>true do |f|
    = f.input :photo, :as=>"file", :class=>"dropavatar", :label=>image_tag(f.object.photo.url, :class=>"dropavatar-preview")
    #...
```

Compatibility
============
We test this gem in our project primarily using Chrome and Safari on Mac
We use Ruby 1.9.3 and Rails 3.2
Primarily we aim to use multi-browser compatible code but internally we don't test for complete compatibility (feel free to report bugs or make suggestions on improvements)

Contributing
============
If you want to contribute to the project please do:

1. Fork the project
2. Create a branch on your fork and make your changes
3. Request a pull request with your changes

*Any contributions to this project will be considered as licensed as MIT and the right to define the license for all contributed code as transferred to Niko Roberts*

Authors
============
The primary author of this library is Niko Roberts, but it is also maintained by other developers within Tasboa.

This project is part of a larger Tasboa project and it was built because we found uploading raw images through standard multipart forms was inefficient and the additional load on the server for cropping the images was an inefficient use of the powers of the web.

Versioning
============
This library aims to adhere to [Semantic Versioning 2.0.0][semver]. Violations
of this scheme should be reported as bugs. Specifically, if a minor or patch
version is released that breaks backward compatibility, that version should be
immediately yanked and/or a new version should be immediately released that
restores compatibility. Breaking changes to the public API will only be
introduced with new major versions. As a result of this policy, you can (and
should) specify a dependency on this gem using the [Pessimistic Version
Constraint][pvc] with two digits of precision. For example:

    'dropavatar-rails', '~> 1.0'
[semver]: http://semver.org/


text:
function [Out, D] = editstanzacalcs(a, k, bab, blead, qblead, z, da)
%EDITSTANZACALCS Replicate multi-stanza calculations from Ecopath
%
% [Out, D] = editstanzacalcs(a, k, bab, blead, qblead, z, da)
%
% This function replicates the EwE "Edit multi-stanza" calculations for a
% single species group.  It calculates B and QB for all mutli-stanza
% subgroups based on the B and QB of the leading stanza group.
%
% Input variables:
%
%   a:      n x 1 vector, where n is the number of subgroups (i.e. age
%           classes) in the multi-stanza group, holding age (in months) at
%           the start of stanza sub-group.  Values must be in order from
%           youngest to oldest stanza.
%
%   k:      scalar, vonBertalanffy growth curve constant (annual)
%
%   bab:    relative biomass accumulation rate (BA/B), (annual).  Can be
%           either a scalar, applying to all subgroups, or a n x 1 vector
%
%   blead:  scalar, biomass of leading stanza
%
%   qblead: scalar, consumption rate of leading stanza (/yr)
%
%   z:      n x 1 vector, mortality rate (/yr) of each subgroup, assumed to
%           be equal to the production rate (P/B) of the subgroup
%
%   da:     discretization interval (months)
%
% Output variables
%
%   Out:    structure with the following fields:
%
%           b:  n x 1, biomass values for each subgroup
%
%           qb: n x 1, consumption rate (/yr) for each subgroup
%
%           ba: n x 1, biomass accumulation rate (/yr) for each subgroup
%
%   D:      structure holding plotting variables:
%
%           x:  nx x 1 vector, age, in months
%
%           y:  nx x 4 array.  Columns correspond to:
%               1:  w, individual weight at age, based on vonBertalanffy
%                   growth curve assuming weight propertional to length
%                   cubed.
%               2:  l, survivorship at age, proportional to number at age
%               3:  w*l, population biomass at age
%               4:  exponent used in survivorship calculation, equal to
%                   sum_{0}^{a}{Z_a} - (a * (BA/B)_a), where a is age in
%                   months

% Copyright 2015 Kelly Kearney

% Setup of discretization.  Note that Ecopath uses 90% as the upper
% bound, and then has an accumulator function later on to deal with the
% extra tail end of the biomass distribution.  I'm instead just using
% 99.99% as the upper limit, which gets me very close to the same numbers
% without adding computation (I don't loop over months like EwE6 does, so
% it's just a matter of having slightly larger matrices).

amax = log(1 - 0.9999^(1/3))./-(k/12);
amax90 = log(1 - 0.9^(1/3))./-(k/12); % Old one, used for plots

xa = 0:da:ceil(amax);

% Which stanza does each month-value fall into?

ia = sum(bsxfun(@gt, xa, a));
ia(ia == 0) = 1;

% BAB value, either scalar for original EwE formulation (one rate for
% whole group), or mutliple values for Rpath extension (one per age
% group)

if isscalar(bab)
    bab2 = bab./12; % to monthly
else
    bab = bab(:); % Make sure column vector
    bab2 = bab(ia)./12; % expand, and to monthly
end

% Expand Z values to month-ages

z = z(ia);

% Biomass and consumption of each stanza

zsum = cumsum(z./12 .* da);    % Integral of Z, 0 to a
l = exp(-zsum- xa'.*bab2);      % survivorship

num = l./sum(l);
w = (1 - exp(-k.*xa'./12)).^3; % weight
wwa = w.^(2/3);

bsa = l.*w./(sum(l.*w));       % relative biomass at a given age
csa = (l.*wwa./(sum(l.*w)));   % relative consumption

alim = [a; Inf];
[bs, qs] = deal(zeros(size(a)));
for ia = 1:length(a)
    isin = xa >= alim(ia) & xa < alim(ia+1);
    bs(ia) = sum(l(isin).*w(isin))./sum(l.*w);

    qs(ia) = sum(l(isin).*wwa(isin))./sum(l.*wwa);

end

btot = blead./bs(end);
Out.b = btot .* bs;

% Note: I'm not getting the exact same values here as in EwE6. I
% think this might be related to the K calculation in the original
% code, but I haven't yet figured out exactly what they're doing
% here...
%
% (from Sub CalculateStanzaParameters, in cEcosimModel.vb)
%
%-----
% K = 0   'temporarily use k to sure the sum:
% For Age = first(BaseCB) To Second(BaseCB)
%     K = K + m_stanza.SplitNo(isp, Age) * m_stanza.WWa(isp, Age)
% Next
%
%
% If K > 0 Then K = cb(BaseCB) * Bio(BaseCB) / K 'THIS IS THE REAL CONSTANT k
%----
%
% I think this is just checking the the sum over what I call qs is 1,
% and normalizing if not.  So far my tests are always at 1 even without
% this check.

qtot = blead.*qblead./qs(end);
q = qtot .* qs;
Out.qb = q./Out.b;

% Calculate BA

Out.ba = Out.b.*bab;

% Values for plots

isless = xa < amax90;
D.x = xa(isless);
D.y = [w l w.*l zsum-xa'.*bab2];
D.y = D.y(isless,:);


text:
package ec2metadata_test

import (
	"net/http"
	"net/http/httptest"
	"os"
	"strings"
	"sync"
	"testing"
	"time"

	"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/aws/aws-sdk-go/aws"
	"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/aws/aws-sdk-go/aws/awserr"
	"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/aws/aws-sdk-go/aws/ec2metadata"
	"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/aws/aws-sdk-go/aws/request"
	"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/aws/aws-sdk-go/awstesting/unit"
	"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/aws/aws-sdk-go/internal/sdktesting"
)

func TestClientOverrideDefaultHTTPClientTimeout(t *testing.T) {
	svc := ec2metadata.New(unit.Session)

	if e, a := http.DefaultClient, svc.Config.HTTPClient; e == a {
		t.Errorf("expect %v, not to equal %v", e, a)
	}

	if e, a := 1*time.Second, svc.Config.HTTPClient.Timeout; e != a {
		t.Errorf("expect %v to be %v", e, a)
	}
}

func TestClientNotOverrideDefaultHTTPClientTimeout(t *testing.T) {
	http.DefaultClient.Transport = &http.Transport{}
	defer func() {
		http.DefaultClient.Transport = nil
	}()

	svc := ec2metadata.New(unit.Session)

	if e, a := http.DefaultClient, svc.Config.HTTPClient; e != a {
		t.Errorf("expect %v, got %v", e, a)
	}

	tr := svc.Config.HTTPClient.Transport.(*http.Transport)
	if tr == nil {
		t.Fatalf("expect transport not to be nil")
	}
	if tr.Dial != nil {
		t.Errorf("expect dial to be nil, was not")
	}
}

func TestClientDisableOverrideDefaultHTTPClientTimeout(t *testing.T) {
	svc := ec2metadata.New(unit.Session, aws.NewConfig().WithEC2MetadataDisableTimeoutOverride(true))

	if e, a := http.DefaultClient, svc.Config.HTTPClient; e != a {
		t.Errorf("expect %v, got %v", e, a)
	}
}

func TestClientOverrideDefaultHTTPClientTimeoutRace(t *testing.T) {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("us-east-1a"))
	}))
	defer server.Close()

	cfg := aws.NewConfig().WithEndpoint(server.URL)
	runEC2MetadataClients(t, cfg, 50)
}

func TestClientOverrideDefaultHTTPClientTimeoutRaceWithTransport(t *testing.T) {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("us-east-1a"))
	}))
	defer server.Close()

	cfg := aws.NewConfig().WithEndpoint(server.URL).WithHTTPClient(&http.Client{
		Transport: &http.Transport{
			DisableKeepAlives: true,
		},
	})

	runEC2MetadataClients(t, cfg, 50)
}

func TestClientDisableIMDS(t *testing.T) {
	restoreEnvFn := sdktesting.StashEnv()
	defer restoreEnvFn()

	os.Setenv("AWS_EC2_METADATA_DISABLED", "true")

	svc := ec2metadata.New(unit.Session)
	resp, err := svc.GetUserData()
	if err == nil {
		t.Fatalf("expect error, got none")
	}
	if len(resp) != 0 {
		t.Errorf("expect no response, got %v", resp)
	}

	aerr := err.(awserr.Error)
	if e, a := request.CanceledErrorCode, aerr.Code(); e != a {
		t.Errorf("expect %v error code, got %v", e, a)
	}
	if e, a := "AWS_EC2_METADATA_DISABLED", aerr.Message(); !strings.Contains(a, e) {
		t.Errorf("expect %v in error message, got %v", e, a)
	}
}

func TestClientStripPath(t *testing.T) {
	cases := map[string]struct {
		Endpoint string
		Expect   string
	}{
		"no change": {
			Endpoint: "http://example.aws",
			Expect:   "http://example.aws",
		},
		"strip path": {
			Endpoint: "http://example.aws/foo",
			Expect:   "http://example.aws",
		},
	}

	for name, c := range cases {
		t.Run(name, func(t *testing.T) {
			restoreEnvFn := sdktesting.StashEnv()
			defer restoreEnvFn()

			svc := ec2metadata.New(unit.Session, &aws.Config{
				Endpoint: aws.String(c.Endpoint),
			})

			if e, a := c.Expect, svc.ClientInfo.Endpoint; e != a {
				t.Errorf("expect %v endpoint, got %v", e, a)
			}
		})
	}
}

func runEC2MetadataClients(t *testing.T, cfg *aws.Config, atOnce int) {
	var wg sync.WaitGroup
	wg.Add(atOnce)
	svc := ec2metadata.New(unit.Session, cfg)
	for i := 0; i < atOnce; i++ {
		go func() {
			defer wg.Done()
			_, err := svc.GetUserData()
			if err != nil {
				t.Errorf("expect no error, got %v", err)
			}
		}()
	}
	wg.Wait()
}


text:
typedef NS_ENUM(NSInteger, SLRequestType) {
    SLRequestTypeGET = 0,
    SLRequestTypePOST = 1
};

@interface SLNetworkTools : AFHTTPSessionManager

+ (__kindof SLNetworkTools*)sharedNetworkTools;

- (void)requestmethodType:(SLRequestType)methodType urlString:(NSString *)urlString parameters:(NSDictionary *)parameters finished:(void (^)(NSDictionary *result, NSError *error))finished;
@end


text:
<?php
declare(strict_types = 1);

namespace Tests\Innmind\Immutable;

use Innmind\Immutable\Accumulate;
use PHPUnit\Framework\TestCase;

class AccumulateTest extends TestCase
{
    public function testInterface()
    {
        $this->assertInstanceOf(
            \Iterator::class,
            new Accumulate((static function() {
                yield 1;
            })()),
        );

        $loaded = false;
        $iterator = new Accumulate((static function() use (&$loaded) {
            yield 1;
            yield 2;
            yield 3;
            $loaded = true;
        })());

        $this->assertFalse($loaded);
        $this->assertSame([1, 2, 3], \iterator_to_array($iterator));
        $this->assertTrue($loaded);
        $this->assertSame([1, 2, 3], \iterator_to_array($iterator));
    }

    public function testSupportsPartialIterations()
    {
        $loaded = false;
        $iterator = new Accumulate((static function() use (&$loaded) {
            yield 1;
            yield 2;
            yield 3;
            yield 4;
            $loaded = true;
        })());

        $this->assertSame(0, $iterator->key());
        $this->assertSame(1, $iterator->current());
        $this->assertNull($iterator->next());
        $this->assertSame(1, $iterator->key());
        $this->assertSame(2, $iterator->current());
        $this->assertNull($iterator->rewind());
        $this->assertFalse($loaded);
        $this->assertSame([1, 2, 3, 4], \iterator_to_array($iterator));
    }

    public function testMixingPartialIterationsInGeneratorsCompositionDoesntTamperIteration()
    {
        $initial = new Accumulate((static function() {
            yield 1;
            yield 2;
        })());
        $decorate = (static function($initial) {
            foreach ($initial as $i) {
                yield $i;
            }

            yield 3;
        })($initial);
        $iterator = new Accumulate($decorate);
        $iterator->rewind();

        $this->assertTrue($iterator->valid());
        $this->assertSame([1, 2], \iterator_to_array($initial));
        $this->assertSame([1, 2, 3], \iterator_to_array($iterator));
    }
}


text:
$LOAD_PATH.unshift 'lib'
require 'textpow'

syntax = Textpow.syntax('javascript')
text = File.read('examples/jquery.js')
processor = Textpow::RecordingProcessor.new

start = Time.now.to_f
(ARGV[0] || 1).to_i.times{ syntax.parse(text,  processor) }
puts Time.now.to_f - start


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

<title>biz.sfs.ebiz.filecloud</title>
<meta name="date" content="2017-04-18">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

biz.sfs.ebiz.filecloud

Classes

Filecloud


text:
<?php

namespace Aws\Sts\Exception;

/**
 * AWS query string is malformed, does not adhere to AWS standards.
 */
class InvalidQueryParameterException extends StsException {}


text:
package org.codelibs.fess.suggest.index;

import java.util.ArrayList;
import java.util.List;

public class SuggestDeleteResponse {
    protected final List<Throwable> errors = new ArrayList<>();
    protected final long took;

    protected SuggestDeleteResponse(final List<Throwable> errors, final long took) {
        this.took = took;
        if (errors != null && !errors.isEmpty()) {
            this.errors.addAll(errors);
        }
    }

    public boolean hasError() {
        return !errors.isEmpty();
    }

    public List<Throwable> getErrors() {
        return errors;
    }

    public long getTook() {
        return took;
    }
}


text:
'use strict';
var HTTPError = require('../lib/HTTPError.js')

/**
 * Error middleware
 * Last called middlewares
 * Send the formatted error to client with the correct code or redirect
 * @param object config
 * @return function
 */
function getError(config) {
  return function error(err, req, res, next) {

    if(!err) {
      err = new HTTPError('No errors - please report', 500, '/')
    }

    var d = new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '')

    if(!config.quiet)
      if(config.dev)
        console.error(d, err.stack);
      else
        console.error(d, err.code + ' - ' + err.message)

    return res.format({
      'text/html': function() {
        if(req.flash)
          req.flash('error', err.message)

        if(err.redirect)
          return res.redirect(err.redirect)
        else
          return res.send('Too bad :(

' + err.message)
      },
      'application/json': function() {
        return res.status(err.code).json(err).end()
      },
      'default': function() {
        return res.status(406).send('Not acceptable')
      }
    })
  }
}

module.exports = getError


text:
package com.github.lindenb.knime5bio.vcf.veprest;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URLEncoder;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.knime.core.data.DataColumnSpecCreator;
import org.knime.core.data.DataRow;
import org.knime.core.data.DataTableSpec;
import org.knime.core.data.DataType;
import org.knime.core.data.append.AppendedColumnRow;
import org.knime.core.data.container.CloseableRowIterator;
import org.knime.core.data.xml.XMLCell;
import org.knime.core.data.xml.XMLCellFactory;
import org.knime.core.node.BufferedDataContainer;
import org.knime.core.node.BufferedDataTable;
import org.knime.core.node.ExecutionContext;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

import com.github.lindenb.knime5bio.htsjdk.variant.KnimeVcfIterator;

import htsjdk.samtools.util.CloserUtil;
import htsjdk.variant.variantcontext.Allele;
import htsjdk.variant.variantcontext.VariantContext;

public class VepRestNodeModel extends AbstractVepRestNodeModel {
@Override
    protected BufferedDataTable[] execute(
    		final BufferedDataTable inDataheader,
    		final BufferedDataTable inDatabody,
    		final ExecutionContext exec) throws Exception
        {
		BufferedDataContainer container=null;
		CloseableRowIterator iter=null;
		 KnimeVcfIterator vcfIn = null;
     	try {
     		final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
     		dbf.setIgnoringComments(true);
     		dbf.setNamespaceAware(false);
     		dbf.setXIncludeAware(false);
     		final DocumentBuilder domBuilder = dbf.newDocumentBuilder();

     		long lastCall=System.currentTimeMillis();
     		final DataTableSpec spec0 = inDatabody.getSpec();
     		final DataTableSpec outspec = new DataTableSpec(
     				spec0,
     				new DataTableSpec(new DataColumnSpecCreator("VEP",XMLCell.TYPE).createSpec())
     				);

     		container = exec.createDataContainer(outspec);

     		exec.createDataContainer(outspec);

     		vcfIn = new KnimeVcfIterator( inDataheader,inDatabody );
     		iter = inDatabody.iterator();
     		while(iter.hasNext())
     			{
     			final DataRow row= iter.next();
     			final VariantContext ctx = vcfIn.decode(row);

     			Document dom=null;
     			for(final Allele alt:ctx.getAlternateAlleles())
	     			{
	     			if(alt.isSymbolic()) continue;
	     			final  StringBuilder uri=new StringBuilder(super.__vepuri.getStringValue());
	     			uri.append(URLEncoder.encode(ctx.getContig(),"UTF-8"));
	     			uri.append(":").append(ctx.getStart()).append("-").append(ctx.getStart()).
	     			append(":1/").append(alt.getDisplayString());
	     			uri.append("?content-type=text/xml");
	     			if(!__extraParams.getStringValue().trim().isEmpty())
		     			{
		     			uri.append("&");
		     			uri.append(__extraParams.getStringValue().trim());
		     			}
	     			final long now= System.currentTimeMillis();

	     			final  long diff = now - lastCall;
	     			if(diff < (long)__waitSeconds.getIntValue()*1000L) {
	     				Thread.sleep((long)__waitSeconds.getIntValue()*1000L-diff);
	     				}

	     			Document lastdoc=null ;
	     			try
	     				{
	     				lastdoc=domBuilder.parse(uri.toString());
	     				}
	     			catch(Exception err) {
	     				lastdoc=domBuilder.newDocument();
	     				Element errorTag = lastdoc.createElement("error");
	     				errorTag.setAttribute("message", String.valueOf(err.getMessage()));
	     				lastdoc.appendChild(errorTag);
	     				StringWriter sw= new StringWriter();
	     				err.printStackTrace(new PrintWriter(sw));
	     				errorTag.appendChild(lastdoc.createTextNode(sw.toString()));
	     				}
	     			if(dom==null) {
	     				dom=lastdoc;
	     				}
	     			else
	     				{
	     				final Element root1 = dom.getDocumentElement();
	     				final Element root2 = lastdoc.getDocumentElement();
	     				for(Node c2=root2.getFirstChild();c2!=null;c2=c2.getNextSibling()) {
	     					if(c2.getNodeType()!=Node.ELEMENT_NODE) continue;
	     					root1.appendChild(dom.importNode(c2, true));
	     					}
	     				}
	     			}

     			container.addRowToTable( new AppendedColumnRow(row,
     					dom==null?DataType.getMissingCell():XMLCellFactory.create(dom))
     					);

     			exec.checkCanceled();
     			}
     		vcfIn.close();vcfIn=null;
     		iter.close();iter=null;
     		container.close();
     		final BufferedDataTable table= container.getTable();
     		container=null;
     		return new BufferedDataTable[]{table};
		} catch (Exception e) {
			getLogger().error("boum", e);
			e.printStackTrace();
			throw e;
		} finally {
			CloserUtil.close(vcfIn);
			CloserUtil.close(iter);
		}
        }
}


text:
Administrator Console
*********************

How Do I Access the Console?
============================
Navigate to http://cloud.neurodata.io/nd/accounts/login/ and if you do not have an account select the register option below the sign in box. Once you create an account log into the console and you will be taken to the main page.

How Do I Create a Dataset?
==========================

Navigate to the datasets drop down menu and select create dataset. Fill in the appropriate data fields for each line (a full explanation of each can be found in :ref:`the data model <datamodel>`). Click create dataset and you should be re-directed to the dataset main page, where you will now see a new dataset with the data you inputted. To use the dataset create a new project/token.

How Do I Update an Existing Dataset?
====================================
To update a dataset navigate to the datasets drop-down menu and select view datasets. To the right of the name of the dataset you wish to modify select "Update Dataset" and change the fields as desired. Warning, editing some of the fields of a dataset can cause data to become unusable, it is preferable for to create a new project if the parameters of your dataset change.

How Do I Create a Project?
==========================

If you have not already created a dataset follow the tutorial here `How Do I Create a Dataset?`_). To create a project navigate to the projects drop down menu and select create project. Fill in the appropriate fields, an explanation of each of which you can see in :ref:`the data model <datamodel>`. Click create project and you should be re-directed to the project main page, where you will now see a new project with the data you selected.

How Do I Update an Existing Project?
====================================
To update a project navigate to the projects drop-down menu and select view projects. To the right of the name of the project you wish to modify select "Update/Details" and change the fields as desired. Warning, editing some of the fields of a project can cause data to become unusable, it is preferable for to create a new project if the parameters of your project change.

How Do I Create a Channel?
==========================

If you have not created a project yet follow the above tutorial in `How Do I Create a Project?`_. Then navigate to the projects drop down menu and select projects. Select the project you wish to create a channel for and select channel, then add channel. Fill in the appropriate fields, an explanation of each of which you can see in :ref:`the data model <datamodel>`. Click create channel and you should be re-directe to the project's channel page, where you will now see a new channel in the project.

How Do I Update an Existing Channel?
====================================
To update a channel navigate to the channels menu to the right of the project name. To the right of the name of the channel you wish to modify select "Update" and change the fields as desired. Warning, editing some of the fields of a channel can cause data to become unusable, it is preferable for to create a new channel if the parameters of your channel change.

How Do I Create a Token?
========================
If you have not created a project yet follow the above tutorial in `How Do I Create a Project?`_. Then navigate to the projects drop down menu and select projects. Select the project you wish to create another token for and select tokens, then add token.

How Do I Create a Token?
========================
To modify the token navigate to the tokens sub-menu in the project menu and select the "Update" option on the token you wish to edit.


text:
// Copyright 2014 Hazy Research (http://i.stanford.edu/hazy)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "app/glm_dense_sgd.h"
#include "app/glm_sparse_sgd.h"
#include "app/glm_dense_scd.h"

/**
 * \brief This is one example of running SGD for logistic regression
 * in DimmWitted. You can find more examples in test/glm_dense.cc
 * and test/glm_sparse.cc, and the documented code in
 * app/glm_dense_sgd.h
 */
int main(int argc, char** argv){
  double rs = test_glm_dense_sgd<DW_MODELREPL_SINGLETHREAD_DEBUG, DW_SHARDING>();
  std::cout << "SUM OF MODEL (Should be ~1.3-1.4): " << rs << std::endl;
  return 0;
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

   <modelVersion>4.0.0</modelVersion>
   <parent>
      <groupId>net.sourceforge.ctakesresources</groupId>
      <artifactId>ctakes-resources</artifactId>
      <version>3.2.1.1</version>
   </parent>
   <artifactId>ctakes-resources-snomed-rword-hsqldb-2011ab</artifactId>
   <name>ctakes-resources-snomed-rword-hsqldb-2011ab</name>
   <description>hsql rare-word index db with 2011ab umls concepts and info for cTakes semantic groups</description>
   <url>http://ctakes.apache.org</url>
   <inceptionYear>2014</inceptionYear>
</project>


text:
/// Copyright (c) 2012 Ecma International.  All rights reserved.
/// Ecma International makes this code available under the terms and conditions set
/// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
/// "Use Terms").   Any redistribution of this code must retain the above
/// copyright and this notice and otherwise comply with the Use Terms.
/**
 * @path ch10/10.4/10.4.3/10.4.3-1-35gs.js
 * @description Strict - checking 'this' from a global scope (Anonymous FunctionExpression defined within an Anonymous FunctionExpression inside strict mode)
 * @onlyStrict
 */

"use strict";
if (! ((function () {
    return ((function () {
        return typeof this;
    })()==="undefined") && ((typeof this)==="undefined");
})())) {
    throw "'this' had incorrect value!";
}


text:
import reflect.runtime.currentMirror

object Name {
  def className(o: Any) = {
    currentMirror.reflect(o).symbol.toString.replace('$', ' ').split(' ').last
  }
}

trait Name {
  override def toString: String = Name.className(this)
}

class Chef extends Name

println(new Chef)


text:
<!doctype html>

    <title>Test Page</title>


text:
@class StuartRegion;

@interface StuartRegionBuilder : NSObject

@property (nonatomic, copy) NSString *name;
@property (nonatomic, strong) StuartCountry *country;

- (StuartRegion *)build;

@end

@interface StuartRegion : NSObject

- (instancetype)initWithBuilder:(StuartRegionBuilder *)builder;

+ (instancetype)regionWithBlock:(void (^)(StuartRegionBuilder *))builderBlock;

@property (nonatomic, readonly) NSString *name;
@property (nonatomic, readonly) StuartCountry *country;

@end


text:
This is the main repository for the Lokki project.

Lokki is an Open Source Project that develops a secure location sharing service. The code is based on a service developed by F-Secure Corporation and open sourced at the end of 2014. This repository is used for high-level tasks, general documentation, and the project web site (in the gh-pages branch).

# Code

[lokki](https://github.com/TheSoftwareFactory/lokki) -- This is the main repository for the project, and includes things like high-level issues, GitHub pages, user documentation, and general developer documentation.

[lokki-android](https://github.com/TheSoftwareFactory/lokki-android) -- This contains the Android client code as well as developer documentation and issues related to the Android client.

[lokki-server](https://github.com/TheSoftwareFactory/lokki-server) -- This contains the Node.js server code as well as developer documentation and issues related to the backend.

[lokki-ios](https://github.com/TheSoftwareFactory/lokki-ios) -- This contains the iOS client code as well as developer documentation and issues related to the iOS client. Not maintained at the moment.

[lokki-wp8](https://github.com/TheSoftwareFactory/lokki-wp8) -- This contains the Windows Phone client code as well as developer documentation and issues related to the Windows Phone client. Not maintained at the moment.

## Workflow

Project roughly follows the process described in [this guide](https://guides.github.com/activities/contributing-to-open-source/), with the following additions:

- Trivial things can be fixed by doing a pull request without having an related issue for them.
- When you start working on an issue, assign yourself to it. You don't have permissions to do that, comment to the issue that you're working on it.
- When creating a pull request, please add words "Connects to #0", replacing #0 with the relevant issue ID, to the pull request description. This [connects the pull request](https://github.com/waffleio/waffle.io/wiki/FAQs#prs-connect-keywords) to the relevant issue in our [waffle board](https://waffle.io/thesoftwarefactory/lokki).
- After making a pull request, you might want to be proactive and try to get someone to review and possibly merge it.
- We're using Continuous Integration, make sure the PR passes on Travis before merging.

# Communication and Collaboration

Join #lokki on IRCNet (for example, irc.stealth.net).

[waffle.io task board](https://waffle.io/thesoftwarefactory/lokki)

[![Stories in Ready](https://badge.waffle.io/thesoftwarefactory/lokki.svg?label=ready&title=Ready)](http://waffle.io/thesoftwarefactory/lokki)


text:
layout: post
title: German mother masturbates
titleinfo: pornvd
desc: Watch German mother masturbates. Pornhub is the ultimate xxx porn and sex site.
---

German mother masturbates

Watch German mother masturbates. Pornhub is the ultimate xxx porn and sex site.


text:
<!doctype html>
<html>
<head>
	<title>Test</title>
	<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>

</body>
</html>


text:
/* tslint:disable:no-unused-variable */

import { TestBed, async, inject } from '@angular/core/testing';
import { CustomerService } from './customer.service';

describe('Service: Customer', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [CustomerService]
    });
  });

  it('should ...', inject([CustomerService], (service: CustomerService) => {
    expect(service).toBeTruthy();
  }));
});


text:
using System.Security.Policy;
using System.Security.Principal;

using AutoMapper;

using EstimatorX.Core.Options;
using EstimatorX.Core.Repositories;
using EstimatorX.Shared.Definitions;
using EstimatorX.Shared.Extensions;
using EstimatorX.Shared.Models;

using FluentRest;

using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

using SendGrid;
using SendGrid.Helpers.Mail;

namespace EstimatorX.Core.Services;

public class InviteService : OrganizationServiceBase<IInviteRepository, Invite>, IServiceTransient, IInviteService
{
    private readonly ISendGridClient _sendGridClient;
    private readonly IOptions<HostingConfiguration> _hostingOptions;
    private readonly IOptions<SendGridConfiguration> _sendGridOptions;
    private readonly IOrganizationRepository _organizationRepository;

    public InviteService(
        ILoggerFactory loggerFactory,
        IMapper mapper,
        IInviteRepository repository,
        IUserCache userCache,
        ISendGridClient sendGridClient,
        IOptions<HostingConfiguration> hostingOptions,
        IOptions<SendGridConfiguration> sendGridOptions,
        IOrganizationRepository organizationRepository)
        : base(loggerFactory, mapper, repository, userCache)
    {
        _sendGridClient = sendGridClient;
        _hostingOptions = hostingOptions;
        _sendGridOptions = sendGridOptions;
        _organizationRepository = organizationRepository;
    }

    public override async Task<Invite> Create(Invite model, IPrincipal principal, CancellationToken cancellationToken)
    {
        var result = await base.Create(model, principal, cancellationToken);

        await Send(result, principal, cancellationToken);

        return result;
    }

    public async Task<Invite> LoadBySecurityKey(string securityKey, IPrincipal principal, CancellationToken cancellationToken)
    {
        var entity = await Repository.FindOneAsync(i => i.SecurityKey == securityKey, cancellationToken: cancellationToken);
        if (entity == null)
            throw new DomainException(System.Net.HttpStatusCode.Forbidden, "Invite not found");

        return entity;
    }

    public async Task<bool> Send(string id, string partitionKey, IPrincipal principal, CancellationToken cancellationToken)
    {
        var invite = await Repository.FindAsync(id, partitionKey, cancellationToken: cancellationToken);
        if (invite == null)
            throw new DomainException(System.Net.HttpStatusCode.InternalServerError, "Invite not found");

        return await Send(invite, principal, cancellationToken);
    }

    public async Task<bool> Redeem(string securityKey, IPrincipal principal, CancellationToken cancellationToken)
    {
        var invite = await Repository.FindOneAsync(i => i.SecurityKey == securityKey, cancellationToken: cancellationToken);
        if (invite == null)
            throw new DomainException(System.Net.HttpStatusCode.BadRequest, "Invalid invite code");

        var user = await CurrentUser(principal);
        if (user == null)
            throw new DomainException(System.Net.HttpStatusCode.BadRequest, "Invalid user");

        var organization = await _organizationRepository.FindAsync(invite.OrganizationId, cancellationToken: cancellationToken);
        if (user == null)
            throw new DomainException(System.Net.HttpStatusCode.BadRequest, "Invalid organization");

        // add user to org
        if (!organization.Members.Any(m => m.Id == user.Id))
        {
            var member = new OrganizationMember
            {
                Id = user.Id,
                Email = user.Email,
                Name = user.Name
            };
            organization.Members.Add(member);

            await _organizationRepository.SaveAsync(organization, cancellationToken);
        }

        // add org to user
        if (!user.Organizations.Any(o => o.Id == organization.Id))
        {
            var organizationName = new IdentifierName
            {
                Id = organization.Id,
                Name = organization.Name
            };
            user.Organizations.Add(organizationName);

            await UserCache.Repository.SaveAsync(user, cancellationToken);
            UserCache.Clear(user.Id);
        }

        // remove invite
        await Repository.DeleteAsync(invite, cancellationToken);

        return true;
    }

    protected override IQueryable<Invite> SearchQuery(IQueryable<Invite> query, string searchTerm)
    {
        if (searchTerm.IsNullOrWhiteSpace())
            return query;

        return query
            .Where(u => u.Name.Contains(searchTerm, StringComparison.InvariantCultureIgnoreCase));
    }

    private async Task<bool> Send(Invite invite, IPrincipal principal, CancellationToken cancellationToken)
    {
        if (!await HasAccess(principal, invite, cancellationToken))
            throw new DomainException(System.Net.HttpStatusCode.Forbidden, "Not authorized to load this entity");

        Logger.LogInformation("Sending invite to: {email}; Organization: {organziation}", invite.Email, invite.OrganizationName);

        string senderName = principal.GetName();
        string senderEmail = principal.GetEmail();

        var link = new UrlBuilder(_hostingOptions.Value.ClientDomain)
            .AppendPath("invite")
            .AppendPath(invite.SecurityKey);

        string subject = $"Invite to the {invite.OrganizationName} organization on EstimatorX.com";
        string body = $"
{senderName} invited you to join the {invite.OrganizationName} organization on EstimatorX.com.
" +
                      "
EstimatorX is a simple project estimation application.
" +
                      $"
{link}
";

        var message = new SendGridMessage();
        message.From = new EmailAddress(_sendGridOptions.Value.FromEmail, _sendGridOptions.Value.FromName);

        if (senderEmail.HasValue())
            message.ReplyTo = new EmailAddress(senderEmail, senderName);

        message.AddTo(invite.Email, invite.Name);

        message.Subject = subject;
        message.AddContent(System.Net.Mime.MediaTypeNames.Text.Html, body);

        var response = await _sendGridClient.SendEmailAsync(message, cancellationToken);

        Logger.LogInformation("Sent invite to: {email}; Organization: {organziation}; Status: {httpStatus}", invite.Email, invite.OrganizationName, response.StatusCode);

        return response.IsSuccessStatusCode;
    }
}


text:
import { FormikValues, useFormikContext } from 'formik';
import * as Yup from 'yup';
import { equals, prop } from 'ramda';

import { Typography } from '@mui/material';
import HelpOutlineIcon from '@mui/icons-material/HelpOutline';

import { SelectEntry } from '../InputField/Select';
import { Listing } from '../api/models';

import {
  Group,
  InputProps,
  InputPropsWithoutGroup,
  InputType
} from './Inputs/models';

export interface BasicForm {
  active: boolean;
  activeSortableFieldsTable: boolean;
  animals: Array<SelectEntry>;
  anotherText: string;
  class: { id: number; name: string } | null;
  custom: string;
  email: string;
  group: { id: number; name: string } | null;
  inviteUsers: Array<{
    role: SelectEntry;
    user: string;
  }>;
  inviteUsers2: Array<string>;
  isForced: boolean;
  language: string;
  name: string;
  password: string;
  roleMapping: Array<{
    role: SelectEntry;
    value: string;
  }>;
  scopes: Array<string>;
  sports: Array<SelectEntry>;
}

const selectEntryValidationSchema = Yup.object().shape({
  id: Yup.number().required('Required'),
  name: Yup.string().required('Required')
});

export const basicFormValidationSchema = Yup.object().shape({
  active: Yup.boolean().required('Active is required'),
  activeSortableFieldsTable: Yup.boolean().required(
    'Active Sortable FieldsTable is required'
  ),
  animals: Yup.array().of(selectEntryValidationSchema.required('Required')),
  anotherText: Yup.string(),
  class: selectEntryValidationSchema.nullable().required('Required'),
  custom: Yup.string().required('Custom is required'),
  email: Yup.string().email('Invalid email').required('Email is required'),
  group: selectEntryValidationSchema.nullable().required('Required'),
  inviteUsers: Yup.array().of(
    Yup.object({
      email: Yup.string()
        .email('Invalid user email')
        .required('Email is required'),
      role: selectEntryValidationSchema
    })
  ),
  inviteUsers2: Yup.array().of(Yup.string().email('Invalid user email')),
  isForced: Yup.boolean().required('Is forced is required'),
  language: Yup.string().required('Language is required'),
  name: Yup.string().required('Name is required'),
  password: Yup.string().required('Password is required'),
  roleMapping: Yup.array().of(
    Yup.object({
      role: selectEntryValidationSchema,
      value: Yup.string().required('Role value is required')
    })
  ),
  scopes: Yup.array().of(
    Yup.string().min(3, '3 characters min').required('Required')
  ),
  sports: Yup.array()
    .of(selectEntryValidationSchema.required('Required'))
    .min(2, 'Choose at least 2 sports')
});

const roleEntries: Array<SelectEntry> = [
  {
    id: 1,
    name: 'Administrator'
  },
  {
    id: 2,
    name: 'User'
  },
  {
    id: 3,
    name: 'Editor'
  }
];

export const basicFormInitialValues = {
  active: false,
  activeSortableFieldsTable: false,
  animals: [],
  class: { id: 0, name: 'Class 0' },
  custom: '',
  email: '',
  group: null,
  inviteUsers: [],
  inviteUsers2: [],
  isForced: false,
  language: 'French',
  name: '',
  password: '',
  roleMapping: [
    {
      priority: 0,
      role: roleEntries[0],
      value: 'example'
    },
    {
      priority: 1,
      role: roleEntries[1],
      value: 'example2'
    },
    {
      priority: 2,
      role: roleEntries[2],
      value: 'example3'
    }
  ],
  scopes: [],
  sports: []
};

export const classOptions = [...Array(10).keys()].map((idx) => ({
  id: idx,
  name: `Class ${idx}`
}));

export const sportOptions = [...Array(10).keys()].map((idx) => ({
  id: idx,
  name: `Sport ${idx}`
}));

export const basicFormGroups: Array<Group> = [
  {
    name: 'First group',
    order: 1
  },
  {
    EndIcon: HelpOutlineIcon,
    TooltipContent: (): JSX.Element => <Typography>Tooltip content</Typography>,
    name: 'Second group',
    order: 2
  }
];

export const basicFormInputs: Array<InputProps> = [
  {
    fieldName: 'name',
    group: 'First group',
    label: 'Name',
    type: InputType.Text
  },
  {
    fieldName: 'email',
    group: 'First group',
    label: 'Email',
    type: InputType.Text
  },
  {
    fieldName: 'active',
    group: 'Second group',
    label: 'Active',
    type: InputType.Switch
  },
  {
    additionalLabel: 'This a very special label',
    fieldName: 'password',
    group: 'First group',
    label: 'Password',
    type: InputType.Password
  },
  {
    fieldName: 'language',
    group: 'First group',
    label: 'Language',
    radio: {
      options: [
        {
          label: 'French',
          value: 'French'
        },
        {
          label: 'English',
          value: 'English'
        }
      ]
    },
    type: InputType.Radio
  },
  {
    fieldName: 'anotherText',
    group: 'First group',
    hideInput: ({ language }) => equals(language, 'French'),
    label: 'Another Text input',
    type: InputType.Text
  },
  {
    fieldName: 'isForced',
    group: 'First group',
    label: 'Is Forced?',
    radio: {
      options: [
        {
          label: 'Is not forced',
          value: false
        },
        {
          label: 'Is forced',
          value: true
        }
      ]
    },
    type: InputType.Radio
  },
  {
    fieldName: '',
    grid: {
      columns: [
        {
          autocomplete: {
            options: classOptions
          },
          fieldName: 'class',
          label: 'Class (Single autocomplete)',
          type: InputType.SingleAutocomplete
        },
        {
          autocomplete: {
            options: sportOptions
          },
          fieldName: 'sports',
          label: 'Sports (Multi autocomplete)',
          type: InputType.MultiAutocomplete
        }
      ]
    },
    group: 'First group',
    label: 'autocompletes',
    type: InputType.Grid
  },
  {
    autocomplete: {
      creatable: true,
      options: []
    },
    fieldName: 'scopes',
    group: 'First group',
    label: 'Scopes (Multi autocomplete that allows value creation)',
    type: InputType.MultiAutocomplete
  },
  {
    fieldName: '',
    grid: {
      columns: [
        {
          connectedAutocomplete: {
            additionalConditionParameters: [],
            endpoint: 'endpoint'
          },
          fieldName: 'group',
          label: 'Group (Single connected autocomplete)',
          type: InputType.SingleConnectedAutocomplete
        },
        {
          connectedAutocomplete: {
            additionalConditionParameters: [],
            endpoint: 'endpoint'
          },
          fieldName: 'animals',
          label: 'Animals (Multi connected autocomplete)',
          type: InputType.MultiConnectedAutocomplete
        }
      ],
      gridTemplateColumns: '400px 1fr'
    },
    group: 'First group',
    label: 'connected autocompletes',
    type: InputType.Grid
  },
  {
    custom: {
      Component: ({ label }: InputPropsWithoutGroup): JSX.Element => (
        <Typography>This is a {label} component</Typography>
      )
    },
    fieldName: 'custom',
    group: 'Second group',
    label: 'Custom',
    type: InputType.Custom
  },
  {
    fieldName: 'inviteUsers',
    fieldsTable: {
      columns: [
        {
          fieldName: 'email',
          label: 'Email',
          required: true,
          type: InputType.Text
        },
        {
          autocomplete: {
            creatable: false,
            options: roleEntries
          },
          fieldName: 'role',
          label: 'Role',
          type: InputType.SingleAutocomplete
        }
      ],
      defaultRowValue: {
        email: 'example@test.fr',
        role: null
      },
      deleteLabel: 'Delete'
    },
    group: 'First group',
    label: 'inviteUsers',
    type: InputType.FieldsTable
  },
  {
    fieldName: 'inviteUsers2',
    fieldsTable: {
      columns: [
        {
          fieldName: 'email',
          label: 'Email',
          required: true,
          type: InputType.Text
        }
      ],
      defaultRowValue: 'example',
      deleteLabel: 'Delete',
      hasSingleValue: true
    },
    group: 'First group',
    label: 'inviteUsers2',
    type: InputType.FieldsTable
  },
  {
    fieldName: 'activeSortableFieldsTable',
    group: 'First group',
    label: 'Active Sortable Fields Table',
    type: InputType.Switch
  },
  {
    fieldName: 'roleMapping',
    fieldsTable: {
      columns: [
        {
          fieldName: 'value',
          label: 'RoleValue',
          required: true,
          type: InputType.Text
        },
        {
          autocomplete: {
            creatable: false,
            options: roleEntries
          },
          fieldName: 'role',
          label: 'RoleAcl',
          type: InputType.SingleAutocomplete
        }
      ],
      defaultRowValue: {
        role: null,
        value: ''
      },
      deleteLabel: 'Delete',
      getSortable: (values: FormikValues): boolean =>
        prop('activeSortableFieldsTable', values)
    },
    group: 'First group',
    label: 'roleMapping',
    type: InputType.FieldsTable
  }
];

export const CustomButton = (): JSX.Element => {
  const { dirty, isValid } = useFormikContext();

  return (
    <div>
      <Typography>Has form changed? {JSON.stringify(dirty)}</Typography>
      <Typography>Is valid? {JSON.stringify(isValid)}</Typography>
    </div>
  );
};

const buildEntities = (from): Array<SelectEntry> => {
  return Array(10)
    .fill(0)
    .map((_, index) => ({
      id: from + index,
      name: `Entity ${from + index}`
    }));
};

export const buildResult = (page): Listing<SelectEntry> => ({
  meta: {
    limit: 10,
    page,
    total: 40
  },
  result: buildEntities((page - 1) * 10)
});