text:
package com.getbeamapp.transit.android.prompt;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Queue;
import java.util.Stack;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;

import android.content.res.Resources;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.webkit.WebView;

import com.getbeamapp.transit.R;
import com.getbeamapp.transit.android.AndroidTransitContext;
import com.getbeamapp.transit.android.TransitAdapter;
import com.getbeamapp.transit.common.TransitException;
import com.getbeamapp.transit.common.TransitJSObject;
import com.getbeamapp.transit.common.TransitContext.PreparedInvocation;

public class TransitPromptAdapter implements TransitAdapter {

    enum TransitRequest {
        INVOKE("__TRANSIT_MAGIC_INVOKE"),
        POLL("__TRANSIT_MAGIC_POLL"),
        RETURN("__TRANSIT_MAGIC_RETURN"),
        EXCEPTION("__TRANSIT_MAGIC_EXCEPTION"),
        BATCH_INVOKE("__TRANSIT_MAGIC_BATCH_INVOKE");

        private String string;

        TransitRequest(String string) {
            assert (string != null);
            this.string = string;
        }

        public static TransitRequest fromString(String s) {
            for (TransitRequest r : TransitRequest.values()) {
                if (r.string.equals(s)) {
                    return r;
                }
            }

            return null;
        }
    }

    enum TransitResponse {
        RETURN("RETURN"),
        EXCEPTION("EXCEPTION"),
        EVAL("EVAL");

        private String string;

        TransitResponse(String string) {
            assert (string != null);
            this.string = string;
        }

        public String getString() {
            return string;
        }
    }

    public static final String TAG = "TransitAdapter";

    private final BlockingDeque<TransitAction> actions = new LinkedBlockingDeque<TransitAction>();

    final WebView webView;

    private AndroidTransitContext context;

    private boolean active = false;

    private boolean polling = false;

    private final ExecutorService asyncThreadPool;

    private final ExecutorService genericThreadPool;

    private final Handler handler;

    private Queue<String> asyncEvaluations = new ConcurrentLinkedQueue<String>();

    private final Runnable consumeAsyncEvaluations;

    private Object notifiedUiThreadLock = new Object();

    private boolean notifiedUiThread = false;

    private boolean finalized = false;

    public TransitPromptAdapter(WebView forWebView) {
        this.webView = forWebView;
        this.context = new AndroidTransitContext(this);
        this.asyncThreadPool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
        this.genericThreadPool = Executors.newCachedThreadPool();
        this.handler = new Handler(Looper.getMainLooper());
        this.consumeAsyncEvaluations = new Runnable() {

            @Override
            public void run() {
                if (webView == null || finalized) {
                    return;
                }

                synchronized (notifiedUiThreadLock) {
                    notifiedUiThread = false;
                }

                StringBuilder script = new StringBuilder();
                script.append("javascript:");

                boolean hasScripts = false;
                String current = null;

                while ((current = asyncEvaluations.poll()) != null) {
                    hasScripts = true;
                    script.append("try{");
                    script.append(current);
                    script.append("}catch(e){console.error(e)};");
                }

                if (hasScripts) {
                    webView.loadUrl(script.toString());
                }
            }

        };
    }

    public final void initialize() {
        Log.d(TAG, "Injecting script...");
        this.active = false;
        this.polling = false;
        webView.loadUrl("javascript:" + getScript());
    }

    public static AndroidTransitContext createContext(WebView webView) {
        return createContext(webView, new TransitChromeClient());
    }

    public static AndroidTransitContext createContext(WebView webView, TransitChromeClient client) {
        TransitPromptAdapter adapter = new TransitPromptAdapter(webView);
        client.setTransitAdapter(adapter);
        webView.setWebChromeClient(client);
        return adapter.getContext();
    }

    public Runnable wrapInvocation(final TransitJSObject invocation) {
        return new Runnable() {
            @Override
            public void run() {
                try {
                    doInvokeNativeAsync(invocation);
                } catch (Exception e) {
                    Log.e(TAG, String.format("[%s] Invocation of `%s` failed", TransitRequest.BATCH_INVOKE, invocation), e);
                }
            }
        };
    }

