text:
package org.apache.accumulo.core.client.impl;

import static java.nio.charset.StandardCharsets.UTF_8;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NoSuchElementException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.apache.accumulo.core.Constants;
import org.apache.accumulo.core.client.AccumuloException;
import org.apache.accumulo.core.client.AccumuloSecurityException;
import org.apache.accumulo.core.client.ConditionalWriter;
import org.apache.accumulo.core.client.ConditionalWriterConfig;
import org.apache.accumulo.core.client.Durability;
import org.apache.accumulo.core.client.Instance;
import org.apache.accumulo.core.client.TableDeletedException;
import org.apache.accumulo.core.client.TableNotFoundException;
import org.apache.accumulo.core.client.TableOfflineException;
import org.apache.accumulo.core.client.TimedOutException;
import org.apache.accumulo.core.client.impl.TabletLocator.TabletServerMutations;
import org.apache.accumulo.core.client.impl.thrift.ThriftSecurityException;
import org.apache.accumulo.core.data.ByteSequence;
import org.apache.accumulo.core.data.Condition;
import org.apache.accumulo.core.data.ConditionalMutation;
import org.apache.accumulo.core.data.impl.KeyExtent;
import org.apache.accumulo.core.data.thrift.TCMResult;
import org.apache.accumulo.core.data.thrift.TCMStatus;
import org.apache.accumulo.core.data.thrift.TCondition;
import org.apache.accumulo.core.data.thrift.TConditionalMutation;
import org.apache.accumulo.core.data.thrift.TConditionalSession;
import org.apache.accumulo.core.data.thrift.TKeyExtent;
import org.apache.accumulo.core.data.thrift.TMutation;
import org.apache.accumulo.core.master.state.tables.TableState;
import org.apache.accumulo.core.rpc.ThriftUtil;
import org.apache.accumulo.core.security.Authorizations;
import org.apache.accumulo.core.security.ColumnVisibility;
import org.apache.accumulo.core.security.VisibilityEvaluator;
import org.apache.accumulo.core.security.VisibilityParseException;
import org.apache.accumulo.core.tabletserver.thrift.NoSuchScanIDException;
import org.apache.accumulo.core.tabletserver.thrift.TabletClientService;
import org.apache.accumulo.core.trace.Trace;
import org.apache.accumulo.core.trace.Tracer;
import org.apache.accumulo.core.trace.thrift.TInfo;
import org.apache.accumulo.core.util.BadArgumentException;
import org.apache.accumulo.core.util.ByteBufferUtil;
import org.apache.accumulo.core.util.NamingThreadFactory;
import org.apache.accumulo.core.util.UtilWaitThread;
import org.apache.accumulo.core.zookeeper.ZooUtil;
import org.apache.accumulo.fate.util.LoggingRunnable;
import org.apache.accumulo.fate.zookeeper.ZooCacheFactory;
import org.apache.accumulo.fate.zookeeper.ZooLock;
import org.apache.accumulo.fate.zookeeper.ZooUtil.LockID;
import org.apache.commons.collections.map.LRUMap;
import org.apache.commons.lang.mutable.MutableLong;
import org.apache.hadoop.io.Text;
import org.apache.thrift.TApplicationException;
import org.apache.thrift.TException;
import org.apache.thrift.TServiceClient;
import org.apache.thrift.transport.TTransportException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.net.HostAndPort;

class ConditionalWriterImpl implements ConditionalWriter {

  private static ThreadPoolExecutor cleanupThreadPool = new ThreadPoolExecutor(1, 1, 10, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());

  static {
    cleanupThreadPool.allowCoreThreadTimeOut(true);
  }

  private static final Logger log = LoggerFactory.getLogger(ConditionalWriterImpl.class);

  private static final int MAX_SLEEP = 30000;

  private Authorizations auths;
  private VisibilityEvaluator ve;
  @SuppressWarnings("unchecked")
  private Map<Text,Boolean> cache = Collections.synchronizedMap(new LRUMap(1000));
  private final ClientContext context;
  private TabletLocator locator;
  private String tableId;
  private long timeout;
  private final Durability durability;

  private static class ServerQueue {
    BlockingQueue<TabletServerMutations<QCMutation>> queue = new LinkedBlockingQueue<>();
    boolean taskQueued = false;
  }

  private Map<String,ServerQueue> serverQueues;
  private DelayQueue<QCMutation> failedMutations = new DelayQueue<>();
  private ScheduledThreadPoolExecutor threadPool;

  private class RQIterator implements Iterator<Result> {

    private BlockingQueue<Result> rq;
    private int count;

    public RQIterator(BlockingQueue<Result> resultQueue, int count) {
      this.rq = resultQueue;
      this.count = count;
    }

    @Override
    public boolean hasNext() {
      return count > 0;
    }

    @Override
    public Result next() {
      if (count <= 0)
        throw new NoSuchElementException();

      try {
        Result result = rq.poll(1, TimeUnit.SECONDS);
        while (result == null) {

          if (threadPool.isShutdown()) {
            throw new NoSuchElementException("ConditionalWriter closed");
          }

          result = rq.poll(1, TimeUnit.SECONDS);
        }
        count--;
        return result;
      } catch (InterruptedException e) {
        throw new RuntimeException(e);
      }
    }

    @Override
    public void remove() {
      throw new UnsupportedOperationException();
    }

  }

  private static class QCMutation extends ConditionalMutation implements Delayed {
    private BlockingQueue<Result> resultQueue;
    private long resetTime;
    private long delay = 50;
    private long entryTime;

    QCMutation(ConditionalMutation cm, BlockingQueue<Result> resultQueue, long entryTime) {
      super(cm);
      this.resultQueue = resultQueue;
      this.entryTime = entryTime;
    }

    @Override
    public int compareTo(Delayed o) {
      QCMutation oqcm = (QCMutation) o;
      return Long.compare(resetTime, oqcm.resetTime);
    }

    @Override
    public int hashCode() {
      return super.hashCode();
    }

    @Override
    public boolean equals(Object o) {
      if (o instanceof QCMutation)
        return compareTo((QCMutation) o) == 0;
      return false;
    }

    @Override
    public long getDelay(TimeUnit unit) {
      return unit.convert(delay - (System.currentTimeMillis() - resetTime), TimeUnit.MILLISECONDS);
    }

    void resetDelay() {
      delay = Math.min(delay * 2, MAX_SLEEP);
      resetTime = System.currentTimeMillis();
    }

    void queueResult(Result result) {
      resultQueue.add(result);
    }
  }

  private ServerQueue getServerQueue(String location) {
    ServerQueue serverQueue;
    synchronized (serverQueues) {
      serverQueue = serverQueues.get(location);
      if (serverQueue == null) {

        serverQueue = new ServerQueue();
        serverQueues.put(location, serverQueue);
      }
    }
    return serverQueue;
  }

  private class CleanupTask implements Runnable {
    private List<SessionID> sessions;

    CleanupTask(List<SessionID> activeSessions) {
      this.sessions = activeSessions;
    }

    @Override
    public void run() {
      TabletClientService.Iface client = null;

      for (SessionID sid : sessions) {
        if (!sid.isActive())
          continue;

        TInfo tinfo = Tracer.traceInfo();
        try {
          client = getClient(sid.location);
          client.closeConditionalUpdate(tinfo, sid.sessionID);
        } catch (Exception e) {} finally {
          ThriftUtil.returnClient((TServiceClient) client);
        }

      }
    }
  }

  private void queueRetry(List<QCMutation> mutations, HostAndPort server) {

    if (timeout < Long.MAX_VALUE) {

      long time = System.currentTimeMillis();

      ArrayList<QCMutation> mutations2 = new ArrayList<>(mutations.size());

      for (QCMutation qcm : mutations) {
        qcm.resetDelay();
        if (time + qcm.getDelay(TimeUnit.MILLISECONDS) > qcm.entryTime + timeout) {
          TimedOutException toe;
          if (server != null)
            toe = new TimedOutException(Collections.singleton(server.toString()));
          else
            toe = new TimedOutException("Conditional mutation timed out");

          qcm.queueResult(new Result(toe, qcm, (null == server ? null : server.toString())));
        } else {
          mutations2.add(qcm);
        }
      }

      if (mutations2.size() > 0)
        failedMutations.addAll(mutations2);

    } else {
      for (QCMutation qcm : mutations)
        qcm.resetDelay();
      failedMutations.addAll(mutations);
    }
  }

  private void queue(List<QCMutation> mutations) {
    List<QCMutation> failures = new ArrayList<>();
    Map<String,TabletServerMutations<QCMutation>> binnedMutations = new HashMap<>();

    try {
      locator.binMutations(context, mutations, binnedMutations, failures);

      if (failures.size() == mutations.size())
        if (!Tables.exists(context.getInstance(), tableId))
          throw new TableDeletedException(tableId);
        else if (Tables.getTableState(context.getInstance(), tableId) == TableState.OFFLINE)
          throw new TableOfflineException(context.getInstance(), tableId);

    } catch (Exception e) {
      for (QCMutation qcm : mutations)
        qcm.queueResult(new Result(e, qcm, null));

      // do not want to queue anything that was put in before binMutations() failed
      failures.clear();
      binnedMutations.clear();
    }

    if (failures.size() > 0)
      queueRetry(failures, null);

    for (Entry<String,TabletServerMutations<QCMutation>> entry : binnedMutations.entrySet()) {
      queue(entry.getKey(), entry.getValue());
    }

  }

  private void queue(String location, TabletServerMutations<QCMutation> mutations) {

    ServerQueue serverQueue = getServerQueue(location);

    synchronized (serverQueue) {
      serverQueue.queue.add(mutations);
      // never execute more than one task per server
      if (!serverQueue.taskQueued) {
        threadPool.execute(new LoggingRunnable(log, Trace.wrap(new SendTask(location))));
        serverQueue.taskQueued = true;
      }
    }

  }

  private void reschedule(SendTask task) {
    ServerQueue serverQueue = getServerQueue(task.location);
    // just finished processing work for this server, could reschedule if it has more work or immediately process the work
    // this code reschedules the the server for processing later... there may be other queues with
    // more data that need to be processed... also it will give the current server time to build
    // up more data... the thinking is that rescheduling instead or processing immediately will result
    // in bigger batches and less RPC overhead

    synchronized (serverQueue) {
      if (serverQueue.queue.size() > 0)
        threadPool.execute(new LoggingRunnable(log, Trace.wrap(task)));
      else
        serverQueue.taskQueued = false;
    }

  }

