text:
package net.java.sip.communicator.plugin.reconnectplugin;

import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.service.protocol.event.*;
import net.java.sip.communicator.util.*;

import java.util.*;

import static net.java.sip.communicator.plugin.reconnectplugin.ReconnectPluginActivator.*;

/**
 * Wraps a provider to listen for registration state changes and act
 * appropriately to make sure we try reconnect it.
 * Keeps a local state to make sure we do not try to process same event twice
 * and schedule undesired reconnects.
 */
public class PPReconnectWrapper
    implements RegistrationStateChangeListener
{
    /**
     * Logger of this class
     */
    private static final Logger logger
        = Logger.getLogger(PPReconnectWrapper.class);

    /**
     * The provider instance.
     */
    private final ProtocolProviderService provider;

    /**
     * The local state of the wrapper, we sync this and update it to avoid
     * double processing of multiple events in multithreaded environment.
     */
    private RegistrationState localState = null;

    /**
     * The local state mutex.
     */
    private final Object localStateMutex = new Object();

    /**
     * Timer for scheduling the reconnect operation.
     */
    private Timer timer = null;

    /**
     * Whether we had scheduled unregister for this provider.
     */
    private boolean currentlyUnregistering = false;

    /**
     * Non null value indicates that on next UNREGISTERED or CONNECTION_FAILED
     * event we need to schedule a reconnect with delay using the value.
     */
    private Long reconnectOnNextUnregisteredDelay = null;

    /**
     * The current reconnect task.
     */
    private ReconnectTask currentReconnect = null;

    /**
     * Protects currentReconnect field.
     */
    private final Object reconnectTaskMutex = new Object();

    /**
     * Creates new wrapper.
     *
     * @param provider the provider that will be handled by this wrapper.
     */
    public PPReconnectWrapper(ProtocolProviderService provider)
    {
        this.provider = provider;
        this.timer = new Timer("Reconnect timer p:"
            + provider.getAccountID().getAccountUniqueID(), true);

        provider.addRegistrationStateChangeListener(this);
    }

    /**
     * Returns the provider instance.
     * @return the provider instance.
     */
    public ProtocolProviderService getProvider()
    {
        return provider;
    }

    /**
     * Clears any listener or resource used.
     */
    public void clear()
    {
        if(timer != null)
        {
            timer.cancel();
            timer = null;
        }

        this.provider.removeRegistrationStateChangeListener(this);

        // if currently reconnecting cancel
        cancelReconnect();
    }

    /**
     * The method is called by a ProtocolProviderService
     * implementation whenever a change in the registration state of the
     * corresponding provider had occurred.
     *
     * @param evt the event describing the status change.
     */
    @Override
    public void registrationStateChanged(RegistrationStateChangeEvent evt)
    {
        RegistrationState state = evt.getNewState();
        // we don't care about protocol providers that don't support
        // reconnection and we are interested only in few state changes
        if (!(evt.getSource() instanceof ProtocolProviderService)
            || !(state.equals(RegistrationState.REGISTERED)
            || state.equals(RegistrationState.UNREGISTERED)
            || state.equals(RegistrationState.CONNECTION_FAILED)))
            return;

        ProtocolProviderService pp = (ProtocolProviderService) evt.getSource();

        synchronized(localStateMutex)
        {
            // state is already handled, nothing to do
            if (state.equals(localState))
            {
                return;
            }

            this.localState = state;

            // if we are in a process of scheduling a reconnect with unregister
            // before that process
            if (this.reconnectOnNextUnregisteredDelay != null)
            {
                long delay = this.reconnectOnNextUnregisteredDelay;
                this.reconnectOnNextUnregisteredDelay = null;

                if ((state.equals(RegistrationState.UNREGISTERED)
                        || state.equals(RegistrationState.CONNECTION_FAILED))
                    && !evt.isUserRequest()
                    && this.currentlyUnregistering)
                {
                    // this is us who triggered the unregister
                    this.currentlyUnregistering = false;

                    createReconnect(delay);
                    return;
                }
            }

            boolean isServerReturnedErroneousInputEvent =
                state.equals(RegistrationState.CONNECTION_FAILED)
                    && evt.getReasonCode() == RegistrationStateChangeEvent
                        .REASON_SERVER_RETURNED_ERRONEOUS_INPUT;

            try
            {
                if (state.equals(RegistrationState.REGISTERED))
                {
                    addReconnectEnabledProvider(this);

                    // if currently reconnecting cancel
                    cancelReconnect();

                    if (logger.isTraceEnabled())
                    {
                        logger.trace("Got Registered for " + pp);
                        traceCurrentPPState();
                    }
                }
                else if (state.equals(RegistrationState.CONNECTION_FAILED)
                        && !isServerReturnedErroneousInputEvent)
                {
                    if (!hasAtLeastOneSuccessfulConnection(pp))
                    {
                        // ignore providers which haven't registered successfully
                        // till now, they maybe miss-configured
                        notifyConnectionFailed(evt);

                        return;
                    }

                    // if currentlyUnregistering it means
                    // we got conn failed cause the pp has tried to unregister
                    // with sending network packet
                    // but this unregister is scheduled from us so skip
                    if (this.currentlyUnregistering)
                    {
                        this.currentlyUnregistering = false;
                        return;
                    }

                    if (anyConnectedInterfaces())
                    {
                        // network is up but something happen and cannot reconnect
                        // strange lets try again after some time
                        reconnect(currentReconnect != null ?
                            currentReconnect.delay : -1);
                    }

                    if(logger.isTraceEnabled())
                    {
                        logger.trace("Got Connection Failed for " + pp,
                            new Exception("tracing exception"));
                        traceCurrentPPState();
                    }
                }
                else if (state.equals(RegistrationState.UNREGISTERED)
                    || isServerReturnedErroneousInputEvent)
                {
                    this.currentlyUnregistering = false;

                    // Removes from list of auto-reconnect only if the unregister
                    // event is by user request
                    if (evt.isUserRequest() || isServerReturnedErroneousInputEvent)
                    {
                        this.clear();

                        removeReconnectEnabledProviders(this);
                    }

                    // if currently reconnecting cancel
                    cancelReconnect();

                    if(logger.isTraceEnabled())
                    {
                        logger.trace("Got Unregistered for " + pp);
                        traceCurrentPPState();
                    }
                }
            }
            catch(Throwable ex)
            {
                logger.error("Error dispatching protocol registration change", ex);
            }
        }
    }

    /**
     * Cancels currently scheduled reconnect task.
     */
    private void cancelReconnect()
    {
        synchronized(reconnectTaskMutex)
        {
            if (this.currentReconnect != null)
            {
                if(logger.isInfoEnabled())
                    logger.info("Cancel reconnect " + this.currentReconnect);

                this.currentReconnect.cancel();
                this.currentReconnect = null;
            }
        }
    }

    /**
     * Creates and schedules new reconnect task if such is not already created.
     * @param delay the delay to use.
     */
    private void createReconnect(long delay)
    {
        synchronized(reconnectTaskMutex)
        {
            if (this.currentReconnect == null)
            {
                this.currentReconnect
                    = scheduleReconnectIfNeeded(delay, this.provider);
            }
            else
            {
                logger.warn("Reconnect with delay:"
                    + this.currentReconnect.delay + " already scheduled for "
                    + this.provider + " attempted schedule with delay:"
                    + delay);
            }
        }
    }

    /**
     * Schedules a reconnect.
     */
    void reconnect()
    {
        // if currently reconnecting cancel and try again
        cancelReconnect();

        this.reconnect(-1);
    }

    /**
     * Schedules a reconnect.
     * @param previousDelay the delay used in the previous reconnect or -1;
     */
    private void reconnect(long previousDelay)
    {
        long delay;

        if (previousDelay != -1)
        {
            delay = Math.min(previousDelay * 2, MAX_RECONNECT_DELAY*1000);
        }
        else
        {
            delay = (long)(RECONNECT_DELAY_MIN
                + Math.random() * RECONNECT_DELAY_MAX)*1000;
        }

        if (this.provider.getRegistrationState().equals(
                RegistrationState.UNREGISTERING)
            || this.provider.getRegistrationState().equals(
                RegistrationState.UNREGISTERED)
            || this.provider.getRegistrationState().equals(
                RegistrationState.CONNECTION_FAILED))
        {
            createReconnect(delay);
        }
        else
        {
            synchronized(localStateMutex)
            {
                // start registering after the pp has unregistered
                this.reconnectOnNextUnregisteredDelay = delay;

                // as we will reconnect, lets unregister
                unregister();
            }
        }
    }

    /**
     * Unregisters the ProtocolProvider.
     */
    void unregister()
    {
        this.currentlyUnregistering = true;

        // if currently reconnecting cancel
        cancelReconnect();

        try
        {
            this.provider.unregister();
        }
        catch(Throwable t)
        {
            logger.error("Error unregistering pp:" + this.provider, t);
        }
    }

    /**
     * Prints current wrapper state.
     * @return string representing current wrapper state.
     */
    @Override
    public String toString()
    {
        StringBuilder builder = new StringBuilder();
        builder.append(getClass().getSimpleName())
            .append("[provider=").append(provider)
            .append(", currentlyUnregistering=").append(currentlyUnregistering)
            .append(", currentReconnect=").append(currentReconnect)
            .append(", reconnectOnNextUnregisteredDelay=")
                .append(reconnectOnNextUnregisteredDelay)
            .append("]");

        return builder.toString();
    }

    /**
     * Schedules a reconnect if needed (if there is timer and connected
     * interfaces and user request is not null).
     * @param delay The delay to use when creating the reconnect task.
     * @param pp the protocol provider that will be reconnected.
     */
    private ReconnectTask scheduleReconnectIfNeeded(
        long delay, ProtocolProviderService pp)
    {
        final ReconnectTask task = new ReconnectTask();
        task.delay = delay;

        if (timer == null)
        {
            return null;
        }

        if (!anyConnectedInterfaces())
        {
            // There is no network, nothing to do, when
            // network is back it will be scheduled to reconnect.
            // This means we started unregistering while
            // network was going down and meanwhile there
            // were no connected interface, this happens
            // when we have more than one connected
            // interface and we got 2 events for down iface

            return null;
        }

        if(logger.isInfoEnabled())
            logger.info("Reconnect " + pp + " after " + task.delay + " ms.");

        timer.schedule(task, task.delay);

        return task;
    }

    /**
     * The task executed by the timer when time for reconnect comes.
     */
    private class ReconnectTask
        extends TimerTask
    {
        /**
         * The delay with which was this task scheduled.
         */
        long delay;

        /**
         * Reconnects the provider.
         */
        @Override
        public void run()
        {
            try
            {
                if (logger.isInfoEnabled())
                    logger.info("Start reconnecting " + provider);

                provider.register(
                    getUIService().getDefaultSecurityAuthority(provider));
            } catch (OperationFailedException ex)
            {
                logger.error("cannot re-register provider will keep going",
                    ex);
            }
        }

        @Override
        public String toString()
        {
            return ReconnectTask.class.getSimpleName()
                + " [delay=" + delay + ", provider=" + provider + "]";
        }
    }
}