    private void doBatchInvoke(final String payload) {
        genericThreadPool.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    for (Object invocation : context.lazyParse(payload)) {
                        assert invocation instanceof TransitJSObject;
                        asyncThreadPool.submit(wrapInvocation((TransitJSObject) invocation));
                    }
                } catch (Exception e) {
                    Log.e(TAG, "[%s] Batch invocation failed", e);
                }
            }
        });
    }

    public boolean onJSCall(final String requestType, final String payload, final TransitFuture<String> result) {

        Log.d(TAG, String.format("type: %s\npayload: %s", requestType, payload));
        final TransitRequest request = TransitRequest.fromString(requestType);

        if (request == null) {
            return false;
        }

        switch (request) {
        case POLL:
            assert !isActive();
            begin(true);
            process(result);
            break;
        case BATCH_INVOKE:
            assert !isActive();
            assert payload.charAt(0) == '[';
            doBatchInvoke(payload);
            result.resolve();
            return true;
        case INVOKE:
            begin();
            doInvokeNative((TransitJSObject) context.parse(payload));
            process(result);
            break;
        case RETURN:
            assert isActive();
            TransitEvalAction actionToResolve = waitingEvaluations.pop();
            Object returnValue = context.parse(payload);
            actionToResolve.resolveWith(returnValue);
            Log.d(TAG, String.format("[%s] %s -> %s", request, actionToResolve.getStringToEvaluate(), returnValue));
            process(result);
            break;
        case EXCEPTION:
            assert isActive();
            TransitEvalAction actionToReject = waitingEvaluations.pop();
            String error = String.valueOf(context.parse(payload));
            actionToReject.rejectWith(error);
            Log.d(TAG, String.format("[%s] Rejected `%s` with `%s`", request, actionToReject.getStringToEvaluate(), error));
            process(result);
            break;
        }

        return true;
    }

    private boolean isUiThread() {
        return Looper.getMainLooper().getThread() == Thread.currentThread();
    }

    protected void ensureOnUiThread(Runnable runnable) {
        if (isUiThread()) {
            runnable.run();
        } else {
            handler.postDelayed(runnable, 1L);
        }
    }

    protected void ensureOnNonUiThread(Runnable runnable) {
        if (isUiThread()) {
            genericThreadPool.submit(runnable);
        } else {
            runnable.run();
        }
    }

    private void pushAction(TransitAction action) {
        assert action != null;
        this.actions.offerFirst(action);
    }

    @Override
    public void releaseProxy(String proxyId) {
        evaluateAsync("transit.releaseElementWithId(\"" + proxyId + "\")");
    }

    @Override
    public final void evaluateAsync(final String stringToEvaluate) {
        Log.d(TAG, "evaluateAsync: " + stringToEvaluate);

        asyncEvaluations.add(stringToEvaluate);

        boolean mustNotify = false;
        synchronized (notifiedUiThreadLock) {
            mustNotify = !notifiedUiThread;

            if (!notifiedUiThread) {
                notifiedUiThread = true;
            }
        }

        if (mustNotify) {
            ensureOnUiThread(consumeAsyncEvaluations);
        }
    }

    @Override
    protected void finalize() throws Throwable {
        this.finalized = true;
        super.finalize();
    }

    public final Object evaluate(String stringToEvaluate) {
        Log.d(TAG, "evaluate: " + stringToEvaluate);

        // TODO: Make sure no "outside" evaluate-calls cause conflicts with
        // active Transit threads

        boolean mustInitPoll = !isActive();

        if (mustInitPoll && isUiThread()) {
            throw new IllegalThreadStateException("Can't call (initial) blocking eval from UI thread.");
        }

        TransitEvalAction action = new TransitEvalAction(stringToEvaluate);
        pushAction(action);

        if (mustInitPoll) {
            pollBegin();
        }

        Log.i(TAG, String.format("%s -> ...", stringToEvaluate));

        try {
            Object result = action.block();
            Log.i(TAG, String.format("%s -> %s", stringToEvaluate, result));
            return result;
        } finally {
            if (mustInitPoll) {
                pollComplete();
            }
        }
    }

    private void pollBegin() {
        assert !isActive();
        evaluateAsync("transit.poll()");
    }

    private void pollComplete() {
        assert isActive();
        assert isPolling();

        Log.i(TAG, "pollComplete()");
        TransitPollCompleteAction action = new TransitPollCompleteAction();
        pushAction(action);
        action.block();
    }

    public static void readResource(Resources res, int id, ByteArrayOutputStream output) {
        try {
            InputStream inputStream = res.openRawResource(id);

            byte[] readBuffer = new byte[4 * 1024];

            int read;

            do {
                read = inputStream.read(readBuffer, 0, readBuffer.length);
                if (read == -1) {
                    break;
                }

                output.write(readBuffer, 0, read);
            } while (true);
        } catch (IOException e) {
            throw new TransitException(e);
        }
    }

    public String getScript() {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        Resources res = webView.getResources();
        readResource(res, R.raw.transit, output);
        readResource(res, R.raw.runtime, output);
        return output.toString();
    }

    protected void doInvokeNativeAsync(final TransitJSObject invocationDescription) {
        Log.d(TAG, String.format("Invoke native function with id: `%s`", invocationDescription.get("nativeId")));
        context.invoke(invocationDescription);
    }

    private void doInvokeNative(final TransitJSObject invocationDescription) {
        final PreparedInvocation preparedInvocation;
        try {
            preparedInvocation = context.prepareInvoke(invocationDescription);
        } catch (Exception e) {
            Log.e(TAG, "Failed to prepare invocation.", e);
            pushAction(new TransitExceptionAction(e));
            return;
        }

        genericThreadPool.submit(new Runnable() {
            @Override
            public void run() {
                TransitAction action = null;

                try {
                    Log.d(TAG, String.format("Invoking native function `%s`", preparedInvocation.getFunction().getProxyId()));
                    Object resultObject = preparedInvocation.invoke();
                    String result = context.convertObjectToExpression(resultObject);
                    action = new TransitReturnResultAction(result);
                    Log.d(TAG, String.format("Native function `%s` returned `%s`", preparedInvocation.getFunction().getProxyId(), resultObject));
                } catch (Exception e) {
                    Log.e(TAG, String.format("%s threw an exception", preparedInvocation.getFunction()), e);
                    action = new TransitExceptionAction(e);
                } finally {
                    pushAction(action);
                }
            }
        });
    }

    private final Stack<TransitEvalAction> waitingEvaluations = new Stack<TransitEvalAction>();

    private void process(final TransitFuture<String> result) {
        genericThreadPool.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    TransitAction action = actions.takeFirst();

                    Log.d(TAG, String.format("Took %s from stack", action.getClass().getSimpleName()));

                    if (action instanceof TransitPollCompleteAction) {
                        assert isPolling();

                        try {
                            end();
                            result.resolve();
                        } finally {
                            ((TransitPollCompleteAction) action).open();
                        }
                    } else if (action instanceof TransitReturnResultAction || action instanceof TransitExceptionAction) {
                        end();
                    } else if (action instanceof TransitEvalAction) {
                        waitingEvaluations.push((TransitEvalAction) action);
                    }

                    result.resolve(action.getJSRepresentation());
                } catch (InterruptedException e) {
                    panic(e);
                }
            }
        });
    }

    private void panic(Throwable e) {
        // TODO
    }

    private void begin() {
        begin(false);
    }

    private void begin(boolean _polling) {
        if (!isActive()) {
            this.active = true;
            this.polling = _polling;
            Log.i(TAG, String.format("begin(polling=%s)", this.polling));
        }
    }

    private void end() {
        if (isActive()) {
            Log.i(TAG, "end()");
            active = false;
            polling = false;
        }
    }

    private boolean isActive() {
        return active;
    }

    private boolean isPolling() {
        return polling;
    }

    public AndroidTransitContext getContext() {
        return context;
    }

}


text:
package com.alow.validacao;

import com.alow.model.Alow;

public class AlowVerifier {
	private static final Integer textoMaxLength = 400;

	public static String isValid(Alow ent){
		String retorno = "";

		// Objeto nulo
		if (ent == null){
			retorno = "Comportamento inesperado. Valor nulo para o Alow.";
			return retorno;
		}

		// Nome
		if(ent.getTexto() == null || ent.getTexto().equals("")){
			retorno = "O texto do alow deve ser preenchido.";
			return retorno;
		}else{
			if (ent.getTexto().length() > textoMaxLength){
				retorno = "O texto do alow deve ter no máximo "+textoMaxLength+" caracteres.";
				return retorno;
			}
		}

		/*// Descricao
		if(ent.getDescricao() == null || ent.getDescricao().equals("")){
			retorno = "A descrição deve ser preenchida.";
			return retorno;
		}else{
			if (ent.getDescricao().length() > 500){
				retorno = "A descrição deve conter no máximo 300 caracteres.";
				return retorno;
			}
		}

		// Data
		if(ent.getData() == null){
			retorno = "Por favor, preencha o campo data.";
			return retorno;
		}

		// Hora
		if(ent.getHora() == null){
			retorno = "Por favor, preencha o campo hora.";
			return retorno;
		}
		*/
		/*// Local
		if(ent.getLocal() == null || bb.getLocal().equals("")){
			retorno = "O local deve ser preenchido.";
			return retorno;
		}else{
			if (bb.getLocal().length() > 50){
				retorno = "O local deve conter no máximo 50 caracteres.";
				return retorno;
			}
		}

		// Estado / Cidade
		if(bb.getEstadoId() == null || bb.getEstadoId() == 0l){
			retorno = "O estado é obrigatório";
			return retorno;
		}

		if(bb.getCidadeId() == null || bb.getCidadeId() == 0l){
			retorno = "A cidade é obrigatória";
			return retorno;
		}

		// Tem Vagas
		if (bb.getTemVagas() == null){
			bb.setTemVagas(false);
		}

		// Gratuito
		if (bb.getGratuito() == null){
			bb.setGratuito(false);
		}*/

		return retorno;
	}

}

redpajama_set_name: RedPajamaGithub


text:
/*
 * This is the Cryptographic Provider API (CP API).
 *
 * This defines how most crypto syscalls that implement the Cryptographic
 * Operations API can invoke the actual providers of cryptographic algorithms
 * (such as LibTomCrypt).
 *
 * To add a new provider, you need to provide an implementation of this
 * interface.
 *
 * The following parameters are commonly used.
 *
 * @ctx: context allocated by the syscall, for later use by the algorithm
 * @algo: algorithm identifier (TEE_ALG_*)
 */

