text:
'''
The queryOptimiser is to validate, analyze the graph sub-queries and also rewrite them.

@author: keshan
'''

# Checks the queries used to create dynamic graphs
def getCoreGraphCommands(whereClause, graphName, graphPara):
    lowerGraphWhereClause = whereClause.lower()

    graphCommandArray = [] #elements of array are [graph:mapper, node:condition,...]

    #retrieve info about dynamic graph
    if graphName != "null":
        graphConstructArray = [] #elements are string
        nameKeyIndex = whereClause.index(graphName)
        isKeyIndex = lowerGraphWhereClause.index("is", nameKeyIndex + len(graphName))
        asKeyIndex = lowerGraphWhereClause.index("as", isKeyIndex + 2)
        graphConstructType = whereClause[isKeyIndex + 2 : asKeyIndex].strip()
        graphConstructArray.append(graphName)
        graphConstructArray.append(graphConstructType)
        graphConstructArray.append(getGraphSubQuery(whereClause, asKeyIndex))
        graphCommandArray.append(graphConstructArray)

    #retrieve info about path expression
    if "/" in graphPara:
        nodes = graphPara.split("/")
        print nodes
        pointerIndex = 0
        for eachNode in nodes:
            if eachNode.isalnum():
                if eachNode[0] != 'v' and eachNode[0] != 'V':
                    raise RuntimeError, "Syntax Error in Path Expression!!"
                nodeConstruct = []
                foundNode = False
                while foundNode == False:
                    try:
                        pointerIndex = whereClause.index(eachNode)
                    except ValueError :
                        raise RuntimeError, "Syntax Error!!"
                    if (whereClause[pointerIndex-1] == " " or whereClause[pointerIndex-1] == ",") and (whereClause[pointerIndex + len(eachNode)] == " " or whereClause[pointerIndex + len(eachNode)] == ","):
                        asIndex = lowerGraphWhereClause.index("as", pointerIndex + len(eachNode))
                        nodeConstruct.append(eachNode)
                        nodeConstruct.append(getGraphSubQuery(whereClause, asIndex))
                        foundNode = True
                        graphCommandArray.append(nodeConstruct)
    return graphCommandArray

#retrieve the sub-query for creating dynamic graphs and node condition
def getGraphSubQuery(whereClause, asIndex):
    leftBracketIndexArrayQuery = []
    bracketIndexQueryPair = []
    foundIRGMapper = False
    pointerIndex = asIndex + 2

    while foundIRGMapper == False:
        pointerIndex += 1
        if whereClause[pointerIndex] == "(":
            leftBracketIndexArrayQuery.append(pointerIndex)

        if whereClause[pointerIndex] == ")":
            bracketIndexQueryPair.append((leftBracketIndexArrayQuery.pop(),pointerIndex))
            if len(leftBracketIndexArrayQuery) == 0:
                foundIRGMapper = True
    subQuery = whereClause[bracketIndexQueryPair[-1][0] + 1 : bracketIndexQueryPair[-1][1]].strip()
    return subQuery

#return the whole graph sub-query
def getGraphQuery(executeCommand, graphKeyIndex, graphCommandArray):
    lowerCaseGraphCommand = executeCommand.lower()

    queryEndKeyIndex = 0
    if lowerCaseGraphCommand[graphKeyIndex] == "p":  #for path operations
        for eachQuery in graphCommandArray:
            queryIndex = executeCommand.index(eachQuery[-1], graphKeyIndex)
            if queryIndex > queryEndKeyIndex:
                queryEndKeyIndex = queryIndex + len(eachQuery[-1])
        lastBracketKeyIndex = executeCommand.index(")", queryEndKeyIndex)
        command = executeCommand[graphKeyIndex : lastBracketKeyIndex+1]
        return command

    elif lowerCaseGraphCommand[graphKeyIndex] == "r" or lowerCaseGraphCommand[graphKeyIndex] == "c": # for rank and cluster operations
        if len(graphCommandArray) == 0:  #for materialized graph
            leftBracketKeyIndex = executeCommand.index('(', graphKeyIndex)
            rightBracketKeyIndex = executeCommand.index(')', leftBracketKeyIndex)
            command = executeCommand[graphKeyIndex:rightBracketKeyIndex+1]
            return command
        else:  #for graph on-the-fly
            queryEndIndex = executeCommand.index(graphCommandArray[0][2], graphKeyIndex) + len(graphCommandArray[0][2])
            lastBracketIndex = executeCommand.index(")", queryEndIndex)
            command = executeCommand[graphKeyIndex : lastBracketIndex+1]
            return command


text:
namespace browser_sync {

bool RootNodeHasChildren(const char* tag,
                         sync_api::UserShare* user_share,
                         bool* has_children) {
  CHECK(has_children);
  *has_children = false;
  sync_api::ReadTransaction trans(user_share);
  sync_api::ReadNode node(&trans);
  if (!node.InitByTagLookup(tag)) {
    LOG(ERROR) << "Root node with tag " << tag << " does not exist";
    return false;
  }
  *has_children = node.GetFirstChildId() != sync_api::kInvalidId;
  return true;
}

namespace {

// Fills in |extension_data_map| with data from
// extension_service.GetSyncDataList().
void SlurpClientData(
    IsValidAndSyncablePredicate is_valid_and_syncable,
    const ExtensionServiceInterface& extension_service,
    ExtensionDataMap* extension_data_map) {
  std::vector<ExtensionSyncData> sync_data_list =
      extension_service.GetSyncDataList(is_valid_and_syncable);
  for (std::vector<ExtensionSyncData>::const_iterator it =
           sync_data_list.begin();
       it != sync_data_list.end(); ++it) {
    std::pair<ExtensionDataMap::iterator, bool> result =
        extension_data_map->insert(std::make_pair(it->id, *it));
    if (!result.second) {
      // The value wasn't inserted, so merge it in.
      result.first->second.Merge(*it);
    }
  }
}

// Gets the boilerplate error message for not being able to find a
// root node.
//
// TODO(akalin): Put this somewhere where all data types can use it.
std::string GetRootNodeDoesNotExistError(const char* root_node_tag) {
  return
      std::string("Server did not create the top-level ") +
      root_node_tag +
      " node. We might be running against an out-of-date server.";
}

// Gets the data from the server for extensions to be synced and
// updates |extension_data_map|.
bool SlurpServerData(
    const char* root_node_tag,
    const ExtensionSpecificsGetter extension_specifics_getter,
    sync_api::UserShare* user_share,
    ExtensionDataMap* extension_data_map) {
  sync_api::WriteTransaction trans(user_share);
  sync_api::ReadNode root(&trans);
  if (!root.InitByTagLookup(root_node_tag)) {
    LOG(ERROR) << GetRootNodeDoesNotExistError(root_node_tag);
    return false;
  }

  int64 id = root.GetFirstChildId();
  while (id != sync_api::kInvalidId) {
    sync_api::ReadNode sync_node(&trans);
    if (!sync_node.InitByIdLookup(id)) {
      LOG(ERROR) << "Failed to fetch sync node for id " << id;
      return false;
    }
    const sync_pb::ExtensionSpecifics& server_data =
        (*extension_specifics_getter)(sync_node);
    ExtensionSyncData sync_data;
    if (!SpecificsToSyncData(server_data, &sync_data)) {
      LOG(ERROR) << "Invalid extensions specifics for id " << id;
      return false;
    }
    (*extension_data_map)[sync_data.id] = sync_data;
    id = sync_node.GetSuccessorId();
  }
  return true;
}

}  // namespace

bool SlurpExtensionData(const ExtensionSyncTraits& traits,
                        const ExtensionServiceInterface& extension_service,
                        sync_api::UserShare* user_share,
                        ExtensionDataMap* extension_data_map) {
  // Read server-side data first so client user settings take
  // precedence.
  if (!SlurpServerData(
          traits.root_node_tag, traits.extension_specifics_getter,
          user_share, extension_data_map)) {
    return false;
  }

  SlurpClientData(
      traits.is_valid_and_syncable, extension_service,
      extension_data_map);
  return true;
}

namespace {

// Updates the server data from the given extension data.  Returns
// whether or not the update was successful.
bool UpdateServer(
    const ExtensionSyncTraits& traits,
    const ExtensionSyncData& data,
    sync_api::WriteTransaction* trans) {
  sync_pb::ExtensionSpecifics specifics;
  SyncDataToSpecifics(data, &specifics);
  const std::string& id = data.id;
  sync_api::WriteNode write_node(trans);
  if (write_node.InitByClientTagLookup(traits.model_type, id)) {
    (*traits.extension_specifics_setter)(specifics, &write_node);
  } else {
    sync_api::ReadNode root(trans);
    if (!root.InitByTagLookup(traits.root_node_tag)) {
      LOG(ERROR) << GetRootNodeDoesNotExistError(traits.root_node_tag);
      return false;
    }
    sync_api::WriteNode create_node(trans);
    if (!create_node.InitUniqueByCreation(traits.model_type, root, id)) {
      LOG(ERROR) << "Could not create node for extension " << id;
      return false;
    }
    (*traits.extension_specifics_setter)(specifics, &create_node);
  }
  return true;
}

}  // namespace

bool FlushExtensionData(const ExtensionSyncTraits& traits,
                        const ExtensionDataMap& extension_data_map,
                        ExtensionServiceInterface* extension_service,
                        sync_api::UserShare* user_share) {
  sync_api::WriteTransaction trans(user_share);
  sync_api::ReadNode root(&trans);
  if (!root.InitByTagLookup(traits.root_node_tag)) {
    LOG(ERROR) << GetRootNodeDoesNotExistError(traits.root_node_tag);
    return false;
  }

  // Update server and client as necessary.
  for (ExtensionDataMap::const_iterator it = extension_data_map.begin();
       it != extension_data_map.end(); ++it) {
    const ExtensionSyncData& extension_data = it->second;
    if (!UpdateServer(traits, extension_data, &trans)) {
      LOG(ERROR) << "Could not update server data for extension "
                 << it->first;
      return false;
    }
    extension_service->ProcessSyncData(extension_data,
                                       traits.is_valid_and_syncable);
  }
  return true;
}

bool UpdateServerData(const ExtensionSyncTraits& traits,
                      const Extension& extension,
                      const ExtensionServiceInterface& extension_service,
                      sync_api::UserShare* user_share,
                      std::string* error) {
  const std::string& id = extension.id();
  ExtensionSyncData data;
  if (!extension_service.GetSyncData(
          extension, traits.is_valid_and_syncable, &data)) {
    *error =
        std::string("UpdateServerData() called for invalid or "
                    "unsyncable extension ") + id;
    LOG(DFATAL) << *error;
    return false;
  }

  sync_api::WriteTransaction trans(user_share);
  if (!UpdateServer(traits, data, &trans)) {
    *error =
        std::string("Could not update server data for extension ") + id;
    LOG(ERROR) << *error;
    return false;
  }
  return true;
}

void RemoveServerData(const ExtensionSyncTraits& traits,
                      const std::string& id,
                      sync_api::UserShare* user_share) {
  sync_api::WriteTransaction trans(user_share);
  sync_api::WriteNode write_node(&trans);
  if (write_node.InitByClientTagLookup(traits.model_type, id)) {
    write_node.Remove();
  } else {
    LOG(ERROR) << "Server data does not exist for extension " << id;
  }
}

}  // namespace browser_sync

redpajama_set_name: RedPajamaGithub