  private TabletServerMutations<QCMutation> dequeue(String location) {
    BlockingQueue<TabletServerMutations<QCMutation>> queue = getServerQueue(location).queue;

    ArrayList<TabletServerMutations<QCMutation>> mutations = new ArrayList<>();
    queue.drainTo(mutations);

    if (mutations.size() == 0)
      return null;

    if (mutations.size() == 1) {
      return mutations.get(0);
    } else {
      // merge multiple request to a single tablet server
      TabletServerMutations<QCMutation> tsm = mutations.get(0);

      for (int i = 1; i < mutations.size(); i++) {
        for (Entry<KeyExtent,List<QCMutation>> entry : mutations.get(i).getMutations().entrySet()) {
          List<QCMutation> list = tsm.getMutations().get(entry.getKey());
          if (list == null) {
            list = new ArrayList<>();
            tsm.getMutations().put(entry.getKey(), list);
          }

          list.addAll(entry.getValue());
        }
      }

      return tsm;
    }
  }

  ConditionalWriterImpl(ClientContext context, String tableId, ConditionalWriterConfig config) {
    this.context = context;
    this.auths = config.getAuthorizations();
    this.ve = new VisibilityEvaluator(config.getAuthorizations());
    this.threadPool = new ScheduledThreadPoolExecutor(config.getMaxWriteThreads(), new NamingThreadFactory(this.getClass().getSimpleName()));
    this.locator = TabletLocator.getLocator(context, new Text(tableId));
    this.serverQueues = new HashMap<>();
    this.tableId = tableId;
    this.timeout = config.getTimeout(TimeUnit.MILLISECONDS);
    this.durability = config.getDurability();

    Runnable failureHandler = new Runnable() {

      @Override
      public void run() {
        List<QCMutation> mutations = new ArrayList<>();
        failedMutations.drainTo(mutations);
        if (mutations.size() > 0)
          queue(mutations);
      }
    };

    failureHandler = new LoggingRunnable(log, failureHandler);

    threadPool.scheduleAtFixedRate(failureHandler, 250, 250, TimeUnit.MILLISECONDS);
  }

  @Override
  public Iterator<Result> write(Iterator<ConditionalMutation> mutations) {

    BlockingQueue<Result> resultQueue = new LinkedBlockingQueue<>();

    List<QCMutation> mutationList = new ArrayList<>();

    int count = 0;

    long entryTime = System.currentTimeMillis();

    mloop: while (mutations.hasNext()) {
      ConditionalMutation mut = mutations.next();
      count++;

      if (mut.getConditions().size() == 0)
        throw new IllegalArgumentException("ConditionalMutation had no conditions " + new String(mut.getRow(), UTF_8));

      for (Condition cond : mut.getConditions()) {
        if (!isVisible(cond.getVisibility())) {
          resultQueue.add(new Result(Status.INVISIBLE_VISIBILITY, mut, null));
          continue mloop;
        }
      }

      // copy the mutations so that even if caller changes it, it will not matter
      mutationList.add(new QCMutation(mut, resultQueue, entryTime));
    }

    queue(mutationList);

    return new RQIterator(resultQueue, count);

  }

  private class SendTask implements Runnable {

    String location;

    public SendTask(String location) {
      this.location = location;

    }

    @Override
    public void run() {
      try {
        TabletServerMutations<QCMutation> mutations = dequeue(location);
        if (mutations != null)
          sendToServer(HostAndPort.fromString(location), mutations);
      } finally {
        reschedule(this);
      }
    }
  }

  private static class CMK {

    QCMutation cm;
    KeyExtent ke;

    public CMK(KeyExtent ke, QCMutation cm) {
      this.ke = ke;
      this.cm = cm;
    }
  }

  private static class SessionID {
    HostAndPort location;
    String lockId;
    long sessionID;
    boolean reserved;
    long lastAccessTime;
    long ttl;

    boolean isActive() {
      return System.currentTimeMillis() - lastAccessTime < ttl * .95;
    }
  }

  private HashMap<HostAndPort,SessionID> cachedSessionIDs = new HashMap<>();

  private SessionID reserveSessionID(HostAndPort location, TabletClientService.Iface client, TInfo tinfo) throws ThriftSecurityException, TException {
    // avoid cost of repeatedly making RPC to create sessions, reuse sessions
    synchronized (cachedSessionIDs) {
      SessionID sid = cachedSessionIDs.get(location);
      if (sid != null) {
        if (sid.reserved)
          throw new IllegalStateException();

        if (!sid.isActive()) {
          cachedSessionIDs.remove(location);
        } else {
          sid.reserved = true;
          return sid;
        }
      }
    }

    TConditionalSession tcs = client.startConditionalUpdate(tinfo, context.rpcCreds(), ByteBufferUtil.toByteBuffers(auths.getAuthorizations()), tableId,
        DurabilityImpl.toThrift(durability));

    synchronized (cachedSessionIDs) {
      SessionID sid = new SessionID();
      sid.reserved = true;
      sid.sessionID = tcs.sessionId;
      sid.lockId = tcs.tserverLock;
      sid.ttl = tcs.ttl;
      sid.location = location;
      if (cachedSessionIDs.put(location, sid) != null)
        throw new IllegalStateException();

      return sid;
    }

  }

  private void invalidateSessionID(HostAndPort location) {
    synchronized (cachedSessionIDs) {
      cachedSessionIDs.remove(location);
    }

  }

  private void unreserveSessionID(HostAndPort location) {
    synchronized (cachedSessionIDs) {
      SessionID sid = cachedSessionIDs.get(location);
      if (sid != null) {
        if (!sid.reserved)
          throw new IllegalStateException();
        sid.reserved = false;
        sid.lastAccessTime = System.currentTimeMillis();
      }
    }
  }

  List<SessionID> getActiveSessions() {
    ArrayList<SessionID> activeSessions = new ArrayList<>();
    for (SessionID sid : cachedSessionIDs.values())
      if (sid.isActive())
        activeSessions.add(sid);
    return activeSessions;
  }

  private TabletClientService.Iface getClient(HostAndPort location) throws TTransportException {
    TabletClientService.Iface client;
    if (timeout < context.getClientTimeoutInMillis())
      client = ThriftUtil.getTServerClient(location, context, timeout);
    else
      client = ThriftUtil.getTServerClient(location, context);
    return client;
  }

  private void sendToServer(HostAndPort location, TabletServerMutations<QCMutation> mutations) {
    TabletClientService.Iface client = null;

    TInfo tinfo = Tracer.traceInfo();

    Map<Long,CMK> cmidToCm = new HashMap<>();
    MutableLong cmid = new MutableLong(0);

    SessionID sessionId = null;

    try {
      Map<TKeyExtent,List<TConditionalMutation>> tmutations = new HashMap<>();

      CompressedIterators compressedIters = new CompressedIterators();
      convertMutations(mutations, cmidToCm, cmid, tmutations, compressedIters);

      // getClient() call must come after converMutations in case it throws a TException
      client = getClient(location);

      List<TCMResult> tresults = null;
      while (tresults == null) {
        try {
          sessionId = reserveSessionID(location, client, tinfo);
          tresults = client.conditionalUpdate(tinfo, sessionId.sessionID, tmutations, compressedIters.getSymbolTable());
        } catch (NoSuchScanIDException nssie) {
          sessionId = null;
          invalidateSessionID(location);
        }
      }

      HashSet<KeyExtent> extentsToInvalidate = new HashSet<>();

      ArrayList<QCMutation> ignored = new ArrayList<>();

      for (TCMResult tcmResult : tresults) {
        if (tcmResult.status == TCMStatus.IGNORED) {
          CMK cmk = cmidToCm.get(tcmResult.cmid);
          ignored.add(cmk.cm);
          extentsToInvalidate.add(cmk.ke);
        } else {
          QCMutation qcm = cmidToCm.get(tcmResult.cmid).cm;
          qcm.queueResult(new Result(fromThrift(tcmResult.status), qcm, location.toString()));
        }
      }

      for (KeyExtent ke : extentsToInvalidate) {
        locator.invalidateCache(ke);
      }

      queueRetry(ignored, location);

    } catch (ThriftSecurityException tse) {
      AccumuloSecurityException ase = new AccumuloSecurityException(context.getCredentials().getPrincipal(), tse.getCode(), Tables.getPrintableTableInfoFromId(
          context.getInstance(), tableId), tse);
      queueException(location, cmidToCm, ase);
    } catch (TTransportException e) {
      locator.invalidateCache(context.getInstance(), location.toString());
      invalidateSession(location, mutations, cmidToCm, sessionId);
    } catch (TApplicationException tae) {
      queueException(location, cmidToCm, new AccumuloServerException(location.toString(), tae));
    } catch (TException e) {
      locator.invalidateCache(context.getInstance(), location.toString());
      invalidateSession(location, mutations, cmidToCm, sessionId);
    } catch (Exception e) {
      queueException(location, cmidToCm, e);
    } finally {
      if (sessionId != null)
        unreserveSessionID(location);
      ThriftUtil.returnClient((TServiceClient) client);
    }
  }

  private void queueRetry(Map<Long,CMK> cmidToCm, HostAndPort location) {
    ArrayList<QCMutation> ignored = new ArrayList<>();
    for (CMK cmk : cmidToCm.values())
      ignored.add(cmk.cm);
    queueRetry(ignored, location);
  }

  private void queueException(HostAndPort location, Map<Long,CMK> cmidToCm, Exception e) {
    for (CMK cmk : cmidToCm.values())
      cmk.cm.queueResult(new Result(e, cmk.cm, location.toString()));
  }

  private void invalidateSession(HostAndPort location, TabletServerMutations<QCMutation> mutations, Map<Long,CMK> cmidToCm, SessionID sessionId) {
    if (sessionId == null) {
      queueRetry(cmidToCm, location);
    } else {
      try {
        invalidateSession(sessionId, location);
        for (CMK cmk : cmidToCm.values())
          cmk.cm.queueResult(new Result(Status.UNKNOWN, cmk.cm, location.toString()));
      } catch (Exception e2) {
        queueException(location, cmidToCm, e2);
      }
    }
  }