#ifndef TEE_CRYP_PROVIDER_H
#define TEE_CRYP_PROVIDER_H

#include <tee_api_types.h>

/* Message digest functions */
struct hash_ops {
	TEE_Result (*get_ctx_size)(uint32_t algo, size_t *size);
	TEE_Result (*init)(void *ctx, uint32_t algo);
	TEE_Result (*update)(void *ctx, uint32_t algo,
			     const uint8_t *data, size_t len);
	TEE_Result (*final)(void *ctx, uint32_t algo, uint8_t *digest,
			    size_t len);
};

/* Symmetric ciphers */
struct cipher_ops {
	TEE_Result (*get_ctx_size)(uint32_t algo, size_t *size);
	TEE_Result (*init)(void *ctx, uint32_t algo,
			    TEE_OperationMode mode,
			    const uint8_t *key1, size_t key1_len,
			    const uint8_t *key2, size_t key2_len,
			    const uint8_t *iv, size_t iv_len);
	TEE_Result (*update)(void *ctx, uint32_t algo,
			     TEE_OperationMode mode,
			     bool last_block, const uint8_t *data,
			     size_t len, uint8_t *dst);
	void       (*final)(void *ctx, uint32_t algo);
	TEE_Result (*get_block_size)(uint32_t algo, size_t *size);
};

/* Message Authentication Code functions */
struct mac_ops {
	TEE_Result (*get_ctx_size)(uint32_t algo, size_t *size);
	TEE_Result (*init)(void *ctx, uint32_t algo,
			   const uint8_t *key, size_t len);
	TEE_Result (*update)(void *ctx, uint32_t algo,
			     const uint8_t *data, size_t len);
	TEE_Result (*final)(void *ctx, uint32_t algo,
			    uint8_t *digest, size_t digest_len);
};

/* Authenticated encryption */
struct authenc_ops {
	TEE_Result (*get_ctx_size)(uint32_t algo, size_t *size);
	TEE_Result (*init)(void *ctx, uint32_t algo,
			   TEE_OperationMode mode,
			   const uint8_t *key, size_t key_len,
			   const uint8_t *nonce, size_t nonce_len,
			   size_t tag_len, size_t aad_len,
			   size_t payload_len);
	TEE_Result (*update_aad)(void *ctx, uint32_t algo,
				 TEE_OperationMode mode,
				 const uint8_t *data, size_t len);
	TEE_Result (*update_payload)(void *ctx, uint32_t algo,
				     TEE_OperationMode mode,
				     const uint8_t *src_data,
				     size_t src_len,
				     uint8_t *dst_data,
				     size_t *dst_len);
	TEE_Result (*enc_final)(void *ctx, uint32_t algo,
				const uint8_t *src_data,
				size_t src_len, uint8_t *dst_data,
				size_t *dst_len, uint8_t *dst_tag,
				size_t *dst_tag_len);
	TEE_Result (*dec_final)(void *ctx, uint32_t algo,
				const uint8_t *src_data,
				size_t src_len, uint8_t *dst_data,
				size_t *dst_len, const uint8_t *tag,
				size_t tag_len);

	void       (*final)(void *ctx, uint32_t algo);
};

/* Implementation-defined big numbers */
struct bignum_ops {
	/*
	 * Allocate a bignum capable of holding an unsigned integer value of
	 * up to bitsize bits
	 */
	struct bignum *(*allocate)(size_t size_bits);
	TEE_Result (*bin2bn)(const uint8_t *from, size_t fromsize,
			     struct bignum *to);
	size_t (*num_bytes)(struct bignum *a);
	size_t (*num_bits)(struct bignum *a);
	void (*bn2bin)(const struct bignum *from, uint8_t *to);
	void (*copy)(struct bignum *to, const struct bignum *from);
	void (*free)(struct bignum *a);
	void (*clear)(struct bignum *a);

	/* return -1 if a<b, 0 if a==b, +1 if a>b */
	int32_t (*compare)(struct bignum *a, struct bignum *b);
};

/* Asymmetric algorithms */

struct rsa_keypair {
	struct bignum *e;	/* Public exponent */
	struct bignum *d;	/* Private exponent */
	struct bignum *n;	/* Modulus */

	/* Optional CRT parameters (all NULL if unused) */
	struct bignum *p;	/* N = pq */
	struct bignum *q;
	struct bignum *qp;	/* 1/q mod p */
	struct bignum *dp;	/* d mod (p-1) */
	struct bignum *dq;	/* d mod (q-1) */
};

struct rsa_public_key {
	struct bignum *e;	/* Public exponent */
	struct bignum *n;	/* Modulus */
};

struct dsa_keypair {
	struct bignum *g;	/* Generator of subgroup (public) */
	struct bignum *p;	/* Prime number (public) */
	struct bignum *q;	/* Order of subgroup (public) */
	struct bignum *y;	/* Public key */
	struct bignum *x;	/* Private key */
};

struct dsa_public_key {
	struct bignum *g;	/* Generator of subgroup (public) */
	struct bignum *p;	/* Prime number (public) */
	struct bignum *q;	/* Order of subgroup (public) */
	struct bignum *y;	/* Public key */
};

struct dh_keypair {
	struct bignum *g;	/* Generator of Z_p (shared) */
	struct bignum *p;	/* Prime modulus (shared) */
	struct bignum *x;	/* Private key */
	struct bignum *y;	/* Public key y = g^x */

	/*
	 * Optional parameters used by key generation.
	 * When not used, q == NULL and xbits == 0
	 */
	struct bignum *q;	/* x must be in the range [2, q-2] */
	uint32_t xbits;		/* Number of bits in the private key */
};

struct ecc_public_key {
	struct bignum *x;	/* Public value x */
	struct bignum *y;	/* Public value y */
	uint32_t curve;	        /* Curve type */
};

struct ecc_keypair {
	struct bignum *d;	/* Private value */
	struct bignum *x;	/* Public value x */
	struct bignum *y;	/* Public value y */
	uint32_t curve;	        /* Curve type */
};

struct acipher_ops {

	/*
	 * Key allocation functions
	 * Allocate the bignum's inside a key structure.
	 * TEE core will later use bignum.free().
	 */
	TEE_Result (*alloc_rsa_keypair)(struct rsa_keypair *s,
					size_t key_size_bits);
	TEE_Result (*alloc_rsa_public_key)(struct rsa_public_key *s,
					   size_t key_size_bits);
	void (*free_rsa_public_key)(struct rsa_public_key *s);
	TEE_Result (*alloc_dsa_keypair)(struct dsa_keypair *s,
					size_t key_size_bits);
	TEE_Result (*alloc_dsa_public_key)(struct dsa_public_key *s,
					   size_t key_size_bits);
	TEE_Result (*alloc_dh_keypair)(struct dh_keypair *s,
				       size_t key_size_bits);
	TEE_Result (*alloc_ecc_public_key)(struct ecc_public_key *s,
					   size_t key_size_bits);
	TEE_Result (*alloc_ecc_keypair)(struct ecc_keypair *s,
					size_t key_size_bits);
	void (*free_ecc_public_key)(struct ecc_public_key *s);

