text:
package com.ripple.client;

import com.ripple.client.enums.Command;
import com.ripple.client.enums.Message;
import com.ripple.client.enums.RPCErr;
import com.ripple.client.pubsub.Publisher;
import com.ripple.client.requests.Request;
import com.ripple.client.responses.Response;
import com.ripple.client.subscriptions.ServerInfo;
import com.ripple.client.subscriptions.SubscriptionManager;
import com.ripple.client.subscriptions.TrackedAccountRoot;
import com.ripple.client.subscriptions.TransactionSubscriptionManager;
import com.ripple.client.transactions.AccountTxPager;
import com.ripple.client.transactions.TransactionManager;
import com.ripple.client.transport.TransportEventHandler;
import com.ripple.client.transport.WebSocketTransport;
import com.ripple.client.types.AccountLine;
import com.ripple.core.coretypes.AccountID;
import com.ripple.core.coretypes.Issue;
import com.ripple.core.coretypes.STObject;
import com.ripple.core.coretypes.hash.Hash256;
import com.ripple.core.coretypes.uint.UInt32;
import com.ripple.core.types.known.sle.LedgerEntry;
import com.ripple.core.types.known.sle.entries.AccountRoot;
import com.ripple.core.types.known.sle.entries.Offer;
import com.ripple.core.types.known.tx.result.TransactionResult;
import com.ripple.crypto.ecdsa.IKeyPair;
import com.ripple.crypto.ecdsa.Seed;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.SocketAddress;
import java.net.URI;
import java.util.*;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;

import static com.ripple.client.requests.Request.Manager;
import static com.ripple.client.requests.Request.VALIDATED_LEDGER;

public class Client extends Publisher<Client.events> implements TransportEventHandler {
    // Logger
    public static final Logger logger = Logger.getLogger(Client.class.getName());

    // Events
    public static interface events<T> extends Publisher.Callback<T> {}
    public static interface OnLedgerClosed extends events<ServerInfo> {}
    public static interface OnConnected extends events<Client> {}
    public static interface OnDisconnected extends events<Client> {}
    public static interface OnSubscribed extends events<ServerInfo> {}
    public static interface OnMessage extends events<JSONObject> {}
    public static interface OnSendMessage extends events<JSONObject> {}
    public static interface OnStateChange extends events<Client> {}
    public static interface OnPathFind extends events<JSONObject> {}
    public static interface OnValidatedTransaction extends events<TransactionResult> {}

    // Fluent binders
    public Client onValidatedTransaction(OnValidatedTransaction cb) {
        on(OnValidatedTransaction.class, cb);
        return this;
    }

    public long getSpeed(){
    	return 1000;
    }

    public Client onLedgerClosed(OnLedgerClosed cb) {
        on(OnLedgerClosed.class, cb);
        return this;
    }

    public Client onConnected(OnConnected onConnected) {
        this.on(OnConnected.class, onConnected);
        return this;
    }

    // Event handler sugar
    public Client onDisconnected(OnDisconnected cb) {
        on(OnDisconnected.class, cb);
        return this;
    }

    // ### Members
    // The implementation of the WebSocket
    WebSocketTransport ws;

    /**
     * When this is non 0, we randomly disconnect when trying to send messages
     * See {@link Client#sendMessage}
     */
    public double randomBugsFrequency = 0;
    Random randomBugs = new Random();
    // When this is set, all transactions will be routed first to this, which
    // will then notify the client
    TransactionSubscriptionManager transactionSubscriptionManager;

    // This is in charge of executing code in the `clientThread`
    protected ScheduledExecutorService service;
    // All code that use the Client api, must be run on this thread

    /**
     See {@link Client#run}
     */
    protected Thread clientThread;
    protected TreeMap<Integer, Request> requests = new TreeMap<Integer, Request>();

    // Keeps track of the `id` doled out to Request objects
    private int cmdIDs;
    // The last uri we were connected to
    String previousUri;

    // Every x ms, we clean up timed out requests
    public long maintenanceSchedule = 10000; //ms

    // Are we currently connected?
    public boolean connected = false;
    // If we haven't received any message from the server after x many
    // milliseconds, disconnect and reconnect again.
    private long reconnectDormantAfter = 20000; // ms
    // ms since unix time of the last indication of an alive connection
    private long lastConnection = -1; // -1 means null
    // Did we disconnect manually? If not, try and reconnect
    private boolean manuallyDisconnected = false;

    // Tracks the serverInfo we are currently connected to
    public ServerInfo serverInfo = new ServerInfo();
    private HashMap<AccountID, Account> accounts = new HashMap<AccountID, Account>();
    // Handles [un]subscription requests, also on reconnect
    public SubscriptionManager subscriptions = new SubscriptionManager();

    // Constructor
    public Client(WebSocketTransport ws) {
        this.ws = ws;
        ws.setHandler(this);

        prepareExecutor();
        // requires executor, so call after prepareExecutor
        scheduleMaintenance();

        subscriptions.on(SubscriptionManager.OnSubscribed.class, new SubscriptionManager.OnSubscribed() {
            @Override
            public void called(JSONObject subscription) {
                if (!connected)
                    return;
                subscribe(subscription);
            }
        });
    }

	public void setProxy(Proxy proxy) {
		ws.setProxy(proxy);
	}

    // ### Getters

    private int reconnectDelay() {
        return 1000;
    }
    public boolean isManuallyDisconnected() {
        return manuallyDisconnected;
    }

    // ### Setters

    public void reconnectDormantAfter(long reconnectDormantAfter) {
        this.reconnectDormantAfter = reconnectDormantAfter;
    }

    public Client transactionSubscriptionManager(TransactionSubscriptionManager transactionSubscriptionManager) {
        this.transactionSubscriptionManager = transactionSubscriptionManager;
        return this;
    }

    // ### Helpers

    public static void log(Level level, String fmt, Object... args) {
        if (logger.isLoggable(level)) {
            logger.log(level, fmt, args);
        }
    }

    public static String prettyJSON(JSONObject object) {
        return object.toString(4);
    }
    public static JSONObject parseJSON(String s) {
        return new JSONObject(s);
    }

    /* --------------------------- CONNECT / RECONNECT -------------------------- */

    /**
     * After calling this method, all subsequent interaction with the api should
     * be called via posting Runnable() run blocks to the Executor.
     *
     * Essentially, all ripple-lib-java api interaction
     * should happen on the one thread.
     *
     * @see #onMessage(org.json.JSONObject)
     */
    public Client connect(final String uri) {
        manuallyDisconnected = false;

        schedule(50, new Runnable() {
            @Override
            public void run() {
                doConnect(uri);
            }
        });
        return this;
    }

    public void doConnect(String uri) {
        log(Level.INFO, "Connecting to " + uri);
        previousUri = uri;
        ws.connect(URI.create(uri));
    }

    public void disconnect() {
        manuallyDisconnected = true;
        ws.disconnect();
        // our disconnect handler should do the rest
    }

    private void emitOnDisconnected() {
        // This ensures that the callback method onDisconnect is
        // called before a new connection is established this keeps
        // the symmetry of connect-> disconnect -> reconnect
        emit(OnDisconnected.class, this);
    }

    /**
     * This will detect stalled connections When connected we are subscribed to
     * a ledger, and ledgers should be at most 20 seconds apart.
     *
     * This also
     */
    private void scheduleMaintenance() {
        schedule(maintenanceSchedule, new Runnable() {
            @Override
            public void run() {
                try {
                    manageTimedOutRequests();
                    int defaultValue = -1;

                    if (!manuallyDisconnected) {
                        if (connected && lastConnection != defaultValue) {
                            long time = new Date().getTime();
                            long msSince = time - lastConnection;
                            if (msSince > reconnectDormantAfter) {
                                lastConnection = defaultValue;
                                reconnect();
                            }
                        }
                    }
                } finally {
                    scheduleMaintenance();
                }
            }
        });
    }

    public void reconnect() {
        disconnect();
        connect(previousUri);
    }

    void manageTimedOutRequests() {
        long now = System.currentTimeMillis();
        ArrayList<Request> timedOut = new ArrayList<Request>();

        for (Request request : requests.values()) {
            if (request.sendTime != 0) {
                long since = now - request.sendTime;
                if (since >= Request.TIME_OUT) {
                    timedOut.add(request);
                }
            }
        }
        for (Request request : timedOut) {
            request.emit(Request.OnTimeout.class, request.response);
            requests.remove(request.id);
        }
    }

    // ### Handler binders binder

    public void connect(final String s, final OnConnected onConnected) {
        run(new Runnable() {
            public void run() {
                connect(s);
                once(OnConnected.class, onConnected);
            }
        });
    }

    public void disconnect(final OnDisconnected onDisconnected) {
        run(new Runnable() {
            public void run() {
                Client.this.once(OnDisconnected.class, onDisconnected);
                disconnect();
            }
        });
    }

    public void whenConnected(boolean nextTick, final OnConnected onConnected) {
        if (connected) {
            if (nextTick) {
                schedule(0, new Runnable() {
                    @Override
                    public void run() {
                        onConnected.called(Client.this);
                    }
                });
            } else {
                onConnected.called(this);
            }
        }  else {
            once(OnConnected.class, onConnected);
        }
    }

    public void nowOrWhenConnected(OnConnected onConnected) {
        whenConnected(false, onConnected);
    }

    public void nextTickOrWhenConnected(OnConnected onConnected) {
        whenConnected(true, onConnected);
    }

    public void dispose() {
        ws = null;
    }

    /* -------------------------------- EXECUTOR -------------------------------- */

    public void run(Runnable runnable) {
        // What if we are already in the client thread?? What happens then ?
        if (runningOnClientThread()) {
            runnable.run();
        } else {
            service.submit(errorHandling(runnable));
        }
    }

    public void schedule(long ms, Runnable runnable) {
        service.schedule(errorHandling(runnable), ms, TimeUnit.MILLISECONDS);
    }

    public boolean runningOnClientThread() {
        return clientThread != null && Thread.currentThread().getId() == clientThread.getId();
    }