  /**
   * The purpose of this code is to ensure that a conditional mutation will not execute when its status is unknown. This allows a user to read the row when the
   * status is unknown and not have to worry about the tserver applying the mutation after the scan.
   *
   * <p>
   * If a conditional mutation is taking a long time to process, then this method will wait for it to finish... unless this exceeds timeout.
   */
  private void invalidateSession(SessionID sessionId, HostAndPort location) throws AccumuloException, AccumuloSecurityException, TableNotFoundException {

    long sleepTime = 50;

    long startTime = System.currentTimeMillis();

    Instance instance = context.getInstance();
    LockID lid = new LockID(ZooUtil.getRoot(instance) + Constants.ZTSERVERS, sessionId.lockId);

    ZooCacheFactory zcf = new ZooCacheFactory();
    while (true) {
      if (!ZooLock.isLockHeld(zcf.getZooCache(instance.getZooKeepers(), instance.getZooKeepersSessionTimeOut()), lid)) {
        // ACCUMULO-1152 added a tserver lock check to the tablet location cache, so this invalidation prevents future attempts to contact the
        // tserver even its gone zombie and is still running w/o a lock
        locator.invalidateCache(context.getInstance(), location.toString());
        return;
      }

      try {
        // if the mutation is currently processing, this method will block until its done or times out
        invalidateSession(sessionId.sessionID, location);

        return;
      } catch (TApplicationException tae) {
        throw new AccumuloServerException(location.toString(), tae);
      } catch (TException e) {
        locator.invalidateCache(context.getInstance(), location.toString());
      }

      if ((System.currentTimeMillis() - startTime) + sleepTime > timeout)
        throw new TimedOutException(Collections.singleton(location.toString()));

      UtilWaitThread.sleep(sleepTime);
      sleepTime = Math.min(2 * sleepTime, MAX_SLEEP);

    }

  }

  private void invalidateSession(long sessionId, HostAndPort location) throws TException {
    TabletClientService.Iface client = null;

    TInfo tinfo = Tracer.traceInfo();

    try {
      client = getClient(location);
      client.invalidateConditionalUpdate(tinfo, sessionId);
    } finally {
      ThriftUtil.returnClient((TServiceClient) client);
    }
  }

  private Status fromThrift(TCMStatus status) {
    switch (status) {
      case ACCEPTED:
        return Status.ACCEPTED;
      case REJECTED:
        return Status.REJECTED;
      case VIOLATED:
        return Status.VIOLATED;
      default:
        throw new IllegalArgumentException(status.toString());
    }
  }

  private void convertMutations(TabletServerMutations<QCMutation> mutations, Map<Long,CMK> cmidToCm, MutableLong cmid,
      Map<TKeyExtent,List<TConditionalMutation>> tmutations, CompressedIterators compressedIters) {

    for (Entry<KeyExtent,List<QCMutation>> entry : mutations.getMutations().entrySet()) {
      TKeyExtent tke = entry.getKey().toThrift();
      ArrayList<TConditionalMutation> tcondMutaions = new ArrayList<>();

      List<QCMutation> condMutations = entry.getValue();

      for (QCMutation cm : condMutations) {
        TMutation tm = cm.toThrift();

        List<TCondition> conditions = convertConditions(cm, compressedIters);

        cmidToCm.put(cmid.longValue(), new CMK(entry.getKey(), cm));
        TConditionalMutation tcm = new TConditionalMutation(conditions, tm, cmid.longValue());
        cmid.increment();
        tcondMutaions.add(tcm);
      }

      tmutations.put(tke, tcondMutaions);
    }
  }

  static class ConditionComparator implements Comparator<Condition> {

    private static final Long MAX = Long.valueOf(Long.MAX_VALUE);

    @Override
    public int compare(Condition c1, Condition c2) {
      int comp = c1.getFamily().compareTo(c2.getFamily());
      if (comp == 0) {
        comp = c1.getQualifier().compareTo(c2.getQualifier());
        if (comp == 0) {
          comp = c1.getVisibility().compareTo(c2.getVisibility());
          if (comp == 0) {
            Long l1 = c1.getTimestamp();
            Long l2 = c2.getTimestamp();
            if (l1 == null) {
              l1 = MAX;
            }

            if (l2 == null) {
              l2 = MAX;
            }

            comp = l2.compareTo(l1);
          }
        }
      }

      return comp;
    }
  }

  private static final ConditionComparator CONDITION_COMPARATOR = new ConditionComparator();

  private List<TCondition> convertConditions(ConditionalMutation cm, CompressedIterators compressedIters) {
    List<TCondition> conditions = new ArrayList<>(cm.getConditions().size());

    // sort conditions inorder to get better lookup performance. Sort on client side so tserver does not have to do it.
    Condition[] ca = cm.getConditions().toArray(new Condition[cm.getConditions().size()]);
    Arrays.sort(ca, CONDITION_COMPARATOR);

    for (Condition cond : ca) {
      long ts = 0;
      boolean hasTs = false;

      if (cond.getTimestamp() != null) {
        ts = cond.getTimestamp();
        hasTs = true;
      }

      ByteBuffer iters = compressedIters.compress(cond.getIterators());

      TCondition tc = new TCondition(ByteBufferUtil.toByteBuffers(cond.getFamily()), ByteBufferUtil.toByteBuffers(cond.getQualifier()),
          ByteBufferUtil.toByteBuffers(cond.getVisibility()), ts, hasTs, ByteBufferUtil.toByteBuffers(cond.getValue()), iters);

      conditions.add(tc);
    }

    return conditions;
  }

  private boolean isVisible(ByteSequence cv) {
    Text testVis = new Text(cv.toArray());
    if (testVis.getLength() == 0)
      return true;

    Boolean b = cache.get(testVis);
    if (b != null)
      return b;

    try {
      Boolean bb = ve.evaluate(new ColumnVisibility(testVis));
      cache.put(new Text(testVis), bb);
      return bb;
    } catch (VisibilityParseException e) {
      return false;
    } catch (BadArgumentException e) {
      return false;
    }
  }

  @Override
  public Result write(ConditionalMutation mutation) {
    return write(Collections.singleton(mutation).iterator()).next();
  }

  @Override
  public void close() {
    threadPool.shutdownNow();
    cleanupThreadPool.execute(new CleanupTask(getActiveSessions()));
  }

}


text:
package io.netty.channel.kqueue;

import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.testsuite.transport.TestsuitePermutation;
import io.netty.testsuite.transport.socket.SocketSslClientRenegotiateTest;

import java.net.SocketAddress;
import java.util.List;

public class KQueueDomainSocketSslClientRenegotiateTest extends SocketSslClientRenegotiateTest {
    @Override
    protected List<TestsuitePermutation.BootstrapComboFactory<ServerBootstrap, Bootstrap>> newFactories() {
        return KQueueSocketTestPermutation.INSTANCE.domainSocket();
    }

    @Override
    protected SocketAddress newSocketAddress() {
        return KQueueSocketTestPermutation.newSocketAddress();
    }
}

redpajama_set_name: RedPajamaGithub


text:
import functools
import inspect
import typing as tg

import typecheck.framework as fw

def typecheck(method, *, input_parameter_error=fw.InputParameterError,
              return_value_error=fw.ReturnValueError):
    argspec = inspect.getfullargspec(method)
    argnames = argspec.args
    if not argspec.annotations or not fw._enabled:
        return method

    default_arg_count = len(argspec.defaults or [])
    non_default_arg_count = len(argnames) - default_arg_count

    method_name = method.__name__
    arg_checkers = [None] * len(argnames)
    kwarg_checkers = {}
    return_checker = None
    kwarg_defaults = argspec.kwonlydefaults or {}

    for n, v in argspec.annotations.items():
        # namespace for defaults w TypeVars; bindings will be forgotten!:
        namespace = fw.TypeVarNamespace()
        checker = fw.Checker.create(v)
        if checker is None:
            raise fw.TypeCheckSpecificationError("invalid typecheck for {0}".format(n))
        if n in argspec.kwonlyargs:
            if n in kwarg_defaults and \
                    not checker.check(kwarg_defaults[n], namespace):
                raise fw.TypeCheckSpecificationError(
                    "the default value for {0} is incompatible "
                    "with its typecheck".format(n))
            kwarg_checkers[n] = checker
        elif n == "return":
            return_checker = checker
        else:
            i = argspec.args.index(n)
            if i >= non_default_arg_count and \
                    not checker.check(argspec.defaults[i - non_default_arg_count],
                                      namespace):
                raise fw.TypeCheckSpecificationError(
                    "the default value for {0} is incompatible "
                    "with its typecheck".format(n))
            arg_checkers[i] = (n, checker)

    def typecheck_invocation_proxy(*args, **kwargs):
        # TODO: '.' not in method_name  for methods. Why not?
        if len(argnames) > 0 and argnames[0] == 'self':
            theself = args[0]  # call to instance method
        else:
            theself = None  # call to function, static method, or class method
        namespace = fw.TypeVarNamespace(theself)
        # Validate positional parameters:
        for declaration, arg in zip(arg_checkers, args):
            if declaration is not None:
                arg_name, checker = declaration
                if not checker.check(arg, namespace):
                    raise input_parameter_error(
                        "{0}() has got an incompatible value "
                        "for {1}: {2}".format(method_name, arg_name,
                                              str(arg) == "" and "''" or arg))
        # Validate named parameters:
        for declaration in arg_checkers:
            if declaration is not None:
                arg_name, checker = declaration
                kwarg = kwargs.get(arg_name, fw.Checker.no_value)
                if kwarg != fw.Checker.no_value:
                    if not checker.check(kwarg, namespace):
                        raise input_parameter_error(
                            "{0}() has got an incompatible value "
                            "for {1}: {2}".format(method_name, arg_name,
                                                  str(
                                                      kwarg) == "" and "''" or kwarg))
        # Validate kwonly named parameters:
        for arg_name, checker in kwarg_checkers.items():
            kwarg = kwargs.get(arg_name, fw.Checker.no_value)
            if not checker.check(kwarg, namespace):
                raise input_parameter_error("{0}() has got an incompatible value "
                                            "for {1}: {2}".format(method_name,
                                                                  arg_name,
                                                                  str(
                                                                      kwarg) == "" and "''" or kwarg))
        # Call method-proper:
        result = method(*args, **kwargs)
        # Check result type:
        if (return_checker is not None and
                not return_checker.check(result, namespace)):
            raise return_value_error("{0}() has returned an incompatible "
                                     "value: {1}".format(method_name, str(
                result) == "" and "''" or result))
        return result
    #-- end of proxy method

    return functools.update_wrapper(typecheck_invocation_proxy, method,
                                    assigned=("__name__", "__module__", "__doc__"))

################################################################################

_exception_class = lambda t: isinstance(t, type) and issubclass(t, Exception)