	/*
	 * Key generation functions
	 */
	TEE_Result (*gen_rsa_key)(struct rsa_keypair *key, size_t key_size);
	TEE_Result (*gen_dsa_key)(struct dsa_keypair *key, size_t key_size);
	TEE_Result (*gen_dh_key)(struct dh_keypair *key, struct bignum *q,
				 size_t xbits);
	TEE_Result (*gen_ecc_key)(struct ecc_keypair *key);

	TEE_Result (*dh_shared_secret)(struct dh_keypair *private_key,
				       struct bignum *public_key,
				       struct bignum *secret);

	TEE_Result (*rsanopad_decrypt)(struct rsa_keypair *key,
				       const uint8_t *src, size_t src_len,
				       uint8_t *dst, size_t *dst_len);
	TEE_Result (*rsanopad_encrypt)(struct rsa_public_key *key,
				       const uint8_t *src, size_t src_len,
				       uint8_t *dst, size_t *dst_len);
	TEE_Result (*rsaes_decrypt)(uint32_t algo, struct rsa_keypair *key,
				    const uint8_t *label, size_t label_len,
				    const uint8_t *src, size_t src_len,
				    uint8_t *dst, size_t *dst_len);
	TEE_Result (*rsaes_encrypt)(uint32_t algo,
				    struct rsa_public_key *key,
				    const uint8_t *label, size_t label_len,
				    const uint8_t *src, size_t src_len,
				    uint8_t *dst, size_t *dst_len);
	/* RSA SSA sign/verify: if salt_len == -1, use default value */
	TEE_Result (*rsassa_sign)(uint32_t algo, struct rsa_keypair *key,
				  int salt_len, const uint8_t *msg,
				  size_t msg_len, uint8_t *sig,
				  size_t *sig_len);
	TEE_Result (*rsassa_verify)(uint32_t algo,
				    struct rsa_public_key *key,
				    int salt_len, const uint8_t *msg,
				    size_t msg_len, const uint8_t *sig,
				    size_t sig_len);
	TEE_Result (*dsa_sign)(uint32_t algo, struct dsa_keypair *key,
			       const uint8_t *msg, size_t msg_len,
			       uint8_t *sig, size_t *sig_len);
	TEE_Result (*dsa_verify)(uint32_t algo, struct dsa_public_key *key,
				 const uint8_t *msg, size_t msg_len,
				 const uint8_t *sig, size_t sig_len);
	TEE_Result (*ecc_sign)(uint32_t algo, struct ecc_keypair *key,
			       const uint8_t *msg, size_t msg_len,
			       uint8_t *sig, size_t *sig_len);
	TEE_Result (*ecc_verify)(uint32_t algo, struct ecc_public_key *key,
				 const uint8_t *msg, size_t msg_len,
				 const uint8_t *sig, size_t sig_len);
	TEE_Result (*ecc_shared_secret)(struct ecc_keypair *private_key,
					struct ecc_public_key *public_key,
					void *secret,
					unsigned long *secret_len);

};

struct prng_ops {
	/* add entropy to PRNG entropy pool */
	TEE_Result (*add_entropy)(const uint8_t *inbuf, size_t len);

	/* to read random data from PRNG implementation	 */
	TEE_Result (*read)(void *buf, size_t blen);
};

/* Cryptographic Provider API */
struct crypto_ops {
	/* Human-readable provider name */
	const char *name;

	TEE_Result (*init)(void);
	struct hash_ops hash;
	struct cipher_ops cipher;
	struct mac_ops mac;
	struct authenc_ops authenc;
	struct acipher_ops acipher;
	struct bignum_ops bignum;
	struct prng_ops prng;
};

extern const struct crypto_ops crypto_ops;

/*
 * Verifies a SHA-256 hash, doesn't require tee_cryp_init() to be called in
 * advance and has as few dependencies as possible.
 *
 * This function is primarily used by pager and early initialization code
 * where the complete crypto library isn't available.
 */
TEE_Result hash_sha256_check(const uint8_t *hash, const uint8_t *data,
		size_t data_size);

#endif /* TEE_CRYP_PROVIDER_H */


text:
#include "third_party/blink/renderer/core/html/html_slot_element.h"

#include "base/containers/adapters.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_assigned_nodes_options.h"
#include "third_party/blink/renderer/core/css/style_change_reason.h"
#include "third_party/blink/renderer/core/css/style_engine.h"
#include "third_party/blink/renderer/core/dom/events/event.h"
#include "third_party/blink/renderer/core/dom/flat_tree_node_data.h"
#include "third_party/blink/renderer/core/dom/mutation_observer.h"
#include "third_party/blink/renderer/core/dom/node_computed_style.h"
#include "third_party/blink/renderer/core/dom/node_traversal.h"
#include "third_party/blink/renderer/core/dom/shadow_root.h"
#include "third_party/blink/renderer/core/dom/slot_assignment.h"
#include "third_party/blink/renderer/core/dom/text.h"
#include "third_party/blink/renderer/core/dom/whitespace_attacher.h"
#include "third_party/blink/renderer/core/frame/web_feature.h"
#include "third_party/blink/renderer/core/html_names.h"
#include "third_party/blink/renderer/core/probe/core_probes.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"