text:
namespace Mass.Core.Commands
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using Mass.Core.Expressions;

    public class WhileCommand : ICommand
    {
        private static int hashcode = typeof(WhileCommand).GetHashCode();

        private IExpression condition;
        private ICommand command;

        public WhileCommand(IExpression condition, ICommand command)
        {
            this.condition = condition;
            this.command = command;
        }

        public object Execute(Context context)
        {
            for (object value = this.condition.Evaluate(context); value != null && !false.Equals(value); value = this.condition.Evaluate(context))
            {
                this.command.Execute(context);
                if (context.HasReturnValue())
                    return context.GetReturnValue();
                if (context.HasContinue())
                    context.ClearContinue();
                if (context.HasBreak())
                {
                    context.ClearBreak();
                    break;
                }
            }

            return null;
        }

        public override bool Equals(object obj)
        {
            if (obj == null)
                return false;

            if (obj is WhileCommand)
            {
                var cmd = (WhileCommand)obj;

                return this.condition.Equals(cmd.condition) && this.command.Equals(cmd.command);
            }

            return false;
        }

        public override int GetHashCode()
        {
            return this.condition.GetHashCode() + this.command.GetHashCode() + hashcode;
        }
    }
}


text:
class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

        has_many :cars

        has_many :drivers, through: :driver_trips, source: :driver
        has_many :driver_trips, foreign_key: :driver_id, class_name: 'Trip'

        has_many :passengers, through: :passenger_riders
        has_many :passenger_riders, foreign_key: :passenger_id, class_name: 'Rider'

        has_many :raters, through: :rater_ratings, source: :rater
        has_many :rater_ratings, foreign_key: :rated_id, class_name: 'Rating'

        has_many :rateds, through: :rated_ratings, source: :rated
        has_many :rated_ratings, foreign_key: :rater_id, class_name: 'Rating'

  after_create :update_access_token!

  validates :email, presence: true

    private

  def update_access_token!
    self.access_token = "#{self.id}:#{Devise.friendly_token}"
    save
  end

end

#User.create!({:email => "guy@gmail.com",  :password => "12345678", :password_confirmation => "12345678" })


text:
var XLSX = require('/Users/pieter/Dev/js-xlsx');
var workbook = XLSX.readFile('/Users/pieter/Exp/js-xlsx/lab/date/date.xlsx', {type: "xlsx", cellDates: true, cellStyles: true});
console.log(workbook.Sheets);


text:
package org.apache.geode.internal.cache.tier.sockets;

import java.io.EOFException;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.Semaphore;
import java.util.regex.Pattern;

import edu.umd.cs.findbugs.annotations.SuppressWarnings;
import org.apache.logging.log4j.Logger;

import org.apache.geode.CopyException;
import org.apache.geode.InternalGemFireError;
import org.apache.geode.SerializationException;
import org.apache.geode.SystemFailure;
import org.apache.geode.cache.CacheLoaderException;
import org.apache.geode.cache.CacheWriterException;
import org.apache.geode.cache.InterestResultPolicy;
import org.apache.geode.cache.Operation;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.RegionDestroyedException;
import org.apache.geode.cache.TransactionException;
import org.apache.geode.cache.persistence.PartitionOfflineException;
import org.apache.geode.cache.query.types.CollectionType;
import org.apache.geode.distributed.DistributedSystemDisconnectedException;
import org.apache.geode.distributed.internal.DistributionConfig;
import org.apache.geode.distributed.internal.DistributionStats;
import org.apache.geode.distributed.internal.membership.InternalDistributedMember;
import org.apache.geode.internal.Assert;
import org.apache.geode.internal.Version;
import org.apache.geode.internal.cache.CachedDeserializable;
import org.apache.geode.internal.cache.DistributedRegion;
import org.apache.geode.internal.cache.EntryEventImpl;
import org.apache.geode.internal.cache.EntrySnapshot;
import org.apache.geode.internal.cache.EventID;
import org.apache.geode.internal.cache.FindVersionTagOperation;
import org.apache.geode.internal.cache.InternalCache;
import org.apache.geode.internal.cache.InternalRegion;
import org.apache.geode.internal.cache.LocalRegion;
import org.apache.geode.internal.cache.LocalRegion.NonTXEntry;
import org.apache.geode.internal.cache.PartitionedRegion;
import org.apache.geode.internal.cache.PartitionedRegionHelper;
import org.apache.geode.internal.cache.TXManagerImpl;
import org.apache.geode.internal.cache.TXStateProxy;
import org.apache.geode.internal.cache.Token;
import org.apache.geode.internal.cache.VersionTagHolder;
import org.apache.geode.internal.cache.execute.ServerToClientFunctionResultSender;
import org.apache.geode.internal.cache.tier.CachedRegionHelper;
import org.apache.geode.internal.cache.tier.Command;
import org.apache.geode.internal.cache.tier.InterestType;
import org.apache.geode.internal.cache.tier.MessageType;
import org.apache.geode.internal.cache.versions.VersionStamp;
import org.apache.geode.internal.cache.versions.VersionTag;
import org.apache.geode.internal.logging.LogService;
import org.apache.geode.internal.offheap.OffHeapHelper;
import org.apache.geode.internal.security.SecurityService;
import org.apache.geode.internal.sequencelog.EntryLogger;
import org.apache.geode.security.GemFireSecurityException;

public abstract class BaseCommand implements Command {
  protected static final Logger logger = LogService.getLogger();

  private static final byte[] OK_BYTES = new byte[] {0};

  public static final int MAXIMUM_CHUNK_SIZE =
      Integer.getInteger("BridgeServer.MAXIMUM_CHUNK_SIZE", 100);

  /** Whether to suppress logging of IOExceptions */
  private static final boolean SUPPRESS_IO_EXCEPTION_LOGGING =
      Boolean.getBoolean(DistributionConfig.GEMFIRE_PREFIX + "bridge.suppressIOExceptionLogging");

  /**
   * Maximum number of concurrent incoming client message bytes that a cache server will allow.
   * Once a server is working on this number additional incoming client messages will wait until one
   * of them completes or fails. The bytes are computed based in the size sent in the incoming msg
   * header.
   */
  private static final int MAX_INCOMING_DATA =
      Integer.getInteger("BridgeServer.MAX_INCOMING_DATA", -1);

  /**
   * Maximum number of concurrent incoming client messages that a cache server will allow. Once a
   * server is working on this number additional incoming client messages will wait until one of
   * them completes or fails.
   */
  private static final int MAX_INCOMING_MESSAGES =
      Integer.getInteger("BridgeServer.MAX_INCOMING_MSGS", -1);

  private static final Semaphore INCOMING_DATA_LIMITER;

  private static final Semaphore INCOMING_MSG_LIMITER;

  static {
    Semaphore semaphore;
    if (MAX_INCOMING_DATA > 0) {
      // backport requires that this is fair since we inc by values > 1
      semaphore = new Semaphore(MAX_INCOMING_DATA, true);
    } else {
      semaphore = null;
    }
    INCOMING_DATA_LIMITER = semaphore;
    if (MAX_INCOMING_MESSAGES > 0) {
      // unfair for best performance
      semaphore = new Semaphore(MAX_INCOMING_MESSAGES, false);
    } else {
      semaphore = null;
    }
    INCOMING_MSG_LIMITER = semaphore;
  }

  protected static byte[] okBytes() {
    return OK_BYTES;
  }

  protected boolean setLastResultReceived(
      ServerToClientFunctionResultSender resultSender) {

    if (resultSender != null) {
      synchronized (resultSender) {
        if (resultSender.isLastResultReceived()) {
          return false;
        } else {
          resultSender.setLastResultReceived(true);
        }
      }
    }
    return true;
  }

  @Override
  public void execute(Message clientMessage, ServerConnection serverConnection,
      SecurityService securityService) {
    // Read the request and update the statistics
    long start = DistributionStats.getStatTime();
    if (EntryLogger.isEnabled() && serverConnection != null) {
      EntryLogger.setSource(serverConnection.getMembershipID(), "c2s");
    }
    boolean shouldMasquerade = shouldMasqueradeForTx(clientMessage, serverConnection);
    try {
      if (shouldMasquerade) {
        InternalCache cache = serverConnection.getCache();
        InternalDistributedMember member =
            (InternalDistributedMember) serverConnection.getProxyID().getDistributedMember();
        TXManagerImpl txMgr = cache.getTxManager();
        TXStateProxy tx = null;
        try {
          tx = txMgr.masqueradeAs(clientMessage, member, false);
          cmdExecute(clientMessage, serverConnection, securityService, start);
          tx.updateProxyServer(txMgr.getMemberId());
        } finally {
          txMgr.unmasquerade(tx);
        }
      } else {
        cmdExecute(clientMessage, serverConnection, securityService, start);
      }

    } catch (TransactionException | CopyException | SerializationException | CacheWriterException
        | CacheLoaderException | GemFireSecurityException | PartitionOfflineException
        | MessageTooLargeException e) {
      handleExceptionNoDisconnect(clientMessage, serverConnection, e);
    } catch (EOFException eof) {
      BaseCommand.handleEOFException(clientMessage, serverConnection, eof);
    } catch (InterruptedIOException e) { // Solaris only
      BaseCommand.handleInterruptedIOException(serverConnection, e);
    } catch (IOException e) {
      BaseCommand.handleIOException(clientMessage, serverConnection, e);
    } catch (DistributedSystemDisconnectedException e) {
      BaseCommand.handleShutdownException(clientMessage, serverConnection, e);
    } catch (VirtualMachineError err) {
      SystemFailure.initiateFailure(err);
      // If this ever returns, rethrow the error. We're poisoned
      // now, so don't let this thread continue.
      throw err;
    } catch (Throwable e) {
      BaseCommand.handleThrowable(clientMessage, serverConnection, e);
    } finally {
      EntryLogger.clearSource();
    }
  }

  /**
   * checks to see if this thread needs to masquerade as a transactional thread. clients after
   * GFE_66 should be able to start a transaction.
   *
   * @return true if thread should masquerade as a transactional thread.
   */
  protected boolean shouldMasqueradeForTx(Message clientMessage,
      ServerConnection serverConnection) {
    return serverConnection.getClientVersion().compareTo(Version.GFE_66) >= 0
        && clientMessage.getTransactionId() > TXManagerImpl.NOTX;
  }

  /**
   * If an operation is retried then some server may have seen it already. We cannot apply this
   * operation to the cache without knowing whether a version tag has already been created for it.
   * Otherwise caches that have seen the event already will reject it but others will not, but will
   * have no version tag with which to perform concurrency checks.
   *

   * The client event should have the event identifier from the client and the region affected by
   * the operation.
   */
  public boolean recoverVersionTagForRetriedOperation(EntryEventImpl clientEvent) {
    InternalRegion r = clientEvent.getRegion();
    VersionTag tag = r.findVersionTagForEvent(clientEvent.getEventId());
    if (tag == null) {
      if (r instanceof DistributedRegion || r instanceof PartitionedRegion) {
        // TODO this could be optimized for partitioned regions by sending the key
        // so that the PR could look at an individual bucket for the event
        tag = FindVersionTagOperation.findVersionTag(r, clientEvent.getEventId(), false);
      }
    }
    if (tag != null) {
      if (logger.isDebugEnabled()) {
        logger.debug("recovered version tag {} for replayed operation {}", tag,
            clientEvent.getEventId());
      }
      clientEvent.setVersionTag(tag);
    }
    return tag != null;
  }