text:
Pseudo - Anonymized Email Relay
===
#### What is it?
Pseudo is an smtp relay server designed to anonymize standard email communication. It ensures confidentiality by stripping out all identifying information from the emails you send, while ensuring that no data from relayed emails is stored on the server.

#### Why?
PGP encryption helps mitigate the risk of a standard man-in-the-middle attack when sending emails; however, once your messages are decrypted on a recipient's machine, there is little protecting your identity if they are compromised. Pseudo allows you to send emails with the safety of know that they cannot easily be traced back to you. It is highly recommended that you use PGP encryption in combination with pseudo for optimal confidentiality.

#### How?
Pseudo exploits the malleability of smtp headers to allow both parties to use email exactly as they normally would with the added benefit of pseudo-anonyminity.

For example:

Alice wants to send an email to Bob and have him reply.
Let's say we are hosting our smtp anonymizer at the IP address 55.5.5.55, and our relay email address is relay@55.5.5.55

Instead of sending the following message:

```
{
	from: alice@mit.edu,
	to: bob@mit.edu,
	subject: New leaked government documents,
	body: Check out the attached files
}
```
```
Alice will now send:

{
	from: alice@mit.edu,
        to: relay@55.5.5.55,
        subject: New leaked government documents||to:bob@mit.edu;,
        body: Check out the attached files
}
```

The relay server will generate a pseudonym for both Alice and Bob to be used in their conversation. These will be sent instead of their emails, and will stay persistent throughout an email conversation so that Alice and Bob will know that they are still talking to the same person. All other identifying information, such as originating IP addresses is simply stripped before relaying.

Now, bob will receive the following message:

```
{
        from: Limber Gecko,
        subject: New leaked government documents,
        body: Check out the attached files,
        replyTo: Limber Gecko <relay@55.5.5.55>
}
```

Where replyTo is the address that is populated in the 'To' field when you click reply to the email. Bob can simply treat this like a normal email- by clicking reply, the server will perform a lookup of the pseudonym 'Limber Gecko' and route it to `alice@mit.edu`. This routing table is encrypted using AES on the server with the key consisting partially of each recipient's pseudonym, meaning that if an adversary gained temporary access to the server, he/she could not decrypt the mappings without knowing the pseudonyms of both Alice and Bob in this conversation.

Furthermore, Alice or Bob can destroy the encrypted mapping of their email/pseudonym on the server at any time by simply replying with `||destroy:true;` appended to the subject line. This is an irreversible action, and allows any past pseudonyms you have used to become untraceable from the server.

===
Getting Started:
===

1. Pseudo is built to run using Postfix as an smtp server. Begin by installing and configuring postfix if you haven't already.

2. After cloning this repo, run `sudo ./config` in the root of this directory to configure proper logging and cleanup settings for Pseudo and Postfix.

3. If everything has been installed correctly, run `sudo node mailhandler.js` to start the relay server.

*Note that Pseudo is currently only tested on Ubuntu 14.04, although it should would fine on other common linux distros.

##### Sending emails
Pseudo accepts parameters from the subject line of an email. Use a double pipe `||` to signal the beginning of parameters. For example, to send a message to `bob@mit.edu` you would append `||to:bob@mit.edu;` to the end of the subject line. The server will strip this out prior to relaying the message. This is also only necessary for the first message of a conversation. After this, it is okay to treat messages as ordinary emails and reply like normal.

===
Security
===

Pseudo is designed to protect your identity from two different types of adverseries: general blackhat hackers, and the government. The system is designed in such a way that gaining access to any one node of the network (whether client or server) gives no information about any other users of the network. Gaining access to any one client machine will obviously only provide anonymous pseudonyms of people who have been contacted. Meanwhile, gaining access to just the server will only provide a blob of encrypted, meaningless data. It is for the most part safe to assume that a hacker won't gain access to both a client system and a server; it is however, highly likely that the government can issue subpoenas for both. This is where the "destroy" function comes in: If the operator of the server maintains a [warrant canary](http://en.wikipedia.org/wiki/Warrant_canary) system, clients can issue destroy commands to protect their information stored on the server.