namespace blink {

namespace {
constexpr size_t kLCSTableSizeLimit = 16;
}

HTMLSlotElement::HTMLSlotElement(Document& document)
    : HTMLElement(html_names::kSlotTag, document) {
  UseCounter::Count(document, WebFeature::kHTMLSlotElement);
}

// static
AtomicString HTMLSlotElement::NormalizeSlotName(const AtomicString& name) {
  return (name.IsNull() || name.empty()) ? g_empty_atom : name;
}

// static
const AtomicString& HTMLSlotElement::UserAgentDefaultSlotName() {
  DEFINE_STATIC_LOCAL(const AtomicString, user_agent_default_slot_name,
                      ("user-agent-default-slot"));
  return user_agent_default_slot_name;
}

// static
const AtomicString& HTMLSlotElement::UserAgentCustomAssignSlotName() {
  DEFINE_STATIC_LOCAL(const AtomicString, user_agent_custom_assign_slot_name,
                      ("user-agent-custom-assign-slot"));
  return user_agent_custom_assign_slot_name;
}

const HeapVector<Member<Node>>& HTMLSlotElement::AssignedNodes() const {
  if (!SupportsAssignment()) {
    DCHECK(assigned_nodes_.empty());
    return assigned_nodes_;
  }
  ContainingShadowRoot()->GetSlotAssignment().RecalcAssignment();
  return assigned_nodes_;
}

namespace {

HeapVector<Member<Node>> CollectFlattenedAssignedNodes(
    const HTMLSlotElement& slot) {
  DCHECK(slot.SupportsAssignment());

  const HeapVector<Member<Node>>& assigned_nodes = slot.AssignedNodes();
  HeapVector<Member<Node>> nodes;
  if (assigned_nodes.empty()) {
    // Fallback contents.
    for (auto& child : NodeTraversal::ChildrenOf(slot)) {
      if (!child.IsSlotable())
        continue;
      if (auto* child_slot = ToHTMLSlotElementIfSupportsAssignmentOrNull(child))
        nodes.AppendVector(CollectFlattenedAssignedNodes(*child_slot));
      else
        nodes.push_back(child);
    }
  } else {
    for (auto& node : assigned_nodes) {
      DCHECK(node->IsSlotable());
      if (auto* assigned_node_slot =
              ToHTMLSlotElementIfSupportsAssignmentOrNull(*node))
        nodes.AppendVector(CollectFlattenedAssignedNodes(*assigned_node_slot));
      else
        nodes.push_back(node);
    }
  }
  return nodes;
}

}  // namespace

const HeapVector<Member<Node>> HTMLSlotElement::FlattenedAssignedNodes() {
  if (!SupportsAssignment()) {
    DCHECK(assigned_nodes_.empty());
    return assigned_nodes_;
  }
  return CollectFlattenedAssignedNodes(*this);
}

const HeapVector<Member<Node>> HTMLSlotElement::AssignedNodesForBinding(
    const AssignedNodesOptions* options) {
  if (options->hasFlatten() && options->flatten())
    return FlattenedAssignedNodes();
  return AssignedNodes();
}

const HeapVector<Member<Element>> HTMLSlotElement::AssignedElements() {
  HeapVector<Member<Element>> elements;
  for (auto& node : AssignedNodes()) {
    if (auto* element = DynamicTo<Element>(node.Get()))
      elements.push_back(*element);
  }
  return elements;
}

const HeapVector<Member<Element>> HTMLSlotElement::AssignedElementsForBinding(
    const AssignedNodesOptions* options) {
  HeapVector<Member<Element>> elements;
  for (auto& node : AssignedNodesForBinding(options)) {
    if (auto* element = DynamicTo<Element>(node.Get()))
      elements.push_back(*element);
  }
  return elements;
}

void HTMLSlotElement::assign(HeapVector<Member<V8UnionElementOrText>>& js_nodes,
                             ExceptionState&) {
  UseCounter::Count(GetDocument(), WebFeature::kSlotAssignNode);
  if (js_nodes.empty() && manually_assigned_nodes_.empty())
    return;

  HeapVector<Member<Node>> nodes;
  for (V8UnionElementOrText* union_node : js_nodes) {
    Node* node = nullptr;
    switch (union_node->GetContentType()) {
      case V8UnionElementOrText::ContentType::kText:
        node = union_node->GetAsText();
        break;
      case V8UnionElementOrText::ContentType::kElement:
        node = union_node->GetAsElement();
        break;
    }
    nodes.push_back(*node);
  }
  Assign(nodes);
}

void HTMLSlotElement::Assign(const HeapVector<Member<Node>>& nodes) {
  if (nodes.empty() && manually_assigned_nodes_.empty())
    return;

  bool updated = false;
  HeapLinkedHashSet<WeakMember<Node>> added_nodes;
  for (Node* node : nodes) {
    added_nodes.insert(node);
    if (auto* previous_slot = node->ManuallyAssignedSlot()) {
      if (previous_slot == this)
        continue;
      previous_slot->manually_assigned_nodes_.erase(node);
      if (previous_slot->SupportsAssignment())
        previous_slot->DidSlotChange(SlotChangeType::kSignalSlotChangeEvent);
    }
    updated = true;
    node->SetManuallyAssignedSlot(this);
  }

  HeapLinkedHashSet<WeakMember<Node>> removed_nodes;
  for (Node* node : manually_assigned_nodes_) {
    if (added_nodes.find(node) == added_nodes.end())
      removed_nodes.insert(node);
  }

  updated |= added_nodes.size() != manually_assigned_nodes_.size();
  if (!updated) {
    for (auto it1 = added_nodes.begin(), it2 = manually_assigned_nodes_.begin();
         it1 != added_nodes.end(); ++it1, ++it2) {
      if (!(*it1 == *it2)) {
        updated = true;
        break;
      }
    }
  }
  DCHECK(updated || removed_nodes.empty());

  if (updated) {
    for (auto removed_node : removed_nodes)
      removed_node->SetManuallyAssignedSlot(nullptr);
    manually_assigned_nodes_.Swap(added_nodes);
    // The slot might not be located in a shadow root yet.
    if (ContainingShadowRoot()) {
      SetShadowRootNeedsAssignmentRecalc();
      DidSlotChange(SlotChangeType::kSignalSlotChangeEvent);
    }
  }
}

void HTMLSlotElement::AppendAssignedNode(Node& host_child) {
  DCHECK(host_child.IsSlotable());
  assigned_nodes_.push_back(&host_child);
}

void HTMLSlotElement::ClearAssignedNodes() {
  assigned_nodes_.clear();
}

void HTMLSlotElement::ClearAssignedNodesAndFlatTreeChildren() {
  ClearAssignedNodes();
  flat_tree_children_.clear();
}

void HTMLSlotElement::UpdateFlatTreeNodeDataForAssignedNodes() {
  Node* previous = nullptr;
  for (auto& current : assigned_nodes_) {
    bool flat_tree_parent_changed = false;
    if (!current->NeedsStyleRecalc() && !current->GetComputedStyle()) {
      if (auto* node_data = current->GetFlatTreeNodeData())
        flat_tree_parent_changed = !node_data->AssignedSlot();
    }
    FlatTreeNodeData& flat_tree_node_data = current->EnsureFlatTreeNodeData();
    flat_tree_node_data.SetAssignedSlot(this);
    flat_tree_node_data.SetPreviousInAssignedNodes(previous);
    if (previous) {
      DCHECK(previous->GetFlatTreeNodeData());
      previous->GetFlatTreeNodeData()->SetNextInAssignedNodes(current);
    }
    previous = current;
    if (flat_tree_parent_changed)
      current->FlatTreeParentChanged();
  }
  if (previous) {
    DCHECK(previous->GetFlatTreeNodeData());
    previous->GetFlatTreeNodeData()->SetNextInAssignedNodes(nullptr);
  }
}

void HTMLSlotElement::DetachDisplayLockedAssignedNodesLayoutTreeIfNeeded() {
  // If the assigned node is now under a display locked subtree and its layout
  // is in 'forced reattach' mode, it means that this node potentially changed
  // slots into a display locked subtree. We would normally update its layout
  // tree during a layout tree update phase, but that is skipped in display
  // locked subtrees. In order to avoid a corrupt layout tree as a result, we
  // detach the node's layout tree.
  for (auto& current : assigned_nodes_) {
    if (current->GetForceReattachLayoutTree())
      current->DetachLayoutTree();
  }
}

void HTMLSlotElement::RecalcFlatTreeChildren() {
  DCHECK(SupportsAssignment());

  HeapVector<Member<Node>> old_flat_tree_children;
  old_flat_tree_children.swap(flat_tree_children_);

  if (assigned_nodes_.empty()) {
    // Use children as fallback
    for (auto& child : NodeTraversal::ChildrenOf(*this)) {
      if (child.IsSlotable())
        flat_tree_children_.push_back(child);
    }
  } else {
    flat_tree_children_ = assigned_nodes_;
    for (auto& node : old_flat_tree_children) {
      // Detach fallback nodes. Host children which are no longer slotted are
      // detached in SlotAssignment::RecalcAssignment().
      if (node->parentNode() == this)
        node->RemovedFromFlatTree();
    }
  }

  NotifySlottedNodesOfFlatTreeChange(old_flat_tree_children,
                                     flat_tree_children_);
}

void HTMLSlotElement::DispatchSlotChangeEvent() {
  DCHECK(!IsInUserAgentShadowRoot() ||
         ContainingShadowRoot()->IsNamedSlotting());
  Event* event = Event::CreateBubble(event_type_names::kSlotchange);
  event->SetTarget(this);
  DispatchScopedEvent(*event);
}

AtomicString HTMLSlotElement::GetName() const {
  return NormalizeSlotName(FastGetAttribute(html_names::kNameAttr));
}

void HTMLSlotElement::AttachLayoutTree(AttachContext& context) {
  HTMLElement::AttachLayoutTree(context);

  if (ChildStyleRecalcBlockedByDisplayLock() || SkippedContainerStyleRecalc())
    return;

  if (SupportsAssignment()) {
    LayoutObject* layout_object = GetLayoutObject();
    AttachContext children_context(context);
    const ComputedStyle* style = GetComputedStyle();
    AdjustForceLegacyLayout(style, &children_context.force_legacy_layout);
    if (layout_object || !style || style->IsEnsuredInDisplayNone()) {
      children_context.previous_in_flow = nullptr;
      children_context.parent = layout_object;
      children_context.next_sibling = nullptr;
      children_context.next_sibling_valid = true;
    }
    children_context.use_previous_in_flow = true;

    for (auto& node : AssignedNodes())
      node->AttachLayoutTree(children_context);
    if (children_context.previous_in_flow)
      context.previous_in_flow = children_context.previous_in_flow;
  }
}

void HTMLSlotElement::DetachLayoutTree(bool performing_reattach) {
  if (SupportsAssignment()) {
    auto* host = OwnerShadowHost();
    const HeapVector<Member<Node>>& flat_tree_children = assigned_nodes_;
    for (auto& node : flat_tree_children) {
      // Don't detach the assigned node if the node is no longer a child of the
      // host.
      //
      // 1. It's no long a direct flat-tree child of this slot.
      // 2. It was already detached when removed from the host.
      // 3. It might already have been inserted in a different part of the DOM,
      //    or a new document tree and been attached.
      // 4. It might have been marked style-dirty in its new location and
      //    calling DetachLayoutTree here would have incorrectly cleared those
      //    dirty bits.
      if (host == node->parentNode())
        node->DetachLayoutTree(performing_reattach);
    }
  }
  HTMLElement::DetachLayoutTree(performing_reattach);
}

void HTMLSlotElement::RebuildDistributedChildrenLayoutTrees(
    WhitespaceAttacher& whitespace_attacher) {
  DCHECK(SupportsAssignment());

  // This loop traverses the nodes from right to left for the same reason as the
  // one described in ContainerNode::RebuildChildrenLayoutTrees().
  for (const auto& child : base::Reversed(flat_tree_children_)) {
    RebuildLayoutTreeForChild(child, whitespace_attacher);
  }
}

void HTMLSlotElement::AttributeChanged(
    const AttributeModificationParams& params) {
  if (params.name == html_names::kNameAttr) {
    if (ShadowRoot* root = ContainingShadowRoot()) {
      if (params.old_value != params.new_value) {
        root->GetSlotAssignment().DidRenameSlot(
            NormalizeSlotName(params.old_value), *this);
      }
    }
  }
  HTMLElement::AttributeChanged(params);
}

Node::InsertionNotificationRequest HTMLSlotElement::InsertedInto(
    ContainerNode& insertion_point) {
  HTMLElement::InsertedInto(insertion_point);
  if (SupportsAssignment()) {
    ShadowRoot* root = ContainingShadowRoot();
    DCHECK(root);
    if (root == insertion_point.ContainingShadowRoot()) {
      // This slot is inserted into the same tree of |insertion_point|
      root->DidAddSlot(*this);
    } else if (insertion_point.isConnected() &&
               root->NeedsSlotAssignmentRecalc()) {
      // Even when a slot and its containing shadow root is removed together
      // and inserted together again, the slot's cached assigned nodes can be
      // stale if the NeedsSlotAssignmentRecalc flag is set, and it may cause
      // infinite recursion in DetachLayoutTree() when one of the stale node
      // is a shadow-including ancestor of this slot by making a circular
      // reference. Clear the cache here to avoid the situation.
      // See http://crbug.com/849599 for details.
      ClearAssignedNodesAndFlatTreeChildren();
    }
  }
  return kInsertionDone;
}

void HTMLSlotElement::RemovedFrom(ContainerNode& insertion_point) {
  // `removedFrom` is called after the node is removed from the tree.
  // That means:
  // 1. If this slot is still in a tree scope, it means the slot has been in a
  //    shadow tree. An inclusive shadow-including ancestor of the shadow host
  //    was originally removed from its parent. See slot s2 below.
  // 2. Or (this slot is not in a tree scope), this slot's inclusive
  //    ancestor was orginally removed from its parent (== insertion point).
  //    This slot and the originally removed node was in the same tree before
  //    removal. See slot s1 below.

  // For example, given the following trees, (srN: = shadow root, sN: = slot)
  // a
  // |- b --sr1
  // |- c   |--d
  //           |- e-----sr2
  //              |- s1 |--f
  //                    |--s2

  // If we call 'e.remove()', then:
  // - For slot s1, s1.removedFrom(d) is called.
  // - For slot s2, s2.removedFrom(d) is called.

  // ContainingShadowRoot() is okay to use here because 1) It doesn't use
  // kIsInShadowTreeFlag flag, and 2) TreeScope has been already updated for the
  // slot.
  if (ShadowRoot* shadow_root = ContainingShadowRoot()) {
    // In this case, the shadow host (or its shadow-inclusive ancestor) was
    // removed originally. In the above example, (this slot == s2) and
    // (shadow_root == sr2). The shadow tree (sr2)'s structure didn't change at
    // all.
    if (shadow_root->NeedsSlotAssignmentRecalc()) {
      // Clear |assigned_nodes_| here, so that the referenced node can get
      // garbage collected if they no longer needed. See also InsertedInto()'s
      // comment for cases that stale |assigned_nodes| can be problematic.
      ClearAssignedNodesAndFlatTreeChildren();
    } else {
      // We don't need to clear |assigned_nodes_| here. That's an important
      // optimization.
    }
  } else if (insertion_point.IsInShadowTree()) {
    // This slot was in a shadow tree and got disconnected from the shadow tree.
    // In the above example, (this slot == s1), (insertion point == d)
    // and (insertion_point->ContainingShadowRoot == sr1).
    insertion_point.ContainingShadowRoot()->GetSlotAssignment().DidRemoveSlot(
        *this);
    ClearAssignedNodesAndFlatTreeChildren();
  } else {
    DCHECK(assigned_nodes_.empty());
  }

  HTMLElement::RemovedFrom(insertion_point);
}

void HTMLSlotElement::RecalcStyleForSlotChildren(
    const StyleRecalcChange change,
    const StyleRecalcContext& style_recalc_context) {
  for (auto& node : flat_tree_children_) {
    if (!change.TraverseChild(*node))
      continue;
    if (auto* element = DynamicTo<Element>(node.Get()))
      element->RecalcStyle(change, style_recalc_context);
    else if (auto* text_node = DynamicTo<Text>(node.Get()))
      text_node->RecalcTextStyle(change);
  }
}

void HTMLSlotElement::NotifySlottedNodesOfFlatTreeChangeByDynamicProgramming(
    const HeapVector<Member<Node>>& old_slotted,
    const HeapVector<Member<Node>>& new_slotted) {
  // Use dynamic programming to minimize the number of nodes being reattached.
  using LCSTable =
      Vector<LCSArray<wtf_size_t, kLCSTableSizeLimit>, kLCSTableSizeLimit>;
  using Backtrack = std::pair<wtf_size_t, wtf_size_t>;
  using BacktrackTable =
      Vector<LCSArray<Backtrack, kLCSTableSizeLimit>, kLCSTableSizeLimit>;

  DEFINE_STATIC_LOCAL(LCSTable*, lcs_table, (new LCSTable(kLCSTableSizeLimit)));
  DEFINE_STATIC_LOCAL(BacktrackTable*, backtrack_table,
                      (new BacktrackTable(kLCSTableSizeLimit)));

  FillLongestCommonSubsequenceDynamicProgrammingTable(
      old_slotted, new_slotted, *lcs_table, *backtrack_table);

  wtf_size_t r = old_slotted.size();
  wtf_size_t c = new_slotted.size();
  while (r > 0 && c > 0) {
    Backtrack backtrack = (*backtrack_table)[r][c];
    if (backtrack == std::make_pair(r - 1, c - 1)) {
      DCHECK_EQ(old_slotted[r - 1], new_slotted[c - 1]);
    } else if (backtrack == std::make_pair(r, c - 1)) {
      new_slotted[c - 1]->FlatTreeParentChanged();
    }
    std::tie(r, c) = backtrack;
  }
  if (c > 0) {
    for (wtf_size_t i = 0; i < c; ++i)
      new_slotted[i]->FlatTreeParentChanged();
  }
}

void HTMLSlotElement::NotifySlottedNodesOfFlatTreeChange(
    const HeapVector<Member<Node>>& old_slotted,
    const HeapVector<Member<Node>>& new_slotted) {
  if (old_slotted == new_slotted)
    return;
  probe::DidPerformSlotDistribution(this);

  // It is very important to minimize the number of reattaching nodes in
  // |new_assigned_nodes| here. The following *works*, in terms of the
  // correctness of the rendering,
  //
  // for (auto& node: new_slotted) {
  //   node->FlatTreeParentChanged();
  // }
  //
  // However, reattaching all ndoes is not good in terms of performance.
  // Reattach is very expensive operation.
  //
  // A possible approach is: Find the Longest Commons Subsequence (LCS) between
  // |old_slotted| and |new_slotted|, and reattach nodes in |new_slotted| which
  // LCS does not include.
  //
  // Note that a relative order between nodes which are not reattached should be
  // preserved in old and new. For example,
  //
  // - old: [1, 4, 2, 3]
  // - new: [3, 1, 2]
  //
  // This case, we must reattach 3 here, as the best possible solution.  If we
  // don't reattach 3, 3's LayoutObject will have an invalid next sibling
  // pointer.  We don't have any chance to update their sibling pointers (3's
  // next and 1's previous).  Sibling pointers between 1 and 2 are correctly
  // updated when we reattach 4, which is done in another code path.
  if (old_slotted.size() + 1 > kLCSTableSizeLimit ||
      new_slotted.size() + 1 > kLCSTableSizeLimit) {
    // Since DP takes O(N^2), we don't use DP if the size is larger than the
    // pre-defined limit.
    NotifySlottedNodesOfFlatTreeChangeNaive(old_slotted, new_slotted);
  } else {
    NotifySlottedNodesOfFlatTreeChangeByDynamicProgramming(old_slotted,
                                                           new_slotted);
  }
}

void HTMLSlotElement::DidSlotChangeAfterRemovedFromShadowTree() {
  DCHECK(!ContainingShadowRoot());
  EnqueueSlotChangeEvent();
  CheckSlotChange(SlotChangeType::kSuppressSlotChangeEvent);
}

void HTMLSlotElement::DidSlotChangeAfterRenaming() {
  DCHECK(SupportsAssignment());
  EnqueueSlotChangeEvent();
  SetShadowRootNeedsAssignmentRecalc();
  CheckSlotChange(SlotChangeType::kSuppressSlotChangeEvent);
}

void HTMLSlotElement::NotifySlottedNodesOfFlatTreeChangeNaive(
    const HeapVector<Member<Node>>& old_assigned_nodes,
    const HeapVector<Member<Node>>& new_assigned_nodes) {
  // Use O(N) naive greedy algorithm to find a *suboptimal* longest common
  // subsequence (LCS), and reattach nodes which are not in suboptimal LCS.  We
  // run a greedy algorithm twice in both directions (scan forward and scan
  // backward), and use the better result.  Though this greedy algorithm is not
  // perfect, it works well in some common cases, such as:

  // Inserting a node:
  // old assigned nodes: [a, b ...., z]
  // new assigned nodes: [a, b ...., z, A]
  // => The algorithm reattaches only node |A|.

  // Removing a node:
  // - old assigned nodes: [a, b, ..., m, n, o, ..., z]
  // - new assigned nodes: [a, b, ..., m, o, ... , z]
  // => The algorithm does not reattach any node.

  // Moving a node:
  // - old assigned nodes: [a, b, ..., z]
  // - new assigned nodes: [b, ..., z, a]
  // => The algorithm reattaches only node |a|.

  // Swapping the first node and the last node
  // - old assigned nodes: [a, b, ..., y, z]
  // - new assigned nodes: [z, b, ..., y, a]
  // => Ideally, we should reattach only |a| and |z|, however, the algorithm
  // does not work well here, reattaching [a, b, ...., y] (or [b, ... y, z]).
  // We could reconsider to support this case if a compelling case arises.

  // TODO(hayato): Consider to write an unit test for the algorithm.  We
  // probably want to make the algorithm templatized so we can test it
  // easily.  Like, Vec<T> greedy_suboptimal_lcs(Vec<T> old, Vec<T> new)

  HeapHashMap<Member<Node>, wtf_size_t> old_index_map;
  for (wtf_size_t i = 0; i < old_assigned_nodes.size(); ++i) {
    old_index_map.insert(old_assigned_nodes[i], i);
  }

  // Scan forward
  HeapVector<Member<Node>> forward_result;

  wtf_size_t i = 0;
  wtf_size_t j = 0;

  while (i < old_assigned_nodes.size() && j < new_assigned_nodes.size()) {
    auto& new_node = new_assigned_nodes[j];
    if (old_assigned_nodes[i] == new_node) {
      ++i;
      ++j;
      continue;
    }
    if (old_index_map.Contains(new_node)) {
      wtf_size_t old_index = old_index_map.at(new_node);
      if (old_index > i) {
        i = old_index_map.at(new_node) + 1;
        ++j;
        continue;
      }
    }
    forward_result.push_back(new_node);
    ++j;
  }

  for (; j < new_assigned_nodes.size(); ++j) {
    forward_result.push_back(new_assigned_nodes[j]);
  }

  // Scan backward
  HeapVector<Member<Node>> backward_result;

  i = old_assigned_nodes.size();
  j = new_assigned_nodes.size();

  while (i > 0 && j > 0) {
    auto& new_node = new_assigned_nodes[j - 1];
    if (old_assigned_nodes[i - 1] == new_node) {
      --i;
      --j;
      continue;
    }
    if (old_index_map.Contains(new_node)) {
      wtf_size_t old_index = old_index_map.at(new_node);
      if (old_index < i - 1) {
        i = old_index;
        --j;
        continue;
      }
    }
    backward_result.push_back(new_node);
    --j;
  }

  for (; j > 0; --j) {
    backward_result.push_back(new_assigned_nodes[j - 1]);
  }

  // Reattach nodes
  if (forward_result.size() <= backward_result.size()) {
    for (auto& node : forward_result) {
      node->FlatTreeParentChanged();
    }
  } else {
    for (auto& node : backward_result) {
      node->FlatTreeParentChanged();
    }
  }
}

void HTMLSlotElement::SetShadowRootNeedsAssignmentRecalc() {
  DCHECK(ContainingShadowRoot());
  ContainingShadowRoot()->GetSlotAssignment().SetNeedsAssignmentRecalc();
}

void HTMLSlotElement::DidSlotChange(SlotChangeType slot_change_type) {
  DCHECK(SupportsAssignment());
  if (slot_change_type == SlotChangeType::kSignalSlotChangeEvent)
    EnqueueSlotChangeEvent();
  SetShadowRootNeedsAssignmentRecalc();
  // Check slotchange recursively since this slotchange may cause another
  // slotchange.
  CheckSlotChange(SlotChangeType::kSuppressSlotChangeEvent);
}

void HTMLSlotElement::CheckFallbackAfterInsertedIntoShadowTree() {
  DCHECK(SupportsAssignment());
  if (HasSlotableChild()) {
    // We use kSuppress here because a slotchange event shouldn't be
    // dispatched if a slot being inserted doesn't get any assigned
    // node, but has a slotable child, according to DOM Standard.
    DidSlotChange(SlotChangeType::kSuppressSlotChangeEvent);
  }
}

void HTMLSlotElement::CheckFallbackAfterRemovedFromShadowTree() {
  if (HasSlotableChild()) {
    // Since a slot was removed from a shadow tree,
    // we don't need to set dirty flag for a disconnected tree.
    // However, we need to call CheckSlotChange because we might need to set a
    // dirty flag for a shadow tree which a parent of the slot may host.
    CheckSlotChange(SlotChangeType::kSuppressSlotChangeEvent);
  }
}

bool HTMLSlotElement::HasSlotableChild() const {
  for (auto& child : NodeTraversal::ChildrenOf(*this)) {
    if (child.IsSlotable())
      return true;
  }
  return false;
}

void HTMLSlotElement::EnqueueSlotChangeEvent() {
  // TODO(kochi): This suppresses slotchange event on user-agent shadows that
  // don't support name based slot assignment, but could be improved further by
  // not running change detection logic in
  // SlotAssignment::Did{Add,Remove}SlotInternal etc., although naive skipping
  // turned out breaking fallback content handling.
  if (IsInUserAgentShadowRoot() && !ContainingShadowRoot()->IsNamedSlotting())
    return;
  if (slotchange_event_enqueued_)
    return;
  MutationObserver::EnqueueSlotChange(*this);
  slotchange_event_enqueued_ = true;
}

bool HTMLSlotElement::HasAssignedNodesSlow() const {
  ShadowRoot* root = ContainingShadowRoot();
  DCHECK(root) << "This should only be called on slots inside a shadow tree";
  SlotAssignment& assignment = root->GetSlotAssignment();
  if (assignment.FindSlotByName(GetName()) != this)
    return false;
  return assignment.FindHostChildBySlotName(GetName());
}

void HTMLSlotElement::ChildrenChanged(const ChildrenChange& change) {
  HTMLElement::ChildrenChanged(change);
  if (SupportsAssignment())
    SetShadowRootNeedsAssignmentRecalc();
}

void HTMLSlotElement::Trace(Visitor* visitor) const {
  visitor->Trace(assigned_nodes_);
  visitor->Trace(flat_tree_children_);
  visitor->Trace(manually_assigned_nodes_);
  HTMLElement::Trace(visitor);
}

}  // namespace blink