  /**
   * If an operation is retried then some server may have seen it already. We cannot apply this
   * operation to the cache without knowing whether a version tag has already been created for it.
   * Otherwise caches that have seen the event already will reject it but others will not, but will
   * have no version tag with which to perform concurrency checks.
   *

   * The client event should have the event identifier from the client and the region affected by
   * the operation.
   */
  protected VersionTag findVersionTagsForRetriedBulkOp(LocalRegion region, EventID eventID) {
    VersionTag tag = region.findVersionTagForClientBulkOp(eventID);
    if (tag != null) {
      if (logger.isDebugEnabled()) {
        logger.debug("recovered version tag {} for replayed bulk operation {}", tag, eventID);
      }
      return tag;
    }
    if (region instanceof DistributedRegion || region instanceof PartitionedRegion) {
      // TODO this could be optimized for partitioned regions by sending the key
      // so that the PR could look at an individual bucket for the event
      tag = FindVersionTagOperation.findVersionTag(region, eventID, true);
    }
    if (tag != null) {
      if (logger.isDebugEnabled()) {
        logger.debug("recovered version tag {} for replayed bulk operation {}", tag, eventID);
      }
    }
    return tag;
  }

  public abstract void cmdExecute(final Message clientMessage,
      final ServerConnection serverConnection, final SecurityService securityService,
      final long start) throws IOException, ClassNotFoundException, InterruptedException;

  protected void writeReply(Message origMsg, ServerConnection serverConnection) throws IOException {
    Message replyMsg = serverConnection.getReplyMessage();
    serverConnection.getCache().getCancelCriterion().checkCancelInProgress(null);
    replyMsg.setMessageType(MessageType.REPLY);
    replyMsg.setNumberOfParts(1);
    replyMsg.setTransactionId(origMsg.getTransactionId());
    replyMsg.addBytesPart(okBytes());
    replyMsg.send(serverConnection);
    if (logger.isTraceEnabled()) {
      logger.trace("{}: rpl tx: {}", serverConnection.getName(), origMsg.getTransactionId());
    }
  }

  protected void writeReplyWithRefreshMetadata(Message origMsg, ServerConnection serverConnection,
      PartitionedRegion pr, byte nwHop) throws IOException {
    Message replyMsg = serverConnection.getReplyMessage();
    serverConnection.getCache().getCancelCriterion().checkCancelInProgress(null);
    replyMsg.setMessageType(MessageType.REPLY);
    replyMsg.setNumberOfParts(1);
    replyMsg.setTransactionId(origMsg.getTransactionId());
    replyMsg.addBytesPart(new byte[] {pr.getMetadataVersion(), nwHop});
    replyMsg.send(serverConnection);
    pr.getPrStats().incPRMetaDataSentCount();
    if (logger.isTraceEnabled()) {
      logger.trace("{}: rpl with REFRESH_METADATA tx: {}", serverConnection.getName(),
          origMsg.getTransactionId());
    }
  }

  private static void handleEOFException(Message msg, ServerConnection serverConnection,
      Exception eof) {
    CachedRegionHelper crHelper = serverConnection.getCachedRegionHelper();
    CacheServerStats stats = serverConnection.getCacheServerStats();
    boolean potentialModification = serverConnection.getPotentialModification();
    if (!crHelper.isShutdown()) {
      if (potentialModification) {
        stats.incAbandonedWriteRequests();
      } else {
        stats.incAbandonedReadRequests();
      }
      if (!SUPPRESS_IO_EXCEPTION_LOGGING) {
        if (potentialModification) {
          int transId = msg != null ? msg.getTransactionId() : Integer.MIN_VALUE;
          logger.warn(
              "{}: EOFException during a write operation on region : {} key: {} messageId: {}",
              new Object[] {serverConnection.getName(), serverConnection.getModRegion(),
                  serverConnection.getModKey(), transId});
        } else {
          logger.debug("EOF exception", eof);
          logger.info("{}: connection disconnect detected by EOF.",
              serverConnection.getName());
        }
      }
    }
    serverConnection.setFlagProcessMessagesAsFalse();
    serverConnection.setClientDisconnectedException(eof);
  }

  private static void handleInterruptedIOException(ServerConnection serverConnection, Exception e) {
    CachedRegionHelper crHelper = serverConnection.getCachedRegionHelper();
    if (!crHelper.isShutdown() && serverConnection.isOpen()) {
      if (!SUPPRESS_IO_EXCEPTION_LOGGING) {
        if (logger.isDebugEnabled())
          logger.debug("Aborted message due to interrupt: {}", e.getMessage(), e);
      }
    }
    serverConnection.setFlagProcessMessagesAsFalse();
    serverConnection.setClientDisconnectedException(e);
  }

  private static void handleIOException(Message msg, ServerConnection serverConnection,
      Exception e) {
    CachedRegionHelper crHelper = serverConnection.getCachedRegionHelper();
    boolean potentialModification = serverConnection.getPotentialModification();

    if (!crHelper.isShutdown() && serverConnection.isOpen()) {
      if (!SUPPRESS_IO_EXCEPTION_LOGGING) {
        if (potentialModification) {
          int transId = msg != null ? msg.getTransactionId() : Integer.MIN_VALUE;
          logger.warn(String.format(
              "%s: Unexpected IOException during operation for region: %s key: %s messId: %s",
              new Object[] {serverConnection.getName(), serverConnection.getModRegion(),
                  serverConnection.getModKey(), transId}),
              e);
        } else {
          logger.warn(String.format("%s: Unexpected IOException: ",
              serverConnection.getName()), e);
        }
      }
    }
    serverConnection.setFlagProcessMessagesAsFalse();
    serverConnection.setClientDisconnectedException(e);
  }

  private static void handleShutdownException(Message msg, ServerConnection serverConnection,
      Exception e) {
    CachedRegionHelper crHelper = serverConnection.getCachedRegionHelper();
    boolean potentialModification = serverConnection.getPotentialModification();

    if (!crHelper.isShutdown()) {
      if (potentialModification) {
        int transId = msg != null ? msg.getTransactionId() : Integer.MIN_VALUE;
        logger.warn(String.format(
            "%s: Unexpected ShutdownException during operation on region: %s key: %s messageId: %s",
            new Object[] {serverConnection.getName(), serverConnection.getModRegion(),
                serverConnection.getModKey(), transId}),
            e);
      } else {
        logger.warn(String.format("%s: Unexpected ShutdownException: ",
            serverConnection.getName()),
            e);
      }
    }
    serverConnection.setFlagProcessMessagesAsFalse();
    serverConnection.setClientDisconnectedException(e);
  }

  private static void handleExceptionNoDisconnect(Message msg, ServerConnection serverConnection,
      Exception e) {
    boolean requiresResponse = serverConnection.getTransientFlag(REQUIRES_RESPONSE);
    boolean responded = serverConnection.getTransientFlag(RESPONDED);
    boolean requiresChunkedResponse = serverConnection.getTransientFlag(REQUIRES_CHUNKED_RESPONSE);
    boolean potentialModification = serverConnection.getPotentialModification();

    try {
      boolean wroteExceptionResponse = false;
      try {
        if (requiresResponse && !responded) {
          if (requiresChunkedResponse) {
            writeChunkedException(msg, e, serverConnection);
          } else {
            writeException(msg, e, false, serverConnection);
          }
          wroteExceptionResponse = true;
          serverConnection.setAsTrue(RESPONDED);
        }
      } finally { // inner try-finally to ensure proper ordering of logging
        if (potentialModification) {
          int transId = msg != null ? msg.getTransactionId() : Integer.MIN_VALUE;
          if (!wroteExceptionResponse) {
            logger.warn(String.format(
                "%s: Unexpected Exception during operation on region: %s key: %s messageId: %s",
                new Object[] {serverConnection.getName(), serverConnection.getModRegion(),
                    serverConnection.getModKey(), transId}),
                e);
          } else {
            if (logger.isDebugEnabled()) {
              logger.debug("{}: Exception during operation on region: {} key: {} messageId: {}",
                  serverConnection.getName(), serverConnection.getModRegion(),
                  serverConnection.getModKey(), transId, e);
            }
          }
        } else {
          if (!wroteExceptionResponse) {
            logger.warn(String.format("%s: Unexpected Exception",
                serverConnection.getName()), e);
          } else {
            if (logger.isDebugEnabled()) {
              logger.debug("{}: Exception: {}", serverConnection.getName(), e.getMessage(), e);
            }
          }
        }
      }
    } catch (IOException ioe) {
      if (logger.isDebugEnabled()) {
        logger.debug("{}: Unexpected IOException writing exception: {}", serverConnection.getName(),
            ioe.getMessage(), ioe);
      }
    }
  }

  private static void handleThrowable(Message msg, ServerConnection serverConnection,
      Throwable th) {
    boolean requiresResponse = serverConnection.getTransientFlag(REQUIRES_RESPONSE);
    boolean responded = serverConnection.getTransientFlag(RESPONDED);
    boolean requiresChunkedResponse = serverConnection.getTransientFlag(REQUIRES_CHUNKED_RESPONSE);
    boolean potentialModification = serverConnection.getPotentialModification();

    try {
      try {
        if (th instanceof Error) {
          logger.fatal(String.format("%s : Unexpected Error on server",
              serverConnection.getName()),
              th);
        }
        if (requiresResponse && !responded) {
          if (requiresChunkedResponse) {
            writeChunkedException(msg, th, serverConnection);
          } else {
            writeException(msg, th, false, serverConnection);
          }
          serverConnection.setAsTrue(RESPONDED);
        }
      } finally { // inner try-finally to ensure proper ordering of logging
        if (!(th instanceof Error || th instanceof CacheLoaderException)) {
          if (potentialModification) {
            int transId = msg != null ? msg.getTransactionId() : Integer.MIN_VALUE;
            logger.warn(String.format(
                "%s: Unexpected Exception during operation on region: %s key: %s messageId: %s",
                new Object[] {serverConnection.getName(), serverConnection.getModRegion(),
                    serverConnection.getModKey(), transId}),
                th);
          } else {
            logger.warn(String.format("%s: Unexpected Exception",
                serverConnection.getName()), th);
          }
        }
      }
    } catch (IOException ioe) {
      if (logger.isDebugEnabled()) {
        logger.debug("{}: Unexpected IOException writing exception: {}", serverConnection.getName(),
            ioe.getMessage(), ioe);
      }
    } finally {
      serverConnection.setFlagProcessMessagesAsFalse();
      serverConnection.setClientDisconnectedException(th);
    }
  }

  protected static void writeChunkedException(Message origMsg, Throwable e,
      ServerConnection serverConnection) throws IOException {
    writeChunkedException(origMsg, e, serverConnection,
        serverConnection.getChunkedResponseMessage());
  }

  protected static void writeChunkedException(Message origMsg, Throwable e,
      ServerConnection serverConnection, ChunkedMessage originalResponse) throws IOException {
    writeChunkedException(origMsg, e, serverConnection, originalResponse, 2);
  }

  private static void writeChunkedException(Message origMsg, Throwable exception,
      ServerConnection serverConnection, ChunkedMessage originalResponse, int numOfParts)
      throws IOException {
    Throwable e = getClientException(serverConnection, exception);
    ChunkedMessage chunkedResponseMsg = serverConnection.getChunkedResponseMessage();
    chunkedResponseMsg.setServerConnection(serverConnection);
    if (originalResponse.headerHasBeenSent()) {
      chunkedResponseMsg.setNumberOfParts(numOfParts);
      chunkedResponseMsg.setLastChunkAndNumParts(true, numOfParts);
      chunkedResponseMsg.addObjPart(e);
      if (numOfParts == 2) {
        chunkedResponseMsg.addStringPart(getExceptionTrace(e));
      }
      if (logger.isDebugEnabled()) {
        logger.debug("{}: Sending exception chunk while reply in progress: {}",
            serverConnection.getName(), e.getMessage(), e);
      }
    } else {
      chunkedResponseMsg.setMessageType(MessageType.EXCEPTION);
      chunkedResponseMsg.setNumberOfParts(numOfParts);
      chunkedResponseMsg.setLastChunkAndNumParts(true, numOfParts);
      chunkedResponseMsg.setTransactionId(origMsg.getTransactionId());
      chunkedResponseMsg.sendHeader();
      chunkedResponseMsg.addObjPart(e);
      if (numOfParts == 2) {
        chunkedResponseMsg.addStringPart(getExceptionTrace(e));
      }
      if (logger.isDebugEnabled()) {
        logger.debug("{}: Sending exception chunk: {}", serverConnection.getName(), e.getMessage(),
            e);
      }
    }
    chunkedResponseMsg.sendChunk(serverConnection);
  }