#@typecheck
def typecheck_with_exceptions(*,
        input_parameter_error: fw.optional(_exception_class) = fw.InputParameterError,
        return_value_error: fw.optional(_exception_class) = fw.ReturnValueError):
    return lambda method: typecheck(method,
                                    input_parameter_error=input_parameter_error,
                                    return_value_error=return_value_error)

################################################################################

# TODO: @dynamictypecheck as @typecheck plus @typing.no_type_check:
# dynamictypecheck = tg.no_type_check_decorator(typecheck)


text:
<ivyconf>
    <properties file="${ivy.conf.dir}/ivyconf.properties"/>
   <conf defaultCache="${ivy.conf.dir}/cache"
	 defaultResolver="chain-resolvers" />
   <resolvers>
      <chain name="chain-resolvers" >
        <filesystem name="lib-jtv" latest="latest-revision">
              <artifact pattern="${lib.jtv}/[organisation]/[module]/[artifact]-[revision].[type]" />
              <ivy pattern="${lib.jtv}/[organisation]/[module]/ivy-[module]-[revision].xml" />
        </filesystem>
        <filesystem name="lib-3rd" latest="latest-revision">
            <artifact pattern="${lib.3rd}/[organisation]/[module]/[artifact]-[revision].[type]" />
            <ivy pattern="${lib.3rd}/[organisation]/[module]/ivy-[module]-[revision].xml" />
        </filesystem>
      </chain>
    </resolvers>
</ivyconf>


text:
package org.sandsoft.cymric.view.components;

import java.net.URL;
import java.util.ResourceBundle;
import javafx.beans.property.StringProperty;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;

/**
 *
 * @author Sudipto Chandra.
 */
public class FilterBox extends GridPane implements Initializable {

    @FXML
    private Button ClearButton;
    @FXML
    private Button SearchButton;
    @FXML
    private TextField SearchText;

    public FilterBox() {

    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        SearchText.textProperty().addListener((event)
                -> ClearButton.setVisible(!SearchText.getText().isEmpty()));
        ClearButton.setOnAction(
                (ActionEvent event) -> SearchText.clear());
        SearchButton.setOnAction(
                (ActionEvent event) -> requestSearch());
        SearchText.setOnAction(
                (ActionEvent event) -> requestSearch());
    }

    /**
     * Raise event to start search.
     */
    private void requestSearch() {
        if (!SearchText.getText().isEmpty()) {

        }
    }

    /**
     * The textual content of this TextInputControl.
     *
     * @return
     */
    public final StringProperty searchTextProperty() {
        return SearchText.textProperty();
    }

    /**
     * Sets the value of the property promptText.
     *
     * @param text The prompt text to display in the TextInputControl, or null
     * if no prompt text is displayed.
     */
    public void setPromptText(String text) {
        SearchText.setPromptText(text);
    }

    /**
     * Sets the text to search in the text-field.
     *
     * @param text
     */
    public void setSearchText(String text) {
        SearchText.setText(text);
    }

    /**
     * Gets the current text to search.
     *
     * @return
     */
    public String getSearchText() {
        return SearchText.getText();
    }
}


text:
package com.clean.demo.pojo;

/**
 * Created by tonghui on 2015/9/25.
 */
public class DbUser {
    private String username;
    private String password;
    private Integer access;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Integer getAccess() {
        return access;
    }

    public void setAccess(Integer access) {
        this.access = access;
    }
}


text:
/*global __DEV__:true, self: true, document: true, window: true, Event: true, localStorage: true, expect: true, it: true, beforeEach: true, describe: true */
/*jshint
  browser: true,
  devel: true,
  node: true,
  nonstandard: true,
  browser:   true,
  regexp:    true,
  smarttabs: true,
  unused: true,
  bitwise:  true,
  curly:    true,
  eqeqeq:   false,
  forin:    false,
  immed:    false,
  latedef:  false,
  noarg:    true,
  noempty:  false,
  nonew:    false,
  plusplus: false,
  regexp:   false,
  undef:    true,
  strict:   false,
  trailing: false,
  asi:      false,
  debug:    true,
  es5:      false,
  esnext:   true,
  evil:     false,
  expr:     true,
  funcscope: false,
  globalstrict: false,
  iterator: false,
  lastsemic: false,
  laxbreak: false,
  laxcomma: false,
  loopfunc: false,
  multistr: false,
  onecase:  false,
  proto:    false,
  regexdash: false,
  scripturl: true,
  smarttabs: false,
  sub:      true,
  supernew: false,
  boss:     false,
  newcap:   false,
  eqnull:   false,
  shadow:   false
*/


text:
"""
A variance method to compute similarity.

:copyright: 2015 Agile Geoscience
:license: Apache 2.0
"""
import numpy as np

def similarity(traces, duration, dt=1, step_out=1, lag=0):
    """
    Compute similarity for each point of a seismic section using
    a variance method between traces.

    For each point, a kernel of n_samples length is extracted from a
    trace. The similarity is calculated as a normalized variance
    between two adjacent trace sections, where a value of 1 is
    obtained by identical if the traces are identical. The step out
    will decide how many adjacent traces will be used for each kernel,
    and should be increased for poor quality data. The lag determines
    how much neighbouring traces can be shifted when calculating
    similiarity, which should be increased for dipping data.

    :param traces: A 2D numpy array arranged as [time, trace].
    :param duration: The length in seconds of the window trace kernel
        used to calculate the similarity.
    :keyword step_out (default=1 ):
        The number of adjacent traces to
        the kernel to check similarity. The maximum
        similarity value will be chosen.
    :keyword lag (default=0):
        The maximum number of time samples adjacent traces
        can be shifted by. The maximum similarity of
        will be used.
    :keyword dt (default=1): The sample interval of the traces in sec.
        (eg. 0.001, 0.002, ...). Will default to one, allowing
        duration to be given in samples.
    """

    half_n_samples = int(duration / (2*dt))

    similarity_cube = np.zeros_like(traces, dtype='float32')
    traces = np.nan_to_num(traces)

    for j in np.arange(-lag, lag+1):

        for i in (np.arange(step_out)):
            for idx in range(similarity_cube.shape[0]):

                # Get the signal
                start_sig_idx = max(0, (idx+(j*(i+1))-half_n_samples))
                stop_sig_idx = min(similarity_cube.shape[0]-1, (idx-((i+1)*j))+half_n_samples)

                # Get the data
                start_data_idx = max(0, (idx - half_n_samples))
                end_data_idx = start_data_idx + (stop_sig_idx - start_sig_idx)

                if(end_data_idx > traces.shape[0]):
                    break

                signal = traces[start_sig_idx:stop_sig_idx, :]
                data = traces[start_data_idx:end_data_idx, :]

                squares = (signal*signal).sum(axis=0)

                squares_of_diff = ((signal[:,1+i:] - data[:, :-(1+i)])**2.).sum(axis=0)

                squares[squares == 0.0] = 0.001
                squares_of_diff[squares_of_diff == 0.0] = 0.001
                sim = 1.0 - np.sqrt(squares_of_diff) / ((np.sqrt(squares[1+i:]) + np.sqrt(squares[:-(1+i)]) ))

                similarity_cube[idx, (i+1):] = np.maximum(sim,
                                                         similarity_cube[idx, (i+1):])

    return similarity_cube


text:
package org.apereo.cas.authentication;

import org.apache.commons.lang3.StringUtils;

/**
 * Authentication security policy that is satisfied iff a specified authentication handler successfully authenticates
 * at least one credential.
 *
 * @author Marvin S. Addison
 * @since 4.0.0
 */
public class RequiredHandlerAuthenticationPolicy implements AuthenticationPolicy {

    /** Authentication handler name that is required to satisfy policy. */
    private String requiredHandlerName;

    /** Flag to try all credentials before policy is satisfied. */
    private boolean tryAll;

    /**
     * Instantiates a new Required handler authentication policy.
     */
    public RequiredHandlerAuthenticationPolicy() {
    }

    /**
     * Instantiates a new required handler authentication policy.
     *
     * @param requiredHandlerName the required handler name
     */
    public RequiredHandlerAuthenticationPolicy(final String requiredHandlerName) {
        this.requiredHandlerName = requiredHandlerName;
    }

    /**
     * Sets the flag to try all credentials before the policy is satisfied.
     * This flag is disabled by default such that the policy is satisfied immediately upon the first
     * credential that is successfully authenticated by the required handler.
     *
     * @param tryAll True to force all credentials to be authenticated, false otherwise.
     */
    public void setTryAll(final boolean tryAll) {
        this.tryAll = tryAll;
    }

    @Override
    public boolean isSatisfiedBy(final Authentication authn) {
        boolean credsOk = true;
        if (this.tryAll) {
            credsOk = authn.getCredentials().size() == authn.getSuccesses().size()
                + authn.getFailures().size();
        }
        return credsOk && StringUtils.isNotBlank(this.requiredHandlerName)
                    && authn.getSuccesses().containsKey(this.requiredHandlerName);
    }
}


text:
import os
import datetime
import odml.base
import odmltables.odml_xls_table as odml_xls_table
from odmltables.xls_style import XlsStyle

pre_enriched_file = 'example2-1.odml'

# EXAMPLE
def run_example():
    # generating OdmlXlsTable object
    xlstable = odml_xls_table.OdmlXlsTable()

    # loading data from odml
    xlstable.load_from_file(pre_enriched_file)

    xlstable.write2file('automatically_enriched.xls')

    # mimicing manual entry of data in the xls
    manual_enrichment()

    xlstable.load_from_xls_table('manually_enriched.xls')

    xlstable.write2odml('example2-2.odml')

def automatic_enrichment():
    # mimic automatized enrichment prior to manual enrichment
    doc = odml.fileio.load('../example1/example1-2.odml')
    animal_props = doc['Animal'].properties

    animal_props['AnimalID'].values = '2A'
    animal_props['Species'].values = 'Meriones unguiculatus'
    animal_props['Sex'].values = 'female'
    animal_props['Birthdate'].values = datetime.datetime.today().date() - datetime.timedelta(100)
    animal_props['Litter'].values = '1A-01'
    animal_props['Seizures'].values = 'not observed'

    odml.fileio.save(doc, pre_enriched_file)

    return doc

def manual_enrichment():
    # mimic manual enrichment of xls
    doc = automatic_enrichment()
    surgery_props = doc['Animal']['Surgery'].properties

    surgery_props['Surgeon'].values = 'Surgeon1'
    surgery_props['Date'].values = datetime.datetime.today().date()
    surgery_props['Weight'].values = 100.0
    surgery_props['Quality'].values = 'good'
    surgery_props['Anaesthetic'].values = 'urethane'
    surgery_props['Painkiller'].values = ''
    surgery_props['Link'].values = '../../surgery/protocols/protocol1.pdf'

    xlstable = odml_xls_table.OdmlXlsTable()
    xlstable.load_from_odmldoc(doc)

    xlstable.write2file('manually_enriched.xls')