text:
package com.rvantwisk.cnctools.data;

import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;

/**
 * Created with IntelliJ IDEA.
 * User: rvt
 * Date: 10/27/13
 * Time: 4:38 PM
 * To change this template use File | Settings | File Templates.
 */

public abstract class AbstractTask {

    private StringProperty name = new SimpleStringProperty();
    private StringProperty description = new SimpleStringProperty();
    private StringProperty className = new SimpleStringProperty();
    private StringProperty fxmlFileName = new SimpleStringProperty();

    public AbstractTask() {
    }

    public AbstractTask(String name, String description, String className, String fxmlFileName) {
        this.name.set(name);
        this.description.set(description);
        this.className.set(className);
        this.fxmlFileName.set(fxmlFileName);
    }

    public String getName() {
        return name.get();
    }

    public String getDescription() {
        return description.get();
    }

    public String getClassName() {
        return className.get();
    }

    public String getFxmlFileName() {
        return fxmlFileName.get();
    }

}


text:
package info.novatec.testit.webtester.eventsystem.events.browser;

import static java.lang.String.format;

import java.io.File;

import info.novatec.testit.webtester.api.browser.Browser;
import info.novatec.testit.webtester.api.events.Event;

/**
 * This {@link Event event} occurs whenever the source code of a page was saved.
 * It includes the file reference to the source code file as a property.
 *
 * @since 0.9.0
 */