It is also important to note that no email or logging information is maintained by pseudo. All sensitive data that passes through the relay server is meticulously scrubbed using the linux `shred` script. The only information retained by the server are the AES-256 encrypted email-pseudonym mappings.

### Limitations

Pseudo does of course have limitations. The major concerns are as follows:

- There is little that can be done to protect identities in the case of a persistent man-in-the-middle
- Without entirely bit-filling the machine, there is no guarantee that data is entirely wiped from the relay server
- Spam. You should only allow authorized emails/IPs to communicate through an instance of pseudo, otherwise it will quickly turn into an anonymized spam proxy server. The cleanest solution to this is probably just to password-protect the server and include the password in the subject parameters in the beginning of an email conversation.
- Due to the ephemerality of pseudonyms, the only way to securely prove your identity to the person you are communicating with is through contexual referencing. Example of this would be to mention a conversation you had with the person the other day, or to mention the outfit you had on. These are identifying features that might give your identity away to another friend, but would not give any information to a hacker or government official.

===
License:
===
MIT

redpajama_set_name: RedPajamaGithub


text:
#include "control_connection.hpp"

#include "collection_iterator.hpp"
#include "constants.hpp"
#include "event_response.hpp"
#include "load_balancing.hpp"
#include "logger.hpp"
#include "query_request.hpp"
#include "result_iterator.hpp"
#include "error_response.hpp"
#include "result_response.hpp"
#include "schema_metadata.hpp"
#include "session.hpp"
#include "timer.hpp"

#include <iomanip>
#include <sstream>
#include <vector>

#define SELECT_LOCAL "SELECT data_center, rack FROM system.local WHERE key='local'"
#define SELECT_LOCAL_TOKENS "SELECT data_center, rack, partitioner, tokens FROM system.local WHERE key='local'"
#define SELECT_PEERS "SELECT peer, data_center, rack, rpc_address FROM system.peers"
#define SELECT_PEERS_TOKENS "SELECT peer, data_center, rack, rpc_address, tokens FROM system.peers"

#define SELECT_KEYSPACES "SELECT * FROM system.schema_keyspaces"
#define SELECT_COLUMN_FAMILIES "SELECT * FROM system.schema_columnfamilies"
#define SELECT_COLUMNS "SELECT * FROM system.schema_columns"
#define SELECT_USERTYPES "SELECT * FROM system.schema_usertypes"

namespace cass {

class ControlStartupQueryPlan : public QueryPlan {
public:
  ControlStartupQueryPlan(const HostMap& hosts)
    : hosts_(hosts)
    , it_(hosts_.begin()) {}