  // Get the exception stacktrace for native clients
  public static String getExceptionTrace(Throwable ex) {
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    ex.printStackTrace(pw);
    pw.close();
    return sw.toString();
  }

  protected static void writeException(Message origMsg, Throwable e, boolean isSevere,
      ServerConnection serverConnection) throws IOException {
    writeException(origMsg, MessageType.EXCEPTION, e, isSevere, serverConnection);
  }

  private static Throwable getClientException(ServerConnection serverConnection, Throwable e) {
    InternalCache cache = serverConnection.getCache();
    if (cache != null) {
      OldClientSupportService svc = cache.getService(OldClientSupportService.class);
      if (svc != null) {
        return svc.getThrowable(e, serverConnection.getClientVersion());
      }
    }
    return e;
  }

  protected static void writeException(Message origMsg, int msgType, Throwable e, boolean isSevere,
      ServerConnection serverConnection) throws IOException {
    Throwable theException = getClientException(serverConnection, e);
    Message errorMsg = serverConnection.getErrorResponseMessage();
    errorMsg.setMessageType(msgType);
    errorMsg.setNumberOfParts(2);
    errorMsg.setTransactionId(origMsg.getTransactionId());
    if (isSevere) {
      String msg = theException.getMessage();
      if (msg == null) {
        msg = theException.toString();
      }
      logger.fatal("Severe cache exception : {}", msg);
    }
    errorMsg.addObjPart(theException);
    errorMsg.addStringPart(getExceptionTrace(theException));
    errorMsg.send(serverConnection);
    if (logger.isDebugEnabled()) {
      logger.debug("{}: Wrote exception: {}", serverConnection.getName(), e.getMessage(), e);
    }
    if (e instanceof MessageTooLargeException) {
      throw (IOException) e;
    }
  }

  protected static void writeErrorResponse(Message origMsg, int messageType,
      ServerConnection serverConnection) throws IOException {
    Message errorMsg = serverConnection.getErrorResponseMessage();
    errorMsg.setMessageType(messageType);
    errorMsg.setNumberOfParts(1);
    errorMsg.setTransactionId(origMsg.getTransactionId());
    errorMsg.addStringPart(
        "Invalid data received. Please see the cache server log file for additional details.");
    errorMsg.send(serverConnection);
  }

  protected static void writeErrorResponse(Message origMsg, int messageType, String msg,
      ServerConnection serverConnection) throws IOException {
    Message errorMsg = serverConnection.getErrorResponseMessage();
    errorMsg.setMessageType(messageType);
    errorMsg.setNumberOfParts(1);
    errorMsg.setTransactionId(origMsg.getTransactionId());
    errorMsg.addStringPart(msg);
    errorMsg.send(serverConnection);
  }

  protected static void writeRegionDestroyedEx(Message msg, String regionName, String title,
      ServerConnection serverConnection) throws IOException {
    String reason = serverConnection.getName() + ": Region named " + regionName + title;
    RegionDestroyedException ex = new RegionDestroyedException(reason, regionName);
    if (serverConnection.getTransientFlag(REQUIRES_CHUNKED_RESPONSE)) {
      writeChunkedException(msg, ex, serverConnection);
    } else {
      writeException(msg, ex, false, serverConnection);
    }
  }

  protected static void writeResponse(Object data, Object callbackArg, Message origMsg,
      boolean isObject, ServerConnection serverConnection) throws IOException {
    Message responseMsg = serverConnection.getResponseMessage();
    responseMsg.setMessageType(MessageType.RESPONSE);
    responseMsg.setTransactionId(origMsg.getTransactionId());

    if (callbackArg == null) {
      responseMsg.setNumberOfParts(1);
    } else {
      responseMsg.setNumberOfParts(2);
    }
    if (data instanceof byte[]) {
      responseMsg.addRawPart((byte[]) data, isObject);
    } else {
      Assert.assertTrue(isObject, "isObject should be true when value is not a byte[]");
      responseMsg.addObjPart(data, false);
    }
    if (callbackArg != null) {
      responseMsg.addObjPart(callbackArg);
    }
    serverConnection.getCache().getCancelCriterion().checkCancelInProgress(null);
    responseMsg.send(serverConnection);
    origMsg.clearParts();
  }

  protected static void writeResponseWithRefreshMetadata(Object data, Object callbackArg,
      Message origMsg, boolean isObject, ServerConnection serverConnection, PartitionedRegion pr,
      byte nwHop) throws IOException {
    Message responseMsg = serverConnection.getResponseMessage();
    responseMsg.setMessageType(MessageType.RESPONSE);
    responseMsg.setTransactionId(origMsg.getTransactionId());

    if (callbackArg == null) {
      responseMsg.setNumberOfParts(2);
    } else {
      responseMsg.setNumberOfParts(3);
    }

    if (data instanceof byte[]) {
      responseMsg.addRawPart((byte[]) data, isObject);
    } else {
      Assert.assertTrue(isObject, "isObject should be true when value is not a byte[]");
      responseMsg.addObjPart(data, false);
    }
    if (callbackArg != null) {
      responseMsg.addObjPart(callbackArg);
    }
    responseMsg.addBytesPart(new byte[] {pr.getMetadataVersion(), nwHop});
    serverConnection.getCache().getCancelCriterion().checkCancelInProgress(null);
    responseMsg.send(serverConnection);
    origMsg.clearParts();
  }

  protected static void writeResponseWithFunctionAttribute(byte[] data, Message origMsg,
      ServerConnection serverConnection) throws IOException {
    Message responseMsg = serverConnection.getResponseMessage();
    responseMsg.setMessageType(MessageType.RESPONSE);
    responseMsg.setTransactionId(origMsg.getTransactionId());
    responseMsg.setNumberOfParts(1);
    responseMsg.addBytesPart(data);
    serverConnection.getCache().getCancelCriterion().checkCancelInProgress(null);
    responseMsg.send(serverConnection);
    origMsg.clearParts();
  }

  protected static void checkForInterrupt(ServerConnection serverConnection, Exception e)
      throws InterruptedException, InterruptedIOException {
    serverConnection.getCachedRegionHelper().checkCancelInProgress(e);
    if (e instanceof InterruptedException) {
      throw (InterruptedException) e;
    }
    if (e instanceof InterruptedIOException) {
      throw (InterruptedIOException) e;
    }
  }

  static void writeQueryResponseChunk(Object queryResponseChunk, CollectionType collectionType,
      boolean lastChunk, ServerConnection serverConnection) throws IOException {
    ChunkedMessage queryResponseMsg = serverConnection.getQueryResponseMessage();
    queryResponseMsg.setNumberOfParts(2);
    queryResponseMsg.setLastChunk(lastChunk);
    queryResponseMsg.addObjPart(collectionType, false);
    queryResponseMsg.addObjPart(queryResponseChunk, false);
    queryResponseMsg.sendChunk(serverConnection);
  }

  protected static void writeQueryResponseException(Message origMsg, Throwable exception,
      ServerConnection serverConnection) throws IOException {
    Throwable e = getClientException(serverConnection, exception);
    ChunkedMessage queryResponseMsg = serverConnection.getQueryResponseMessage();
    ChunkedMessage chunkedResponseMsg = serverConnection.getChunkedResponseMessage();
    if (queryResponseMsg.headerHasBeenSent()) {
      // fix for bug 35442
      // This client is expecting 2 parts in this message so send 2 parts
      queryResponseMsg.setServerConnection(serverConnection);
      queryResponseMsg.setNumberOfParts(2);
      queryResponseMsg.setLastChunkAndNumParts(true, 2);
      queryResponseMsg.addObjPart(e);
      queryResponseMsg.addStringPart(getExceptionTrace(e));
      if (logger.isDebugEnabled()) {
        logger.debug("{}: Sending exception chunk while reply in progress: {}",
            serverConnection.getName(), e.getMessage(), e);
      }
      queryResponseMsg.sendChunk(serverConnection);
    } else {
      chunkedResponseMsg.setServerConnection(serverConnection);
      chunkedResponseMsg.setMessageType(MessageType.EXCEPTION);
      chunkedResponseMsg.setNumberOfParts(2);
      chunkedResponseMsg.setLastChunkAndNumParts(true, 2);
      chunkedResponseMsg.setTransactionId(origMsg.getTransactionId());
      chunkedResponseMsg.sendHeader();
      chunkedResponseMsg.addObjPart(e);
      chunkedResponseMsg.addStringPart(getExceptionTrace(e));
      if (logger.isDebugEnabled()) {
        logger.debug("{}: Sending exception chunk: {}", serverConnection.getName(), e.getMessage(),
            e);
      }
      chunkedResponseMsg.sendChunk(serverConnection);
    }
  }

  protected static void writeChunkedErrorResponse(Message origMsg, int messageType, String message,
      ServerConnection serverConnection) throws IOException {
    // Send chunked response header identifying error message
    ChunkedMessage chunkedResponseMsg = serverConnection.getChunkedResponseMessage();
    if (logger.isDebugEnabled()) {
      logger.debug("{}: Sending error message header type: {} transaction: {}",
          serverConnection.getName(), messageType, origMsg.getTransactionId());
    }
    chunkedResponseMsg.setMessageType(messageType);
    chunkedResponseMsg.setTransactionId(origMsg.getTransactionId());
    chunkedResponseMsg.sendHeader();

    // Send actual error
    if (logger.isDebugEnabled()) {
      logger.debug("{}: Sending error message chunk: {}", serverConnection.getName(), message);
    }
    chunkedResponseMsg.setNumberOfParts(1);
    chunkedResponseMsg.setLastChunk(true);
    chunkedResponseMsg.addStringPart(message);
    chunkedResponseMsg.sendChunk(serverConnection);
  }

  protected static void writeFunctionResponseException(Message origMsg, int messageType,
      ServerConnection serverConnection, Throwable exception) throws IOException {
    Throwable e = getClientException(serverConnection, exception);
    ChunkedMessage functionResponseMsg = serverConnection.getFunctionResponseMessage();
    ChunkedMessage chunkedResponseMsg = serverConnection.getChunkedResponseMessage();
    if (functionResponseMsg.headerHasBeenSent()) {
      functionResponseMsg.setServerConnection(serverConnection);
      functionResponseMsg.setNumberOfParts(2);
      functionResponseMsg.setLastChunkAndNumParts(true, 2);
      functionResponseMsg.addObjPart(e);
      functionResponseMsg.addStringPart(getExceptionTrace(e));
      if (logger.isDebugEnabled()) {
        logger.debug("{}: Sending exception chunk while reply in progress: {}",
            serverConnection.getName(), e.getMessage(), e);
      }
      functionResponseMsg.sendChunk(serverConnection);
    } else {
      chunkedResponseMsg.setServerConnection(serverConnection);
      chunkedResponseMsg.setMessageType(messageType);
      chunkedResponseMsg.setNumberOfParts(2);
      chunkedResponseMsg.setLastChunkAndNumParts(true, 2);
      chunkedResponseMsg.setTransactionId(origMsg.getTransactionId());
      chunkedResponseMsg.sendHeader();
      chunkedResponseMsg.addObjPart(e);
      chunkedResponseMsg.addStringPart(getExceptionTrace(e));
      if (logger.isDebugEnabled()) {
        logger.debug("{}: Sending exception chunk: {}", serverConnection.getName(), e.getMessage(),
            e);
      }
      chunkedResponseMsg.sendChunk(serverConnection);
    }
  }