@SuppressWarnings("serial")
public class SavedSourceCodeEvent extends AbstractBrowserEvent {

    private File pageSourceFile;

    public SavedSourceCodeEvent(Browser browser, File pageSourceFile) {
        super(browser);
        this.pageSourceFile = pageSourceFile;
    }

    @Override
    public String getEventMessage() {
        return format("saved page source and saved it as: %s", pageSourceFile);
    }

    public File getPageSourceFile() {
        return pageSourceFile;
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<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>

    <groupId>com.twilio</groupId>
    <artifactId>starter-java</artifactId>
    <version>1.0-SNAPSHOT</version>

<!--    <packaging>war</packaging>-->

    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <!-- library dependencies -->
    <dependencies>
        <dependency>
            <groupId>com.sparkjava</groupId>
            <artifactId>spark-core</artifactId>
            <version>2.7.2</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.26</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.7.26</version>
        </dependency>
        <dependency>
            <groupId>com.twilio.sdk</groupId>
            <artifactId>twilio</artifactId>
            <version>7.40.1</version>
        </dependency>
    </dependencies>

    <build>
        <finalName>${project.name}</finalName>
        <plugins>
            <plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <finalName>${project.name}-with-dependencies</finalName>
                    <!-- Don't add "jar-with-dependencies" at the end -->
                    <appendAssemblyId>false</appendAssemblyId>
                    <descriptorRefs>
                        <!-- This tells Maven to include all dependencies -->
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                    <archive>
                        <manifest>
                            <mainClass>com.twilio.starter.Application</mainClass>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>