    protected void prepareExecutor() {
        service = new ScheduledThreadPoolExecutor(1, new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                clientThread = new Thread(r);
                return clientThread;
            }
        });
    }

    public static abstract class ThrowingRunnable implements Runnable {
        public abstract void throwingRun() throws Exception;

        @Override
        public void run() {
            try {
                throwingRun();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

    private Runnable errorHandling(final Runnable runnable) {
        return new Runnable() {
            @Override
            public void run() {
                try {
                    runnable.run();
                } catch (Exception e) {
                    onException(e);
                }
            }
        };
    }

    protected void onException(Exception e) {
        e.printStackTrace(System.out);
        if (logger.isLoggable(Level.WARNING)) {
            log(Level.WARNING, "Exception {0}", e);
        }
    }

    private void resetReconnectStatus() {
        lastConnection = new Date().getTime();
    }

    private void updateServerInfo(JSONObject msg) {
        serverInfo.update(msg);
    }

    /* ------------------------- TRANSPORT EVENT HANDLER ------------------------ */

    /**
     * This is to ensure we run everything on {@link Client#clientThread}
     */
    @Override
    public void onMessage(final JSONObject msg) {
        resetReconnectStatus();
        run(new Runnable() {
            @Override
            public void run() {
                onMessageInClientThread(msg);
            }
        });
    }

    @Override
    public void onConnecting(int attempt) {
    }

    @Override
    public void onError(Exception error) {
        onException(error);
    }

    @Override
    public void onDisconnected(boolean willReconnect) {
        run(new Runnable() {
            @Override
            public void run() {
                doOnDisconnected();
            }
        });
    }

    @Override
    public void onConnected() {
        run(new Runnable() {
            public void run() {
                doOnConnected();
            }
        });
    }

    /* ----------------------- CLIENT THREAD EVENT HANDLER ---------------------- */

    public void onMessageInClientThread(JSONObject msg) {
        Message type = Message.valueOf(msg.optString("type", null));

        try {
            emit(OnMessage.class, msg);
            if (logger.isLoggable(Level.FINER)) {
                log(Level.FINER, "Receive `{0}`: {1}", type, prettyJSON(msg));
            }

            switch (type) {
                case serverStatus:
                    updateServerInfo(msg);
                    break;
                case ledgerClosed:
                    updateServerInfo(msg);
                    // TODO
                    emit(OnLedgerClosed.class, serverInfo);
                    break;
                case response:
                    onResponse(msg);
                    break;
                case transaction:
                    onTransaction(msg);
                    break;
                case path_find:
                    emit(OnPathFind.class, msg);
                    break;
                default:
                    unhandledMessage(msg);
                    break;
            }
        } catch (Exception e) {
            logger.log(Level.SEVERE, e.getLocalizedMessage(), e);
            // This seems to be swallowed higher up, (at least by the
            // Java-WebSocket transport implementation)
            throw new RuntimeException(e);
        } finally {
            emit(OnStateChange.class, this);
        }
    }
    private void doOnDisconnected() {
        logger.entering(getClass().getName(), "doOnDisconnected");
        connected = false;
        emitOnDisconnected();

        if (!manuallyDisconnected) {
            schedule(reconnectDelay(), new Runnable() {
                @Override
                public void run() {
                    connect(previousUri);
                }
            });
        } else {
            logger.fine("Currently disconnecting, so will not reconnect");
        }

        logger.entering(getClass().getName(), "doOnDisconnected");
    }

    private void doOnConnected() {
        resetReconnectStatus();

        logger.entering(getClass().getName(), "doOnConnected");
        connected = true;
        emit(OnConnected.class, this);

        subscribe(prepareSubscription());
        logger.exiting(getClass().getName(), "doOnConnected");
    }

    void unhandledMessage(JSONObject msg) {
        log(Level.WARNING, "Unhandled message: " + msg);
    }

    void onResponse(JSONObject msg) {
        Request request = requests.remove(msg.optInt("id", -1));

        if (request == null) {
            log(Level.WARNING, "Response without a request: {0}", msg);
            return;
        }
        request.handleResponse(msg);
    }

    void onTransaction(JSONObject msg) {
        TransactionResult tr = new TransactionResult(msg, TransactionResult
                .Source
                .transaction_subscription_notification);
        if (tr.validated) {
            if (transactionSubscriptionManager != null) {
                transactionSubscriptionManager.notifyTransactionResult(tr);
            } else {
                onTransactionResult(tr);
            }
        }
    }

    public void onTransactionResult(TransactionResult tr) {
        log(Level.INFO, "Transaction {0} is validated", tr.hash);
        Map<AccountID, STObject> affected = tr.modifiedRoots();

        if (affected != null) {
            Hash256 transactionHash = tr.hash;
            UInt32 transactionLedgerIndex = tr.ledgerIndex;

            for (Map.Entry<AccountID, STObject> entry : affected.entrySet()) {
                Account account = accounts.get(entry.getKey());
                if (account != null) {
                    STObject rootUpdates = entry.getValue();
                    account.getAccountRoot()
                            .updateFromTransaction(
                                    transactionHash, transactionLedgerIndex, rootUpdates);
                }
            }
        }

        Account initator = accounts.get(tr.initiatingAccount());
        if (initator != null) {
            log(Level.INFO, "Found initiator {0}, notifying transactionManager", initator);
            initator.transactionManager().notifyTransactionResult(tr);
        } else {
            log(Level.INFO, "Can't find initiating account!");
        }
        emit(OnValidatedTransaction.class, tr);
    }

    public void sendMessage(JSONObject object) {
        if (logger.isLoggable(Level.FINER)) {
            logger.log(Level.FINER, "Send: {0}", prettyJSON(object));
        }
        emit(OnSendMessage.class, object);
        ws.sendMessage(object);

        if (randomBugsFrequency != 0) {
            if (randomBugs.nextDouble() > (1D - randomBugsFrequency)) {
                disconnect();
                connect(previousUri);
                String msg = "I disconnected you, now I'm gonna throw, " +
                        "deal with it suckah! ;)";
                logger.warning(msg);
                throw new RuntimeException(msg);
            }

        }
    }

    /* -------------------------------- ACCOUNTS -------------------------------- */

    public Account accountFromSeed(String masterSeed) {
        IKeyPair kp = Seed.fromBase58(masterSeed).keyPair();
        return account(AccountID.fromKeyPair(kp), kp);
    }

    public Account account(final AccountID id, IKeyPair keyPair) {
        if (accounts.containsKey(id)) {
            return accounts.get(id);
        } else {
            TrackedAccountRoot accountRoot = accountRoot(id);
            Account account = new Account(
                    id,
                    keyPair,
                    accountRoot,
                    new TransactionManager(this, accountRoot, id, keyPair)
            );
            accounts.put(id, account);
            subscriptions.addAccount(id);

            return account;
        }
    }

    private TrackedAccountRoot accountRoot(AccountID id) {
        TrackedAccountRoot accountRoot = new TrackedAccountRoot();
        requestAccountRoot(id, accountRoot);
        return accountRoot;
    }

    private void requestAccountRoot(final AccountID id,
                                    final TrackedAccountRoot accountRoot) {

        makeManagedRequest(Command.ledger_entry, new Manager<JSONObject>() {
            @Override
            public boolean retryOnUnsuccessful(Response r) {
                return r == null || r.rpcerr == null || r.rpcerr != RPCErr.entryNotFound;
            }

            @Override
            public void cb(Response response, JSONObject jsonObject) throws JSONException {
                if (response.succeeded) {
                    accountRoot.setFromJSON(jsonObject);
                } else {
                    log(Level.INFO, "Unfunded account: {0}", response.message);
                    accountRoot.setUnfundedAccount(id);
                }
            }
        }, new Request.Builder<JSONObject>() {
            @Override
            public void beforeRequest(Request request) {
                request.json("account_root", id);
            }

            @Override
            public JSONObject buildTypedResponse(Response response) {
                return response.result.getJSONObject("node");
            }
        });
    }

    /* ------------------------------ SUBSCRIPTIONS ----------------------------- */

    private void subscribe(JSONObject subscription) {
        Request request = newRequest(Command.subscribe);

        request.json(subscription);
        request.on(Request.OnSuccess.class, new Request.OnSuccess() {
            @Override
            public void called(Response response) {
                // TODO ... make sure this isn't just an account subscription
                serverInfo.update(response.result);
                emit(OnSubscribed.class, serverInfo);
            }
        });
        request.request();
    }

    private JSONObject prepareSubscription() {
        subscriptions.pauseEventEmissions();
        subscriptions.addStream(SubscriptionManager.Stream.ledger);
        subscriptions.addStream(SubscriptionManager.Stream.server);
        subscriptions.unpauseEventEmissions();
        return subscriptions.allSubscribed();
    }

    /* ------------------------------ REQUESTS ------------------------------ */

    public Request newRequest(Command cmd) {
        return new Request(cmd, cmdIDs++, this);
    }

    public void sendRequest(final Request request) {
        Logger reqLog = Request.logger;

        try {
            requests.put(request.id, request);
            request.bumpSendTime();
            sendMessage(request.toJSON());
            // Better safe than sorry
        } catch (Exception e) {
            if (reqLog.isLoggable(Level.WARNING)) {
                reqLog.log(Level.WARNING, "Exception when trying to request: {0}", e);
            }
            nextTickOrWhenConnected(new OnConnected() {
                @Override
                public void called(Client args) {
                    sendRequest(request);
                }
            });
        }
    }

    // ### Managed Requests API

    public <T> Request makeManagedRequest(final Command cmd, final Manager<T> manager, final Request.Builder<T> builder) {
        final Request request = newRequest(cmd);
        final boolean[] responded = new boolean[]{false};
        request.once(Request.OnTimeout.class, new Request.OnTimeout() {
            @Override
            public void called(Response args) {
                if (!responded[0] && manager.retryOnUnsuccessful(null)) {
                    logRetry(request, "Request timed out");
                    request.clearAllListeners();
                    queueRetry(50, cmd, manager, builder);
                }
            }
        });
        final OnDisconnected cb = new OnDisconnected() {
            @Override
            public void called(Client c) {
                if (!responded[0] && manager.retryOnUnsuccessful(null)) {
                    logRetry(request, "Client disconnected");
                    request.clearAllListeners();
                    queueRetry(50, cmd, manager, builder);
                }
            }
        };
        once(OnDisconnected.class, cb);
        request.once(Request.OnResponse.class, new Request.OnResponse() {
            @Override
            public void called(final Response response) {
                responded[0] = true;
                Client.this.removeListener(OnDisconnected.class, cb);

                if (response.succeeded) {
                    final T t = builder.buildTypedResponse(response);
                    manager.cb(response, t);
                } else {
                    if (manager.retryOnUnsuccessful(response)) {
                        queueRetry(50, cmd, manager, builder);
                    } else {
                        manager.cb(response, null);
                    }
                }
            }
        });
        builder.beforeRequest(request);
        manager.beforeRequest(request);
        request.request();
        return request;
    }

    private <T> void queueRetry(int ms,
                                final Command cmd,
                                final Manager<T> manager,
                                final Request.Builder<T> builder) {
        schedule(ms, new Runnable() {
            @Override
            public void run() {
                makeManagedRequest(cmd, manager, builder);
            }
        });
    }

    private void logRetry(Request request, String reason) {
        if (logger.isLoggable(Level.WARNING)) {
            log(Level.WARNING, previousUri + ": " + reason + ", muting listeners " +
                    "for " + request.json() + "and trying again");
        }
    }

    // ### Managed Requests

    public AccountTxPager accountTxPager(AccountID accountID) {
        return new AccountTxPager(this, accountID, null);
    }

    public void requestLedgerEntry(final Hash256 index, final Number ledger_index, final Manager<LedgerEntry> cb) {
        makeManagedRequest(Command.ledger_entry, cb, new Request.Builder<LedgerEntry>() {
            @Override
            public void beforeRequest(Request request) {
                if (ledger_index != null) {
                    request.json("ledger_index", ledgerIndex(ledger_index));
                }
                request.json("index", index.toJSON());
            }
            @Override
            public LedgerEntry buildTypedResponse(Response response) {
                String node_binary = response.result.optString("node_binary");
                STObject node = STObject.translate.fromHex(node_binary);
                node.put(Hash256.index, index);
                return (LedgerEntry) node;
            }
        });
    }

    private Object ledgerIndex(Number ledger_index) {
        long l = ledger_index.longValue();
        if (l == VALIDATED_LEDGER) {
            return "validated";
        }
        return l;
    }

    public void requestAccountInfo(final AccountID addy, final Manager<AccountRoot> manager) {
        makeManagedRequest(Command.account_info, manager, new Request.Builder<AccountRoot>() {
            @Override
            public void beforeRequest(Request request) {
                request.json("account", addy);
            }

            @Override
            public AccountRoot buildTypedResponse(Response response) {
                JSONObject root = response.result.optJSONObject("account_data");
                return (AccountRoot) STObject.fromJSONObject(root);
            }
        });
    }

    public void requestLedgerData(final long ledger_index, final Manager<ArrayList<LedgerEntry>> manager) {
        makeManagedRequest(Command.ledger_data, manager, new Request.Builder<ArrayList<LedgerEntry>>() {
            @Override
            public void beforeRequest(Request request) {
                request.json("ledger_index", ledger_index);
                request.json("binary", true);
            }

            @Override
            public ArrayList<LedgerEntry> buildTypedResponse(Response response) {
                JSONArray state = response.result.getJSONArray("state");
                ArrayList<LedgerEntry> result = new ArrayList<LedgerEntry>();
                for (int i = 0; i < state.length(); i++) {
                    JSONObject stateObject = state.getJSONObject(i);
                    LedgerEntry le = (LedgerEntry) STObject.fromHex(stateObject.getString("data"));
                    le.index(Hash256.fromHex(stateObject.getString("index")));
                    result.add(le);
                }
                return result;
            }
        });
    }

    public void requestAccountLines(final AccountID addy, final Manager<ArrayList<AccountLine>> manager) {
        makeManagedRequest(Command.account_lines, manager, new Request.Builder<ArrayList<AccountLine>>() {
            @Override
            public void beforeRequest(Request request) {
                request.json("account", addy);
            }

            @Override
            public ArrayList<AccountLine> buildTypedResponse(Response response) {
                ArrayList<AccountLine> lines = new ArrayList<AccountLine>();
                JSONArray array = response.result.optJSONArray("lines");
                for (int i = 0; i < array.length(); i++) {
                    JSONObject line = array.optJSONObject(i);
                    lines.add(AccountLine.fromJSON(addy, line));
                }
                return lines;
            }
        });
    }

    public void requestHostID(final Callback<String> callback) {
        makeManagedRequest(Command.server_info, new Manager<String>() {
            @Override
            public void cb(Response response, String hostid) throws JSONException {
                callback.called(hostid);
            }

            @Override
            public boolean retryOnUnsuccessful(Response r) {
                return true;
            }
        }, new Request.Builder<String>() {
            @Override
            public void beforeRequest(Request request) {

            }

            @Override
            public String buildTypedResponse(Response response) {
                JSONObject info = response.result.getJSONObject("info");
                return info.getString("hostid");
            }
        });
    }

    public void requestBookOffers(final Number ledger_index,
                                  final Issue get,
                                  final Issue pay,
                                  final Manager<ArrayList<Offer>> cb) {
        makeManagedRequest(Command.book_offers, cb, new Request.Builder<ArrayList<Offer>>() {
            @Override
            public void beforeRequest(Request request) {
                request.json("taker_gets", get.toJSON());
                request.json("taker_pays", pay.toJSON());

                if (ledger_index != null) {
                    request.json("ledger_index", ledger_index);
                }
            }
            @Override
            public ArrayList<Offer> buildTypedResponse(Response response) {
                ArrayList<Offer> offers = new ArrayList<Offer>();
                JSONArray offersJson = response.result.getJSONArray("offers");
                for (int i = 0; i < offersJson.length(); i++) {
                    JSONObject jsonObject = offersJson.getJSONObject(i);
                    STObject object = STObject.fromJSONObject(jsonObject);
                    offers.add((Offer) object);
                }
                return offers;
            }
        });
    }

    public void requestLedger(final Number ledger_index, final Manager<JSONObject> cb) {
        makeManagedRequest(Command.ledger, cb, new Request.Builder<JSONObject>() {
            @Override
            public void beforeRequest(Request request) {
                request.json("ledger_index", ledgerIndex(ledger_index));
            }

            @Override
            public JSONObject buildTypedResponse(Response response) {
                return response.result.optJSONObject("ledger");
            }
        });
    }

    public void requestTransaction(final Hash256 hash, final Manager<TransactionResult> cb) {
        makeManagedRequest(Command.tx, cb, new Request.Builder<TransactionResult>() {
            @Override
            public void beforeRequest(Request request) {
                request.json("binary", true);
                request.json("transaction", hash);
            }

            @Override
            public TransactionResult buildTypedResponse(Response response) {
                return new TransactionResult(response.result, TransactionResult.Source.request_tx_binary);
            }
        });
    }

    // TODO: some nice way of using lambdas for the common case
    // sending null, is one way of indicating `some` kind of error
    // but that's kind of lame.
    @Deprecated // before it even got started
    public void requestTransaction(final Hash256 hash, final Callback<TransactionResult> cb) {
        requestTransaction(hash, new Manager<TransactionResult>() {
            @Override
            public void cb(Response response, TransactionResult transactionResult) throws JSONException {
                if (response.succeeded) {
                    cb.called(transactionResult);
                } else {
                    throw new RuntimeException("Failed" + response.message);
                }
            }
        });
    }

    // ### Request builders
    // These all return Request

    public Request submit(String tx_blob, boolean fail_hard) {
        Request req = newRequest(Command.submit);
        req.json("tx_blob", tx_blob);
        req.json("fail_hard", fail_hard);
        return req;
    }

    public Request accountLines(AccountID account) {
        Request req = newRequest(Command.account_lines);
        req.json("account", account.address);
        return req;

    }

    public Request accountInfo(AccountID account) {
        Request req = newRequest(Command.account_info);
        req.json("account", account.address);
        return req;
    }

    public Request ping() {
        return newRequest(Command.ping);
    }

    public Request subscribeAccount(AccountID... accounts) {
        Request request = newRequest(Command.subscribe);
        JSONArray accounts_arr = new JSONArray();
        for (AccountID acc : accounts) {
            accounts_arr.put(acc);
        }
        request.json("accounts", accounts_arr);
        return request;
    }

    public Request subscribeBookOffers(Issue get, Issue pay,int limit) {
        Request request = newRequest(Command.subscribe);
        JSONObject book = new JSONObject();
        JSONArray books = new JSONArray(new Object[] { book });
        book.put("snapshot", true);
        book.put("taker_gets", get.toJSON());
        book.put("taker_pays", pay.toJSON());
        book.put("limit", limit);
        request.json("books", books);

        return request;
    }

    public Request requestBookOffers(Issue get, Issue pay,int limit) {
        Request request = newRequest(Command.book_offers);
    	request.json("ledger_index","validated");
        request.json("taker_gets", get.toJSON());
        request.json("taker_pays", pay.toJSON());
        request.json("limit", limit);
        return request;
    }
}


text:
NS_ASSUME_NONNULL_BEGIN

@implementation SDLSlider

- (instancetype)init {
    if (self = [super initWithName:SDLNameSlider]) {
    }
    return self;
}

- (instancetype)initWithNumTicks:(UInt8)numTicks position:(UInt8)position sliderHeader:(NSString *)sliderHeader sliderFooter:(nullable NSString *)sliderFooter timeout:(UInt16)timeout {
    NSArray<NSString *> *footer = nil;
    if (sliderFooter != nil) {
        footer = @[sliderFooter];
    }

    return [self initWithNumTicks:numTicks position:position sliderHeader:sliderHeader sliderFooters:footer timeout:timeout];
}

- (instancetype)initWithNumTicks:(UInt8)numTicks position:(UInt8)position sliderHeader:(NSString *)sliderHeader sliderFooters:(nullable NSArray<NSString *> *)sliderFooters timeout:(UInt16)timeout {
    self = [self initWithNumTicks:numTicks position:position];
    if (!self) {
        return nil;
    }

    self.sliderHeader = sliderHeader;
    self.sliderFooter = [sliderFooters mutableCopy];
    self.timeout = @(timeout);

    return self;
}

- (instancetype)initWithNumTicks:(UInt8)numTicks position:(UInt8)position {
    self = [self init];
    if (!self) {
        return nil;
    }

    self.numTicks = @(numTicks);
    self.position = @(position);

    return self;
}

- (void)setNumTicks:(NSNumber<SDLInt> *)numTicks {
    [parameters sdl_setObject:numTicks forName:SDLNameNumberTicks];
}

- (NSNumber<SDLInt> *)numTicks {
    return [parameters sdl_objectForName:SDLNameNumberTicks];
}

- (void)setPosition:(NSNumber<SDLInt> *)position {
    [parameters sdl_setObject:position forName:SDLNamePosition];
}

- (NSNumber<SDLInt> *)position {
    return [parameters sdl_objectForName:SDLNamePosition];
}

- (void)setSliderHeader:(NSString *)sliderHeader {
    [parameters sdl_setObject:sliderHeader forName:SDLNameSliderHeader];
}

- (NSString *)sliderHeader {
    return [parameters sdl_objectForName:SDLNameSliderHeader];
}

- (void)setSliderFooter:(nullable NSArray<NSString *> *)sliderFooter {
    [parameters sdl_setObject:sliderFooter forName:SDLNameSliderFooter];
}

- (nullable NSArray<NSString *> *)sliderFooter {
    return [parameters sdl_objectForName:SDLNameSliderFooter];
}

- (void)setTimeout:(nullable NSNumber<SDLInt> *)timeout {
    [parameters sdl_setObject:timeout forName:SDLNameTimeout];
}

- (nullable NSNumber<SDLInt> *)timeout {
    return [parameters sdl_objectForName:SDLNameTimeout];
}

@end

NS_ASSUME_NONNULL_END

redpajama_set_name: RedPajamaGithub


text:
/*
 *
 * Points actions
 *
 */

import {
  LOAD_POINT, LOAD_POINTS, LOAD_POINTS_SUCCESS, LOAD_POINTS_FAIL,
  SYNC_DOWNSTREAM, SYNC_UPSTREAM,
  ADD_POINT, SAVE_POINT, SAVE_POINTS
} from './constants';

export function loadPoint(placeSlug, pointSlug) {
  return {
    type: LOAD_POINT,
    payload: { placeSlug, pointSlug }
  };
}

export function loadPoints(placeSlug) {
  return {
    type: LOAD_POINTS,
    payload: placeSlug
  };
}
//
export function addPoint(info) {
  return {
    type: ADD_POINT,
    payload: info
  }
}
//
export function saveNewPoint(pointInfo) {
  return {
    type: SAVE_POINT,
    payload: pointInfo
  };
}

export function savePoints(points) {
  return {
    type: SAVE_POINTS,
    payload: points
  };
}

export function loadSyncUpstream(db) {
  return {
    type: SYNC_UPSTREAM,
    payload: db
  };
}
//
// export function loadPointsSuccess() {
//   return {
//     type: LOAD_POINTS_SUCCESS,
//   };
// }
// export function loadPointsFail() {
//   return {
//     type: LOAD_POINTS_FAIL,
//   };
// }
//
export function loadSyncDownstream(dbToSync) {
  return {
    type: SYNC_DOWNSTREAM,
    payload: dbToSync
  };
}


text:
package org.apache.shindig.gadgets.js;

import static org.junit.Assert.assertEquals;

import com.google.common.collect.ImmutableList;

import org.apache.shindig.common.uri.Uri;
import org.apache.shindig.gadgets.uri.JsUriManager.JsUri;
import org.apache.shindig.gadgets.uri.UriStatus;
import org.easymock.EasyMock;
import org.easymock.IMocksControl;
import org.junit.Before;
import org.junit.Test;

import java.util.List;

/**
 * Tests for {@link AddJslLoadedVariableProcessor}.
 */
public class AddJslLoadedVariableProcessorTest {
  private static final String REQ_1_LIB = "foo";
  private static final String REQ_2_LIB = "gig";
  private static final String LOAD_LIB = "bar";
  private static final String URI = "http://localhost";
  private static final List<String> REQ_LIBS = ImmutableList.of(
      REQ_1_LIB, REQ_2_LIB, REQ_1_LIB, REQ_2_LIB, LOAD_LIB);
  private static final List<String> LOAD_LIBS = ImmutableList.of(
      LOAD_LIB, LOAD_LIB);

  private IMocksControl control;
  private JsRequest request;
  private JsUri jsUri;
  private JsResponseBuilder response;
  private AddJslLoadedVariableProcessor processor;

  @Before
  public void setUp() {
    control = EasyMock.createControl();
    request = control.createMock(JsRequest.class);
    response = new JsResponseBuilder();
    processor = new AddJslLoadedVariableProcessor();
  }

  @Test
  public void testSucceeds() throws Exception {
    setUpJsUri(URI + "/" + REQ_1_LIB + ".js");
    control.replay();
    processor.process(request, response);
    assertEquals(String.format(AddJslLoadedVariableProcessor.TEMPLATE,
        "['foo','gig']"), response.build().toJsString());
    control.verify();
  }

  @Test
  public void testSkips() throws Exception {
    setUpJsUri(URI + "?nohint=1");
    control.replay();
    processor.process(request, response);
    assertEquals("", response.build().toJsString());
    control.verify();
  }

  private void setUpJsUri(String uri) {
    jsUri = new JsUri(UriStatus.VALID_UNVERSIONED, Uri.parse(uri), REQ_LIBS, LOAD_LIBS);
    EasyMock.expect(request.getJsUri()).andReturn(jsUri);
  }
}


text:
namespace testsuite {

struct SomeConstRecord final {
    int16_t number1;
    int16_t number2;

    SomeConstRecord(int16_t number1_,
                    int16_t number2_)
    : number1(std::move(number1_))
    , number2(std::move(number2_))
    {}
};

}  // namespace testsuite


text:
package org.apache.ignite.internal.processors.cache;

import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.apache.ignite.internal.managers.discovery.DiscoveryCustomMessage;
import org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion;
import org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtPartitionExchangeId;
import org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtPartitionsFullMessage;
import org.apache.ignite.internal.util.typedef.F;
import org.apache.ignite.internal.util.typedef.internal.S;
import org.apache.ignite.lang.IgniteUuid;
import org.jetbrains.annotations.Nullable;

/**
 *
 */
public class CacheAffinityChangeMessage implements DiscoveryCustomMessage {
    /** */
    private static final long serialVersionUID = 0L;

    /** */
    private IgniteUuid id = IgniteUuid.randomUuid();

    /** */
    private AffinityTopologyVersion topVer;

    /** */
    private GridDhtPartitionExchangeId exchId;

    /** */
    private Map<Integer, Map<Integer, List<UUID>>> assignmentChange;

    /** */
    private Map<Integer, IgniteUuid> cacheDeploymentIds;

    /** */
    private GridDhtPartitionsFullMessage partsMsg;

    /** */
    private transient boolean exchangeNeeded;

    /**
     * Constructor used when message is created after cache rebalance finished.
     *
     * @param topVer Topology version.
     * @param assignmentChange Assignment change.
     * @param cacheDeploymentIds Cache deployment ID.
     */
    public CacheAffinityChangeMessage(AffinityTopologyVersion topVer,
        Map<Integer, Map<Integer, List<UUID>>> assignmentChange,
        Map<Integer, IgniteUuid> cacheDeploymentIds) {
        assert !F.isEmpty(assignmentChange) : assignmentChange;

        this.topVer = topVer;
        this.assignmentChange = assignmentChange;
        this.cacheDeploymentIds = cacheDeploymentIds;
    }

    /**
     * Constructor used when message is created to finish exchange.
     *
     * @param exchId Exchange ID.
     * @param partsMsg Partitions messages.
     * @param assignmentChange Assignment change.
     */
    public CacheAffinityChangeMessage(GridDhtPartitionExchangeId exchId,
        GridDhtPartitionsFullMessage partsMsg,
        Map<Integer, Map<Integer, List<UUID>>> assignmentChange) {
        this.exchId = exchId;
        this.partsMsg = partsMsg;
        this.assignmentChange = assignmentChange;
    }

    /**
     * @return Cache deployment IDs.
     */
    public Map<Integer, IgniteUuid> cacheDeploymentIds() {
        return cacheDeploymentIds;
    }

    /**
     * @return {@code True} if request should trigger partition exchange.
     */
    public boolean exchangeNeeded() {
        return exchangeNeeded;
    }

    /**
     * @param exchangeNeeded {@code True} if request should trigger partition exchange.
     */
    public void exchangeNeeded(boolean exchangeNeeded) {
        this.exchangeNeeded = exchangeNeeded;
    }

    /**
     * @return Partitions message.
     */
    public GridDhtPartitionsFullMessage partitionsMessage() {
        return partsMsg;
    }

    /**
     * @return Affinity assignments.
     */
    @Nullable public Map<Integer, Map<Integer, List<UUID>>> assignmentChange() {
        return assignmentChange;
    }

    /**
     * @return Exchange version.
     */
    @Nullable public GridDhtPartitionExchangeId exchangeId() {
        return exchId;
    }

    /**
     * @return Topology version.
     */
    public AffinityTopologyVersion topologyVersion() {
        return topVer;
    }

    /** {@inheritDoc} */
    @Override public IgniteUuid id() {
        return id;
    }

    /** {@inheritDoc} */
    @Nullable @Override public DiscoveryCustomMessage ackMessage() {
        return null;
    }

    /** {@inheritDoc} */
    @Override public boolean isMutable() {
        return false;
    }

    /** {@inheritDoc} */
    @Override public String toString() {
        return S.toString(CacheAffinityChangeMessage.class, this);
    }
}


text:
namespace BtsPortal.Entities.Esb
{
    public enum FaultStatusType : int
    {
        UnResolved = 1,
        Resolved = 2,
        //Resubmitted = 3,
        Flagged = 4
    }

    public enum AlertCriteria
    {
        Application,
        ErrorType,
        FailureCategory,
        FaultCode,
        FaultGenerator,
        FaultSeverity,
        MachineName,
        Scope,
        ServiceName
    }

    public enum AlertType
    {
        Transactional = 1,
        Summary
    }
}


text:
package mesosphere.marathon
package core.health.impl

import akka.Done
import akka.actor.{ ActorRef, ActorRefFactory }
import akka.event.EventStream
import akka.pattern.ask
import akka.stream.Materializer
import akka.util.Timeout
import scala.concurrent.ExecutionContext.Implicits.global
import mesosphere.marathon.core.event.{ AddHealthCheck, RemoveHealthCheck }
import mesosphere.marathon.core.group.GroupManager
import mesosphere.marathon.core.health._
import mesosphere.marathon.core.health.impl.AppHealthCheckActor.ApplicationKey
import mesosphere.marathon.core.health.impl.HealthCheckActor.{ AppHealth, GetAppHealth, GetInstanceHealth }
import mesosphere.marathon.core.instance.Instance
import mesosphere.marathon.core.task.Task
import mesosphere.marathon.core.task.termination.KillService
import mesosphere.marathon.core.task.tracker.InstanceTracker
import mesosphere.marathon.state.{ AppDefinition, PathId, Timestamp }
import mesosphere.util.RWLock
import org.apache.mesos.Protos.TaskStatus

import scala.async.Async._
import scala.collection.immutable.{ Map, Seq }
import scala.collection.mutable
import scala.concurrent.Future
import scala.concurrent.duration._

class MarathonHealthCheckManager(
    actorRefFactory: ActorRefFactory,
    killService: KillService,
    eventBus: EventStream,
    instanceTracker: InstanceTracker,
    groupManager: GroupManager)(implicit mat: Materializer) extends HealthCheckManager {

  protected[this] case class ActiveHealthCheck(
      healthCheck: HealthCheck,
      actor: ActorRef)

  protected[this] var appHealthChecks: RWLock[mutable.Map[PathId, Map[Timestamp, Set[ActiveHealthCheck]]]] =
    RWLock(mutable.Map.empty.withDefaultValue(Map.empty.withDefaultValue(Set.empty)))

  protected[this] var appHealthChecksActor: ActorRef = actorRefFactory.actorOf(AppHealthCheckActor.props(eventBus))

  override def list(appId: PathId): Set[HealthCheck] =
    listActive(appId).map(_.healthCheck)

  protected[this] def listActive(appId: PathId): Set[ActiveHealthCheck] =
    appHealthChecks.readLock { ahcs =>
      ahcs(appId).values.flatten.toSet
    }

  protected[this] def listActive(appId: PathId, appVersion: Timestamp): Set[ActiveHealthCheck] =
    appHealthChecks.readLock { ahcs =>
      ahcs(appId)(appVersion)
    }

  override def add(app: AppDefinition, healthCheck: HealthCheck, instances: Seq[Instance]): Unit =
    appHealthChecks.writeLock { ahcs =>
      val healthChecksForApp = listActive(app.id, app.version)

      if (healthChecksForApp.exists(_.healthCheck == healthCheck)) {
        log.debug(s"Not adding duplicated health check for app [$app.id] and version [${app.version}]: [$healthCheck]")
      } else {
        log.info(s"Adding health check for app [${app.id}] and version [${app.version}]: [$healthCheck]")

        val ref = actorRefFactory.actorOf(
          HealthCheckActor.props(app, appHealthChecksActor, killService, healthCheck, instanceTracker, eventBus))
        val newHealthChecksForApp =
          healthChecksForApp + ActiveHealthCheck(healthCheck, ref)

        appHealthChecksActor ! AppHealthCheckActor.AddHealthCheck(
          ApplicationKey(app.id, app.version), healthCheck)

        healthCheck match {
          case _: MesosHealthCheck =>
            instances.foreach { instance =>
              instance.tasksMap.values.withFilter(_.isRunning).map(_.status.mesosStatus).foreach {
                case Some(mesosStatus) if mesosStatus.hasHealthy =>
                  val health = if (mesosStatus.getHealthy) Healthy(instance.instanceId, instance.runSpecVersion, publishEvent = false)
                  else Unhealthy(instance.instanceId, instance.runSpecVersion, "", publishEvent = false)
                  ref ! health
                case None =>
              }
            }
          case _ =>
        }

        val appMap = ahcs(app.id) + (app.version -> newHealthChecksForApp)
        ahcs += app.id -> appMap

        eventBus.publish(AddHealthCheck(app.id, app.version, healthCheck))
      }
    }

  override def addAllFor(app: AppDefinition, instances: Seq[Instance]): Unit =
    appHealthChecks.writeLock { _ => // atomically add all checks for this app version
      app.healthChecks.foreach(add(app, _, instances))
    }

  override def remove(appId: PathId, appVersion: Timestamp, healthCheck: HealthCheck): Unit =
    appHealthChecks.writeLock { ahcs =>
      val healthChecksForVersion: Set[ActiveHealthCheck] = listActive(appId, appVersion)
      val toRemove: Set[ActiveHealthCheck] = healthChecksForVersion.filter(_.healthCheck == healthCheck)
      for (ahc <- toRemove) {
        log.info(s"Removing health check for app [$appId] and version [$appVersion]: [$healthCheck]")
        deactivate(ahc)
        eventBus.publish(RemoveHealthCheck(appId))
      }
      val newHealthChecksForVersion = healthChecksForVersion -- toRemove
      val currentHealthChecksForApp = ahcs(appId)
      val newHealthChecksForApp = if (newHealthChecksForVersion.isEmpty) {
        currentHealthChecksForApp - appVersion
      } else {
        currentHealthChecksForApp + (appVersion -> newHealthChecksForVersion)
      }

      appHealthChecksActor ! AppHealthCheckActor.RemoveHealthCheck(
        ApplicationKey(appId, appVersion), healthCheck)

      if (newHealthChecksForApp.isEmpty) ahcs -= appId
      else ahcs += (appId -> newHealthChecksForApp)
    }

  override def removeAll(): Unit =
    appHealthChecks.writeLock {
      _.keys foreach removeAllFor
    }

  override def removeAllFor(appId: PathId): Unit =
    appHealthChecks.writeLock { ahcs =>
      for {
        (version, activeHealthChecks) <- ahcs(appId)
        activeHealthCheck <- activeHealthChecks
      } {
        remove(appId, version, activeHealthCheck.healthCheck)
      }
    }

  /**
    * Reconcile all health checks for all instances of the given apps.
    * Note: there can be Instances with different versions of the application.
    *       This reconciliation logic will always use the related version of the application to reconcile health checks.
    *
    * @param apps all applications to reconcile
    * @return a future which will be complete, if the reconciliation for all apps is done.
    */
  @SuppressWarnings(Array("all"))
  override def reconcile(apps: Seq[AppDefinition]): Future[Done] = {

    def reconcileApp(app: AppDefinition, instances: Seq[Instance]): Future[Done] = {
      val appId = app.id
      log.info(s"reconcile [$appId] with latest version [${app.version}]")

      val instancesByVersion = instances.groupBy(_.version)

      val activeAppVersions: Set[Timestamp] = {
        val versions: Set[Timestamp] = instances.map(_.runSpecVersion)(collection.breakOut)
        versions + app.version
      }

      val healthCheckAppVersions: Set[Timestamp] = appHealthChecks.writeLock { ahcs =>
        // remove health checks for which the app version is not current and no tasks remain
        // since only current version tasks are launched.
        for {
          (version, activeHealthChecks) <- ahcs(appId)
          if version != app.version && !activeAppVersions.contains(version)
          activeHealthCheck <- activeHealthChecks
        } remove(appId, version, activeHealthCheck.healthCheck)

        ahcs(appId).keySet
      }

      // add missing health checks for the current
      // reconcile all running versions of the current app
      val appVersionsWithoutHealthChecks: Set[Timestamp] = activeAppVersions -- healthCheckAppVersions
      val res: Set[Future[Unit]] = appVersionsWithoutHealthChecks.map { version =>
        groupManager.appVersion(appId, version.toOffsetDateTime).map {
          case None =>
            // FIXME: If the app version of the task is not available anymore, no health check is started.
            // We generated a new app version for every scale change. If maxVersions is configured, we
            // throw away old versions such that we may not have the app configuration of all tasks available anymore.
            log.warn(
              s"Cannot find health check configuration for [$appId] and version [$version], " +
                "using most recent one.")

          case Some(appVersion) =>
            log.info(s"addAllFor [$appId] version [$version]")
            addAllFor(appVersion, instancesByVersion.getOrElse(version, Seq.empty))
        }
      }
      Future.sequence(res).map(_ => Done)
    }

    async {
      val instances = await(instanceTracker.instancesBySpec())
      val reconciledApps = apps.map(app => reconcileApp(app, instances.specInstances(app.id)))
      await(Future.sequence(reconciledApps).map(_ => Done))
    }
  }

  override def update(taskStatus: TaskStatus, version: Timestamp): Unit =
    appHealthChecks.readLock { ahcs =>
      // construct a health result from the incoming task status
      val instanceId = Task.Id(taskStatus.getTaskId).instanceId
      val maybeResult: Option[HealthResult] =
        if (taskStatus.hasHealthy) {
          val healthy = taskStatus.getHealthy
          log.info(s"Received status for $instanceId with version [$version] and healthy [$healthy]")
          Some(if (healthy) Healthy(instanceId, version) else Unhealthy(instanceId, version, ""))
        } else {
          log.debug(s"Ignoring status for $instanceId with no health information")
          None
        }

      // collect health check actors for the associated app's Mesos checks.
      val healthCheckActors: Seq[ActorRef] = listActive(instanceId.runSpecId, version).collect {
        case ActiveHealthCheck(hc: MesosHealthCheck, ref) => ref
      }(collection.breakOut)

      // send the result to each health check actor
      for {
        result <- maybeResult
        ref <- healthCheckActors
      } {
        log.info(s"Forwarding health result [$result] to health check actor [$ref]")
        ref ! result
      }
    }

  override def status(appId: PathId, instanceId: Instance.Id): Future[Seq[Health]] = {
    implicit val timeout: Timeout = Timeout(2, SECONDS)

    val futureAppVersion: Future[Option[Timestamp]] = for {
      maybeTaskState <- instanceTracker.instance(instanceId)
    } yield maybeTaskState.map(_.runSpecVersion)

    futureAppVersion.flatMap {
      case None => Future.successful(Nil)
      case Some(appVersion) =>
        Future.sequence(
          listActive(appId, appVersion).collect {
            case ActiveHealthCheck(_, actor) =>
              (actor ? GetInstanceHealth(instanceId)).mapTo[Health]
          }(collection.breakOut)
        )
    }
  }

  override def statuses(appId: PathId): Future[Map[Instance.Id, Seq[Health]]] = {
    appHealthChecks.readLock { ahcs =>
      implicit val timeout: Timeout = Timeout(2, SECONDS)
      val futureHealths: Seq[Future[HealthCheckActor.AppHealth]] = ahcs(appId).values.flatMap { checks =>
        checks.map {
          case ActiveHealthCheck(_, actor) => (actor ? GetAppHealth).mapTo[AppHealth]
        }
      }(collection.breakOut)

      Future.sequence(futureHealths).map { healths =>
        healths.flatMap(_.health).groupBy(_.instanceId).withDefaultValue(Nil)
      }
    }
  }

  protected[this] def deactivate(healthCheck: ActiveHealthCheck): Unit =
    appHealthChecks.writeLock { _ => actorRefFactory.stop(healthCheck.actor) }

}


text:
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.

using System.Threading.Tasks;
using Duende.IdentityServer.Events;
using Duende.IdentityServer.Models;
using Duende.IdentityServer.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Rsk.Samples.IdentityServer4.AdminUiIntegration.Middleware;
using Rsk.Samples.IdentityServer4.AdminUiIntegration.Models;
using Rsk.Samples.IdentityServer4.AdminUiIntegration.Services;

namespace Rsk.Samples.IdentityServer4.AdminUiIntegration.Controllers
{
    [SecurityHeaders]
    public class HomeController : Controller
    {
        private readonly IIdentityServerInteractionService interaction;
        private readonly IEventStore eventStore;

        public HomeController(IIdentityServerInteractionService interaction, IEventStore eventStore)
        {
            this.interaction = interaction;
            this.eventStore = eventStore;
        }

        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// Shows the error page
        /// </summary>
        public async Task<IActionResult> Error(string errorId)
        {
            var vm = new ErrorViewModel();

            // retrieve error details from IdentityServer
            var message = await interaction.GetErrorContextAsync(errorId);

            //try and get more details regarding the error from the IdentityServer event cache
            var cachedEventInformation = eventStore.GetEventByTraceID(HttpContext.TraceIdentifier);

            if (message != null)
            {
                vm.Error = message;
                vm.EventStoreMessage = cachedEventInformation;
            }

            return View("Error", vm);
        }
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Polyblastia flavicans Müll. Arg.

### Remarks
null


text:
<?php

namespace WindowsAzure\ServiceBus\Models;

use WindowsAzure\Common\Internal\Atom\Entry;
use WindowsAzure\Common\Internal\Atom\Content;
use WindowsAzure\Common\Internal\Serialization\XmlSerializer;
use WindowsAzure\Common\Internal\Resources;
use WindowsAzure\Common\Internal\Validate;

/**
 * The information of a subscription.
 *
 * @category  Microsoft
 *
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 *
 * @version   Release: 0.5.0_2016-11
 *
 * @link      https://github.com/WindowsAzure/azure-sdk-for-php
 */
class SubscriptionInfo extends Entry
{
    /**
     * The entry of the subscription info.
     *
     * @var Entry
     */
    private $_entry;

    /**
     * The description of the subscription.
     *
     * @var SubscriptionDescription
     */
    private $_subscriptionDescription;

    /**
     * Creates a SubscriptionInfo instance with specified parameters.
     *
     * @param string                  $title                   The title of
     *                                                         the subscription
     * @param SubscriptionDescription $subscriptionDescription The description
     *                                                         of the subscription
     */
    public function __construct(
        $title = Resources::EMPTY_STRING,
        SubscriptionDescription $subscriptionDescription = null
    ) {
        Validate::isString($title, 'title');
        if (is_null($subscriptionDescription)) {
            $subscriptionDescription = new SubscriptionDescription();
        }
        $this->_subscriptionDescription = $subscriptionDescription;
        $this->_entry = new Entry();
        $this->_entry->setTitle($title);
        $this->_entry->setAttribute(
            Resources::XMLNS,
            Resources::SERVICE_BUS_NAMESPACE
        );
    }

    /**
     * Populates the properties of the subscription info instance with a XML string.
     *
     * @param string $entryXml A XML string representing a subscription
     *                         information instance
     */
    public function parseXml($entryXml)
    {
        $this->_entry->parseXml($entryXml);
        $content = $this->_entry->getContent();
        if (is_null($content)) {
            $this->_subscriptionDescription = null;
        } else {
            $this->_subscriptionDescription = SubscriptionDescription::create(
                $content->getText()
            );
        }
    }

    /**
     * Writes XML based on the subscription information.
     *
     * @param \XMLWriter $xmlWriter The XML writer
     */
    public function writeXml(\XMLWriter $xmlWriter)
    {
        $content = null;
        if (!is_null($this->_subscriptionDescription)) {
            $content = new Content();
            $content->setText(
                XmlSerializer::objectSerialize(
                    $this->_subscriptionDescription,
                    'SubscriptionDescription'
                )
            );
        }
        $this->_entry->setContent($content);
        $this->_entry->writeXml($xmlWriter);
    }

    /**
     * Gets the entry of the subscription info.
     *
     * @return Entry
     */
    public function getEntry()
    {
        return $this->_entry;
    }

    /**
     * Sets the entry of the subscription info.
     *
     * @param Entry $entry The entry of the subscription info
     */
    public function setEntry($entry)
    {
        $this->_entry = $entry;
    }

    /**
     * Gets the title.
     *
     * @return string
     */
    public function getTitle()
    {
        return $this->_entry->getTitle();
    }

    /**
     * Sets the title.
     *
     * @param string $title The title of the queue info
     */
    public function setTitle($title)
    {
        $this->_entry->setTitle($title);
    }

    /**
     * Gets the subscription description.
     *
     * @return SubscriptionDescription
     */
    public function getSubscriptionDescription()
    {
        return $this->_subscriptionDescription;
    }

    /**
     * Sets the subscription description.
     *
     * @param SubscriptionDescription $subscriptionDescription The description of
     *                                                         the subscription
     */
    public function setSubscriptionDescription(SubscriptionDescription $subscriptionDescription)
    {
        $this->_subscriptionDescription = $subscriptionDescription;
    }

    /**
     * Gets the lock duration.
     *
     * @return int
     */
    public function getLockDuration()
    {
        return $this->_subscriptionDescription->getLockDuration();
    }

    /**
     * Sets the lock duration.
     *
     * @param string $lockDuration The duration of the lock
     */
    public function setLockDuration($lockDuration)
    {
        $this->_subscriptionDescription->setLockDuration($lockDuration);
    }

    /**
     * Gets requires session.
     *
     * @return bool
     */
    public function getRequiresSession()
    {
        return $this->_subscriptionDescription->getRequiresSession();
    }

    /**
     * Sets the requires session.
     *
     * @param bool $requiresSession The requires session
     */
    public function setRequiresSession($requiresSession)
    {
        $this->_subscriptionDescription->setRequiresSession($requiresSession);
    }

    /**
     * Gets default message time to live.
     *
     * @return string
     */
    public function getDefaultMessageTimeToLive()
    {
        return $this->_subscriptionDescription->getDefaultMessageTimeToLive();
    }

    /**
     * Sets default message time to live.
     *
     * @param string $defaultMessageTimeToLive The default message time to live
     */
    public function setDefaultMessageTimeToLive($defaultMessageTimeToLive)
    {
        $this->_subscriptionDescription->setDefaultMessageTimeToLive(
            $defaultMessageTimeToLive
        );
    }

    /**
     * Gets dead lettering on message expiration.
     *
     * @return string
     */
    public function getDeadLetteringOnMessageExpiration()
    {
        $subscriptionDesc = $this->_subscriptionDescription;

        return $subscriptionDesc->getDeadLetteringOnMessageExpiration();
    }

    /**
     * Sets dead lettering on message expiration.
     *
     * @param string $deadLetteringOnMessageExpiration The dead lettering
     *                                                 on message expiration
     */
    public function setDeadLetteringOnMessageExpiration(
        $deadLetteringOnMessageExpiration
    ) {
        $this->_subscriptionDescription->setDeadLetteringOnMessageExpiration(
            $deadLetteringOnMessageExpiration
        );
    }

    /**
     * Gets dead lettering on filter evaluation exceptions.
     *
     * @return string
     */
    public function getDeadLetteringOnFilterEvaluationExceptions()
    {
        $subscriptionDesc = $this->_subscriptionDescription;

        return $subscriptionDesc->getDeadLetteringOnFilterEvaluationExceptions();
    }

    /**
     * Sets dead lettering on filter evaluation exceptions.
     *
     * @param string $deadLetteringOnFilterEvaluationExceptions Sets dead lettering
     *                                                          on filter evaluation exceptions
     */
    public function setDeadLetteringOnFilterEvaluationExceptions(
        $deadLetteringOnFilterEvaluationExceptions
    ) {
        $subscriptionDesc = $this->_subscriptionDescription;
        $subscriptionDesc->setDeadLetteringOnFilterEvaluationExceptions(
            $deadLetteringOnFilterEvaluationExceptions
        );
    }

    /**
     * Gets the default rule description.
     *
     * @return string
     */
    public function getDefaultRuleDescription()
    {
        return $this->_subscriptionDescription->getDefaultRuleDescription();
    }

    /**
     * Sets the default rule description.
     *
     * @param string $defaultRuleDescription The default rule description
     */
    public function setDefaultRuleDescription($defaultRuleDescription)
    {
        $this->_subscriptionDescription->setDefaultRuleDescription(
            $defaultRuleDescription
        );
    }

    /**
     * Gets the count of the message.
     *
     * @return int
     */
    public function getMessageCount()
    {
        return $this->_subscriptionDescription->getMessageCount();
    }

    /**
     * Sets the count of the message.
     *
     * @param string $messageCount The count of the message
     */
    public function setMessageCount($messageCount)
    {
        $this->_subscriptionDescription->setMessageCount($messageCount);
    }

    /**
     * Gets maximum delivery count.
     *
     * @return int
     */
    public function getMaxDeliveryCount()
    {
        return $this->_subscriptionDescription->getMaxDeliveryCount();
    }

    /**
     * Sets maximum delivery count.
     *
     * @param int $maxDeliveryCount The maximum delivery count
     */
    public function setMaxDeliveryCount($maxDeliveryCount)
    {
        $this->_subscriptionDescription->setMaxDeliveryCount($maxDeliveryCount);
    }

    /**
     * Gets enable batched operations.
     *
     * @return bool
     */
    public function getEnableBatchedOperations()
    {
        return $this->_subscriptionDescription->getEnableBatchedOperations();
    }

    /**
     * Sets enable batched operations.
     *
     * @param bool $enableBatchedOperations Enable batched operations
     */
    public function setEnableBatchedOperations($enableBatchedOperations)
    {
        $this->_subscriptionDescription->setEnableBatchedOperations(
            $enableBatchedOperations
        );
    }
}


text:
package uk.ac.ebi.embl.flatfile.writer.xml;

import java.io.IOException;
import java.io.StringWriter;

import uk.ac.ebi.embl.api.entry.Entry;
import uk.ac.ebi.embl.api.entry.reference.Article;
import uk.ac.ebi.embl.flatfile.writer.WrapType;
import uk.ac.ebi.embl.flatfile.writer.embl.EmblArticleWriter;
import uk.ac.ebi.ena.xml.SimpleXmlWriter;

public class XmlArticleWriter {

	private Entry entry;
    private Article article;

	public XmlArticleWriter(Entry entry, Article article) {
		this.entry = entry;
		this.article = article;
	}

    public boolean write(SimpleXmlWriter writer) throws IOException {
    	StringWriter stringWriter = new StringWriter();
    	(new EmblArticleWriter(entry, article, WrapType.EMBL_WRAP, "")).write(stringWriter);
    	writer.writeElementText(stringWriter.toString());
    	return true;
	}
}


text:
package com.google.javascript.jscomp;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.google.common.base.Preconditions;
import com.google.javascript.jscomp.AnalyzerState.*;

/**
 * @author arcadoss
 */
class MyValueAnalyzer extends MyFlowAnalysis<AnalyzerState> {
  AnalyzerMemory memory;

  MyValueAnalyzer(MyFlowGraph targetCfg, JoinOp<AnalyzerState> analyzerStateJoinOp, WhereOp<AnalyzerState> whereOp) {
    super(targetCfg, analyzerStateJoinOp, whereOp);
    memory = new AnalyzerMemory();
  }

  @Override
  boolean isForward() {
    return true;
  }

  @Override
  AnalyzerState flowThrough(MyNode node, AnalyzerState input) {
    switch (node.getCommand()) {
      case SKIP:
        return input;

      case DECLARE_VARIABLE:
        return handleDeclare(input, node.getOperands());

      case READ_VARIABLE:
        return handleReadVariable(input, node.getOperands());

      case WRITE_VARIABLE:
        return handleWriteVariable(input, node.getOperands());

      case CONSTANT:
        return handleConstant(input, node.getOperands());

      case READ_PROPERTY:
        return handleReadProperty(input, node.getOperands());

      case WRITE_PROPERTY:
        return handleWriteProperty(input, node.getOperands());

      case DELETE_PROPERTY:
        return handleDeleteProperty(input, node.getOperands());

      case IF:
        return handleIf(input, node.getOperands());

      case ENTRY:
        return handleEntry(input, node.getOperands());

      case EXIT:
        return handleExit(input, node.getOperands());

      case EXIT_EXC:
        return handleExitExc(input, node.getOperands());

      case CALL:
        return handleCall(input, node.getOperands());

      case AFTER_CALL:
        return handleAfterCall(input, node.getOperands());

      case CONSTRUCT:
        return handleConstruct(input, node.getOperands());

      case RETURN:
        return handleReturn(input, node.getOperands());

      case THROW:
        return handleThrow(input, node.getOperands());

      case CATCH:
        return handleCatch(input, node.getOperands());

      case FOR_IN:
        return handleForIn(input, node.getOperands());

      case WITH:
        return handleWith(input, node.getOperands());

      case BITOR:
        return handleBitor(input, node.getOperands());

      case BITXOR:
        return handleBitxor(input, node.getOperands());

      case BITAND:
        return handleBitand(input, node.getOperands());

      case AND:
        return handleAnd(input, node.getOperands());

      case OR:
        return handleOr(input, node.getOperands());

      case LSH:
        return handleLsh(input, node.getOperands());

      case RSH:
        return handleRsh(input, node.getOperands());

      case URSH:
        return handleUrsh(input, node.getOperands());

      case ADD:
        return handleAdd(input, node.getOperands());

      case SUB:
        return handleSub(input, node.getOperands());

      case MUL:
        return handleMul(input, node.getOperands());

      case DIV:
        return handleDiv(input, node.getOperands());

      case MOD:
        return handleMod(input, node.getOperands());

      case EQ:
        return handleEq(input, node.getOperands());

      case NE:
        return handleNe(input, node.getOperands());

      case SHNE:
        return handleShne(input, node.getOperands());

      case SHEQ:
        return handleSheq(input, node.getOperands());

      case LT:
        return handleLt(input, node.getOperands());

      case LE:
        return handleLe(input, node.getOperands());

      case GT:
        return handleGt(input, node.getOperands());

      case GE:
        return handleGe(input, node.getOperands());

      case IN:
        return handleIn(input, node.getOperands());

      case NEG:
        return handleNeg(input, node.getOperands());

      case POS:
        return handlePos(input, node.getOperands());

      case BITNOT:
        return handleBitnot(input, node.getOperands());

      case NOT:
        return handleNot(input, node.getOperands());

      case INSTANCEOF:
        return handleInstanceof(input, node.getOperands());

      case TYPEOF:
        return handleTypeof(input, node.getOperands());

      case INC:
        return handleInc(input, node.getOperands());

      case DEC:
        return handleDec(input, node.getOperands());

      case HOOK:
        return handleHook(input, node.getOperands());

      case PSEUDO_NODE:
      case PSEUDO_ROOT:
      case PSEUDO_EXIT:
        throw new IllegalStateException("Pseudo nodes meeted during flow traversal");
    }
    return null;
  }

  private AnalyzerState handleReadVariable(AnalyzerState input, List<MyValuable> operands) {
    AnalyzerState output = new AnalyzerState(input);

    String fromVar = (String) operands.get(0).getValue();
    String tempVar = (String) operands.get(1).getValue();

    Store heap = output.getStore();
    Stack stack = output.getStack();
    Set<ExecutionContext> runningContexts = stack.getContext();
    Map<String,Value> temp = stack.getTempValues();

    Value value = new Value();
    Value undefValue = Value.makeUndef();
    for (ExecutionContext context : runningContexts) {
      LinkedList<Label> chain = context.getScopeChain();

      boolean changed = false;
      for (Label hierarchyObject : chain) {
        if (heap.contains(hierarchyObject)) {
          changed = true;
          AbsObject obj = heap.get(hierarchyObject);
          value.union(obj.getValue(fromVar));
          break;
        }
      }

      if (!changed) {
        // it should be raised exception here, but i have no time
        value.union(undefValue);
      }
    }

    temp.put(tempVar, value);
    output.marker.toUncond();

    return output;
  }

  private AnalyzerState handleDeclare(AnalyzerState input, List<MyValuable> operands) {
    Preconditions.checkPositionIndex(0, operands.size());

    AnalyzerState output = new AnalyzerState(input);
    String varName = (String) operands.get(0).getValue();

    Label label = memory.createObject();
    AbsObject obj = memory.getObject(label);

    Stack stack = output.getStack();
    Store heap = output.getStore();
    Set<ExecutionContext> runningContexts = stack.getContext();

    for (ExecutionContext context : runningContexts) {
      Label varObjLabel = context.getVarObj();
      AbsObject varObj = memory.getObject(varObjLabel);
      Value val = Value.makeObj(label);
      Property props = new Property(val);

      varObj.put(varName, props);
    }

    return output;
  }

  private AnalyzerState handleAdd(AnalyzerState input, List<MyValuable> operands) {
    String lValName = (String) operands.get(0).getValue();
    String rValName = (String) operands.get(1).getValue();
    String resName = (String) operands.get(2).getValue();

    AnalyzerState output = new AnalyzerState(input);

    Map<String, Value> temp = output.getStack().getTempValues();

    Value lVal = temp.get(lValName);
    Value rVal = temp.get(rValName);

    temp.put(resName, Value.add(lVal, rVal));
    output.getMarker().toUncond();

    return output;
  }

  private AnalyzerState handleAfterCall(AnalyzerState input, List<MyValuable> operands) {
    return input;
  }

  private AnalyzerState handleAnd(AnalyzerState input, List<MyValuable> operands) {
    return input;
  }

  private AnalyzerState handleBitand(AnalyzerState input, List<MyValuable> operands) {
    return input;
  }

  private AnalyzerState handleBitnot(AnalyzerState input, List<MyValuable> operands) {
    return input;
  }

  private AnalyzerState handleBitor(AnalyzerState input, List<MyValuable> operands) {
    return input;
  }

  private AnalyzerState handleBitxor(AnalyzerState input, List<MyValuable> operands) {
    return input;
  }

  private AnalyzerState handleCall(AnalyzerState input, List<MyValuable> operands) {
    return input;
  }

  private AnalyzerState handleCatch(AnalyzerState input, List<MyValuable> operands) {
    return input;
  }

  private AnalyzerState handleConstant(AnalyzerState input, List<MyValuable> operands) {
    return input;
  }

  private AnalyzerState handleConstruct(AnalyzerState input, List<MyValuable> operands) {
    return input;
  }

  private AnalyzerState handleDec(AnalyzerState input, List<MyValuable> operands) {
    return input;
  }

  private AnalyzerState handleDeleteProperty(AnalyzerState input, List<MyValuable> operands) {
    return input;
  }

  private AnalyzerState handleDiv(AnalyzerState input, List<MyValuable> operands) {
    return input;
  }

  private AnalyzerState handleEntry(AnalyzerState input, List<MyValuable> operands) {
    return input;
  }

  private AnalyzerState handleEq(AnalyzerState input, List<MyValuable> operands) {
    return input;
  }

  private AnalyzerState handleExit(AnalyzerState input, List<MyValuable> operands) {
    return input;
  }

  private AnalyzerState handleExitExc(AnalyzerState input, List<MyValuable> operands) {
    return input;
  }

  private AnalyzerState handleForIn(AnalyzerState input, List<MyValuable> operands) {
    return input;
  }

  private AnalyzerState handleGe(AnalyzerState input, List<MyValuable> operands) {
    return input;
  }

  private AnalyzerState handleGt(AnalyzerState input, List<MyValuable> operands) {
    return input;
  }

  private AnalyzerState handleHook(AnalyzerState input, List<MyValuable> operands) {
    return input;
  }

  private AnalyzerState handleIf(AnalyzerState input, List<MyValuable> operands) {
    return input;
  }

  private AnalyzerState handleIn(AnalyzerState input, List<MyValuable> operands) {
    return input;
  }

  private AnalyzerState handleInc(AnalyzerState input, List<MyValuable> operands) {
    return input;
  }

  private AnalyzerState handleInstanceof(AnalyzerState input, List<MyValuable> operands) {
    return input;
  }

  private AnalyzerState handleLe(AnalyzerState input, List<MyValuable> operands) {
    return input;
  }

  private AnalyzerState handleLsh(AnalyzerState input, List<MyValuable> operands) {
    return input;
  }

  private AnalyzerState handleLt(AnalyzerState input, List<MyValuable> operands) {
    return input;
  }

  private AnalyzerState handleMod(AnalyzerState input, List<MyValuable> operands) {
    return input;
  }

  private AnalyzerState handleMul(AnalyzerState input, List<MyValuable> operands) {
    return input;
  }

  private AnalyzerState handleNe(AnalyzerState input, List<MyValuable> operands) {
    return input;
  }

  private AnalyzerState handleNeg(AnalyzerState input, List<MyValuable> operands) {
    return input;
  }

  private AnalyzerState handleNot(AnalyzerState input, List<MyValuable> operands) {
    return input;
  }

  private AnalyzerState handleOr(AnalyzerState input, List<MyValuable> operands) {
    return input;
  }

  private AnalyzerState handlePos(AnalyzerState input, List<MyValuable> operands) {
    return input;
  }

  private AnalyzerState handleReadProperty(AnalyzerState input, List<MyValuable> operands) {
    return input;
  }

  private AnalyzerState handleReturn(AnalyzerState input, List<MyValuable> operands) {
    return input;
  }

  private AnalyzerState handleRsh(AnalyzerState input, List<MyValuable> operands) {
    return input;
  }

  private AnalyzerState handleSheq(AnalyzerState input, List<MyValuable> operands) {
    return input;
  }

  private AnalyzerState handleShne(AnalyzerState input, List<MyValuable> operands) {
    return input;
  }

  private AnalyzerState handleSub(AnalyzerState input, List<MyValuable> operands) {
    return input;
  }

  private AnalyzerState handleThrow(AnalyzerState input, List<MyValuable> operands) {
    return input;
  }

  private AnalyzerState handleTypeof(AnalyzerState input, List<MyValuable> operands) {
    return input;
  }

  private AnalyzerState handleUrsh(AnalyzerState input, List<MyValuable> operands) {
    return input;
  }

  private AnalyzerState handleWith(AnalyzerState input, List<MyValuable> operands) {
    return input;
  }

  private AnalyzerState handleWriteProperty(AnalyzerState input, List<MyValuable> operands) {
    return input;
  }

  private AnalyzerState handleWriteVariable(AnalyzerState input, List<MyValuable> operands) {
    return input;
  }

  @Override
  AnalyzerState createInitialEstimateLattice() {
    return AnalyzerState.bottom();
  }

  @Override
  AnalyzerState createEntryLattice() {
    return AnalyzerState.createGlobal();
  }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Biblthca Lichenol. 92: 138 (2006)

#### Original name
Thelotrema insigne Zahlbr.

### Remarks
null


text:
using Newtonsoft.Json;

namespace ESI.NET.Models.Corporation
{
    public class Shareholder
    {
        [JsonProperty("share_count")]
        public long ShareCount { get; set; }

        [JsonProperty("shareholder_id")]
        public int ShareholderId { get; set; }

        [JsonProperty("shareholder_type")]
        public string ShareholderType { get; set; }
    }
}


text:
using namespace System;
using namespace System::Globalization;
using namespace PcapDotNet::Core;

PacketTotalStatistics^ OfflinePacketCommunicator::TotalStatistics::get()
{
    throw gcnew InvalidOperationException("Can't get " + PacketTotalStatistics::typeid->Name + " for offline devices");
}

void OfflinePacketCommunicator::Transmit(PacketSendBuffer^, bool)
{
    throw gcnew InvalidOperationException("Can't transmit queue to an offline device");
}

OfflinePacketCommunicator::OfflinePacketCommunicator(String^ filename)
: PacketCommunicator(OpenFile(filename), nullptr)
{
}

// Private

// static
pcap_t* OfflinePacketCommunicator::OpenFile(String^ fileName)
{
    std::wstring unamangedFilename = MarshalingServices::ManagedToUnmanagedWideString(fileName);
    FILE* file = _wfopen(unamangedFilename.c_str(), L"rb");
	if (file == NULL)
		throw gcnew InvalidOperationException(String::Format(CultureInfo::InvariantCulture, "Failed opening file {0}.", fileName));

    char errorBuffer[PCAP_ERRBUF_SIZE];
    pcap_t *pcapDescriptor = pcap_fopen_offline(file, errorBuffer);
    if (pcapDescriptor == NULL)
    {
        int fcloseResult = fclose(file);
        String^ errorMessage = String::Format(CultureInfo::InvariantCulture, "Failed opening file {0}. Error: {1}.", fileName, gcnew String(errorBuffer));
        if (fcloseResult != 0)
            errorMessage += " Also failed closing the file.";
        throw gcnew InvalidOperationException(errorMessage);
    }

    return pcapDescriptor;
}


text:
//Write a program that extracts from a given text all sentences containing given word.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

class ExtractSentences
{
    static void Main()
    {
        Console.Write("Enter text{atleast 2 sentences}: ");
        string text = Console.ReadLine();
        Console.Write("Enter word to check with: ");
        string word = Console.ReadLine();
        StringBuilder newText = new StringBuilder();

        string[] sentences = text.Split('.');
        for (int i = 0; i < sentences.Length; i++)
        {
            string[] words = sentences[i].Split(' ');
            for (int j = 0; j < words.Length; j++)
            {
                if (words[j] == word)
                {
                    newText.Append(sentences[i]);
                    newText.Append(".");
                }
            }
        }
        Console.WriteLine(newText.ToString());
    }
}


text:
<?php

class Google_Service_Plus_PeopleFeed extends Google_Collection
{
  protected $collection_key = 'items';
  public $etag;
  protected $itemsType = 'Google_Service_Plus_Person';
  protected $itemsDataType = 'array';
  public $kind;
  public $nextPageToken;
  public $selfLink;
  public $title;
  public $totalItems;

  public function setEtag($etag)
  {
    $this->etag = $etag;
  }
  public function getEtag()
  {
    return $this->etag;
  }
  public function setItems($items)
  {
    $this->items = $items;
  }
  public function getItems()
  {
    return $this->items;
  }
  public function setKind($kind)
  {
    $this->kind = $kind;
  }
  public function getKind()
  {
    return $this->kind;
  }
  public function setNextPageToken($nextPageToken)
  {
    $this->nextPageToken = $nextPageToken;
  }
  public function getNextPageToken()
  {
    return $this->nextPageToken;
  }
  public function setSelfLink($selfLink)
  {
    $this->selfLink = $selfLink;
  }
  public function getSelfLink()
  {
    return $this->selfLink;
  }
  public function setTitle($title)
  {
    $this->title = $title;
  }
  public function getTitle()
  {
    return $this->title;
  }
  public function setTotalItems($totalItems)
  {
    $this->totalItems = $totalItems;
  }
  public function getTotalItems()
  {
    return $this->totalItems;
  }
}


text:
import Service from '@ember/service';
import { addQueryParam, addQueryParams } from 'shared/utils/util';
import fetch from '@rancher/ember-api-store/utils/fetch';
import { inject as service } from '@ember/service';
import { get, set } from '@ember/object';
import { reject } from 'rsvp';

const DIGITALOCEAN_API = 'api.digitalocean.com/v2';

export default Service.extend({
  app:           service(),

  request(auth = {}, command, opt = {}, out) {
    let url     = `${ get(this, 'app.proxyEndpoint') }/`;
    let token   = get(auth, 'token');
    let headers = { 'Accept': 'application/json' };

    if (get(auth, 'type') === 'cloud') {
      set(headers, 'x-api-cattleauth-header', `Bearer credID=${ token } passwordField=accessToken`);
    } else {
      set(headers, 'X-Api-Auth-Header', `Bearer ${ token }`);
    }

    if ( opt.url ) {
      url += opt.url.replace(/^http[s]?\/\//, '');
    } else {
      url += `${ DIGITALOCEAN_API }/${ command }`;
      url = addQueryParam(url, 'per_page', opt.per_page || 100);
      url = addQueryParams(url, opt.params || {});
    }

    return fetch(url, { headers }).then((res) => {
      let body = res.body;

      if ( out ) {
        out[command].pushObjects(body[command]);
      } else {
        out = body;
      }

      // De-paging
      if ( body && body.links && body.links.pages && body.links.pages.next ) {
        opt.url = body.links.pages.next;

        return this.apiRequest(command, opt, out).then(() => {
          return out;
        });
      } else {
        return out;
      }
    }).catch((err) => {
      return reject(err);
    });
  }
});


text:
package pl.aborek.demo.tasklist.user.rest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import pl.aborek.demo.tasklist.user.app.UserService;
import pl.aborek.demo.tasklist.user.app.command.CreateUser;
import pl.aborek.demo.tasklist.user.domain.User;

import javax.websocket.server.PathParam;
import java.util.List;

import static pl.aborek.demo.tasklist.util.PageRequestUtil.createPageRequest;

@Controller
@RequestMapping(path = "/users")
public class UserController {

    private final UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    @RequestMapping(method = RequestMethod.GET)
    public HttpEntity<List<User>> list(@RequestParam(required = false) Integer pageSize, @RequestParam(required = false) Integer pageNumber) {
        return new ResponseEntity(userService.findAll(createPageRequest(pageSize, pageNumber)), HttpStatus.OK);
    }

    @RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
    public HttpEntity<User> create(@RequestBody CreateUser createUser) {
        return new ResponseEntity(userService.create(createUser), HttpStatus.CREATED);
    }

    @RequestMapping(path = "/user/{userId}", method = RequestMethod.PUT)
    public HttpEntity<User> update(@PathVariable String userId, @PathParam("firstName") String firstName, @PathParam("lastName") String lastName) {
        return new ResponseEntity(userService.update(userId, firstName, lastName), HttpStatus.OK);
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="transparent_color">#0000</color>
    <color name="white_color">#ffffffff</color>
    <color name="black_color">#ff000000</color>
    <color name="default_background_color">#f5f4f9</color>
    <color name="default_title_background_color">#f7f7f8</color>
    <color name="default_title_bottom_line_color">#abaaae</color>

</resources>


text:
class ROM::Migrator

  # Base class for migrations
  #
  # @example
  #   class CreateUsers < ROM::Migrator::Migration
  #     up do
  #       create_table(:users).add(name: :text, age: :int)
  #     end
  #
  #     down do
  #       drop_table(:users)
  #     end
  #   end
  #
  #   migration = CreateUsers.new(gateway) # using some gateway
  #   migration.apply
  #   migration.reverse
  #
  # @api public
  #
  # @abstract
  #
  # @author nepalez <andrew.kozin@gmail.com>
  #
  class Migration

    include ROM::Options, Errors
    option :gateway,   reader: true
    option :logger,    reader: true
    option :number,    reader: true
    option :registrar, reader: true

    # Gets or sets the block to be called when the migration is applied
    #
    # @abstract
    #
    # @return [Proc]
    #
    def self.up(&block)
      @up = block if block
      @up || proc {}
    end

    # Gets or sets the block to be called when the migration is reversed
    #
    # @abstract
    #
    # @return [Proc]
    #
    def self.down(&block)
      @down = block if block
      @down || proc {}
    end

    # @!method initialize(options)
    # Initializes the migration for some gateway
    #
    # The gateway provides custom methods to make changes to persistence.
    # Because it calls <potentially> stateful connection
    # (migration --> gateway --> generator --> connection),
    # a mutex is used for thread safety.
    #
    # When migration is initialized with a number, its appying and reversing
    # is registered to persistence. Otherwise it just changes the
    # persistence without any possibility to step back.
    #
    # @param [Hash] options
    # @option options [ROM::Gateway] gateway
    #   The gateway that provides access to persistence.
    # @option options [ROM::Migrator::Registrar] registrar
    #   The object responcible for registering applied migrations.
    # @option options [::Logger] :logger
    #   The logger to store results of migration.
    # @option options [#to_s] :number
    #   The optional number of the migration.
    #
    def initialize(_)
      super
      @up   = self.class.up
      @down = self.class.down
    end

    # Applies the migration to persistence
    #
    # If the [#number] was provided, then registers it in the persistence
    #
    # @return [self] itself
    #
    def apply
      with_logging(:applied) do
        registrar.apply(number) { gateway.instance_eval(&@up) }
      end
    end

    # Reverses the migration in persistence
    #
    # If the [#number] wasn't provided, then unregisters its in the persistence
    #
    # @return [self] itself
    #
    def reverse
      with_logging(:reversed) do
        registrar.reverse(number) { gateway.instance_eval(&@down) }
      end
    end

    # Describes the migration
    #
    # @return [String]
    #
    def to_s
      number ? "migration number '#{number}'" : "migration"
    end

    private

    def with_logging(done)
      yield
      logger.info "The #{self} has been #{done}"
      self
    rescue => error
      logger.error "The error occured when #{self} was #{done}: #{error}"
      raise
    end

  end # class Migration

end # class ROM::Migrator


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

<TITLE>
B-Index
</TITLE>

<META NAME="date" CONTENT="2014-02-06">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../stylesheet.css" TITLE="Style">

      Package
      Class
      Use
      Tree
      Deprecated
    Index
      Help

 PREV LETTER
 NEXT LETTER

  FRAMES
 NO FRAMES

  All Classes

A B C D G I L R S U

B

BuildConfig - Class in com.microsoft.office365.lists
The Class BuildConfig.
BuildConfig() -
Constructor for class com.microsoft.office365.lists.BuildConfig

      Package
      Class
      Use
      Tree
      Deprecated
    Index
      Help

 PREV LETTER
 NEXT LETTER

  FRAMES
 NO FRAMES

  All Classes

A B C D G I L R S U


text:
using FluentValidation;
using SOURCE.BackOffice.Web.ViewModels.Pages.Document;
using System;

namespace SOURCE.BackOffice.Web.ViewModels.Validators.Document
{
    public class PieceJointeViewModelValidator : AbstractValidator<PieceJointeViewModel>
    {
        public PieceJointeViewModelValidator()
        {
            RuleFor(x => x.Libelle)
                .Must(LinkLibelleNotEmpty)
                .WithMessage("UPLOAD_VALIDATION_LIBELLE_OBLIGATOIRE");

            RuleFor(x => x.Url)
                .Must(LinkUrlNotEmpty)
                .WithMessage("UPLOAD_VALIDATION_URL_OBLIGATOIRE");
        }

        private bool LinkLibelleNotEmpty(PieceJointeViewModel instance, string Libelle)
        {
            return instance.IsFile || !string.IsNullOrWhiteSpace(Libelle);
        }
        private bool LinkUrlNotEmpty(PieceJointeViewModel instance, string Url)
        {
            return instance.IsFile || !string.IsNullOrWhiteSpace(Url);
        }
    }
}


text:
#include <aws/s3-crt/model/GetBucketRequestPaymentResult.h>
#include <aws/core/utils/xml/XmlSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>

#include <utility>

using namespace Aws::S3Crt::Model;
using namespace Aws::Utils::Xml;
using namespace Aws::Utils;
using namespace Aws;

GetBucketRequestPaymentResult::GetBucketRequestPaymentResult() :
    m_payer(Payer::NOT_SET)
{
}

GetBucketRequestPaymentResult::GetBucketRequestPaymentResult(const Aws::AmazonWebServiceResult<XmlDocument>& result) :
    m_payer(Payer::NOT_SET)
{
  *this = result;
}

GetBucketRequestPaymentResult& GetBucketRequestPaymentResult::operator =(const Aws::AmazonWebServiceResult<XmlDocument>& result)
{
  const XmlDocument& xmlDocument = result.GetPayload();
  XmlNode resultNode = xmlDocument.GetRootElement();

  if(!resultNode.IsNull())
  {
    XmlNode payerNode = resultNode.FirstChild("Payer");
    if(!payerNode.IsNull())
    {
      m_payer = PayerMapper::GetPayerForName(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(payerNode.GetText()).c_str()).c_str());
    }
  }

  return *this;
}


text:
module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine', 'fixture'],
    files: [
      "node_modules/systemjs/dist/system.js",
      "node_modules/angular/angular.js",
      "node_modules/angular-mocks/angular-mocks.js",
      "node_modules/angular-ui-router/release/angular-ui-router.js",
      "bundle.js",
      "bootstrap.js",
      "tests/*"
    ],
    exclude: [
    ],
    preprocessors: {
      'tests/*.ts': ['typescript'],
      'tests/*.json': ['json_fixtures']
    },
    jsonFixturesPreprocessor: {
      variableName: '__json__'
    },
    typescriptPreprocessor: {
      options: {
        sourceMap: false,
        target: 'ES5',
        noImplicitAny: true,
        noResolve: true,
        removeComments: true
      },
      transformPath: function (path) {
        return path.replace(/\.ts$/, '.js');
      }
    },
    reporters: ['progress'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: false,
    concurrency: Infinity
  })
}