if __name__=='__main__':
    if os.path.isfile(pre_enriched_file):
        print('Mimicing manual odml enrichment.')
        run_example()
    else:
        print('Performing automatic pre enrichment of odml template.')
        automatic_enrichment()


text:
<ion-view view-title="" hide-back-button="true">
  <ion-nav-bar class="bar-stable">
	  <ion-nav-buttons side="right">
	    <button class="button button-positive button-clear no-animation" ng-click="startApp()">Skip</button>
	  </ion-nav-buttons>
  </ion-nav-bar>
  <ion-slide-box on-slide-changed="slideChanged(index)" show-pager="true">
    <ion-slide class="intro col1 slider-bg">

{{ 'APP_INTRO_HEADER_SLIDE_1' | translate }}
{{ 'APP_INTRO_CONTENT_SLIDE_1' | translate }}

      <button class="button button-clear button-block intro-footer" ng-click="next()">{{ 'APP_INTRO_CTA_BTN_SLIDE_1' | translate }}</button>
    </ion-slide>

    <ion-slide class="intro col2 slider-bg">

{{ 'APP_INTRO_HEADER_SLIDE_2' | translate }}
{{ 'APP_INTRO_CONTENT_SLIDE_2' | translate }}

      <button class="button button-clear button-block intro-footer" ng-click="next()">{{ 'APP_INTRO_CTA_BTN_SLIDE_2' | translate }}</button>
    </ion-slide>

    <ion-slide class="intro col3 slider-bg">

{{ 'APP_INTRO_HEADER_SLIDE_3' | translate }}
{{ 'APP_INTRO_CONTENT_SLIDE_3' | translate }}

      <button class="button button-clear button-block intro-footer" ng-click="next()">{{ 'APP_INTRO_CTA_BTN_SLIDE_3' | translate }}</button>
    </ion-slide>
    <ion-slide class="intro col4 slider-bg">

{{ 'APP_INTRO_HEADER_SLIDE_4' | translate }}
{{ 'APP_INTRO_CONTENT_SLIDE_4' | translate }}

      <button class="button button-clear button-block intro-footer" ng-click="next()">{{ 'APP_INTRO_CTA_BTN_SLIDE_4' | translate }}</button>
    </ion-slide>
    <ion-slide class="intro col5 slider-bg">

{{ 'APP_INTRO_HEADER_SLIDE_5' | translate }}
{{ 'APP_INTRO_CONTENT_SLIDE_5' | translate }}

      <form name="signupUserForm" class="avionic-intro" novalidate="novalidate">

            <input id="text" type="email" name="email" placeholder="{{'APP_SIGNUP_EMAIL' | translate }}" ng-model="user.username" ng-minlength="5" ng-maxlength="64" required="required">

              <input id="password" name="password" type="password" placeholder="{{ 'APP_SIGNUP_PASSWORD' | translate }}" ng-model="user.password" ng-minlength="5" ng-maxlength="30" required="required">

            {{ 'APP_INTRO_CTA_TERMS_INTRO_SLIDE_5' | translate }} {{ 'APP_INTRO_CTA_TERMSCONDITIONS_SLIDE_5' | translate }} {{ 'APP_INTRO_CTA_AND_SLIDE_5' | translate }} {{ 'APP_INTRO_CTA_PRIVACY_SLIDE_5' | translate }}

      </form>

      <button class="button button-clear button-block intro-footer" ng-click="signupUser()">{{ 'APP_INTRO_CTA_BTN_SLIDE_5' | translate }}</button>
    </ion-slide>
  </ion-slide-box>
</ion-view>


text:
using System;
using System.Collections.Concurrent;
using System.Reflection;

namespace Reflectinator
{
    public static class Field
    {
        private static readonly ConcurrentDictionary<Tuple<Type, Type, Type, string>, IField> _fieldsMap = new ConcurrentDictionary<Tuple<Type, Type, Type, string>, IField>();

        public static IField Get(FieldInfo fieldInfo)
        {
            return _fieldsMap.GetOrAdd(
                Tuple.Create(fieldInfo.DeclaringType, fieldInfo.FieldType, fieldInfo.DeclaringType, fieldInfo.Name),
                t =>
                    (IField)(fieldInfo.IsStatic
                        ? Activator.CreateInstance(typeof(StaticField<,>).MakeGenericType(fieldInfo.DeclaringType, fieldInfo.FieldType), BindingFlags.NonPublic | BindingFlags.Instance, null, new object[] { fieldInfo }, null)
                        : Activator.CreateInstance(typeof(Field<,>).MakeGenericType(fieldInfo.DeclaringType, fieldInfo.FieldType), BindingFlags.NonPublic | BindingFlags.Instance, null, new object[] { fieldInfo }, null)));
        }

        public static Field<TDeclaringType, TFieldType> Get<TDeclaringType, TFieldType>(FieldInfo fieldInfo)
        {
            return (Field<TDeclaringType, TFieldType>)_fieldsMap.GetOrAdd(
                Tuple.Create(typeof(TDeclaringType), typeof(TFieldType), fieldInfo.DeclaringType, fieldInfo.Name),
                t =>
                    fieldInfo.IsStatic
                        ? new StaticField<TDeclaringType, TFieldType>(fieldInfo)
                        : new Field<TDeclaringType, TFieldType>(fieldInfo));
        }

        public static IStaticField GetStatic(FieldInfo fieldInfo)
        {
            if (!fieldInfo.IsStatic)
            {
                throw new ArgumentException("Cannot call GetStatic(FieldInfo) on a non-static FieldInfo.", "fieldInfo");
            }

            return (IStaticField)_fieldsMap.GetOrAdd(
                Tuple.Create(fieldInfo.DeclaringType, fieldInfo.FieldType, fieldInfo.DeclaringType, fieldInfo.Name),
                t => (IField)Activator.CreateInstance(typeof(StaticField<,>).MakeGenericType(fieldInfo.DeclaringType, fieldInfo.FieldType), BindingFlags.NonPublic | BindingFlags.Instance, null, new object[] { fieldInfo }, null));
        }