  protected static void writeFunctionResponseError(Message origMsg, int messageType, String message,
      ServerConnection servConn) throws IOException {
    ChunkedMessage functionResponseMsg = servConn.getFunctionResponseMessage();
    ChunkedMessage chunkedResponseMsg = servConn.getChunkedResponseMessage();
    if (functionResponseMsg.headerHasBeenSent()) {
      functionResponseMsg.setNumberOfParts(1);
      functionResponseMsg.setLastChunk(true);
      functionResponseMsg.addStringPart(message);
      if (logger.isDebugEnabled()) {
        logger.debug("{}: Sending Error chunk while reply in progress: {}", servConn.getName(),
            message);
      }
      functionResponseMsg.sendChunk(servConn);
    } else {
      chunkedResponseMsg.setMessageType(messageType);
      chunkedResponseMsg.setNumberOfParts(1);
      chunkedResponseMsg.setLastChunk(true);
      chunkedResponseMsg.setTransactionId(origMsg.getTransactionId());
      chunkedResponseMsg.sendHeader();
      chunkedResponseMsg.addStringPart(message);
      if (logger.isDebugEnabled()) {
        logger.debug("{}: Sending Error chunk: {}", servConn.getName(), message);
      }
      chunkedResponseMsg.sendChunk(servConn);
    }
  }

  protected static void writeKeySetErrorResponse(Message origMsg, int messageType, String message,
      ServerConnection servConn) throws IOException {
    // Send chunked response header identifying error message
    ChunkedMessage chunkedResponseMsg = servConn.getKeySetResponseMessage();
    if (logger.isDebugEnabled()) {
      logger.debug("{}: Sending error message header type: {} transaction: {}", servConn.getName(),
          messageType, origMsg.getTransactionId());
    }
    chunkedResponseMsg.setMessageType(messageType);
    chunkedResponseMsg.setTransactionId(origMsg.getTransactionId());
    chunkedResponseMsg.sendHeader();
    // Send actual error
    if (logger.isDebugEnabled()) {
      logger.debug("{}: Sending error message chunk: {}", servConn.getName(), message);
    }
    chunkedResponseMsg.setNumberOfParts(1);
    chunkedResponseMsg.setLastChunk(true);
    chunkedResponseMsg.addStringPart(message);
    chunkedResponseMsg.sendChunk(servConn);
  }

  static Message readRequest(ServerConnection servConn) {
    Message requestMsg = null;
    try {
      requestMsg = servConn.getRequestMessage();
      requestMsg.receive(servConn, MAX_INCOMING_DATA, INCOMING_DATA_LIMITER, INCOMING_MSG_LIMITER);
      return requestMsg;
    } catch (EOFException eof) {
      handleEOFException(null, servConn, eof);
      // TODO: Check if there is any need for explicitly returning

    } catch (InterruptedIOException e) { // Solaris only
      handleInterruptedIOException(servConn, e);

    } catch (IOException e) {
      handleIOException(null, servConn, e);

    } catch (DistributedSystemDisconnectedException e) {
      handleShutdownException(null, servConn, e);

    } catch (VirtualMachineError err) {
      SystemFailure.initiateFailure(err);
      // If this ever returns, rethrow the error. We're poisoned
      // now, so don't let this thread continue.
      throw err;
    } catch (Throwable e) {
      SystemFailure.checkFailure();
      handleThrowable(null, servConn, e);
    }
    return requestMsg;
  }

  protected static void fillAndSendRegisterInterestResponseChunks(LocalRegion region, Object riKey,
      int interestType, InterestResultPolicy policy, ServerConnection servConn) throws IOException {
    fillAndSendRegisterInterestResponseChunks(region, riKey, interestType, false, policy, servConn);
  }

  /**
   * serializeValues is unused for clients < GFE_80
   */
  protected static void fillAndSendRegisterInterestResponseChunks(LocalRegion region, Object riKey,
      int interestType, boolean serializeValues, InterestResultPolicy policy,
      ServerConnection servConn) throws IOException {
    // Client is not interested.
    if (policy.isNone()) {
      sendRegisterInterestResponseChunk(region, riKey, new ArrayList(), true, servConn);
      return;
    }
    if (policy.isKeysValues() && servConn.getClientVersion().compareTo(Version.GFE_80) >= 0) {
      handleKeysValuesPolicy(region, riKey, interestType, serializeValues, servConn);
      return;
    }
    if (riKey instanceof List) {
      handleList(region, (List) riKey, policy, servConn);
      return;
    }
    if (!(riKey instanceof String)) {
      handleSingleton(region, riKey, policy, servConn);
      return;
    }

    switch (interestType) {
      case InterestType.OQL_QUERY:
        // Not supported yet
        throw new InternalGemFireError(
            "not yet supported");

      case InterestType.FILTER_CLASS:
        throw new InternalGemFireError(
            "not yet supported");

      case InterestType.REGULAR_EXPRESSION:
        String regEx = (String) riKey;
        if (regEx.equals(".*")) {
          handleAllKeys(region, policy, servConn);
        } else {
          handleRegEx(region, regEx, policy, servConn);
        }
        break;

      case InterestType.KEY:
        if (riKey.equals("ALL_KEYS")) {
          handleAllKeys(region, policy, servConn);
        } else {
          handleSingleton(region, riKey, policy, servConn);
        }
        break;

      default:
        throw new InternalGemFireError(
            "unknown interest type");
    }
  }

  private static void handleKeysValuesPolicy(LocalRegion region, Object riKey, int interestType,
      boolean serializeValues, ServerConnection servConn) throws IOException {
    if (riKey instanceof List) {
      handleKVList(region, (List) riKey, serializeValues, servConn);
      return;
    }
    if (!(riKey instanceof String)) {
      handleKVSingleton(region, riKey, serializeValues, servConn);
      return;
    }

    switch (interestType) {
      case InterestType.OQL_QUERY:
        throw new InternalGemFireError(
            "not yet supported");

      case InterestType.FILTER_CLASS:
        throw new InternalGemFireError(
            "not yet supported");

      case InterestType.REGULAR_EXPRESSION:
        String regEx = (String) riKey;
        if (regEx.equals(".*")) {
          handleKVAllKeys(region, null, serializeValues, servConn);
        } else {
          handleKVAllKeys(region, regEx, serializeValues, servConn);
        }
        break;

      case InterestType.KEY:
        if (riKey.equals("ALL_KEYS")) {
          handleKVAllKeys(region, null, serializeValues, servConn);
        } else {
          handleKVSingleton(region, riKey, serializeValues, servConn);
        }
        break;

      default:
        throw new InternalGemFireError(
            "unknown interest type");
    }
  }

  /**
   * @param list is a List of entry keys
   */
  private static void sendRegisterInterestResponseChunk(Region region, Object riKey, List list,
      boolean lastChunk, ServerConnection servConn) throws IOException {
    ChunkedMessage chunkedResponseMsg = servConn.getRegisterInterestResponseMessage();
    chunkedResponseMsg.setNumberOfParts(1);
    chunkedResponseMsg.setLastChunk(lastChunk);
    chunkedResponseMsg.addObjPart(list, false);
    String regionName = region == null ? " null " : region.getFullPath();
    if (logger.isDebugEnabled()) {
      logger.debug(
          "{}: Sending{}register interest response chunk for region: {} for keys: {} chunk=<{}>",
          servConn.getName(), lastChunk ? " last " : " ", regionName, riKey, chunkedResponseMsg);
    }

    chunkedResponseMsg.sendChunk(servConn);
  }

  /**
   * Determines whether keys for destroyed entries (tombstones) should be sent to clients in
   * register-interest results.
   *
   * @return true if tombstones should be sent to the client
   */
  private static boolean sendTombstonesInRIResults(ServerConnection servConn,
      InterestResultPolicy policy) {
    return policy == InterestResultPolicy.KEYS_VALUES
        && servConn.getClientVersion().compareTo(Version.GFE_80) >= 0;
  }

  /**
   * Process an interest request involving a list of keys
   *
   * @param region the region
   * @param keyList the list of keys
   * @param policy the policy
   */
  private static void handleList(LocalRegion region, List keyList, InterestResultPolicy policy,
      ServerConnection servConn) throws IOException {
    if (region instanceof PartitionedRegion) {
      // too bad java doesn't provide another way to do this...
      handleListPR((PartitionedRegion) region, keyList, policy, servConn);
      return;
    }
    List newKeyList = new ArrayList(MAXIMUM_CHUNK_SIZE);
    // Handle list of keys
    if (region != null) {
      for (Object entryKey : keyList) {
        if (region.containsKey(entryKey)
            || sendTombstonesInRIResults(servConn, policy) && region.containsTombstone(entryKey)) {

          appendInterestResponseKey(region, keyList, entryKey, newKeyList, servConn);
        }
      }
    }
    // Send the last chunk (the only chunk for individual and list keys)
    // always send it back, even if the list is of zero size.
    sendRegisterInterestResponseChunk(region, keyList, newKeyList, true, servConn);
  }

  /**
   * Handles both RR and PR cases
   */
  @SuppressWarnings(value = "NP_NULL_PARAM_DEREF",
      justification = "Null value handled in sendNewRegisterInterestResponseChunk()")
  private static void handleKVSingleton(LocalRegion region, Object entryKey,
      boolean serializeValues, ServerConnection servConn) throws IOException {
    VersionedObjectList values = new VersionedObjectList(MAXIMUM_CHUNK_SIZE, true,
        region == null || region.getAttributes().getConcurrencyChecksEnabled(), serializeValues);

    if (region != null) {
      if (region.containsKey(entryKey) || region.containsTombstone(entryKey)) {
        VersionTagHolder versionHolder = createVersionTagHolder();
        ClientProxyMembershipID id = servConn == null ? null : servConn.getProxyID();
        // From Get70.getValueAndIsObject()
        Object data = region.get(entryKey, null, true, true, true, id, versionHolder, true);
        VersionTag vt = versionHolder.getVersionTag();

        updateValues(values, entryKey, data, vt);
      }
    }
    // Send the last chunk (the only chunk for individual and list keys)
    // always send it back, even if the list is of zero size.
    sendNewRegisterInterestResponseChunk(region, entryKey, values, true, servConn);
  }

  /**
   * Process an interest request consisting of a single key
   *
   * @param region the region
   * @param entryKey the key
   * @param policy the policy
   */
  private static void handleSingleton(LocalRegion region, Object entryKey,
      InterestResultPolicy policy, ServerConnection servConn) throws IOException {
    List keyList = new ArrayList(1);
    if (region != null) {
      if (region.containsKey(entryKey)
          || sendTombstonesInRIResults(servConn, policy) && region.containsTombstone(entryKey)) {
        appendInterestResponseKey(region, entryKey, entryKey, keyList, servConn);
      }
    }
    // Send the last chunk (the only chunk for individual and list keys)
    // always send it back, even if the list is of zero size.
    sendRegisterInterestResponseChunk(region, entryKey, keyList, true, servConn);
  }