  virtual SharedRefPtr<Host> compute_next() {
    if (it_ == hosts_.end()) return SharedRefPtr<Host>();
    const SharedRefPtr<Host>& host = it_->second;
    ++it_;
    return host;
  }

private:
  const HostMap hosts_;
  HostMap::const_iterator it_;
};

bool ControlConnection::determine_address_for_peer_host(const Address& connected_address,
                                                        const Value* peer_value,
                                                        const Value* rpc_value,
                                                        Address* output) {
  Address peer_address;
  Address::from_inet(peer_value->data(), peer_value->size(),
                     connected_address.port(), &peer_address);
  if (rpc_value->size() > 0) {
    Address::from_inet(rpc_value->data(), rpc_value->size(),
                       connected_address.port(), output);
    if (connected_address.compare(*output) == 0 ||
        connected_address.compare(peer_address) == 0) {
      LOG_DEBUG("system.peers on %s contains a line with rpc_address for itself. "
                "This is not normal, but is a known problem for some versions of DSE. "
                "Ignoring this entry.", connected_address.to_string(false).c_str());
      return false;
    }
    if (bind_any_ipv4_.compare(*output) == 0 ||
        bind_any_ipv6_.compare(*output) == 0) {
      LOG_WARN("Found host with 'bind any' for rpc_address; using listen_address (%s) to contact instead. "
               "If this is incorrect you should configure a specific interface for rpc_address on the server.",
               peer_address.to_string(false).c_str());
      *output = peer_address;
    }
  } else {
    LOG_WARN("No rpc_address for host %s in system.peers on %s. "
             "Ignoring this entry.", peer_address.to_string(false).c_str(),
             connected_address.to_string(false).c_str());
    return false;
  }
  return true;
}

ControlConnection::ControlConnection()
  : state_(CONTROL_STATE_NEW)
  , session_(NULL)
  , connection_(NULL)
  , protocol_version_(0)
  , query_tokens_(false) {}

const SharedRefPtr<Host> ControlConnection::connected_host() const {
  return session_->get_host(current_host_address_);
}

void ControlConnection::clear() {
  state_ = CONTROL_STATE_NEW;
  session_ = NULL;
  connection_ = NULL;
  reconnect_timer_.stop();
  query_plan_.reset();
  protocol_version_ = 0;
  last_connection_error_.clear();
  query_tokens_ = false;
}

void ControlConnection::connect(Session* session) {
  session_ = session;
  query_plan_.reset(new ControlStartupQueryPlan(session_->hosts_)); // No hosts lock necessary (read-only)
  protocol_version_ = session_->config().protocol_version();
  query_tokens_ = session_->config().token_aware_routing();
  if (protocol_version_ < 0) {
    protocol_version_ = CASS_HIGHEST_SUPPORTED_PROTOCOL_VERSION;
  }

  if (session_->config().use_schema()) {
    set_event_types(CASS_EVENT_TOPOLOGY_CHANGE | CASS_EVENT_STATUS_CHANGE |
                    CASS_EVENT_SCHEMA_CHANGE);
  } else {
    set_event_types(CASS_EVENT_TOPOLOGY_CHANGE | CASS_EVENT_STATUS_CHANGE);
  }

  reconnect(false);
}

void ControlConnection::close() {
  state_ = CONTROL_STATE_CLOSED;
  if (connection_ != NULL) {
    connection_->close();
  }
  reconnect_timer_.stop();
}

void ControlConnection::schedule_reconnect(uint64_t ms) {
  reconnect_timer_.start(session_->loop(),
                         ms,
                         this,
                         ControlConnection::on_reconnect);
}

void ControlConnection::reconnect(bool retry_current_host) {
  if (state_ == CONTROL_STATE_CLOSED) {
    return;
  }

  if (!retry_current_host) {
    if (!query_plan_->compute_next(&current_host_address_)) {
      if (state_ == CONTROL_STATE_READY) {
        schedule_reconnect(1000); // TODO(mpenick): Configurable?
      } else {
        session_->on_control_connection_error(CASS_ERROR_LIB_NO_HOSTS_AVAILABLE,
                                              "No hosts available for the control connection");
      }
      return;
    }
  }

  if (connection_ != NULL) {
    connection_->close();
  }

  connection_ = new Connection(session_->loop(),
                               session_->config(),
                               session_->metrics(),
                               current_host_address_,
                               "", // No keyspace
                               protocol_version_,
                               this);
  connection_->connect();
}

void ControlConnection::on_ready(Connection* connection) {
  LOG_DEBUG("Connection ready on host %s",
            connection->address().to_string().c_str());

  // A protocol version is need to encode/decode maps properly
  session_->cluster_meta().set_protocol_version(protocol_version_);

  // The control connection has to refresh meta when there's a reconnect because
  // events could have been missed while not connected.
  query_meta_all();
}

void ControlConnection::on_close(Connection* connection) {
  bool retry_current_host = false;

  if (state_ != CONTROL_STATE_CLOSED) {
    LOG_WARN("Lost control connection on host %s", connection->address_string().c_str());
  }

  // This pointer to the connection is no longer valid once it's closed
  connection_ = NULL;

  if (state_ == CONTROL_STATE_NEW) {
    if (connection->is_invalid_protocol()) {
      if (protocol_version_ <= 1) {
        LOG_ERROR("Host %s does not support any valid protocol version",
                  connection->address_string().c_str());
        session_->on_control_connection_error(CASS_ERROR_LIB_UNABLE_TO_DETERMINE_PROTOCOL,
                                             "Not even protocol version 1 is supported");
        return;
      }
      LOG_WARN("Host %s does not support protocol version %d. "
               "Trying protocol version %d...",
               connection->address_string().c_str(),
               protocol_version_,
               protocol_version_ - 1);
      protocol_version_--;
      retry_current_host = true;
    } else if (connection->is_auth_error()) {
      session_->on_control_connection_error(CASS_ERROR_SERVER_BAD_CREDENTIALS,
                                            connection->error_message());
      return;
    } else if (connection->is_ssl_error()) {
      session_->on_control_connection_error(connection->ssl_error_code(),
                                            connection->error_message());
      return;
    }
  }

  reconnect(retry_current_host);
}

void ControlConnection::on_event(EventResponse* response) {
  switch (response->event_type()) {
    case CASS_EVENT_TOPOLOGY_CHANGE: {
      std::string address_str = response->affected_node().to_string();
      switch (response->topology_change()) {
        case EventResponse::NEW_NODE: {
          LOG_INFO("New node %s added", address_str.c_str());
          SharedRefPtr<Host> host = session_->get_host(response->affected_node());
          if (!host) {
            host = session_->add_host(response->affected_node());
            refresh_node_info(host, true, true);
          }
          break;
        }

        case EventResponse::REMOVED_NODE: {
          LOG_INFO("Node %s removed", address_str.c_str());
          SharedRefPtr<Host> host = session_->get_host(response->affected_node());
          if (host) {
            session_->on_remove(host);
            session_->cluster_meta().remove_host(host);
          } else {
            LOG_DEBUG("Tried to remove host %s that doesn't exist", address_str.c_str());
          }
          break;
        }

        case EventResponse::MOVED_NODE:
          LOG_INFO("Node %s moved", address_str.c_str());
          SharedRefPtr<Host> host = session_->get_host(response->affected_node());
          if (host) {
            refresh_node_info(host, false, true);
          } else {
            LOG_DEBUG("Move event for host %s that doesn't exist", address_str.c_str());
            session_->cluster_meta().remove_host(host);
          }
          break;
      }
      break;
    }

    case CASS_EVENT_STATUS_CHANGE: {
      std::string address_str = response->affected_node().to_string();
      switch (response->status_change()) {
        case EventResponse::UP: {
          LOG_INFO("Node %s is up", address_str.c_str());
          on_up(response->affected_node());
          break;
        }

        case EventResponse::DOWN: {
          LOG_INFO("Node %s is down", address_str.c_str());
          on_down(response->affected_node());
          break;
        }
      }
      break;
    }

    case CASS_EVENT_SCHEMA_CHANGE:
      LOG_DEBUG("Schema change (%d): %.*s %.*s\n",
                response->schema_change(),
                (int)response->keyspace().size(), response->keyspace().data(),
                (int)response->target().size(), response->target().data());
      switch (response->schema_change()) {
        case EventResponse::CREATED:
        case EventResponse::UPDATED:
          switch (response->schema_change_target()) {
            case EventResponse::KEYSPACE:
              refresh_keyspace(response->keyspace());
              break;
            case EventResponse::TABLE:
              refresh_table(response->keyspace(), response->target());
              break;
            case EventResponse::TYPE:
              refresh_type(response->keyspace(), response->target());
              break;
          }
          break;

        case EventResponse::DROPPED:
          switch (response->schema_change_target()) {
            case EventResponse::KEYSPACE:
              session_->cluster_meta().drop_keyspace(response->keyspace().to_string());
              break;
            case EventResponse::TABLE:
              session_->cluster_meta().drop_table(response->keyspace().to_string(),
                                                  response->target().to_string());
              break;
            case EventResponse::TYPE:
              session_->cluster_meta().drop_type(response->keyspace().to_string(),
                                                 response->target().to_string());
              break;
          }
          break;

      }
      break;

    default:
      assert(false);
      break;
  }
}

//TODO: query and callbacks should be in ClusterMetadata
// punting for now because of tight coupling of Session and CC state
void ControlConnection::query_meta_all() {
  ScopedRefPtr<ControlMultipleRequestHandler<QueryMetadataAllData> > handler(
        new ControlMultipleRequestHandler<QueryMetadataAllData>(this, ControlConnection::on_query_meta_all, QueryMetadataAllData()));
  handler->execute_query(SELECT_LOCAL_TOKENS);
  handler->execute_query(SELECT_PEERS_TOKENS);

  if (session_->config().use_schema()) {
    handler->execute_query(SELECT_KEYSPACES);
    handler->execute_query(SELECT_COLUMN_FAMILIES);
    handler->execute_query(SELECT_COLUMNS);
    if (protocol_version_ >= 3) {
      handler->execute_query(SELECT_USERTYPES);
    }
  }
}

void ControlConnection::on_query_meta_all(ControlConnection* control_connection,
                                          const QueryMetadataAllData& unused,
                                          const MultipleRequestHandler::ResponseVec& responses) {
  Connection* connection = control_connection->connection_;
  if (connection == NULL) {
    return;
  }

  Session* session = control_connection->session_;

  session->cluster_meta().clear();

  bool is_initial_connection = (control_connection->state_ == CONTROL_STATE_NEW);

  // If the 'system.local' table is empty the connection isn't used as a control
  // connection because at least one node's information is required (itself). An
  // empty 'system.local' can happen during the bootstrapping process on some
  // versions of Cassandra. If this happens we defunct the connection and move
  // to the next node in the query plan.
  {
    SharedRefPtr<Host> host = session->get_host(connection->address());
    if (host) {
      host->set_mark(session->current_host_mark_);

      ResultResponse* local_result =
          static_cast<ResultResponse*>(responses[0].get());

      if (local_result->row_count() > 0) {
        local_result->decode_first_row();
        control_connection->update_node_info(host, &local_result->first_row());
      } else {
        LOG_WARN("No row found in %s's local system table",
                 connection->address_string().c_str());
        connection->defunct();
        return;
      }
    } else {
      LOG_WARN("Host %s from local system table not found",
               connection->address_string().c_str());
      connection->defunct();
      return;
    }
  }

  {
    ResultResponse* peers_result =
        static_cast<ResultResponse*>(responses[1].get());
    peers_result->decode_first_row();
    ResultIterator rows(peers_result);
    while (rows.next()) {
      Address address;
      const Row* row = rows.row();
      if (!determine_address_for_peer_host(connection->address(),
                                           row->get_by_name("peer"),
                                           row->get_by_name("rpc_address"),
                                           &address)) {
        continue;
      }

      SharedRefPtr<Host> host = session->get_host(address);
      bool is_new = false;
      if (!host) {
        is_new = true;
        host = session->add_host(address);
      }

      host->set_mark(session->current_host_mark_);

      control_connection->update_node_info(host, rows.row());
      if (is_new && !is_initial_connection) {
        session->on_add(host, false);
      }
    }
  }

  session->purge_hosts(is_initial_connection);

  if (session->config().use_schema()) {
    session->cluster_meta().update_keyspaces(static_cast<ResultResponse*>(responses[2].get()));
    session->cluster_meta().update_tables(static_cast<ResultResponse*>(responses[3].get()),
        static_cast<ResultResponse*>(responses[4].get()));
    if (control_connection->protocol_version_ >= 3) {
      session->cluster_meta().update_usertypes(static_cast<ResultResponse*>(responses[5].get()));
    }
    session->cluster_meta().build();
  }

  if (is_initial_connection) {
    control_connection->state_ = CONTROL_STATE_READY;
    session->on_control_connection_ready();
    // Create a new query plan that considers all the new hosts from the
    // "system" tables.
    control_connection->query_plan_.reset(session->new_query_plan());
  }
}

void ControlConnection::refresh_node_info(SharedRefPtr<Host> host,
                                          bool is_new_node,
                                          bool query_tokens) {
  if (connection_ == NULL) {
    return;
  }

  bool is_connected_host = host->address().compare(connection_->address()) == 0;

  std::string query;
  ControlHandler<RefreshNodeData>::ResponseCallback response_callback;

  bool token_query = query_tokens_ && (host->was_just_added() || query_tokens);
  if (is_connected_host || !host->listen_address().empty()) {
    if (is_connected_host) {
      query.assign(token_query ? SELECT_LOCAL_TOKENS : SELECT_LOCAL);
    } else {
      query.assign(token_query ? SELECT_PEERS_TOKENS : SELECT_PEERS);
      query.append(" WHERE peer = '");
      query.append(host->listen_address());
      query.append("'");
    }
    response_callback = ControlConnection::on_refresh_node_info;
  } else {
    query.assign(token_query ? SELECT_PEERS_TOKENS : SELECT_PEERS);
    response_callback = ControlConnection::on_refresh_node_info_all;
  }

  LOG_DEBUG("refresh_node_info: %s", query.c_str());

  RefreshNodeData data(host, is_new_node);
  ScopedRefPtr<ControlHandler<RefreshNodeData> > handler(
        new ControlHandler<RefreshNodeData>(new QueryRequest(query),
                                            this,
                                            response_callback,
                                            data));
  if (!connection_->write(handler.get())) {
    LOG_ERROR("No more stream available while attempting to refresh node info");
  }
}

void ControlConnection::on_refresh_node_info(ControlConnection* control_connection,
                                             const RefreshNodeData& data,
                                             Response* response) {
  Connection* connection = control_connection->connection_;
  if (connection == NULL) {
    return;
  }

  ResultResponse* result =
      static_cast<ResultResponse*>(response);

  if (result->row_count() == 0) {
    std::string host_address_str = data.host->address().to_string();
    LOG_ERROR("No row found for host %s in %s's local/peers system table. "
              "%s will be ignored.",
              host_address_str.c_str(),
              connection->address_string().c_str(),
              host_address_str.c_str());
    return;
  }
  result->decode_first_row();
  control_connection->update_node_info(data.host, &result->first_row());

  if (data.is_new_node) {
    control_connection->session_->on_add(data.host, false);
  }
}

void ControlConnection::on_refresh_node_info_all(ControlConnection* control_connection,
                                                 const RefreshNodeData& data,
                                                 Response* response) {
  Connection* connection = control_connection->connection_;
  if (connection == NULL) {
    return;
  }

  ResultResponse* result =
      static_cast<ResultResponse*>(response);

  if (result->row_count() == 0) {
    std::string host_address_str = data.host->address().to_string();
    LOG_ERROR("No row found for host %s in %s's peers system table. "
              "%s will be ignored.",
              host_address_str.c_str(),
              connection->address_string().c_str(),
              host_address_str.c_str());
    return;
  }

  result->decode_first_row();
  ResultIterator rows(result);
  while (rows.next()) {
    const Row* row = rows.row();
    Address address;
    bool is_valid_address
        = determine_address_for_peer_host(connection->address(),
                                          row->get_by_name("peer"),
                                          row->get_by_name("rpc_address"),
                                          &address);
    if (is_valid_address && data.host->address().compare(address) == 0) {
      control_connection->update_node_info(data.host, row);
      if (data.is_new_node) {
        control_connection->session_->on_add(data.host, false);
      }
      break;
    }
  }
}

void ControlConnection::update_node_info(SharedRefPtr<Host> host, const Row* row) {
  const Value* v;

  std::string rack;
  row->get_string_by_name("rack", &rack);

  std::string dc;
  row->get_string_by_name("data_center", &dc);

  // This value is not present in the "system.local" query
  v = row->get_by_name("peer");
  if (v != NULL) {
    Address listen_address;
    Address::from_inet(v->data(), v->size(),
                       connection_->address().port(),
                       &listen_address);
    host->set_listen_address(listen_address.to_string());
  }

  if ((!rack.empty() && rack != host->rack()) ||
      (!dc.empty() && dc != host->dc())) {
    if (!host->was_just_added()) {
      session_->load_balancing_policy_->on_remove(host);
    }
    host->set_rack_and_dc(rack, dc);
    if (!host->was_just_added()) {
      session_->load_balancing_policy_->on_add(host);
    }
  }

  if (query_tokens_) {
    std::string partitioner;
    if (row->get_string_by_name("partitioner", &partitioner)) {
      session_->cluster_meta().set_partitioner(partitioner);
    }
    v = row->get_by_name("tokens");
    if (v != NULL) {
      CollectionIterator i(v);
      TokenStringList tokens;
      while (i.next()) {
        tokens.push_back(i.value()->to_string_ref());
      }
      if (!tokens.empty()) {
        session_->cluster_meta().update_host(host, tokens);
      }
    }
  }
}

void ControlConnection::refresh_keyspace(const StringRef& keyspace_name) {
  std::string query(SELECT_KEYSPACES);
  query.append(" WHERE keyspace_name='")
       .append(keyspace_name.data(), keyspace_name.size())
       .append("'");

  LOG_DEBUG("Refreshing keyspace %s", query.c_str());

  connection_->write(
        new ControlHandler<std::string>(new QueryRequest(query),
                                        this,
                                        ControlConnection::on_refresh_keyspace,
                                        keyspace_name.to_string()));
}

void ControlConnection::on_refresh_keyspace(ControlConnection* control_connection,
                                            const std::string& keyspace_name,
                                            Response* response) {
  ResultResponse* result = static_cast<ResultResponse*>(response);
  if (result->row_count() == 0) {
    LOG_ERROR("No row found for keyspace %s in system schema table.",
              keyspace_name.c_str());
    return;
  }
  control_connection->session_->cluster_meta().update_keyspaces(result);
}

void ControlConnection::refresh_table(const StringRef& keyspace_name,
                                      const StringRef& table_name) {
  std::string cf_query(SELECT_COLUMN_FAMILIES);
  cf_query.append(" WHERE keyspace_name='").append(keyspace_name.data(), keyspace_name.size())
          .append("' AND columnfamily_name='").append(table_name.data(), table_name.size()).append("'");

  std::string col_query(SELECT_COLUMNS);
  col_query.append(" WHERE keyspace_name='").append(keyspace_name.data(), keyspace_name.size())
           .append("' AND columnfamily_name='").append(table_name.data(), table_name.size()).append("'");

  LOG_DEBUG("Refreshing table %s; %s", cf_query.c_str(), col_query.c_str());

  ScopedRefPtr<ControlMultipleRequestHandler<RefreshTableData> > handler(
        new ControlMultipleRequestHandler<RefreshTableData>(this,
                                                            ControlConnection::on_refresh_table,
                                                            RefreshTableData(keyspace_name.to_string(), table_name.to_string())));
  handler->execute_query(cf_query);
  handler->execute_query(col_query);
}

void ControlConnection::on_refresh_table(ControlConnection* control_connection,
                                         const RefreshTableData& data,
                                         const MultipleRequestHandler::ResponseVec& responses) {
  ResultResponse* column_family_result = static_cast<ResultResponse*>(responses[0].get());
  if (column_family_result->row_count() == 0) {
    LOG_ERROR("No row found for column family %s.%s in system schema table.",
              data.keyspace_name.c_str(), data.table_name.c_str());
    return;
  }

  Session* session = control_connection->session_;
  session->cluster_meta().update_tables(column_family_result,
                                        static_cast<ResultResponse*>(responses[1].get()));
}

void ControlConnection::refresh_type(const StringRef& keyspace_name,
                                     const StringRef& type_name) {

  std::string query(SELECT_USERTYPES);
  query.append(" WHERE keyspace_name='").append(keyspace_name.data(), keyspace_name.size())
                .append("' AND type_name='").append(type_name.data(), type_name.size()).append("'");

  LOG_DEBUG("Refreshing type %s", query.c_str());

  connection_->write(
        new ControlHandler<std::pair<std::string, std::string> >(new QueryRequest(query),
                                        this,
                                        ControlConnection::on_refresh_type,
                                        std::make_pair(keyspace_name.to_string(), type_name.to_string())));
}

void ControlConnection::on_refresh_type(ControlConnection* control_connection,
                                        const std::pair<std::string, std::string>& keyspace_and_type_names,
                                        Response* response) {
  ResultResponse* result = static_cast<ResultResponse*>(response);
  if (result->row_count() == 0) {
    LOG_ERROR("No row found for keyspace %s and type %s in system schema table.",
              keyspace_and_type_names.first.c_str(),
              keyspace_and_type_names.first.c_str());
    return;
  }
  control_connection->session_->cluster_meta().update_usertypes(result);
}

bool ControlConnection::handle_query_invalid_response(Response* response) {
  if (check_error_or_invalid_response("ControlConnection", CQL_OPCODE_RESULT,
                                      response)) {
    if (connection_ != NULL) {
      connection_->defunct();
    }
    return true;
  }
  return false;
}

void ControlConnection::handle_query_failure(CassError code, const std::string& message) {
  // TODO(mpenick): This is a placeholder and might not be the right action for
  // all error scenarios
  if (connection_ != NULL) {
    connection_->defunct();
  }
}

void ControlConnection::handle_query_timeout() {
  // TODO(mpenick): Is this the best way to handle a timeout?
  if (connection_ != NULL) {
    connection_->defunct();
  }
}

void ControlConnection::on_up(const Address& address) {
  SharedRefPtr<Host> host = session_->get_host(address);
  if (host) {
    if (host->is_up()) return;

    // Immediately mark the node as up and asynchronously attempt
    // to refresh the node's information. This is done because
    // a control connection may not be available because it's
    // waiting for a node to be marked as up.
    session_->on_up(host);
    refresh_node_info(host, false);
  } else {
    host = session_->add_host(address);
    refresh_node_info(host, true);
  }
}

void ControlConnection::on_down(const Address& address) {
  SharedRefPtr<Host> host = session_->get_host(address);
  if (host) {
    if (host->is_down()) return;

    session_->on_down(host);
  } else {
    LOG_DEBUG("Tried to down host %s that doesn't exist", address.to_string().c_str());
  }
}

void ControlConnection::on_reconnect(Timer* timer) {
  ControlConnection* control_connection = static_cast<ControlConnection*>(timer->data());
  control_connection->query_plan_.reset(control_connection->session_->new_query_plan());
  control_connection->reconnect(false);
}

template<class T>
void ControlConnection::ControlMultipleRequestHandler<T>::on_set(
    const MultipleRequestHandler::ResponseVec& responses) {
  bool has_error = false;
  for (MultipleRequestHandler::ResponseVec::const_iterator it = responses.begin(),
       end = responses.end(); it != end; ++it) {
    if (control_connection_->handle_query_invalid_response(it->get())) {
      has_error = true;
    }
  }
  if (has_error) return;
  response_callback_(control_connection_, data_, responses);
}

Address ControlConnection::bind_any_ipv4_("0.0.0.0", 0);
Address ControlConnection::bind_any_ipv6_("::", 0);

} // namespace cass