        public static StaticField<TDeclaringType, TFieldType> GetStatic<TDeclaringType, TFieldType>(FieldInfo fieldInfo)
        {
            return (StaticField<TDeclaringType, TFieldType>)_fieldsMap.GetOrAdd(
                Tuple.Create(typeof(TDeclaringType), typeof(TFieldType), fieldInfo.DeclaringType, fieldInfo.Name),
                t => new StaticField<TDeclaringType, TFieldType>(fieldInfo));
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace StreamSurfer.Models
{
    public class Movie
    {
        public int ID { get; set; }
        public string Title { get; set; }
        public string Poster { get; set; }
        public string Artwork { get; set; }
        public string Desc { get; set; }
        public string Aired { get; set; }
        public string Rating { get; set; }
        public string Cast { get; set; }

        public List<Synonym> Synonyms { get; set; }
        public List<MovieGenre> MovieGenre { get; set; }
        public List<MovieService> MovieService { get; set; }
        public List<MyListShows> MyListShows { get; set; }
    }
}


text:
package com.mapr.synth.distributions;

import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Random;

public class IpAddressDistribution {
    private double ipV4Probability = 0.3;
    private Random base = new Random();

    public void setIpV4Probability(double ipV4Probability) {
        this.ipV4Probability = ipV4Probability;
    }

    public void setSeed(long seed) {
        base.setSeed(seed);
    }

    public InetAddress sample() {
        if (base.nextDouble() < ipV4Probability) {
            byte[] bits = new byte[4];
            base.nextBytes(bits);
            try {
                return Inet4Address.getByAddress(bits);
            } catch (UnknownHostException e) {
                throw new IllegalStateException("Can't happen ... we gave the right number of bytes");
            }
        } else {
            byte[] bits = new byte[16];
            base.nextBytes(bits);
            if (base.nextDouble() < 0.1) {
                for (int i = 2; i < 8; i++) {
                    bits[i] = 0;
                }
            }
            try {
                return Inet6Address.getByAddress(bits);
            } catch (UnknownHostException e) {
                throw new IllegalStateException("Can't happen ... we gave the right number of bytes");
            }
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Xml.Serialization;
// ReSharper disable PossibleNullReferenceException
#pragma warning disable 1591

namespace TWCore.Serialization
{
	/// <summary>
	/// Generic object
	/// </summary>
	[DataContract]
	public class GenericObject
	{
		[DebuggerBrowsable(DebuggerBrowsableState.Never)] private bool _isArray;
		[DebuggerBrowsable(DebuggerBrowsableState.Never)] private bool _isList;
		[DebuggerBrowsable(DebuggerBrowsableState.Never)] private bool _isDictionary;

		#region Properties
		/// <summary>
		/// Type name
		/// </summary>
		[XmlAttribute, DataMember, Newtonsoft.Json.JsonProperty(
			NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
			TypeNameHandling = Newtonsoft.Json.TypeNameHandling.None,
			ItemTypeNameHandling = Newtonsoft.Json.TypeNameHandling.None)]
		public string Type { get; set; }
		/// <summary>
		/// Is Array Object
		/// </summary>
		[XmlIgnore]
		public bool IsArray
		{
			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			get => Array != null || _isArray;
			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			set => _isArray = value;
		}
		/// <summary>
		/// Is List Object
		/// </summary>
		[XmlIgnore]
		public bool IsList
		{
			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			get => List != null || _isList;
			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			set => _isList = value;
		}
		/// <summary>
		/// Is Dictionary Object
		/// </summary>
		[XmlIgnore]
		public bool IsDictionary
		{
			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			get => Dictionary != null || _isDictionary;
			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			set => _isDictionary = value;
		}
		/// <summary>
		/// Properties
		/// </summary>
		[DataMember, Newtonsoft.Json.JsonProperty(
			NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
			TypeNameHandling = Newtonsoft.Json.TypeNameHandling.None,
			ItemTypeNameHandling = Newtonsoft.Json.TypeNameHandling.None)]
		public Dictionary<string, GenericObject> Properties { get; set; }
		/// <summary>
		/// Dictionary Data
		/// </summary>
		[DataMember, Newtonsoft.Json.JsonProperty(
			NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
			TypeNameHandling = Newtonsoft.Json.TypeNameHandling.None,
			ItemTypeNameHandling = Newtonsoft.Json.TypeNameHandling.None)]
		public Dictionary<object, GenericObject> Dictionary { get; set; }
		/// <summary>
		/// List Data
		/// </summary>
		[DataMember, Newtonsoft.Json.JsonProperty(
			NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
			TypeNameHandling = Newtonsoft.Json.TypeNameHandling.None,
			ItemTypeNameHandling = Newtonsoft.Json.TypeNameHandling.None)]
		public List<GenericObject> List { get; set; }
		/// <summary>
		/// Array Data
		/// </summary>
		[DataMember, Newtonsoft.Json.JsonProperty(
			NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
			TypeNameHandling = Newtonsoft.Json.TypeNameHandling.None,
			ItemTypeNameHandling = Newtonsoft.Json.TypeNameHandling.None)]
		public GenericObject[] Array { get; set; }
		/// <summary>
		/// Value Data
		/// </summary>
		[DataMember, Newtonsoft.Json.JsonProperty(
			NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
		public object Value { get; set; }
		#endregion

		#region .ctor
		/// <summary>
		/// Generic object
		/// </summary>
		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public GenericObject() { }
		/// <summary>
		/// Generic object
		/// </summary>
		/// <param name="type">Type value</param>
		/// <param name="isArray">Is Array value</param>
		/// <param name="isList">Is List value</param>
		/// <param name="isDictionary">Is Dictionary value</param>
		/// <param name="properties">Properties array value</param>
		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public GenericObject(string type, bool isArray, bool isList, bool isDictionary, string[] properties)
		{
			Type = type;
			IsArray = isArray;
			IsList = isList;
			IsDictionary = isDictionary;

			if (properties?.Any() == true)
			{
				Properties = new Dictionary<string, GenericObject>();
				foreach (var property in properties)
					Properties[property] = null;
			}
			if (IsList)
			{
				List = new List<GenericObject>();
			}
			if (IsDictionary)
			{
				Dictionary = new Dictionary<object, GenericObject>();
			}
		}
		#endregion

		#region Public Methods
		/// <summary>
		/// Get the object property value
		/// </summary>
		/// <param name="key">Object property name</param>
		/// <returns>Property value</returns>
		public GenericObject this[string key]
		{
			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			get
			{
				if (IsDictionary && Dictionary.TryGetValue(key, out var dictioValue))
					return dictioValue;
				if (Properties.TryGetValue(key, out var value))
					return value;
				if (!IsDictionary)
					throw new Exception("Property is not found in the object");
				throw new KeyNotFoundException();
			}
		}
		/// <summary>
		/// Get the object dictionary value
		/// </summary>
		/// <param name="key">Object dictionary name</param>
		/// <returns>Property value</returns>
		public GenericObject this[object key]
		{
			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			get
			{
				if (IsDictionary && Dictionary.TryGetValue(key, out var dictioValue))
					return dictioValue;
				if (!IsDictionary)
					throw new Exception("The object is not a Dictionary");
				throw new KeyNotFoundException();
			}
		}
		/// <summary>
		/// Get the index value of an array or list
		/// </summary>
		/// <param name="index">Index number</param>
		/// <returns>Object value</returns>
		public GenericObject this[int index]
		{
			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			get
			{
				if (IsArray)
				{
					if (Array != null)
						return Array[index];
					else
						throw new Exception("The ArrayData has not been initialized");
				}
				if (IsList)
					return List[index];
				throw new Exception("The object is not an Array/List");
			}
		}
		#endregion

		#region Other Methods
		/// <summary>
		/// Set property value
		/// </summary>
		/// <param name="key">Object property key</param>
		/// <param name="value">Object property value</param>
		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void SetProperty(string key, object value)
		{
			if (value is GenericObject gObject)
				Properties[key] = gObject;
			else if (value is null)
				Properties[key] = null;
			else
				Properties[key] = new GenericObject { Value = value };
		}
		/// <summary>
		/// Init array value
		/// </summary>
		/// <param name="capacity">Array capacity</param>
		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void InitArray(int capacity)
		{
			Array = new GenericObject[capacity];
		}
		/// <summary>
		/// Set an array value
		/// </summary>
		/// <param name="index">Index of the array</param>
		/// <param name="value">Object value</param>
		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void SetArrayValue(int index, object value)
		{
			if (value is GenericObject gObject)
				Array[index] = gObject;
			else if (value is null)
				Array[index] = null;
			else
				Array[index] = new GenericObject { Value = value };
		}
		/// <summary>
		/// Set a list value
		/// </summary>
		/// <param name="index">Index of the list</param>
		/// <param name="value">Object value</param>
		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void SetListValue(int index, object value)
		{
			if (value is GenericObject gObject)
				List[index] = gObject;
			else if (value is null)
				List[index] = null;
			else
				List[index] = new GenericObject { Value = value };
		}
		/// <summary>
		/// Add a list value
		/// </summary>
		/// <param name="value">Object value</param>
		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void AddListValue(object value)
		{
			if (value is GenericObject gObject)
				List.Add(gObject);
			else if (value is null)
				List.Add(null);
			else
				List.Add(new GenericObject { Value = value });
		}
		/// <summary>
		/// Set a dictionary key/value
		/// </summary>
		/// <param name="key">Dictionary key</param>
		/// <param name="value">Dictionary value</param>
		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void SetDictionaryValue(object key, object value)
		{
			if (value is GenericObject gObject)
				Dictionary[key] = gObject;
			else if (value is null)
				Dictionary[key] = null;
			else
				Dictionary[key] = new GenericObject { Value = value };
		}
		#endregion
	}

}


text:
// Copyright 2020 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef V8_HEAP_OFF_THREAD_FACTORY_INL_H_
#define V8_HEAP_OFF_THREAD_FACTORY_INL_H_

#include "src/heap/off-thread-factory.h"

#include "src/heap/factory-base-inl.h"
#include "src/roots/roots-inl.h"

namespace v8 {
namespace internal {

#define ROOT_ACCESSOR(Type, name, CamelName)  \
  Handle<Type> OffThreadFactory::name() {     \
    return read_only_roots().name##_handle(); \
  }
READ_ONLY_ROOT_LIST(ROOT_ACCESSOR)
#undef ROOT_ACCESSOR

#define ACCESSOR_INFO_ACCESSOR(Type, name, CamelName)                          \
  Handle<Type> OffThreadFactory::name() {                                      \
    /* Do a bit of handle location magic to cast the Handle without having */  \
    /* to pull in Type::cast. We know the type is right by construction.   */  \
    return Handle<Type>(                                                       \
        isolate()->isolate_->root_handle(RootIndex::k##CamelName).location()); \
  }
ACCESSOR_INFO_ROOT_LIST(ACCESSOR_INFO_ACCESSOR)
#undef ACCESSOR_INFO_ACCESSOR

#endif  // V8_HEAP_OFF_THREAD_FACTORY_INL_H_

}  // namespace internal
}  // namespace v8


text:
package com.taobao.tddl.sample;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import com.taobao.tddl.client.jdbc.TDataSource;

public class YongchuanSample {

    public static void main(String[] args) throws Exception {

        com.taobao.tddl.client.jdbc.TDataSource ds = new TDataSource();
        ds.setDynamicRule(true);
        // init a datasource with dynamic config on diamond
        ds.setAppName("TMALL_SERVICE_DPC");

        ds.init();

        System.out.println("init done");

        Connection conn = ds.getConnection();

        PreparedStatement ps = conn.prepareStatement("select last_insert_id()");

        ResultSet rs = ps.executeQuery();
        while (rs.next()) {
            StringBuilder sb = new StringBuilder();
            int count = rs.getMetaData().getColumnCount();
            for (int i = 1; i <= count; i++) {

                String key = rs.getMetaData().getColumnLabel(i);
                Object val = rs.getObject(i);
                sb.append("[" + rs.getMetaData().getTableName(i) + "." + key + "->" + val + "]");
            }
            System.out.println(sb.toString());
        }

        ps.close();
        conn.close();

        System.out.println("query done");

    }

}


text:
This sample demonstrates input date feature basic functionalities, include:

* The date displayed info when input type is set by "date"


text:
#include "channel_credentials.h"
#include "call_credentials.h"

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <php.h>
#include <php_ini.h>
#include <ext/standard/info.h>
#include <ext/spl/spl_exceptions.h>
#include "php_grpc.h"

#include <zend_exceptions.h>
#include <zend_hash.h>

#include <grpc/support/alloc.h>
#include <grpc/grpc.h>
#include <grpc/grpc_security.h>

zend_class_entry *grpc_ce_channel_credentials;
static char *default_pem_root_certs = NULL;

static grpc_ssl_roots_override_result get_ssl_roots_override(
    char **pem_root_certs) {
  *pem_root_certs = default_pem_root_certs;
  if (default_pem_root_certs == NULL) {
    return GRPC_SSL_ROOTS_OVERRIDE_FAIL;
  }
  return GRPC_SSL_ROOTS_OVERRIDE_OK;
}

#if PHP_MAJOR_VERSION < 7

/* Frees and destroys an instance of wrapped_grpc_channel_credentials */
void free_wrapped_grpc_channel_credentials(void *object TSRMLS_DC) {
  wrapped_grpc_channel_credentials *creds =
      (wrapped_grpc_channel_credentials *)object;
  if (creds->wrapped != NULL) {
    grpc_channel_credentials_release(creds->wrapped);
  }
  zend_object_std_dtor(&creds->std TSRMLS_CC);
  efree(creds);
}

/* Initializes an instance of wrapped_grpc_channel_credentials to be
 * associated with an object of a class specified by class_type */
zend_object_value create_wrapped_grpc_channel_credentials(
    zend_class_entry *class_type TSRMLS_DC) {
  zend_object_value retval;
  wrapped_grpc_channel_credentials *intern;

  intern = (wrapped_grpc_channel_credentials *)emalloc(
      sizeof(wrapped_grpc_channel_credentials));
  memset(intern, 0, sizeof(wrapped_grpc_channel_credentials));

  zend_object_std_init(&intern->std, class_type TSRMLS_CC);
  object_properties_init(&intern->std, class_type);
  retval.handle = zend_objects_store_put(
      intern, (zend_objects_store_dtor_t)zend_objects_destroy_object,
      free_wrapped_grpc_channel_credentials, NULL TSRMLS_CC);
  retval.handlers = zend_get_std_object_handlers();
  return retval;
}

#else

static zend_object_handlers channel_credentials_ce_handlers;

/* Frees and destroys an instance of wrapped_grpc_channel_credentials */
static void free_wrapped_grpc_channel_credentials(zend_object *object) {
  wrapped_grpc_channel_credentials *creds =
    wrapped_grpc_channel_creds_from_obj(object);
  if (creds->wrapped != NULL) {
    grpc_channel_credentials_release(creds->wrapped);
  }
  zend_object_std_dtor(&creds->std);
}

/* Initializes an instance of wrapped_grpc_channel_credentials to be
 * associated with an object of a class specified by class_type */
zend_object *create_wrapped_grpc_channel_credentials(zend_class_entry
                                                     *class_type) {
  wrapped_grpc_channel_credentials *intern;
  intern = ecalloc(1, sizeof(wrapped_grpc_channel_credentials) +
                   zend_object_properties_size(class_type));
  zend_object_std_init(&intern->std, class_type);
  object_properties_init(&intern->std, class_type);
  intern->std.handlers = &channel_credentials_ce_handlers;
  return &intern->std;
}

#endif

zval *grpc_php_wrap_channel_credentials(grpc_channel_credentials
                                        *wrapped TSRMLS_DC) {
  zval *credentials_object;
  PHP_GRPC_MAKE_STD_ZVAL(credentials_object);
  object_init_ex(credentials_object, grpc_ce_channel_credentials);
  wrapped_grpc_channel_credentials *credentials =
    Z_WRAPPED_GRPC_CHANNEL_CREDS_P(credentials_object);
  credentials->wrapped = wrapped;
  return credentials_object;
}

/**
 * Set default roots pem.
 * @param string pem_roots PEM encoding of the server root certificates
 * @return void
 */
PHP_METHOD(ChannelCredentials, setDefaultRootsPem) {
  char *pem_roots;
  php_grpc_int pem_roots_length;

  /* "s" == 1 string */
  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &pem_roots,
                            &pem_roots_length) == FAILURE) {
    zend_throw_exception(spl_ce_InvalidArgumentException,
                         "setDefaultRootsPem expects 1 string", 1 TSRMLS_CC);
    return;
  }
  default_pem_root_certs = gpr_malloc((pem_roots_length + 1) * sizeof(char));
  memcpy(default_pem_root_certs, pem_roots, pem_roots_length + 1);
}

/**
 * Create a default channel credentials object.
 * @return ChannelCredentials The new default channel credentials object
 */
PHP_METHOD(ChannelCredentials, createDefault) {
  grpc_channel_credentials *creds = grpc_google_default_credentials_create();
  zval *creds_object;
  PHP_GRPC_MAKE_STD_ZVAL(creds_object);
  creds_object = grpc_php_wrap_channel_credentials(creds TSRMLS_CC);
  RETURN_DESTROY_ZVAL(creds_object);
}

/**
 * Create SSL credentials.
 * @param string pem_root_certs PEM encoding of the server root certificates
 * @param string pem_private_key PEM encoding of the client's private key
 *     (optional)
 * @param string pem_cert_chain PEM encoding of the client's certificate chain
 *     (optional)
 * @return ChannelCredentials The new SSL credentials object
 */
PHP_METHOD(ChannelCredentials, createSsl) {
  char *pem_root_certs = NULL;
  grpc_ssl_pem_key_cert_pair pem_key_cert_pair;

  php_grpc_int root_certs_length = 0;
  php_grpc_int private_key_length = 0;
  php_grpc_int cert_chain_length = 0;

  pem_key_cert_pair.private_key = pem_key_cert_pair.cert_chain = NULL;

  /* "|s!s!s!" == 3 optional nullable strings */
  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s!s!s!",
                            &pem_root_certs, &root_certs_length,
                            &pem_key_cert_pair.private_key,
                            &private_key_length,
                            &pem_key_cert_pair.cert_chain,
                            &cert_chain_length) == FAILURE) {
    zend_throw_exception(spl_ce_InvalidArgumentException,
                         "createSsl expects 3 optional strings", 1 TSRMLS_CC);
    return;
  }
  grpc_channel_credentials *creds = grpc_ssl_credentials_create(
      pem_root_certs,
      pem_key_cert_pair.private_key == NULL ? NULL : &pem_key_cert_pair, NULL);
  zval *creds_object;
  PHP_GRPC_MAKE_STD_ZVAL(creds_object);
  creds_object = grpc_php_wrap_channel_credentials(creds TSRMLS_CC);
  RETURN_DESTROY_ZVAL(creds_object);
}

/**
 * Create composite credentials from two existing credentials.
 * @param ChannelCredentials cred1 The first credential
 * @param CallCredentials cred2 The second credential
 * @return ChannelCredentials The new composite credentials object
 */
PHP_METHOD(ChannelCredentials, createComposite) {
  zval *cred1_obj;
  zval *cred2_obj;

  /* "OO" == 2 Objects */
  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "OO", &cred1_obj,
                            grpc_ce_channel_credentials, &cred2_obj,
                            grpc_ce_call_credentials) == FAILURE) {
    zend_throw_exception(spl_ce_InvalidArgumentException,
                         "createComposite expects 2 Credentials", 1 TSRMLS_CC);
    return;
  }
  wrapped_grpc_channel_credentials *cred1 =
    Z_WRAPPED_GRPC_CHANNEL_CREDS_P(cred1_obj);
  wrapped_grpc_call_credentials *cred2 =
    Z_WRAPPED_GRPC_CALL_CREDS_P(cred2_obj);
  grpc_channel_credentials *creds =
      grpc_composite_channel_credentials_create(cred1->wrapped, cred2->wrapped,
                                                NULL);
  zval *creds_object;
  PHP_GRPC_MAKE_STD_ZVAL(creds_object);
  creds_object = grpc_php_wrap_channel_credentials(creds TSRMLS_CC);
  RETURN_DESTROY_ZVAL(creds_object);
}

/**
 * Create insecure channel credentials
 * @return null
 */
PHP_METHOD(ChannelCredentials, createInsecure) {
  RETURN_NULL();
}

static zend_function_entry channel_credentials_methods[] = {
  PHP_ME(ChannelCredentials, setDefaultRootsPem, NULL,
         ZEND_ACC_PUBLIC | ZEND_ACC_STATIC)
  PHP_ME(ChannelCredentials, createDefault, NULL,
         ZEND_ACC_PUBLIC | ZEND_ACC_STATIC)
  PHP_ME(ChannelCredentials, createSsl, NULL,
         ZEND_ACC_PUBLIC | ZEND_ACC_STATIC)
  PHP_ME(ChannelCredentials, createComposite, NULL,
         ZEND_ACC_PUBLIC | ZEND_ACC_STATIC)
  PHP_ME(ChannelCredentials, createInsecure, NULL,
         ZEND_ACC_PUBLIC | ZEND_ACC_STATIC)
  PHP_FE_END
};

void grpc_init_channel_credentials(TSRMLS_D) {
  zend_class_entry ce;
  INIT_CLASS_ENTRY(ce, "Grpc\\ChannelCredentials",
                   channel_credentials_methods);
  grpc_set_ssl_roots_override_callback(get_ssl_roots_override);
  ce.create_object = create_wrapped_grpc_channel_credentials;
  grpc_ce_channel_credentials = zend_register_internal_class(&ce TSRMLS_CC);
#if PHP_MAJOR_VERSION >= 7
  memcpy(&channel_credentials_ce_handlers,
         zend_get_std_object_handlers(),
         sizeof(zend_object_handlers));
  channel_credentials_ce_handlers.offset =
    XtOffsetOf(wrapped_grpc_channel_credentials, std);
  channel_credentials_ce_handlers.free_obj =
    free_wrapped_grpc_channel_credentials;
#endif
}


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".activity.recyclerview.MultiTypeRecyclerViewActivity">

    <Button
        android:id="@+id/set_view0"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="setView0"
        android:text="view0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>

    <Button
        android:id="@+id/set_view1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="setView1"
        android:text="view1"
        app:layout_constraintLeft_toRightOf="@+id/set_view0"
        app:layout_constraintTop_toTopOf="@+id/set_view0"/>

    <Button
        android:id="@+id/set_view2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="setView2"
        android:text="view2"
        app:layout_constraintLeft_toRightOf="@+id/set_view1"
        app:layout_constraintTop_toTopOf="@+id/set_view0"/>

    <Button
        android:id="@+id/set_head"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="setHead"
        android:text="head"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/set_view1"/>

    <Button
        android:id="@+id/set_content"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="setContent"
        android:text="content"
        app:layout_constraintLeft_toRightOf="@+id/set_head"
        app:layout_constraintTop_toTopOf="@+id/set_head"/>

    <Button
        android:id="@+id/set_foot"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="setFoot"
        android:text="foot"
        app:layout_constraintLeft_toRightOf="@+id/set_content"
        app:layout_constraintTop_toTopOf="@+id/set_head"/>

    <Button
        android:id="@+id/check"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="checkDataType"
        android:text="check"
        app:layout_constraintLeft_toRightOf="@+id/set_foot"
        app:layout_constraintTop_toTopOf="@+id/set_head"/>

    <Button
        android:id="@+id/add_one"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="addOne"
        android:text="1"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/set_foot"/>

    <Button
        android:id="@+id/add_two"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="addTwo"
        android:text="2"
        app:layout_constraintLeft_toRightOf="@+id/add_one"
        app:layout_constraintTop_toTopOf="@+id/add_one"/>

    <Button
        android:id="@+id/add_three"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="addThree"
        android:text="3"
        app:layout_constraintLeft_toRightOf="@+id/add_two"
        app:layout_constraintTop_toTopOf="@+id/add_one"/>

    <Button
        android:id="@+id/add_four"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="addFour"
        android:text="4"
        app:layout_constraintLeft_toRightOf="@+id/add_three"
        app:layout_constraintTop_toTopOf="@+id/add_one"/>

    <Button
        android:id="@+id/add_five"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="addFive"
        android:text="5"
        app:layout_constraintLeft_toRightOf="@+id/add_four"
        app:layout_constraintTop_toTopOf="@+id/add_one"/>

    <TextView
        android:id="@+id/result"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:background="#44ffcc"
        android:gravity="center_vertical"
        android:minHeight="48dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toLeftOf="@+id/remove"
        app:layout_constraintTop_toBottomOf="@+id/add_one"
        tools:text="-->>result-->>result-->>result-->>result-->>result-->>result-->>result"/>

    <Button
        android:id="@+id/remove"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="removeByType"
        android:text="remove"
        app:layout_constraintBottom_toBottomOf="@+id/result"
        app:layout_constraintRight_toLeftOf="@+id/run"
        app:layout_constraintTop_toTopOf="@+id/result"/>

    <Button
        android:id="@+id/run"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="run"
        android:text="run"
        app:layout_constraintBottom_toBottomOf="@+id/result"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="@+id/result"/>

    <View
        android:id="@+id/divider"
        android:layout_width="0dp"
        android:layout_height="1dp"
        android:layout_marginBottom="2dp"
        android:layout_marginTop="2dp"
        android:background="#cccccc"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/result"/>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:orientation="horizontal"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/divider"/>
</android.support.constraint.ConstraintLayout>


text:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">

    <FrameLayout
        android:id="@+id/splash_root"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:scrollbars="none">

        <ImageView
            android:id="@+id/spalash_background"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scaleType="centerCrop" />

    </FrameLayout>
</layout>


text:
/* global describe, it, require */
'use strict';

// MODULES //

var // Expectation library:
	chai = require( 'chai' ),

	// Module to be tested:
	signum = require( './../lib/array.js' );

// VARIABLES //

var expect = chai.expect,
	assert = chai.assert;

// TESTS //

describe( 'array signum', function tests() {

	it( 'should export a function', function test() {
		expect( signum ).to.be.a( 'function' );
	});

	it( 'should evaluate the signum function', function test() {

		var data, expected, actual;

		data = [ 10, -1, 234, -0.344, 5, 0, -0 ];

		actual = new Array( data.length );
		actual = signum( actual, data );
		expected = [ 1, -1, 1, -1, 1, 0, -0 ];

		assert.deepEqual( actual, expected );
	});

	it( 'should return an empty array if provided an empty array', function test() {
		var s;

		s = signum( [], [] );
		assert.deepEqual( s, [] );

		s = signum( new Int8Array(), new Int8Array() );
		assert.deepEqual( s, new Int8Array() );
	});

});


text:
package com.azure.resourcemanager.hybridcontainerservice.generated;

import com.azure.core.util.BinaryData;
import com.azure.resourcemanager.hybridcontainerservice.models.AgentPoolProfile;
import com.azure.resourcemanager.hybridcontainerservice.models.CloudProviderProfile;
import com.azure.resourcemanager.hybridcontainerservice.models.CloudProviderProfileInfraNetworkProfile;
import com.azure.resourcemanager.hybridcontainerservice.models.CloudProviderProfileInfraStorageProfile;
import com.azure.resourcemanager.hybridcontainerservice.models.Mode;
import com.azure.resourcemanager.hybridcontainerservice.models.OsType;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

public final class AgentPoolProfileTests {
    @Test
    public void testDeserialize() {
        AgentPoolProfile model =
            BinaryData
                .fromString(
                    "{\"count\":811282573,\"availabilityZones\":[\"rimz\",\"npvswjdkirso\",\"dqxhcrmnohjtckwh\"],\"maxCount\":1629637737,\"maxPods\":1580515344,\"minCount\":614073164,\"mode\":\"System\",\"nodeLabels\":{\"norcjxvsnbyxqab\":\"sqwpgrjb\",\"shurzafbljjgpbto\":\"mocpc\",\"mkljavb\":\"c\",\"pku\":\"idtqajzyu\"},\"nodeTaints\":[\"rlkhbzhfepgzgq\",\"xzlocxscp\",\"ierhhbcsglummaj\"],\"osType\":\"Linux\",\"nodeImageVersion\":\"dxob\",\"vmSize\":\"dxkqpx\",\"cloudProviderProfile\":{\"infraNetworkProfile\":{\"vnetSubnetIds\":[\"onpimexgstxg\",\"po\",\"gmaajrm\"]},\"infraStorageProfile\":{\"storageSpaceIds\":[\"zrlovmclwhijcoej\",\"tbzaqsqsycbkbfk\",\"ukdkexxppofmxa\",\"c\"]}}}")
                .toObject(AgentPoolProfile.class);
        Assertions.assertEquals(811282573, model.count());
        Assertions.assertEquals("rimz", model.availabilityZones().get(0));
        Assertions.assertEquals(1629637737, model.maxCount());
        Assertions.assertEquals(1580515344, model.maxPods());
        Assertions.assertEquals(614073164, model.minCount());
        Assertions.assertEquals(Mode.SYSTEM, model.mode());
        Assertions.assertEquals("sqwpgrjb", model.nodeLabels().get("norcjxvsnbyxqab"));
        Assertions.assertEquals("rlkhbzhfepgzgq", model.nodeTaints().get(0));
        Assertions.assertEquals(OsType.LINUX, model.osType());
        Assertions.assertEquals("dxob", model.nodeImageVersion());
        Assertions.assertEquals("dxkqpx", model.vmSize());
        Assertions
            .assertEquals("onpimexgstxg", model.cloudProviderProfile().infraNetworkProfile().vnetSubnetIds().get(0));
        Assertions
            .assertEquals(
                "zrlovmclwhijcoej", model.cloudProviderProfile().infraStorageProfile().storageSpaceIds().get(0));
    }

    @Test
    public void testSerialize() {
        AgentPoolProfile model =
            new AgentPoolProfile()
                .withCount(811282573)
                .withAvailabilityZones(Arrays.asList("rimz", "npvswjdkirso", "dqxhcrmnohjtckwh"))
                .withMaxCount(1629637737)
                .withMaxPods(1580515344)
                .withMinCount(614073164)
                .withMode(Mode.SYSTEM)
                .withNodeLabels(
                    mapOf(
                        "norcjxvsnbyxqab", "sqwpgrjb", "shurzafbljjgpbto", "mocpc", "mkljavb", "c", "pku", "idtqajzyu"))
                .withNodeTaints(Arrays.asList("rlkhbzhfepgzgq", "xzlocxscp", "ierhhbcsglummaj"))
                .withOsType(OsType.LINUX)
                .withNodeImageVersion("dxob")
                .withVmSize("dxkqpx")
                .withCloudProviderProfile(
                    new CloudProviderProfile()
                        .withInfraNetworkProfile(
                            new CloudProviderProfileInfraNetworkProfile()
                                .withVnetSubnetIds(Arrays.asList("onpimexgstxg", "po", "gmaajrm")))
                        .withInfraStorageProfile(
                            new CloudProviderProfileInfraStorageProfile()
                                .withStorageSpaceIds(
                                    Arrays.asList("zrlovmclwhijcoej", "tbzaqsqsycbkbfk", "ukdkexxppofmxa", "c"))));
        model = BinaryData.fromObject(model).toObject(AgentPoolProfile.class);
        Assertions.assertEquals(811282573, model.count());
        Assertions.assertEquals("rimz", model.availabilityZones().get(0));
        Assertions.assertEquals(1629637737, model.maxCount());
        Assertions.assertEquals(1580515344, model.maxPods());
        Assertions.assertEquals(614073164, model.minCount());
        Assertions.assertEquals(Mode.SYSTEM, model.mode());
        Assertions.assertEquals("sqwpgrjb", model.nodeLabels().get("norcjxvsnbyxqab"));
        Assertions.assertEquals("rlkhbzhfepgzgq", model.nodeTaints().get(0));
        Assertions.assertEquals(OsType.LINUX, model.osType());
        Assertions.assertEquals("dxob", model.nodeImageVersion());
        Assertions.assertEquals("dxkqpx", model.vmSize());
        Assertions
            .assertEquals("onpimexgstxg", model.cloudProviderProfile().infraNetworkProfile().vnetSubnetIds().get(0));
        Assertions
            .assertEquals(
                "zrlovmclwhijcoej", model.cloudProviderProfile().infraStorageProfile().storageSpaceIds().get(0));
    }

    @SuppressWarnings("unchecked")
    private static <T> Map<String, T> mapOf(Object... inputs) {
        Map<String, T> map = new HashMap<>();
        for (int i = 0; i < inputs.length; i += 2) {
            String key = (String) inputs[i];
            T value = (T) inputs[i + 1];
            map.put(key, value);
        }
        return map;
    }
}


text:
/* Base16 Atelier Lakeside Light - Theme */

/* by Bram de Haan (http://atelierbram.github.io/syntax-highlighting/atelier-schemes/lakeside/) */

/* Original Base16 color scheme by Chris Kempson (https://github.com/chriskempson/base16) */

/* https://github.com/jmblog/color-themes-for-highlightjs */

/* Atelier Lakeside Light Comment */

.hljs-comment,
.hljs-title {
  color: #5a7b8c;
}

/* Atelier Lakeside Light Red */

.hljs-variable,
.hljs-attribute,
.hljs-tag,
.hljs-regexp,
.ruby .hljs-constant,
.xml .hljs-tag .hljs-title,
.xml .hljs-pi,
.xml .hljs-doctype,
.html .hljs-doctype,
.css .hljs-id,
.css .hljs-class,
.css .hljs-pseudo {
  color: #d22d72;
}

/* Atelier Lakeside Light Orange */

.hljs-number,
.hljs-preprocessor,
.hljs-pragma,
.hljs-built_in,
.hljs-literal,
.hljs-params,
.hljs-constant {
  color: #935c25;
}

/* Atelier Lakeside Light Yellow */

.hljs-ruby .hljs-class .hljs-title,
.css .hljs-rules .hljs-attribute {
  color: #8a8a0f;
}

/* Atelier Lakeside Light Green */

.hljs-string,
.hljs-value,
.hljs-inheritance,
.hljs-header,
.ruby .hljs-symbol,
.xml .hljs-cdata {
  color: #568c3b;
}

/* Atelier Lakeside Light Aqua */

.css .hljs-hexcolor {
  color: #2d8f6f;
}

/* Atelier Lakeside Light Blue */

.hljs-function,
.python .hljs-decorator,
.python .hljs-title,
.ruby .hljs-function .hljs-title,
.ruby .hljs-title .hljs-keyword,
.perl .hljs-sub,
.javascript .hljs-title,
.coffeescript .hljs-title {
  color: #257fad;
}

/* Atelier Lakeside Light Purple */

.hljs-keyword,
.javascript .hljs-function {
  color: #5d5db1;
}

.hljs {
  display: block;
  overflow-x: auto;
  background: #ebf8ff;
  color: #516d7b;
  padding: 0.5em;
  -webkit-text-size-adjust: none;
}

.coffeescript .javascript,
.javascript .xml,
.tex .hljs-formula,
.xml .javascript,
.xml .vbscript,
.xml .css,
.xml .hljs-cdata {
  opacity: 0.5;
}