  /**
   * Process an interest request of type ALL_KEYS
   *
   * @param region the region
   * @param policy the policy
   */
  private static void handleAllKeys(LocalRegion region, InterestResultPolicy policy,
      ServerConnection servConn) throws IOException {
    List keyList = new ArrayList(MAXIMUM_CHUNK_SIZE);
    if (region != null) {
      for (Object entryKey : region.keySet(sendTombstonesInRIResults(servConn, policy))) {
        appendInterestResponseKey(region, "ALL_KEYS", entryKey, keyList, servConn);
      }
    }
    // Send the last chunk (the only chunk for individual and list keys)
    // always send it back, even if the list is of zero size.
    sendRegisterInterestResponseChunk(region, "ALL_KEYS", keyList, true, servConn);
  }

  private static void handleKVAllKeys(LocalRegion region, String regex, boolean serializeValues,
      ServerConnection servConn) throws IOException {

    if (region instanceof PartitionedRegion) {
      handleKVKeysPR((PartitionedRegion) region, regex, serializeValues, servConn);
      return;
    }

    VersionedObjectList values = new VersionedObjectList(MAXIMUM_CHUNK_SIZE, true,
        region == null || region.getAttributes().getConcurrencyChecksEnabled(), serializeValues);

    if (region != null) {

      Pattern keyPattern = null;
      if (regex != null) {
        keyPattern = Pattern.compile(regex);
      }

      for (Object key : region.keySet(true)) {
        VersionTagHolder versionHolder = createVersionTagHolder();
        if (keyPattern != null) {
          if (!(key instanceof String)) {
            // key is not a String, cannot apply regex to this entry
            continue;
          }
          if (!keyPattern.matcher((String) key).matches()) {
            // key does not match the regex, this entry should not be
            // returned.
            continue;
          }
        }

        ClientProxyMembershipID id = servConn == null ? null : servConn.getProxyID();
        Object data = region.get(key, null, true, true, true, id, versionHolder, true);
        VersionTag versionTag = versionHolder.getVersionTag();
        updateValues(values, key, data, versionTag);

        if (values.size() == MAXIMUM_CHUNK_SIZE) {
          sendNewRegisterInterestResponseChunk(region, regex != null ? regex : "ALL_KEYS", values,
              false, servConn);
          values.clear();
        }
      } // for
    } // if

    // Send the last chunk (the only chunk for individual and list keys)
    // always send it back, even if the list is of zero size.
    sendNewRegisterInterestResponseChunk(region, regex != null ? regex : "ALL_KEYS", values, true,
        servConn);
  }

  private static void handleKVKeysPR(PartitionedRegion region, Object keyInfo,
      boolean serializeValues, ServerConnection servConn) throws IOException {

    VersionedObjectList values = new VersionedObjectList(MAXIMUM_CHUNK_SIZE, true,
        region.getConcurrencyChecksEnabled(), serializeValues);

    if (keyInfo instanceof List) {
      HashMap<Integer, HashSet> bucketKeys = new HashMap<>();
      for (Object key : (List) keyInfo) {
        int id = PartitionedRegionHelper.getHashKey(region, null, key, null, null);
        if (bucketKeys.containsKey(id)) {
          bucketKeys.get(id).add(key);
        } else {
          HashSet<Object> keys = new HashSet<>();
          keys.add(key);
          bucketKeys.put(id, keys);
        }
      }
      region.fetchEntries(bucketKeys, values, servConn);
    } else { // keyInfo is a String
      region.fetchEntries((String) keyInfo, values, servConn);
    }

    // Send the last chunk (the only chunk for individual and list keys)
    // always send it back, even if the list is of zero size.
    sendNewRegisterInterestResponseChunk(region, keyInfo != null ? keyInfo : "ALL_KEYS", values,
        true, servConn);
  }

  /**
   * Copied from Get70.getValueAndIsObject(), except a minor change. (Make the method static instead
   * of copying it here?)
   */
  private static void updateValues(VersionedObjectList values, Object key, Object value,
      VersionTag versionTag) {
    boolean isObject = true;

    // If the value in the VM is a CachedDeserializable,
    // get its value. If it is Token.REMOVED, Token.DESTROYED,
    // Token.INVALID, or Token.LOCAL_INVALID
    // set it to null. If it is NOT_AVAILABLE, get the value from
    // disk. If it is already a byte[], set isObject to false.
    boolean wasInvalid = false;
    if (value instanceof CachedDeserializable) {
      value = ((CachedDeserializable) value).getValue();
    } else if (isRemovalToken(value)) {
      value = null;
    } else if (value == Token.INVALID || value == Token.LOCAL_INVALID) {
      value = null; // fix for bug 35884
      wasInvalid = true;
    } else if (value instanceof byte[]) {
      isObject = false;
    }
    boolean keyNotPresent = !wasInvalid && (value == null || value == Token.TOMBSTONE);

    if (keyNotPresent) {
      values.addObjectPartForAbsentKey(key, value, versionTag);
    } else {
      values.addObjectPart(key, value, isObject, versionTag);
    }
  }

  private static boolean isRemovalToken(final Object value) {
    return value == Token.REMOVED_PHASE1 || value == Token.REMOVED_PHASE2
        || value == Token.DESTROYED || value == Token.TOMBSTONE;
  }

  public static void appendNewRegisterInterestResponseChunkFromLocal(LocalRegion region,
      VersionedObjectList values, Object riKeys, Set keySet, ServerConnection servConn)
      throws IOException {
    ClientProxyMembershipID requestingClient = servConn == null ? null : servConn.getProxyID();
    for (Object key : keySet) {
      VersionTagHolder versionHolder = createVersionTagHolder();

      Object value = region.get(key, null, true, true, true, requestingClient, versionHolder, true);

      updateValues(values, key, value, versionHolder.getVersionTag());

      if (values.size() == MAXIMUM_CHUNK_SIZE) {
        // Send the chunk and clear the list
        // values.setKeys(null); // Now we need to send keys too.
        sendNewRegisterInterestResponseChunk(region, riKeys != null ? riKeys : "ALL_KEYS", values,
            false, servConn);
        values.clear();
      }
    } // for
  }

  public static void appendNewRegisterInterestResponseChunk(LocalRegion region,
      VersionedObjectList values, Object riKeys, Set<Map.Entry> set, ServerConnection servConn)
      throws IOException {
    for (Entry entry : set) {
      if (entry instanceof Region.Entry) { // local entries
        VersionTag vt;
        Object key;
        Object value;
        if (entry instanceof EntrySnapshot) {
          vt = ((EntrySnapshot) entry).getVersionTag();
          key = ((EntrySnapshot) entry).getRegionEntry().getKey();
          value = ((EntrySnapshot) entry).getRegionEntry().getValue(null);
          updateValues(values, key, value, vt);
        } else {
          VersionStamp vs = ((NonTXEntry) entry).getRegionEntry().getVersionStamp();
          vt = vs == null ? null : vs.asVersionTag();
          key = entry.getKey();
          value = ((NonTXEntry) entry).getRegionEntry().getValueRetain(region, true);
          try {
            updateValues(values, key, value, vt);
          } finally {
            OffHeapHelper.release(value);
          }
        }
      } else { // Map.Entry (remote entries)
        List list = (List) entry.getValue();
        Object value = list.get(0);
        VersionTag tag = (VersionTag) list.get(1);
        updateValues(values, entry.getKey(), value, tag);
      }
      if (values.size() == MAXIMUM_CHUNK_SIZE) {
        // Send the chunk and clear the list
        sendNewRegisterInterestResponseChunk(region, riKeys != null ? riKeys : "ALL_KEYS", values,
            false, servConn);
        values.clear();
      }
    } // for
  }

  public static void sendNewRegisterInterestResponseChunk(LocalRegion region, Object riKey,
      VersionedObjectList list, boolean lastChunk, ServerConnection servConn) throws IOException {
    ChunkedMessage chunkedResponseMsg = servConn.getRegisterInterestResponseMessage();
    chunkedResponseMsg.setNumberOfParts(1);
    chunkedResponseMsg.setLastChunk(lastChunk);
    chunkedResponseMsg.addObjPart(list, false);
    String regionName = region == null ? " null " : region.getFullPath();
    if (logger.isDebugEnabled()) {
      logger.debug(
          "{}: Sending{}register interest response chunk for region: {} for keys: {} chunk=<{}>",
          servConn.getName(), lastChunk ? " last " : " ", regionName, riKey, chunkedResponseMsg);
    }
    chunkedResponseMsg.sendChunk(servConn);
  }

  /**
   * Process an interest request of type {@link InterestType#REGULAR_EXPRESSION}
   */
  private static void handleRegEx(LocalRegion region, String regex, InterestResultPolicy policy,
      ServerConnection servConn) throws IOException {
    if (region instanceof PartitionedRegion) {
      // too bad java doesn't provide another way to do this...
      handleRegExPR((PartitionedRegion) region, regex, policy, servConn);
      return;
    }
    List keyList = new ArrayList(MAXIMUM_CHUNK_SIZE);
    // Handle the regex pattern
    if (region != null) {
      Pattern keyPattern = Pattern.compile(regex);
      for (Object entryKey : region.keySet(sendTombstonesInRIResults(servConn, policy))) {
        if (!(entryKey instanceof String)) {
          // key is not a String, cannot apply regex to this entry
          continue;
        }
        if (!keyPattern.matcher((String) entryKey).matches()) {
          // key does not match the regex, this entry should not be returned.
          continue;
        }

        appendInterestResponseKey(region, regex, entryKey, keyList, servConn);
      }
    }
    // Send the last chunk (the only chunk for individual and list keys)
    // always send it back, even if the list is of zero size.
    sendRegisterInterestResponseChunk(region, regex, keyList, true, servConn);
  }

  /**
   * Process an interest request of type {@link InterestType#REGULAR_EXPRESSION}
   */
  private static void handleRegExPR(final PartitionedRegion region, final String regex,
      final InterestResultPolicy policy, final ServerConnection servConn) throws IOException {
    final List keyList = new ArrayList(MAXIMUM_CHUNK_SIZE);
    region.getKeysWithRegEx(regex, sendTombstonesInRIResults(servConn, policy),
        new PartitionedRegion.SetCollector() {
          @Override
          public void receiveSet(Set theSet) throws IOException {
            appendInterestResponseKeys(region, regex, theSet, keyList, servConn);
          }
        });
    // Send the last chunk (the only chunk for individual and list keys)
    // always send it back, even if the list is of zero size.
    sendRegisterInterestResponseChunk(region, regex, keyList, true, servConn);
  }

  /**
   * Process an interest request involving a list of keys
   */
  private static void handleListPR(final PartitionedRegion region, final List keyList,
      final InterestResultPolicy policy, final ServerConnection servConn) throws IOException {
    final List newKeyList = new ArrayList(MAXIMUM_CHUNK_SIZE);
    region.getKeysWithList(keyList, sendTombstonesInRIResults(servConn, policy),
        new PartitionedRegion.SetCollector() {
          @Override
          public void receiveSet(Set theSet) throws IOException {
            appendInterestResponseKeys(region, keyList, theSet, newKeyList, servConn);
          }
        });
    // Send the last chunk (the only chunk for individual and list keys)
    // always send it back, even if the list is of zero size.
    sendRegisterInterestResponseChunk(region, keyList, newKeyList, true, servConn);
  }