text:
require( "ex" )

-- DEBUGGING -----------------------------------------------------------------
--

print( "-- CURRENT DIRECTORY --------------------------------------------------------" )
local oldCurDir = os.currentdir()
print( oldCurDir )
print( "-- CHANGE DIRECTORY (UP ONE DIRECTORY) --------------------------------------" )
os.chdir( ".." )
print( os.currentdir() )
print( "-- CHANGE DIRECTORY (BACK TO ORIGINAL) --------------------------------------" )
os.chdir( oldCurDir )
print( os.currentdir() )

print( "\n-- $PATH ENVIRONMENT VARIABLE -----------------------------------------------" )
print( os.getenv( "PATH" ) )

print( "\n-- ENUMERATE ALL ENVIRONMENT VARIABLES --------------------------------------" )
local e = assert( os.environ() )
table.foreach( e, function( nam, val ) print( string.format( "%s=%s", nam, val) ) end )

print( "\n-- SHOW ALL FILES AND DIRECTORIES IN THE CURRENT DIRECTORY ------------------" )
for e in assert(os.dir(".")) do
	print(string.format("%.4s %9d  %s", e.type or 'Unknown', e.size or -1, e.name))
end

print( "\n-- PING GOOGLE.COM ----------------------------------------------------------" )
local proc = assert( os.spawn( "ping", { "google.com" } ) )
print( proc )
print( "Process exit code:", assert( proc:wait() ) )


text:
package org.ohmage.domain.campaign;

import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.ohmage.domain.campaign.Prompt.LabelValuePair;
import org.ohmage.domain.campaign.prompt.ChoicePrompt;
import org.ohmage.domain.campaign.prompt.CustomChoicePrompt;
import org.ohmage.domain.campaign.prompt.RemoteActivityPrompt;
import org.ohmage.domain.campaign.response.RemoteActivityPromptResponse;
import org.ohmage.exception.DomainException;

/**
 * Base class for all prompt responses.
 *
 * @author John Jenkins
 */
public abstract class PromptResponse extends Response {
	/**
	 * The name of the JSON object field representing the name of the prompt
	 * that was used to create this response value.
	 */
	public static final String JSON_KEY_PROMPT_ID = "prompt_id";
	/**
	 * The name of the JSON object field representing the value for the
	 * response to this prompt.
	 */
	public static final String JSON_KEY_RESPONSE = "value";

	/**
	 * The prompt that was presented to the user to create this response.
	 */
	private final Prompt prompt;

	/**
	 * The iteration of this prompt that generated this prompt.
	 */
	private final Integer repeatableSetIteration;

	/**
	 * Creates a prompt response.
	 *
	 * @param prompt The prompt that was presented to the user in order to
	 * 				 generate this prompt response.
	 *
	 * @param noResponse A NoResponse object which represents the allowed
	 * 					 values if the prompt does not have a response.
	 *
	 * @param repeatableSetIteration If the 'prompt' was part of a repeatable
	 * 								 set, this is the iteration of that
	 * 								 repeatable set on which this response was
	 * 								 made.
	 *
	 * @throws DomainException Thrown if the prompt is null.
	 */
	public PromptResponse(
			final Prompt prompt,
			final Integer repeatableSetIteration,
			final Object response)
			throws DomainException {

		super(prompt.validateValue(response));

		if(
				(repeatableSetIteration == null) &&
				(prompt.getParent() != null)) {

			throw new DomainException(
					"The repeatable set iteration is null, but this prompt is part of a repeatable set.");
		}
		else if(
				(repeatableSetIteration != null) &&
				(prompt.getParent() == null)) {

			throw new DomainException(
					"The repeatable set iteration is not null, but this prompt is not part of a repeatable set.");
		}
		else if(
				(repeatableSetIteration != null) &&
				(repeatableSetIteration < 0)) {

			throw new DomainException(
					"The repeatable set iteration value is negative.");
		}

		this.prompt = prompt;
		this.repeatableSetIteration = repeatableSetIteration;
	}