  private static void handleKVList(final LocalRegion region, final List keyList,
      boolean serializeValues, final ServerConnection servConn) throws IOException {

    if (region instanceof PartitionedRegion) {
      handleKVKeysPR((PartitionedRegion) region, keyList, serializeValues, servConn);
      return;
    }
    VersionedObjectList values = new VersionedObjectList(MAXIMUM_CHUNK_SIZE, true,
        region == null || region.getAttributes().getConcurrencyChecksEnabled(), serializeValues);

    // Handle list of keys
    if (region != null) {

      for (Object key : keyList) {
        if (region.containsKey(key) || region.containsTombstone(key)) {
          VersionTagHolder versionHolder = createVersionTagHolder();

          ClientProxyMembershipID id = servConn == null ? null : servConn.getProxyID();
          Object data = region.get(key, null, true, true, true, id, versionHolder, true);
          VersionTag versionTag = versionHolder.getVersionTag();
          updateValues(values, key, data, versionTag);

          if (values.size() == MAXIMUM_CHUNK_SIZE) {
            // Send the chunk and clear the list
            // values.setKeys(null); // Now we need to send keys too.
            sendNewRegisterInterestResponseChunk(region, keyList, values, false, servConn);
            values.clear();
          }
        }
      }
    }
    // Send the last chunk (the only chunk for individual and list keys)
    // always send it back, even if the list is of zero size.
    sendNewRegisterInterestResponseChunk(region, keyList, values, true, servConn);
  }

  private static VersionTagHolder createVersionTagHolder() {
    VersionTagHolder versionHolder = new VersionTagHolder();
    versionHolder.setOperation(Operation.GET_FOR_REGISTER_INTEREST);
    return versionHolder;
  }

  /**
   * Append an interest response
   *
   * @param region the region (for debugging)
   * @param riKey the registerInterest "key" (what the client is interested in)
   * @param entryKey key we're responding to
   * @param list list to append to
   */
  private static void appendInterestResponseKey(LocalRegion region, Object riKey, Object entryKey,
      List list, ServerConnection servConn) throws IOException {
    list.add(entryKey);
    if (logger.isDebugEnabled()) {
      logger.debug("{}: appendInterestResponseKey <{}>; list size was {}; region: {}",
          servConn.getName(), entryKey, list.size(), region.getFullPath());
    }
    if (list.size() == MAXIMUM_CHUNK_SIZE) {
      // Send the chunk and clear the list
      sendRegisterInterestResponseChunk(region, riKey, list, false, servConn);
      list.clear();
    }
  }

  private static void appendInterestResponseKeys(LocalRegion region, Object riKey,
      Collection entryKeys, List collector, ServerConnection servConn) throws IOException {
    for (final Object entryKey : entryKeys) {
      appendInterestResponseKey(region, riKey, entryKey, collector, servConn);
    }
  }
}


text:
package com.mkyong.form.validator;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.mkyong.form.model.User;
import com.mkyong.form.service.UserService;

//http://docs.spring.io/spring/docs/current/spring-framework-reference/html/validation.html#validation-mvc-configuring
@Component
public class UserFormValidator implements Validator {

	@Autowired
	@Qualifier("emailValidator")
	EmailValidator emailValidator;

	@Autowired
	UserService userService;

	@Override
	public boolean supports(Class<?> clazz) {
		return User.class.equals(clazz);
	}

	@Override
	public void validate(Object target, Errors errors) {

		User user = (User) target;

		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "NotEmpty.userForm.name");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", "NotEmpty.userForm.email");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "address", "NotEmpty.userForm.address");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "NotEmpty.userForm.password");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "confirmPassword","NotEmpty.userForm.confirmPassword");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "sex", "NotEmpty.userForm.sex");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "country", "NotEmpty.userForm.country");

		if(!emailValidator.valid(user.getEmail())){
			errors.rejectValue("email", "Pattern.userForm.email");
		}

		if(user.getNumber()==null || user.getNumber()<=0){
			errors.rejectValue("number", "NotEmpty.userForm.number");
		}

		if(user.getCountry().equalsIgnoreCase("none")){
			errors.rejectValue("country", "NotEmpty.userForm.country");
		}

		if (!user.getPassword().equals(user.getConfirmPassword())) {
			errors.rejectValue("confirmPassword", "Diff.userform.confirmPassword");
		}

		if (user.getFramework() == null || user.getFramework().size() < 2) {
			errors.rejectValue("framework", "Valid.userForm.framework");
		}

		if (user.getSkill() == null || user.getSkill().size() < 3) {
			errors.rejectValue("skill", "Valid.userForm.skill");
		}

	}

}


text:
@interface IndicatorView : UIView

@property (weak, nonatomic) IBOutlet UILabel *titleLabel;

//有加载动画的提示view time_sec 为0 时不隐藏
+ (void)showLoadViewAt:(UIView * )superView
             withTitle:(NSString *)title
             hideAfter:(CGFloat)time_sec;

//只有文字的提示
+ (void)showIndicatorWith:(NSString *)title
                       at:(UIView * )superView
                hideAfter:(CGFloat)time_sec;

//隐藏提示view
+ (void)hiddenLoadViewAt:(UIView *)superview
               according:(NSString *)title;
@end


text:
using System.Collections.Generic;
using CSC.CSClassroom.Model.Users;

namespace CSC.CSClassroom.WebApp.ViewModels.Shared
{
	/// <summary>
	/// A list of users to display.
	/// </summary>
	public class UserListViewModel
	{
		/// <summary>
		/// The users to display.
		/// </summary>
		public IList<User> Users { get; }

		/// <summary>
		/// The actions to show.
		/// </summary>
		public IList<UserAction> Actions { get; }

		/// <summary>
		/// Constructor.
		/// </summary>
		public UserListViewModel(IList<User> users, IList<UserAction> actions)
		{
			Users = users;
			Actions = actions;
		}
	}
}


text: <ce-file-upload ce-upload="upload(data)"></ce-file-upload>


text:
package com.imgix.test;

import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;

import com.imgix.URLBuilder;
import com.imgix.URLHelper;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.*;

@RunWith(JUnit4.class)
public class TestAll {

  @Rule public ExpectedException exception = ExpectedException.none();
  public static ExpectedException urlException = ExpectedException.none();

  @Test
  public void testURLBuilderRaisesExceptionOnNoDomains() {
    exception.expect(IllegalArgumentException.class);
    new URLBuilder(new String());
  }

  @Test
  public void testURLBuilderUsesHttpsByDefault() {
    // Test `URLBuilder` uses https by default.
    // This test uses the single-parameter constructor.
    // The single parameter constructor is the only constructor
    // where "default" makes sense. E.g. calling
    // `URLBuilder("example.imgix.net", true)`
    // passes `true` to the constructor explicitly.
    URLBuilder ub = new URLBuilder("example.imgix.net");
    String expected = "https://example.imgix.net/image/file.png?ixlib=java-" + URLBuilder.VERSION;
    assertEquals(expected, ub.createURL("image/file.png"));
  }

  @Test
  public void testSetUseHttpsFalse() {
    // Test `setUseHttps` to `false`.
    URLBuilder ub = new URLBuilder("example.imgix.net");
    ub.setUseHttps(false);
    String expected = "http://example.imgix.net/image/file.png?ixlib=java-" + URLBuilder.VERSION;
    assertEquals(expected, ub.createURL("image/file.png"));
  }

  @Test
  public void testSetUseHttpsTrue() {
    // Test `setUseHttps` to `true`.
    URLBuilder ub = new URLBuilder("example.imgix.net");
    ub.setUseHttps(true);
    String expected = "https://example.imgix.net/image/file.png?ixlib=java-" + URLBuilder.VERSION;
    assertEquals(expected, ub.createURL("image/file.png"));
  }

  @Test
  public void testHelperBuildAbsolutePath() {
    URLHelper uh = new URLHelper("securejackangers.imgix.net", "/example/chester.png", "http");
    assertEquals("http://securejackangers.imgix.net/example/chester.png", uh.getURL());
  }

  @Test
  public void testHelperBuildRelativePath() {
    URLHelper uh = new URLHelper("securejackangers.imgix.net", "example/chester.png", "http");
    assertEquals("http://securejackangers.imgix.net/example/chester.png", uh.getURL());
  }

  @Test
  public void testHelperBuildNestedPath() {
    URLHelper uh =
        new URLHelper(
            "securejackangers.imgix.net", "http://www.somedomain.com/example/chester.png", "http");
    assertEquals(
        "http://securejackangers.imgix.net/http%3A%2F%2Fwww.somedomain.com%2Fexample%2Fchester.png",
        uh.getURL());
  }

  @Test
  public void testUnmutatedUrlParams() {
    String domain = "test.imgix.net";
    String path = "image.png";
    URLBuilder ub = new URLBuilder(domain, true, "", true);
    HashMap<String, String> nullParameters = new HashMap<String, String>();
    ub.createURL(path, nullParameters);
    assertTrue(nullParameters.isEmpty());
  }

  @RunWith(Parameterized.class)
  public static class TestHelperBuildPathWithParams {
    @Parameters(name = "''{0}' URL generated correctly'")
    public static Iterable<Object[]> data() {
      return Arrays.asList(
          new Object[][] {
            {
              "Nested Path With Params",
              "http://www.somedomain.com/example/chester.png",
              "http://securejackangers.imgix.net/http%3A%2F%2Fwww.somedomain.com%2Fexample%2Fchester.png?w=500"
            },
            {
              "Relative Path With Params",
              "example/chester.png",
              "http://securejackangers.imgix.net/example/chester.png?w=500"
            },
            {
              "Relative Path With Unencoded Space",
              "example/chester 1.png",
              "http://securejackangers.imgix.net/example/chester%201.png?w=500"
            },
            {
              "Relative Path With Unencoded Plus",
              "example/chester" + "+1" + ".png",
              "http://securejackangers.imgix.net/example/chester%2B1.png?w=500"
            },
            {
              "Relative Path With Unencoded Colon",
              "example/chester" + ":1" + ".png",
              "http://securejackangers.imgix.net/example/chester%3A1.png?w=500"
            },
            {
              "Relative Path With Unencoded Question Mark",
              "example/chester" + "?1" + ".png",
              "http://securejackangers.imgix.net/example/chester%3F1.png?w=500"
            },
            {
              "Relative Path With Unencoded Hash",
              "example/chester" + "#1" + ".png",
              "http://securejackangers.imgix.net/example/chester%231.png?w=500"
            },
            {
              "Relative Path With Unencoded Reserved Characters",
              "example/chester" + "/&$+,:;=?@#.jpg",
              "http://securejackangers.imgix.net/example/chester/%26%24%2B%2C%3A%3B%3D%3F%40%23.jpg?w=500"
            },
            {
              "Relative Path With Unencoded Reserved Delimiters",
              "example/chester" + "/ <>[]{}|\\^%.jpg",
              "http://securejackangers.imgix.net/example/chester/%20%3C%3E%5B%5D%7B%7D%7C%5C%5E%25.jpg?w=500"
            },
            {
              "Relative Path With Unencoded Unicode Characters",
              "example/chester" + "/ساندویچ.jpg",
              "http://securejackangers.imgix.net/example/chester/%D8%B3%D8%A7%D9%86%D8%AF%D9%88%DB%8C%DA%86.jpg?w=500"
            },
            {
              "Absolute Path With Params",
              "/example/chester.png",
              "http://securejackangers.imgix.net/example/chester.png?w=500"
            },
            // TODO(luis): enable encoded path suppport at a later date
            // {
            //   "Absolute Path With Encoded Unicode Characters",
            //
            // "/example/I%20cann%C3%B8t%20bel%C3%AE%C3%A9v%E2%88%91%20it%20wor%EF%A3%BFs!%20%F0%9F%98%B1",
            //
            // "http://securejackangers.imgix.net/example/I%20cann%C3%B8t%20bel%C3%AE%C3%A9v%E2%88%91%20it%20wor%EF%A3%BFs!%20%F0%9F%98%B1?w=500"
            // },
            {
              "Absolute Path With Unencoded Unicode Characters",
              "/example/I cannøt belîév∑ it wors! 😱",
              "http://securejackangers.imgix.net/example/I%20cann%C3%B8t%20bel%C3%AE%C3%A9v%E2%88%91%20it%20wor%EF%A3%BFs!%20%F0%9F%98%B1?w=500"
            },
          });
    }