	/**
	 * Returns the prompt on which this prompt response is based.
	 *
	 * @return The prompt on which this prompt response is based.
	 */
	public Prompt getPrompt() {
		return prompt;
	}

	/**
	 * If the prompt used to generate this prompt response was part of a
	 * repeatable set, then this will return the iteration of that repeatable
	 * set on which this response was generated. If it is not part of a
	 * repeatable set, null will be returned.
	 *
	 * @return The iteration of the repeatable set that is this prompt's parent
	 * 		   on which this response was generated. If the prompt was not part
	 * 		   of a repeatable set, null is returned.
	 */
	public Integer getRepeatableSetIteration() {
		return repeatableSetIteration;
	}

	/**
	 * Creates a JSONObject that represents this object.
	 *
	 * @return A JSONObject that represents this object.
	 *
	 * @throws JSONException There was a problem creating the JSONObject.
	 */
	@Override
	public JSONObject toJson(final boolean withId) throws JSONException {
		JSONObject result = new JSONObject();

		if(withId) {
			result.put(JSON_KEY_PROMPT_ID, prompt.getId());

			result.put(JSON_KEY_RESPONSE, getResponse());
		}
		else {
			result.put("prompt_text", prompt.getText());
			result.put("prompt_type", prompt.getType().toString());
			result.put("prompt_index", prompt.getIndex());
			result.put("prompt_unit", prompt.getUnit());

			if((prompt instanceof ChoicePrompt) &&
					(! (prompt instanceof CustomChoicePrompt))) {

				ChoicePrompt choicePrompt = (ChoicePrompt) prompt;
				Map<Integer, LabelValuePair> choices =
						choicePrompt.getChoices();

				JSONObject choiceGlossary = new JSONObject();
				for(Integer choiceKey : choices.keySet()) {
					choiceGlossary.put(
							choiceKey.toString(),
							choices.get(choiceKey).toJson());
				}

				result.put("prompt_choice_glossary", choiceGlossary);
			}

			if(this instanceof RemoteActivityPromptResponse &&
					(! wasNotDisplayed()) && (! wasSkipped())) {
				JSONArray gameResults = (JSONArray) getResponse();
				double numResults = gameResults.length();

				if(numResults != 0) {
					double total = 0;
					for(int i = 0; i < numResults; i++) {
						total +=
								gameResults.getJSONObject(i).getDouble(
										RemoteActivityPrompt.JSON_KEY_SCORE);
					}

					result.put("prompt_response", total / numResults);
				}
				else {
					result.put("prompt_response", "Activity Not Performed");
				}
			}
			else {
				result.put("prompt_response", getResponse());
			}
		}

		return result;
	}

	/**
	 * Return's the prompt's unique identifier.
	 */
	@Override
	public String getId() {
		return prompt.getId();
	}

	/**
	 * Generates a hash code for this prompt response.
	 *
	 * @return This prompt's hash code.
	 */
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = super.hashCode();
		result = prime * result + ((prompt == null) ? 0 : prompt.hashCode());
		result = prime
				* result
				+ ((repeatableSetIteration == null) ? 0
						: repeatableSetIteration.hashCode());
		return result;
	}

	/**
	 * Determines if this prompt response is equal to another object.
	 *
	 * @param obj The other object.
	 *
	 * @return True if this prompt response is logically equal to the other
	 * 		   object; false, otherwise.
	 */
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (!super.equals(obj))
			return false;
		if (getClass() != obj.getClass())
			return false;
		PromptResponse other = (PromptResponse) obj;
		if (prompt == null) {
			if (other.prompt != null)
				return false;
		} else if (!prompt.equals(other.prompt))
			return false;
		if (repeatableSetIteration == null) {
			if (other.repeatableSetIteration != null)
				return false;
		} else if (!repeatableSetIteration.equals(other.repeatableSetIteration))
			return false;
		return true;
	}
}


text:
package client

import (
	"testing"
)

// This test file just ensures that Fake and structs it is embedded in
// implement Interface.

func TestFakeImplementsInterface(t *testing.T) {
	_ = Interface(&Fake{})
}

type MyFake struct {
	*Fake
}

func TestEmbeddedFakeImplementsInterface(t *testing.T) {
	_ = Interface(MyFake{&Fake{}})
	_ = Interface(&MyFake{&Fake{}})
}


text:
require "perftools"
require "mongoid"
require "quantify_mongoid"
require "./perf/models"

Mongoid.connect_to("quantify_mongoid_perf")

Mongoid.purge!

puts "Starting profiler"

puts "[ Intantiate Person with default quantity defined ]"
PerfTools::CpuProfiler.start("perf/person_new.profile") do
  100.times do |n|
    Person.new
  end
end

puts "[ Assign Product#length = <Quantity> ]"
product = Product.new
quantity = Quantity.new(100,'cm')
PerfTools::CpuProfiler.start("perf/product_quantity_assign.profile") do
  100.times do |n|
    product.length = quantity
  end
end

puts "[ Lookup Product#length_value ]"
product = Product.create!(length: Quantity.new(100,'cm'))
product_id = product.id
PerfTools::CpuProfiler.start("perf/product_read_quantity_value.profile") do
  100.times do |n|
    Product.find(product_id).length_value
  end
end

puts "[ Lookup Product#length_unit ]"
product = Product.create!(length: Quantity.new(100,'cm'))
product_id = product.id
PerfTools::CpuProfiler.start("perf/product_read_quantity_unit.profile") do
  100.times do |n|
    Product.find(product_id).length_unit
  end
end

puts "[ Assign Product#length_value = '10' (no default defined) ]"
product = Product.new
PerfTools::CpuProfiler.start("perf/product_read_quantity_value.profile") do
  100.times do |n|
    product.length_value =  '10'
  end
end

puts "[ Assign Product#length_unit = 'm' (no default defined) ]"
product = Product.new
PerfTools::CpuProfiler.start("perf/product_read_quantity_unit.profile") do
  100.times do |n|
    product.length_unit = 'm'
  end
end

puts "[ Assign Product#length_unit = 'm² kg/s³ A (no default defined) ]"
product = Product.new
PerfTools::CpuProfiler.start("perf/product_read_quantity_unit.profile") do
  10.times do |n|
    product.length_unit = 'm² kg/s³ A'
  end
end

puts "[ Lookup Product#length_unit_string ]"
product = Product.create!(length: Quantity.new(100,'cm'))
product_id = product.id
PerfTools::CpuProfiler.start("perf/product_read_quantity_unit.profile") do
  100.times do |n|
    Product.find(product_id).length_unit_string
  end
end

puts "[ Create Product with Quantity assignment ]"
PerfTools::CpuProfiler.start("perf/product_create_with_quantity_field.profile") do
  100.times do |n|
    Product.create!(length: Quantity.new(100,'cm'))
  end
end

puts "[ Create Product with separate Quantity and unit assignment ]"
PerfTools::CpuProfiler.start("perf/create_with_quantity_value_and_unit.profile") do
  100.times do |n|
    Product.create!(length_value: 100, length_unit: 'cm')
  end
end

puts "[ Quantity#mongoize ]"
quantity = Quantity.new(100,'mV')
PerfTools::CpuProfiler.start("perf/mongoize.profile") do
  100.times do |n|
    Quantity.mongoize(quantity)
  end
end

puts "[ Quantity#demongoize ]"
hash = Quantity.new(100,'mV').mongoize
PerfTools::CpuProfiler.start("perf/demongoize.profile") do
  100.times do |n|
    Quantity.demongoize(hash)
  end
end


text:
//   Copyright 2015 Esri
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at

//       http://www.apache.org/licenses/LICENSE-2.0

//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ArcGIS.Desktop.Mapping;
using ArcGIS.Desktop.Framework.Threading.Tasks;

namespace MapToolWithOverlayControl
{
  /// <summary>
  /// Class providing the behavior for the custom map tool.
  /// </summary>
  internal class ShowCoordinatesTool : MapTool
  {
    public ShowCoordinatesTool()
    {
      //Set the tools OverlayControlID to the DAML id of the embeddable control
      OverlayControlID = "MapToolWithOverlayControl_EmbeddableControl";
    }

    protected override void OnToolMouseDown(MapViewMouseButtonEventArgs e)
    {
      //On mouse down check if the mouse button pressed is the left mouse button. If it is handle the event.
      if (e.ChangedButton == System.Windows.Input.MouseButton.Left)
        e.Handled = true;
    }

    /// <summary>
    /// Called when the OnToolMouseDown event is handled. Allows the opportunity to perform asynchronous operations corresponding to the event.
    /// </summary>
    protected override Task HandleMouseDownAsync(MapViewMouseButtonEventArgs e)
    {
      //Get the instance of the ViewModel
      var vm = OverlayEmbeddableControl as EmbeddedControlViewModel;
      if (vm == null)
        return Task.FromResult(0);

      //Get the map coordinates from the click point and set the property on the ViewModel.
      return QueuedTask.Run(() =>
      {
        var mapPoint = MapView.Active.ClientToMap(e.ClientPoint);
        var sb = new StringBuilder();
        sb.AppendLine(string.Format("X: {0}", mapPoint.X));
        sb.Append(string.Format("Y: {0}", mapPoint.Y));
        if (mapPoint.HasZ)
        {
          sb.AppendLine();
          sb.Append(string.Format("Z: {0}", mapPoint.Z));
        }
        vm.ClickText = sb.ToString();
      });
    }
  }
}


text:
title: Project proposal
category: project
authors: quaid
wiki_category: Project
wiki_title: Category:Project proposal
wiki_revision_count: 2
wiki_last_updated: 2011-11-12
---

# Project proposal

These are proposals for projects to join the oVirt project.

<Category:Project>


text:
var _ = require('underscore');

var t = require('./utils/testing'); // Testing dependency
var u = require('../lib/utils');

var logger = u.logger('xsite-test');

describe('Infinispan xsite cluster client', function() {

  // Since Jasmine 1.3 does not have beforeAll callback, execute
  // any cleanup as first test so that it only gets executed once.
  it('start sites', function(done) {
      logger.debugf("Starting servers for xsite replication tests.");
      t.launchClusterNodeAndWaitView('server-earth', t.earth1Config, t.earth1['port'], t.earth1MCastAddr, 1, t.client)
          .then(function(client) {return t.launchClusterNodeAndWaitView('server-moon', t.moon1Config, t.moon1['port'], t.moon1MCastAddr, 1, client);})
          .then(function () {
            logger.debugf("Both moon and earth servers started");
          }).catch(t.failed(done)).finally(done);
  }, 15000);

  it('can manually switch and fail over sites', function(done) {
    siteClients().then(function(cs) {
      expect(cs[0].getTopologyInfo().getMembers()).toEqual([t.earth1]);
      expect(cs[1].getTopologyInfo().getMembers()).toEqual([t.moon1]);
      return cs[0].getTopologyInfo().switchToCluster('server-moon')
        .then(function() {
          expect(cs[0].getTopologyInfo().getMembers()).toEqual([t.moon1]);
          return cs[0].getTopologyInfo().switchToDefaultCluster();
        })
        .then(function() {
          expect(cs[0].getTopologyInfo().getMembers()).toEqual([t.earth1]);
          return cs[0].put('xsite-key', 'xsite-value');
        })
        .then(assertGet('xsite-key', 'xsite-value', cs[0]))
        .then(assertGet('xsite-key', 'xsite-value', cs[1]))
        .then(t.stopClusterNode(t.earth1['port'], true))
        // Client connected to surviving site should find data
        .then(assertGet('xsite-key', 'xsite-value', cs[1]))
        // Client connected to crashed site should failover
        .then(assertGet('xsite-key', 'xsite-value', cs[0]))
        .then(function() {
          expect(cs[0].getTopologyInfo().getMembers()).toEqual([t.moon1]);
          expect(cs[1].getTopologyInfo().getMembers()).toEqual([t.moon1]);
        })
        // Re-launch site stopped site and stop alive site
        .then(assertGet('xsite-key', 'xsite-value', cs[0]))
        .then(function(client) { return t.launchClusterNodeAndWaitView('server-earth', t.earth1Config, t.earth1['port'], t.earth1MCastAddr, 1, client); })
        .then(t.stopClusterNode(t.moon1['port'], true))
        // Client connected to failed over site should come back to original site
        .then(assertGet('xsite-key', undefined, cs[0]))
        .then(function() {
          expect(cs[0].getTopologyInfo().getMembers()).toEqual([t.earth1]);
        })
        .then(function() {
          return cs[0].put('xsite-key-2', 'xsite-value-2');
        })
        .then(assertGet('xsite-key-2', 'xsite-value-2', cs[0]))
          //Stopping the rest of the servers to finish the test
        .then(t.stopClusterNode(t.earth1['port'], true))
        .finally(function() {
          return Promise.all(_.map(cs, function(c) { return c.disconnect(); }));
        });
    })
    .catch(t.failed(done)).finally(done);
  }, 15000);

});

function assertGet(k, expected, client) {
  return function() {
    return client.get(k)
      .then(function(v) {
        expect(v).toBe(expected);
      })
  }
}

function clusterSiteMoon() {
  return {
    cacheName: t.xsiteCacheName,
    authentication: t.authOpts.authentication,
    clusters: [
      {
        name: 'server-moon',
        servers: [t.moon1]
      }
    ]
  };
}

function siteClients() {
  return Promise.all([
    t.client(t.earth1, clusterSiteMoon()),
    t.client(t.moon1, {cacheName:
      t.xsiteCacheName,
      authentication: t.authOpts.authentication
    })
  ]);
}