    @Parameter(0)
    public String tInputName;

    @Parameter(1)
    public String tInput;

    @Parameter(2)
    public String tExpected;

    public void testHelperBuildPathWithParams(String input, String expected) {
      tInput = input;
      tExpected = expected;
    }

    @Test
    public void test() {
      URLHelper uh = new URLHelper("securejackangers.imgix.net", tInput, "http");
      uh.setParameter("w", 500);
      assertThat("${tInputName} is not ${tExpected}", uh.getURL(), containsString(tExpected));
    }
  }

  @Test
  public void testHelperBuildSignedURLWithHashMapParams() {

    Map<String, String> params = new HashMap<String, String>();
    params.put("w", "500");

    URLHelper uh =
        new URLHelper(
            "securejackangers.imgix.net", "example/chester.png", "http", "Q61NvXIy", params);
    assertEquals(
        "http://securejackangers.imgix.net/example/chester.png?w=500&s=787b9057d5c077fe168b4849737d8a90",
        uh.getURL());
  }

  @Test
  public void testHelperBuildSignedURLWithHashSetterParams() {
    URLHelper uh =
        new URLHelper("securejackangers.imgix.net", "example/chester.png", "http", "Q61NvXIy");

    uh.setParameter("w", 500);

    assertEquals(
        "http://securejackangers.imgix.net/example/chester.png?w=500&s=787b9057d5c077fe168b4849737d8a90",
        uh.getURL());
  }

  @Test
  public void testHelperBuildSignedURLWithWebProxyWithNoEncoding() {
    URLHelper uh =
        new URLHelper(
            "jackttl2.imgix.net",
            "http://a.abcnews.com/assets/images/navigation/abc-logo.png?r=20",
            "http",
            "JHrM2ezd");
    assertEquals(
        "http://jackttl2.imgix.net/http%3A%2F%2Fa.abcnews.com%2Fassets%2Fimages%2Fnavigation%2Fabc-logo.png%3Fr%3D20?s=cf82defe3436a957262d0e64c21e72f9",
        uh.getURL());
  }

  @Test
  public void testHelperBuildSignedURLWithWebProxyWithEncoding() {
    URLHelper uh =
        new URLHelper(
            "jackttl2.imgix.net",
            "http%3A%2F%2Fa.abcnews.com%2Fassets%2Fimages%2Fnavigation%2Fabc-logo.png%3Fr%3D20",
            "http",
            "JHrM2ezd");
    assertEquals(
        "http://jackttl2.imgix.net/http%3A%2F%2Fa.abcnews.com%2Fassets%2Fimages%2Fnavigation%2Fabc-logo.png%3Fr%3D20?s=cf82defe3436a957262d0e64c21e72f9",
        uh.getURL());
  }

  @Test
  public void testBuildSignedURLWithWebProxyWithUnencodedInput() {
    URLHelper uh =
        new URLHelper(
            "imgix-library-web-proxy-test-source.imgix.net",
            "https://paulstraw.imgix.net/colon:test/benice.jpg",
            "https",
            "qN5VOqaLGQUFzETO");
    assertEquals(
        "https://imgix-library-web-proxy-test-source.imgix.net/https%3A%2F%2Fpaulstraw.imgix.net%2Fcolon%3Atest%2Fbenice.jpg?s=175a054524d75840735855b9263be591",
        uh.getURL());
  }

  @Test
  public void testBuilderWithFullyQualifiedURL() {
    URLBuilder ub = new URLBuilder("my-social-network.imgix.net", true, "FOO123bar", false);
    assertEquals(
        "https://my-social-network.imgix.net/http%3A%2F%2Favatars.com%2Fjohn-smith.png?s=493a52f008c91416351f8b33d4883135",
        ub.createURL("http://avatars.com/john-smith.png"));
  }

  @Test
  public void testBuilderWithFullyQualifiedURLAndParameters() {
    URLBuilder ub = new URLBuilder("my-social-network.imgix.net", true, "FOO123bar", false);
    Map<String, String> params = new HashMap<String, String>();
    params.put("w", "400");
    params.put("h", "300");
    assertEquals(
        "https://my-social-network.imgix.net/http%3A%2F%2Favatars.com%2Fjohn-smith.png?h=300&w=400&s=a201fe1a3caef4944dcb40f6ce99e746",
        ub.createURL("http://avatars.com/john-smith.png", params));
  }

  @Test
  public void testHelperBuildSignedUrlWithIxlibParam() {
    URLBuilder ub = new URLBuilder("assets.imgix.net", true, "", true);
    assertTrue(hasURLParameter(ub.createURL("/users/1.png"), "ixlib"));

    ub = new URLBuilder("assets.imgix.net", true, "", false);
    assertFalse(hasURLParameter(ub.createURL("/users/1.png"), "ixlib"));
  }

  @Test
  public void testTargetWidths() {
    ArrayList<Integer> actual = URLBuilder.targetWidths(100, 8192, 0.08);
    int[] targetWidths = {
      100, 116, 135, 156, 181, 210, 244, 283, 328, 380, 441, 512, 594, 689, 799, 927, 1075, 1247,
      1446, 1678, 1946, 2257, 2619, 3038, 3524, 4087, 4741, 5500, 6380, 7401, 8192
    };
    for (int i = 0; i < targetWidths.length; ++i) {
      assertEquals(targetWidths[i], (int) actual.get(i));
    }
  }

  @Test
  public void testParamKeysAreEscaped() {
    Map<String, String> params = new HashMap<String, String>();
    params.put("hello world", "interesting");

    URLHelper uh = new URLHelper("demo.imgix.net", "demo.png", "https", null, params);

    assertEquals("https://demo.imgix.net/demo.png?hello%20world=interesting", uh.getURL());
  }

  @Test
  public void testParamValuesAreEscaped() {
    Map<String, String> params = new HashMap<String, String>();
    params.put("hello_world", "/foo\"> <script>alert(\"hacked\")</script><");

    URLHelper uh = new URLHelper("demo.imgix.net", "demo.png", "https", null, params);

    assertEquals(
        "https://demo.imgix.net/demo.png?hello_world=%2Ffoo%22%3E%20%3Cscript%3Ealert(%22hacked%22)%3C%2Fscript%3E%3C",
        uh.getURL());
  }

  @Test
  public void testBase64ParamVariantsAreBase64Encoded() {
    Map<String, String> params = new HashMap<String, String>();
    params.put("txt64", "I cannøt belîév∑ it wors! 😱");

    URLHelper uh = new URLHelper("demo.imgix.net", "~text", "https", null, params);

    assertEquals(
        "https://demo.imgix.net/~text?txt64=SSBjYW5uw7h0IGJlbMOuw6l24oiRIGl0IHdvcu-jv3MhIPCfmLE",
        uh.getURL());
  }

  @Test
  public void testUnmutatedCreateUrlParams() {
    String DOMAIN = "test.imgix.net";
    String PATH = "image.png";
    URLBuilder defaultClient = new URLBuilder(DOMAIN, true, "", false);
    HashMap<String, String> nullParameters = new HashMap<String, String>();
    String actual = defaultClient.createSrcSet(PATH, nullParameters, 100, 500, 0.1);

    assertTrue(nullParameters.isEmpty());
  }

  @Test
  public void testExtractDomain() {
    String url = "http://jackangers.imgix.net/chester.png";
    assertEquals("jackangers.imgix.net", extractDomain(url));
  }

  @RunWith(Parameterized.class)
  public static class TestInvalidDomain {
    @Parameters(name = "'domain with '{0}' throws exception'")
    public static Iterable<Object[]> data() {
      return Arrays.asList(
          new Object[][] {
            {"Slash", "test.imgix.net/"},
            {"Prepend Scheme", "https://test.imgix.net"},
            {"Append Dash", "test.imgix.net-"},
          });
    }

    @Parameter(0)
    public String tInputName;

    @Parameter(1)
    public String tInput;

    public void testInvalidDomain(String input, String expected) {
      tInput = input;
    }

    @Test(expected = IllegalArgumentException.class)
    public void test() {
      new URLBuilder(tInput);
    }
  }

  private static String extractDomain(String url) {
    try {
      URI parsed = new URI(url);
      String curDomain = parsed.getAuthority();

      return curDomain;
    } catch (URISyntaxException e) {
      e.printStackTrace();
    }

    return "";
  }

  private static boolean hasURLParameter(String url, String param) {
    try {
      URI parsed = new URI(url);
      String query = parsed.getQuery();
      return query != null && query.contains(param);
    } catch (URISyntaxException e) {
      return false;
    }
  }
}


text:
SDL Digital Experience Accelerator CM-side framework content
===

This folder contains all the required building blocks for a DXA installation including:

* Installation scripts/Tools
* DXA CM Content for master/framework and example publications

Using the following msbuild command will package up this content into a /dist folder for importing into a content manager:
```
msbuild ciBuild.proj /t:Artifacts
```

Any future changes or additions to base CM content for DXA should be exported and placed in this folder.


text:
package org.dynalang.dynalink.beans;

import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import org.dynalang.dynalink.CallSiteDescriptor;
import org.dynalang.dynalink.linker.GuardedInvocation;
import org.dynalang.dynalink.linker.LinkRequest;
import org.dynalang.dynalink.linker.LinkerServices;
import org.dynalang.dynalink.linker.TypeBasedGuardingDynamicLinker;
import org.dynalang.dynalink.support.CallSiteDescriptorFactory;
import org.dynalang.dynalink.support.Guards;

/**
 * Simple linker that implements the "dyn:call" operation for {@link DynamicMethod} objects - the objects returned by
 * "dyn:getMethod" from {@link AbstractJavaLinker}.
 */
class DynamicMethodLinker implements TypeBasedGuardingDynamicLinker {
    @Override
    public boolean canLinkType(final Class<?> type) {
        return DynamicMethod.class.isAssignableFrom(type);
    }

    @Override
    public GuardedInvocation getGuardedInvocation(final LinkRequest linkRequest, final LinkerServices linkerServices) {
        final Object receiver = linkRequest.getReceiver();
        if(!(receiver instanceof DynamicMethod)) {
            return null;
        }
        final CallSiteDescriptor desc = linkRequest.getCallSiteDescriptor();
        if(desc.getNameTokenCount() != 2 && desc.getNameToken(CallSiteDescriptor.SCHEME) != "dyn") {
            return null;
        }
        final String operator = desc.getNameToken(CallSiteDescriptor.OPERATOR);
        if(operator == "call") {
            final MethodHandle invocation = ((DynamicMethod)receiver).getInvocation(
                    CallSiteDescriptorFactory.dropParameterTypes(desc, 0, 1), linkerServices);
            if(invocation == null) {
                return null;
            }
            return new GuardedInvocation(MethodHandles.dropArguments(invocation, 0,
                    desc.getMethodType().parameterType(0)), Guards.getIdentityGuard(receiver));
        }
        return null;
    }
}


text:
'use strict';

/* Module for Category */

var categoryModule = angular.module('category.module', ['myApp']);

/**
 * Module for category
 */
categoryModule.config(['$routeProvider', function($routeProvider) {
    // Pages routes
    $routeProvider.when('/category',    {templateUrl: 'partials/category/category_list.html', controller: 'CategoryCtrl'});
    $routeProvider.when('/category/new', {templateUrl: 'partials/category/category_form.html', controller: 'CategoryCtrl'});
    $routeProvider.when('/category/:corpid/:uid', {templateUrl: 'partials/category/category_form.html', controller: 'CategoryCtrl'});
}]);