text:
package com.intellij.util.containers;

import com.intellij.util.ArrayUtil;
import com.intellij.util.ArrayUtilRt;
import com.intellij.util.concurrency.AtomicFieldUpdater;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;

import java.util.*;

/**
 * This class is a
 * - lock-free (CAS instead of ReentrantLock)
 * - less-memory (no lock field)
 * - less-garbage (does not create Object[0] arrays)
 * - non-cloneable, non-serializable, no-subList-method variant of {@link java.util.concurrent.CopyOnWriteArrayList}.
 * It generally is faster than COWAL in case of low write-contention.
 * (Note that it is not advisable to use COWAL in high write-contention code anyway, consider using {@link java.util.concurrent.ConcurrentHashMap}) instead)
 */
class LockFreeCopyOnWriteArrayList<E> implements List<E>, RandomAccess, ConcurrentList<E> {
  @NotNull private volatile Object[] array;

  LockFreeCopyOnWriteArrayList() {
    array = ArrayUtil.EMPTY_OBJECT_ARRAY;
  }
  LockFreeCopyOnWriteArrayList(@NotNull Collection<? extends E> c) {
    array = c.isEmpty() ? ArrayUtil.EMPTY_OBJECT_ARRAY : c.toArray();
  }

  @NotNull
  @TestOnly
  Object[] getArray() {
    return array;
  }

  private static final AtomicFieldUpdater<LockFreeCopyOnWriteArrayList, Object[]> ARRAY_UPDATER
    = AtomicFieldUpdater.forFieldOfType(LockFreeCopyOnWriteArrayList.class, Object[].class);

  private boolean replaceArray(@NotNull Object[] oldArray, @NotNull Object[] newArray) {
    return ARRAY_UPDATER.compareAndSet(this, oldArray, newArray);
  }

  /**
   * Returns the number of elements in this list.
   *
   * @return the number of elements in this list
   */
  @Override
  public int size() {
    return array.length;
  }

  /**
   * @return <tt>true</tt> if this list contains no elements
   */
  @Override
  public boolean isEmpty() {
    return size() == 0;
  }

  /**
   * Test for equality, coping with nulls.
   */
  private static boolean eq(Object o1, Object o2) {
    return o1 == null ? o2 == null : o1.equals(o2);
  }

  /**
   * static version of indexOf, to allow repeated calls without
   * needing to re-acquire array each time.
   *
   * @param o        element to search for
   * @param elements the array
   * @param index    first index to search
   * @param fence    one past last index to search
   * @return index of element, or -1 if absent
   */
  private static int indexOf(Object o, @NotNull Object[] elements, int index, int fence) {
    if (o == null) {
      for (int i = index; i < fence; i++) {
        if (elements[i] == null) {
          return i;
        }
      }
    }
    else {
      for (int i = index; i < fence; i++) {
        if (o.equals(elements[i])) {
          return i;
        }
      }
    }
    return -1;
  }

  /**
   * static version of lastIndexOf.
   *
   * @param o        element to search for
   * @param elements the array
   * @param index    first index to search
   * @return index of element, or -1 if absent
   */
  private static int lastIndexOf(Object o, @NotNull Object[] elements, int index) {
    if (o == null) {
      for (int i = index; i >= 0; i--) {
        if (elements[i] == null) {
          return i;
        }
      }
    }
    else {
      for (int i = index; i >= 0; i--) {
        if (o.equals(elements[i])) {
          return i;
        }
      }
    }
    return -1;
  }

  /**
   * Returns <tt>true</tt> if this list contains the specified element.
   * More formally, returns <tt>true</tt> if and only if this list contains
   * at least one element <tt>e</tt> such that
   * <tt>(o==null ? e==null : o.equals(e))</tt>.
   *
   * @param o element whose presence in this list is to be tested
   * @return <tt>true</tt> if this list contains the specified element
   */
  @Override
  public boolean contains(Object o) {
    Object[] elements = array;
    return indexOf(o, elements, 0, elements.length) >= 0;
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public int indexOf(Object o) {
    Object[] elements = array;
    return indexOf(o, elements, 0, elements.length);
  }

  /**
   * Returns the index of the first occurrence of the specified element in
   * this list, searching forwards from <tt>index</tt>, or returns -1 if
   * the element is not found.
   * More formally, returns the lowest index <tt>i</tt> such that
   * <tt>(i >= index && (e==null ? get(i)==null : e.equals(get(i))))</tt>,
   * or -1 if there is no such index.
   *
   * @param e     element to search for
   * @param index index to start searching from
   * @return the index of the first occurrence of the element in
   *         this list at position <tt>index</tt> or later in the list;
   *         <tt>-1</tt> if the element is not found.
   * @throws IndexOutOfBoundsException if the specified index is negative
   */
  public int indexOf(E e, int index) {
    Object[] elements = array;
    return indexOf(e, elements, index, elements.length);
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public int lastIndexOf(Object o) {
    Object[] elements = array;
    return lastIndexOf(o, elements, elements.length - 1);
  }

  /**
   * Returns the index of the last occurrence of the specified element in
   * this list, searching backwards from <tt>index</tt>, or returns -1 if
   * the element is not found.
   * More formally, returns the highest index <tt>i</tt> such that
   * <tt>(i <= index && (e==null ? get(i)==null : e.equals(get(i))))</tt>,
   * or -1 if there is no such index.
   *
   * @param e     element to search for
   * @param index index to start searching backwards from
   * @return the index of the last occurrence of the element at position
   *         less than or equal to <tt>index</tt> in this list;
   *         -1 if the element is not found.
   * @throws IndexOutOfBoundsException if the specified index is greater
   *                                   than or equal to the current size of this list
   */
  public int lastIndexOf(E e, int index) {
    Object[] elements = array;
    return lastIndexOf(e, elements, index);
  }

  /**
   * Returns an array containing all of the elements in this list
   * in proper sequence (from first to last element).
   *

   *
The returned array will be "safe" in that no references to it are
   * maintained by this list.  (In other words, this method must allocate
   * a new array).  The caller is thus free to modify the returned array.
   *

   *
This method acts as bridge between array-based and collection-based
   * APIs.
   *
   * @return an array containing all the elements in this list
   */
  @NotNull
  @Override
  public Object[] toArray() {
    Object[] elements = array;
    if (elements.length == 0) return ArrayUtilRt.EMPTY_OBJECT_ARRAY;

    return Arrays.copyOf(elements, elements.length, Object[].class);
  }

  /**
   * Returns an array containing all of the elements in this list in
   * proper sequence (from first to last element); the runtime type of
   * the returned array is that of the specified array.  If the list fits
   * in the specified array, it is returned therein.  Otherwise, a new
   * array is allocated with the runtime type of the specified array and
   * the size of this list.
   *

   *
If this list fits in the specified array with room to spare
   * (i.e., the array has more elements than this list), the element in
   * the array immediately following the end of the list is set to
   * <tt>null</tt>.  (This is useful in determining the length of this
   * list only if the caller knows that this list does not contain
   * any null elements.)
   *

   *
Like the {@link #toArray()} method, this method acts as bridge between
   * array-based and collection-based APIs.  Further, this method allows
   * precise control over the runtime type of the output array, and may,
   * under certain circumstances, be used to save allocation costs.
   *

   *
Suppose <tt>x</tt> is a list known to contain only strings.
   * The following code can be used to dump the list into a newly
   * allocated array of <tt>String</tt>:
   *

   *

   *     String[] y = x.toArray(new String[0]);

   *
   * Note that <tt>toArray(new Object[0])</tt> is identical in function to
   * <tt>toArray()</tt>.
   *
   * @param a the array into which the elements of the list are to
   *          be stored, if it is big enough; otherwise, a new array of the
   *          same runtime type is allocated for this purpose.
   * @return an array containing all the elements in this list
   * @throws ArrayStoreException  if the runtime type of the specified array
   *                              is not a supertype of the runtime type of every element in
   *                              this list
   * @throws NullPointerException if the specified array is null
   */
  @NotNull
  @Override
  @SuppressWarnings("unchecked")
  public <T> T[] toArray(@NotNull T[] a) {
    Object[] elements = array;
    int len = elements.length;
    if (a.length < len) {
      return (T[])Arrays.copyOf(elements, len, a.getClass());
    }
    System.arraycopy(elements, 0, a, 0, len);
    if (a.length > len) {
      a[len] = null;
    }
    return a;
  }

  // Positional Access Operations

  @SuppressWarnings("unchecked")
  private E get(@NotNull Object[] a, int index) {
    return (E)a[index];
  }

  /**
   * {@inheritDoc}
   *
   * @throws IndexOutOfBoundsException {@inheritDoc}
   */
  @Override
  public E get(int index) {
    return get(array, index);
  }

  /**
   * Replaces the element at the specified position in this list with the
   * specified element.
   *
   */
  @Override
  public E set(int index, E element) throws IndexOutOfBoundsException {
    E oldValue;
    Object[] elements;
    Object[] newElements;
    do {
      elements = array;
      oldValue = get(elements, index);

      if (oldValue == element) {
        // Not quite a no-op; ensures volatile write semantics
        newElements = elements;
      }
      else {
        newElements = createArraySet(elements, index, element);
      }
    } while(!replaceArray(elements, newElements));
    return oldValue;
  }

  @NotNull
  private static Object[] createArraySet(@NotNull Object[] elements, int index, Object element) {
    int len = elements.length;
    Object[] newElements = Arrays.copyOf(elements, len, Object[].class);
    newElements[index] = element;
    return newElements;
  }

  /**
   * Appends the specified element to the end of this list.
   *
   * @param e element to be appended to this list
   * @return <tt>true</tt> (as specified by {@link Collection#add})
   */
  @Override
  public boolean add(E e) {
    while (true) {
      Object[] elements = array;
      Object[] newElements = createArrayAdd(elements, e);
      if (replaceArray(elements, newElements)) break;
    }
    return true;
  }

  @NotNull
  private Object[] createArrayAdd(@NotNull Object[] elements, E e) {
    int len = elements.length;
    Object[] newElements = new Object[len + 1];
    if (len != 0) {
      System.arraycopy(elements, 0, newElements, 0, len);
    }
    newElements[len] = e;
    return newElements;
  }

  /**
   * Inserts the specified element at the specified position in this
   * list. Shifts the element currently at that position (if any) and
   * any subsequent elements to the right (adds one to their indices).
   *
   */
  @Override
  public void add(int index, E element) throws IndexOutOfBoundsException {
    while (true) {
      Object[] elements = array;
      Object[] newElements = createArrayAdd(elements, index, element);
      if (replaceArray(elements, newElements)) break;
    }
  }

  @NotNull
  private Object[] createArrayAdd(@NotNull Object[] elements, int index, E element) {
    int len = elements.length;
    if (index > len || index < 0) {
      throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + len);
    }
    Object[] newElements = new Object[len + 1];
    if (index != 0) {
      System.arraycopy(elements, 0, newElements, 0, index);
    }
    int numMoved = len - index;
    if (numMoved != 0) {
      System.arraycopy(elements, index, newElements, index + 1, numMoved);
    }
    newElements[index] = element;
    return newElements;
  }

  /**
   * Removes the element at the specified position in this list.
   * Shifts any subsequent elements to the left (subtracts one from their
   * indices).  Returns the element that was removed from the list.
   *
   */
  @Override
  public E remove(int index) throws IndexOutOfBoundsException {
    E oldValue;
    while (true) {
      Object[] elements = array;
      Object[] newElements = createArrayRemove(elements, index);
      if (replaceArray(elements, newElements)) {
        oldValue = get(elements, index);
        break;
      }
    }
    return oldValue;
  }

  @NotNull
  private static Object[] createArrayRemove(@NotNull Object[] elements, int index) {
    int len = elements.length;
    Object[] newElements = len == 1 ? ArrayUtilRt.EMPTY_OBJECT_ARRAY : new Object[len - 1];
    if (index != 0) {
      System.arraycopy(elements, 0, newElements, 0, index);
    }
    int numMoved = len - index - 1;
    if (numMoved != 0) {
      System.arraycopy(elements, index + 1, newElements, index, numMoved);
    }
    return newElements;
  }

  /**
   * Removes the first occurrence of the specified element from this list,
   * if it is present.  If this list does not contain the element, it is
   * unchanged.  More formally, removes the element with the lowest index
   * <tt>i</tt> such that
   * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>
   * (if such an element exists).  Returns <tt>true</tt> if this list
   * contained the specified element (or equivalently, if this list
   * changed as a result of the call).
   *
   * @param o element to be removed from this list, if present
   * @return <tt>true</tt> if this list contained the specified element
   */
  @Override
  public boolean remove(Object o) {
    while (true) {
      Object[] elements = array;
      Object[] newElements = createArrayRemove(elements, o);
      if (newElements == null) {
        return false;
      }
      if (replaceArray(elements, newElements)) return true;
    }
  }

  // null means not found
  @Nullable
  private static Object[] createArrayRemove(@NotNull Object[] elements, Object o) {
    int len = elements.length;
    if (len == 0) {
      return null;
    }
    // Copy while searching for element to remove
    // This wins in the normal case of element being present
    int newLen = len - 1;
    Object[] newElements = newLen == 0 ? ArrayUtilRt.EMPTY_OBJECT_ARRAY : new Object[newLen];

    int i;
    for (i = newLen; i != 0; --i) {
      Object element = elements[i];
      if (eq(o, element)) {
        // found one;  copy remaining and exit
        System.arraycopy(elements, 0, newElements, 0, i);
        break;
      }
      newElements[i-1] = element;
    }

    // special handling for last cell
    if (i == 0 && !eq(o, elements[0])) {
      return null;
    }
    return newElements;
  }

  /**
   * Removes from this list all of the elements whose index is between
   * <tt>fromIndex</tt>, inclusive, and <tt>toIndex</tt>, exclusive.
   * Shifts any succeeding elements to the left (reduces their index).
   * This call shortens the list by <tt>(toIndex - fromIndex)</tt> elements.
   * (If <tt>toIndex==fromIndex</tt>, this operation has no effect.)
   *
   * @param fromIndex index of first element to be removed
   * @param toIndex   index after last element to be removed
   * @throws IndexOutOfBoundsException if fromIndex or toIndex out of range
   *                                   ({@code {fromIndex < 0 || toIndex > size() || toIndex < fromIndex})
   */
  private void removeRange(int fromIndex, int toIndex) {
    Object[] elements;
    Object[] newElements;
    do {
      elements = array;
      int len = elements.length;

      if (fromIndex < 0 || toIndex > len || toIndex < fromIndex) {
        throw new IndexOutOfBoundsException();
      }
      int newlen = len - (toIndex - fromIndex);
      int numMoved = len - toIndex;
      if (numMoved == 0) {
        newElements = Arrays.copyOf(elements, newlen, Object[].class);
      }
      else {
        newElements = new Object[newlen];
        System.arraycopy(elements, 0, newElements, 0, fromIndex);
        System.arraycopy(elements, toIndex, newElements, fromIndex, numMoved);
      }
    }
    while (!replaceArray(elements, newElements));
  }

  /**
   * Append the element if not present.
   *
   * @param e element to be added to this list, if absent
   * @return <tt>true</tt> if the element was added
   */
  @Override
  public boolean addIfAbsent(E e) {
    Object[] elements;
    Object[] newElements;
    do {
      // Copy while checking if already present.
      // This wins in the most common case where it is not present
      elements = array;
      int len = elements.length;
      newElements = new Object[len + 1];
      for (int i = 0; i < len; ++i) {
        if (eq(e, elements[i])) {
          return false; // exit, throwing away copy
        }
        newElements[i] = elements[i];
      }
      newElements[len] = e;
    }
    while (!replaceArray(elements, newElements));
    return true;
  }

  /**
   * Returns <tt>true</tt> if this list contains all of the elements of the
   * specified collection.
   *
   * @param c collection to be checked for containment in this list
   * @return <tt>true</tt> if this list contains all of the elements of the
   *         specified collection
   * @throws NullPointerException if the specified collection is null
   * @see #contains(Object)
   */
  @Override
  public boolean containsAll(@NotNull Collection<?> c) {
    Object[] elements = array;
    int len = elements.length;
    for (Object e : c) {
      if (indexOf(e, elements, 0, len) < 0) {
        return false;
      }
    }
    return true;
  }

  /**
   * Removes from this list all of its elements that are contained in
   * the specified collection. This is a particularly expensive operation
   * in this class because of the need for an internal temporary array.
   *
   * @param c collection containing elements to be removed from this list
   * @return <tt>true</tt> if this list changed as a result of the call
   * @throws ClassCastException   if the class of an element of this list
   *                              is incompatible with the specified collection
   *                              (optional)
   * @throws NullPointerException if this list contains a null element and the
   *                              specified collection does not permit null elements
   *                              (optional),
   *                              or if the specified collection is null
   * @see #remove(Object)
   */
  @Override
  public boolean removeAll(@NotNull Collection<?> c) {
    if (c.isEmpty()) return false;
    while (true) {
      Object[] elements = array;
      Object[] newElements = createArrayRemoveAll(elements, c);
      if (newElements == null) return false;
      if (replaceArray(elements, newElements)) return true;
    }
  }

  // null means not found
  @Nullable
  private static Object[] createArrayRemoveAll(@NotNull Object[] elements, @NotNull Collection<?> c) {
    int len = elements.length;
    if (len == 0) {
      return null;
    }
    // temp array holds those elements we know we want to keep
    int newLen = 0;
    Object[] temp = new Object[len];
    for (Object element : elements) {
      if (!c.contains(element)) {
        temp[newLen++] = element;
      }
    }
    if (newLen == len) {
      return null;
    }
    return Arrays.copyOf(temp, newLen, Object[].class);
  }

  /**
   * Retains only the elements in this list that are contained in the
   * specified collection.  In other words, removes from this list all of
   * its elements that are not contained in the specified collection.
   *
   * @param c collection containing elements to be retained in this list
   * @return <tt>true</tt> if this list changed as a result of the call
   * @throws ClassCastException   if the class of an element of this list
   *                              is incompatible with the specified collection
   *                              (optional)
   * @throws NullPointerException if this list contains a null element and the
   *                              specified collection does not permit null elements
   *                              (optional),
   *                              or if the specified collection is null
   * @see #remove(Object)
   */
  @Override
  public boolean retainAll(@NotNull Collection<?> c) {
    while (true) {
      Object[] elements = array;
      Object[] newElements = createArrayRetainAll(elements, c);
      if (newElements == null) return false;
      if (replaceArray(elements, newElements)) return true;
    }
  }

  @Nullable
  private static Object[] createArrayRetainAll(@NotNull Object[] elements, @NotNull Collection<?> c) {
    int len = elements.length;
    if (len == 0) {
      return null;
    }
    // temp array holds those elements we know we want to keep
    int newlen = 0;
    Object[] temp = new Object[len];
    for (Object element : elements) {
      if (c.contains(element)) {
        temp[newlen++] = element;
      }
    }
    if (newlen == len) {
      return null;
    }
    return Arrays.copyOf(temp, newlen, Object[].class);
  }

  /**
   * Appends all of the elements in the specified collection that
   * are not already contained in this list, to the end of
   * this list, in the order that they are returned by the
   * specified collection's iterator.
   *
   * @param c collection containing elements to be added to this list
   * @return the number of elements added
   * @throws NullPointerException if the specified collection is null
   * @see #addIfAbsent(Object)
   */
  @Override
  public int addAllAbsent(@NotNull Collection<? extends E> c) {
    Object[] cs = c.toArray();
    if (cs.length == 0) {
      return 0;
    }

    Object[] uniq = new Object[cs.length];
    Object[] elements;
    Object[] newElements;
    int added;
    do {
      elements = array;
      added = 0;
      int len = elements.length;
      for (Object e : cs) { // scan for duplicates
        if (indexOf(e, elements, 0, len) < 0 &&
            indexOf(e, uniq, 0, added) < 0) {
          uniq[added++] = e;
        }
      }
      if (added == 0) {
        return 0;
      }
      newElements = Arrays.copyOf(elements, len + added, Object[].class);
      System.arraycopy(uniq, 0, newElements, len, added);
    }
    while (!replaceArray(elements, newElements));
    return added;
  }

  /**
   * Removes all of the elements from this list.
   * The list will be empty after this call returns.
   */
  @Override
  public void clear() {
    array = ArrayUtilRt.EMPTY_OBJECT_ARRAY;
  }

  /**
   * Appends all of the elements in the specified collection to the end
   * of this list, in the order that they are returned by the specified
   * collection's iterator.
   *
   * @param c collection containing elements to be added to this list
   * @return <tt>true</tt> if this list changed as a result of the call
   * @throws NullPointerException if the specified collection is null
   * @see #add(Object)
   */
  @Override
  public boolean addAll(@NotNull Collection<? extends E> c) {
    if (c.isEmpty()) return false;
    Object[] cs = c.toArray();
    if (cs.length == 0) {
      return false;
    }

    while (true) {
      Object[] elements = array;
      Object[] newElements = createArrayAddAll(elements, cs);
      if (replaceArray(elements, newElements)) return true;
    }
  }

  @NotNull
  private static Object[] createArrayAddAll(@NotNull Object[] elements, @NotNull Object[] cs) {
    int len = elements.length;
    Object[] newElements = Arrays.copyOf(elements, len + cs.length, Object[].class);
    System.arraycopy(cs, 0, newElements, len, cs.length);
    return newElements;
  }
  /**
   * Inserts all of the elements in the specified collection into this
   * list, starting at the specified position.  Shifts the element
   * currently at that position (if any) and any subsequent elements to
   * the right (increases their indices).  The new elements will appear
   * in this list in the order that they are returned by the
   * specified collection's iterator.
   *
   * @param index index at which to insert the first element
   *              from the specified collection
   * @param c     collection containing elements to be added to this list
   * @return <tt>true</tt> if this list changed as a result of the call
   * @throws NullPointerException      if the specified collection is null
   * @see #add(int, Object)
   */
  @Override
  public boolean addAll(int index, @NotNull Collection<? extends E> c) throws IndexOutOfBoundsException {
    Object[] cs = c.toArray();
    if (cs.length == 0) {
      return false;
    }

    while (true) {
      Object[] elements = array;
      Object[] newElements = createArrayAddAll(elements, index, cs);
      if (replaceArray(elements, newElements)) break;
    }

    return true;
  }

  @NotNull
  private static Object[] createArrayAddAll(@NotNull Object[] elements, int index, @NotNull Object[] cs) {
    int len = elements.length;
    if (index > len || index < 0) {
      throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + len);
    }
    int numMoved = len - index;
    Object[] newElements;
    if (numMoved == 0) {
      newElements = Arrays.copyOf(elements, len + cs.length, Object[].class);
    }
    else {
      newElements = new Object[len + cs.length];
      System.arraycopy(elements, 0, newElements, 0, index);
      System.arraycopy(elements, index, newElements, index + cs.length, numMoved);
    }
    System.arraycopy(cs, 0, newElements, index, cs.length);
    return newElements;
  }

  /**
   * Returns a string representation of this list.  The string
   * representation consists of the string representations of the list's
   * elements in the order they are returned by its iterator, enclosed in
   * square brackets (<tt>"[]"</tt>).  Adjacent elements are separated by
   * the characters <tt>", "</tt> (comma and space).  Elements are
   * converted to strings as by {@link String#valueOf(Object)}.
   *
   * @return a string representation of this list
   */
  @Override
  @NotNull
  public String toString() {
    return Arrays.toString(array);
  }

  /**
   * Compares the specified object with this list for equality.
   * Returns {@code true} if the specified object is the same object
   * as this object, or if it is also a {@link List} and the sequence
   * of elements returned by an {@linkplain List#iterator() iterator}
   * over the specified list is the same as the sequence returned by
   * an iterator over this list.  The two sequences are considered to
   * be the same if they have the same length and corresponding
   * elements at the same position in the sequence are equal.
   * Two elements {@code e1} and {@code e2} are considered
   * equal if {@code (e1 == null ? e2 == null : e1.equals(e2))}.
   *
   * @param o the object to be compared for equality with this list
   * @return {@code true} if the specified object is equal to this list
   */
  @Override
  public boolean equals(Object o) {
    if (o == this) {
      return true;
    }
    if (!(o instanceof List)) {
      return false;
    }

    List<?> list = (List<?>)o;
    Iterator<?> it = list.iterator();
    for (Object element : array) {
      if (!it.hasNext() || !eq(element, it.next())) {
        return false;
      }
    }
    return !it.hasNext();
  }

  /**
   * Returns the hash code value for this list.
   *

   *
This implementation uses the definition in {@link List#hashCode}.
   *
   * @return the hash code value for this list
   */
  @Override
  public int hashCode() {
    int hashCode = 1;
    for (Object obj : array) {
      hashCode = 31 * hashCode + (obj == null ? 0 : obj.hashCode());
    }
    return hashCode;
  }

  /**
   * Returns an iterator over the elements in this list in proper sequence.
   *

   *
The returned iterator provides a snapshot of the state of the list
   * when the iterator was constructed. No synchronization is needed while
   * traversing the iterator. The iterator does NOT support the
   * <tt>remove</tt> method.
   *
   * @return an iterator over the elements in this list in proper sequence
   */
  @NotNull
  @Override
  public Iterator<E> iterator() {
    Object[] elements = array;
    if (elements.length == 0) return EmptyIterator.getInstance();

    return new COWIterator(elements, 0);
  }

  /**
   * {@inheritDoc}
   *

   *
The returned iterator provides a snapshot of the state of the list
   * when the iterator was constructed. No synchronization is needed while
   * traversing the iterator. The iterator does NOT support the
   * <tt>remove</tt>, <tt>set</tt> or <tt>add</tt> methods.
   */
  @NotNull
  @Override
  public ListIterator<E> listIterator() {
    return listIterator(0);
  }

  /**
   * {@inheritDoc}
   *

   *
The returned iterator provides a snapshot of the state of the list
   * when the iterator was constructed. No synchronization is needed while
   * traversing the iterator. The iterator does NOT support the
   * <tt>remove</tt>, <tt>set</tt> or <tt>add</tt> methods.
   *
   * @throws IndexOutOfBoundsException {@inheritDoc}
   */
  @NotNull
  @Override
  public ListIterator<E> listIterator(final int index) {
    Object[] elements = array;
    int len = elements.length;
    if (index < 0 || index > len) {
      throw new IndexOutOfBoundsException("Index: " + index);
    }

    return elements.length == 0 ? EmptyListIterator.<E>getInstance() : new COWIterator(elements, index);
  }

  private class COWIterator implements ListIterator<E> {
    /**
     * Snapshot of the array
     */
    private final Object[] snapshot;
    /**
     * Index of element to be returned by subsequent call to next.
     */
    private int cursor;
    private int lastRet = -1; // index of last element returned; -1 if no such

    private COWIterator(@NotNull Object[] elements, int initialCursor) {
      cursor = initialCursor;
      snapshot = elements;
    }

    @Override
    public boolean hasNext() {
      return cursor < snapshot.length;
    }

    @Override
    public boolean hasPrevious() {
      return cursor > 0;
    }

    @Override
    @SuppressWarnings("unchecked")
    public E next() {
      if (!hasNext()) {
        throw new NoSuchElementException();
      }
      lastRet = cursor;
      return (E)snapshot[cursor++];
    }

    @Override
    @SuppressWarnings("unchecked")
    public E previous() {
      if (!hasPrevious()) {
        throw new NoSuchElementException();
      }
      return (E)snapshot[lastRet = --cursor];
    }

    @Override
    public int nextIndex() {
      return cursor;
    }

    @Override
    public int previousIndex() {
      return cursor - 1;
    }

    @Override
    public void remove() {
      if (lastRet < 0) {
        throw new NoSuchElementException();
      }
      @SuppressWarnings("unchecked")
      E e = (E)snapshot[lastRet];
      lastRet = -1;
      LockFreeCopyOnWriteArrayList.this.remove(e);
    }

    @Override
    public void set(E e) {
      throw new UnsupportedOperationException();
    }

    @Override
    public void add(E e) {
      throw new UnsupportedOperationException();
    }
  }

  @NotNull
  @Override
  public List<E> subList(int fromIndex, int toIndex) {
    throw new UnsupportedOperationException();
  }
}


text:
<?php

// autoload class on bundle member model
Autoloader::directories(array(
	Bundle::path('jenjang').'models',
));

redpajama_set_name: RedPajamaGithub


text:
#region License

#endregion

using System.Xml;
using Spring.Aop.Config;
using Spring.Objects.Factory.Config;
using Spring.Objects.Factory.Support;
using Spring.Objects.Factory.Xml;
using Spring.Transaction.Interceptor;

namespace Spring.Transaction.Config
{
    ///
    /// IObjectDefinitionParser implementation that allows users to easily configure all the
    /// infrastructure objects required to enable attribute-driven transction demarcation.
    ///
    /// <author>Rob Harrop</author>
    /// <author>Juergen Hoeller</author>
    /// <author>Mark Pollack (.NET)</author>
    public class AttributeDrivenObjectDefinitionParser : AbstractObjectDefinitionParser
    {
        ///
        /// The 'proxy-target-type' attribute
        ///
        private static readonly string PROXY_TARGET_TYPE = "proxy-target-type";

        ///
        /// The 'order' property/attribute
        ///
        private static readonly string ORDER = "order";

        ///
        /// Central template method to actually parse the supplied XmlElement
        /// into one or more IObjectDefinitions.
        ///
        /// <param name="element">The element that is to be parsed into one or more <see cref="IObjectDefinition"/>s</param>
        /// <param name="parserContext">The the object encapsulating the current state of the parsing process;
        /// provides access to a <see cref="IObjectDefinitionRegistry"/></param>
        /// <returns>
        /// The primary IObjectDefinition resulting from the parsing of the supplied XmlElement
        /// </returns>
        protected override AbstractObjectDefinition ParseInternal(XmlElement element, ParserContext parserContext)
        {
            ConfigureAutoProxyCreator(parserContext, element);

            //Create the TransactionAttributeSource
            RootObjectDefinition sourceDef = new RootObjectDefinition(typeof(AttributesTransactionAttributeSource));
            sourceDef.Role = ObjectRole.ROLE_INFRASTRUCTURE;
            string sourceName = parserContext.ReaderContext.RegisterWithGeneratedName(sourceDef);

            //Create the TransactionInterceptor definition.
            RootObjectDefinition interceptorDefinition = new RootObjectDefinition(typeof(TransactionInterceptor));
            interceptorDefinition.Role = ObjectRole.ROLE_INFRASTRUCTURE;
            RegisterTransactionManager(element, interceptorDefinition);
            interceptorDefinition.PropertyValues.Add(TxNamespaceUtils.TRANSACTION_ATTRIBUTE_SOURCE, new RuntimeObjectReference(sourceName));
            String interceptorName = parserContext.ReaderContext.RegisterWithGeneratedName(interceptorDefinition);

            // Create the TransactionAttributeSourceAdvisor definition.
            RootObjectDefinition advisorDef = new RootObjectDefinition(typeof(ObjectFactoryTransactionAttributeSourceAdvisor));
            advisorDef.Role = ObjectRole.ROLE_INFRASTRUCTURE;
            advisorDef.PropertyValues.Add("transactionAttributeSource", new RuntimeObjectReference(sourceName));
            advisorDef.PropertyValues.Add("adviceObjectName", interceptorName);

            if (element.HasAttribute(ORDER))
            {
                advisorDef.PropertyValues.Add(ORDER, GetAttributeValue(element, ORDER));
            }

            return advisorDef;
        }

        private void RegisterTransactionManager(XmlElement element, RootObjectDefinition interceptorDefinition)
        {
            string transactionManagerName = GetAttributeValue(element, TxNamespaceUtils.TRANSACTION_MANAGER_ATTRIBUTE);
            interceptorDefinition.PropertyValues.Add(TxNamespaceUtils.TRANSACTION_MANAGER_PROPERTY,
                                          new RuntimeObjectReference(transactionManagerName));

        }

        ///
        /// Configures the auto proxy creator.
        ///
        /// <param name="parserContext">The parser context.</param>
        /// <param name="element">The element.</param>
        private static void ConfigureAutoProxyCreator(ParserContext parserContext, XmlElement element)
        {
            AopNamespaceUtils.RegisterAutoProxyCreatorIfNecessary(parserContext, element);

            bool proxyTargetClass = parserContext.ParserHelper.IsTrueStringValue(GetAttributeValue(element, PROXY_TARGET_TYPE));
            if (proxyTargetClass)
            {
                AopNamespaceUtils.ForceAutoProxyCreatorToUseDecoratorProxy(parserContext.Registry);
            }
        }

        ///
        /// Gets a value indicating whether an ID should be generated instead of read
        /// from the passed in XmlElement.
        ///
        /// <value><c>true</c> if should generate id; otherwise, <c>false</c>.</value>
        /// <remarks>Note that this flag is about always generating an ID; the parser
        /// won't even check for an "id" attribute in this case.
        /// </remarks>
        protected override bool ShouldGenerateId
        {
            get { return true; }
        }
    }
}


text:
help(){
    echo "Usage: $0 [OPTION]..."
    echo "Run yamlpal's test suite(s) or some convenience commands"
    echo "  -h, --help         Show this help output"
    echo "  -p, --pep8         Run pep8 checks"
    echo "  -l, --lint         Run pylint checks"
    echo "  -s, --stats        Show some project stats"
    echo "  --no-coverage      Don't make a unit test coverage report"
    echo ""
    exit 0;
}

run_pep8_check(){
    # FLAKE 8
    # H307: like imports should be grouped together
    # H405: multi line docstring summary not separated with an empty line
    # H803: git title must end with a period
    # H904: Wrap long lines in parentheses instead of a backslash
    # H802: git commit title should be under 50 chars
    # H701: empty localization string
    FLAKE8_IGNORE="H307,H405,H803,H904,H802,H701"
    # exclude settings files and virtualenvs
    FLAKE8_EXCLUDE="*settings.py,*.venv/*.py"
    echo "Running flake8..."
    flake8 --ignore=$FLAKE8_IGNORE --max-line-length=120 --exclude=$FLAKE8_EXCLUDE yamlpal
}

run_unit_tests(){
    OMIT="/usr/*,*venv*,*travis*"
    if [ -n "$testargs" ]; then
        # pytest -s => show std output (i.e print statements)
        coverage run --omit=$OMIT -m pytest -s "$testargs"
    else
        coverage run --omit=$OMIT -m pytest -s yamlpal
    fi
    TEST_RESULT=$?
    if [ $include_coverage -eq 1 ]; then
        COVERAGE_REPORT=$(coverage report -m)
        echo "$COVERAGE_REPORT"
    fi

    if [ $TEST_RESULT  -gt 0 ]; then
        exit $TEST_RESULT;
    fi
}

run_stats(){
    echo "*** Code ***"
    radon raw -s yamlpal | tail -n 6
}

clean(){
    set +e
    find yamlpal -type d  -name "__pycache__" -exec rm -rf {} \; 2> /dev/null
    set -e
}

# default behavior
just_pep8=0
just_lint=0
just_stats=0
just_clean=0
include_coverage=1
testargs=""

while [ "$#" -gt 0 ]; do
    case "$1" in
        -h|--help) shift; help;;
        -c|--clean) shift; just_clean=1;;
        -p|--pep8) shift; just_pep8=1;;
        -l|--lint) shift; just_lint=1;;
        -s|--stats) shift; just_stats=1;;
        --no-coverage)shift; include_coverage=0;;
        *) testargs="$1"; shift;
   esac
done

if [ $just_pep8 -eq 1 ]; then
    run_pep8_check
    exit $?
fi

if [ $just_stats -eq 1 ]; then
    run_stats
    exit $?
fi

if [ $just_clean -eq 1 ]; then
    clean
    exit $?
fi

run_unit_tests || exit


text:
package converter.shared

sealed trait TodoPriority

case object TodoLow extends TodoPriority

case object TodoNormal extends TodoPriority

case object TodoHigh extends TodoPriority

case class TodoItem(id: String, content: String, priority: TodoPriority, completed: Boolean)


text:
SensorTag-for-Windows
=====================

Sample code that talks to Texus Instruments SensorTag Bluetooth LE device for Windows Universal Apps.  This code supports both versions CC2541 and CC2650

First pair your SensorTag with your Windows 8.1 device, then this app will automatically connect to it and show you all the data.

The SensorTagLibrary code is the part that is designed to be reused in your apps, it provides most of the bluetooth characteristic data available on the SensorTag.


text:
<?php
namespace TmlpStats\Api\Parsers;

use App;
use TmlpStats\Api\Exceptions as ApiExceptions;
use TmlpStats\Api\Parsers;

class Factory
{
    public static function build($type, $options = [])
    {
        $input = ['options' => $options];
        switch ($type) {
            case 'array':
                return App::make(Parsers\ArrayParser::class);
            case 'bool':
                return App::make(Parsers\BoolParser::class);
            case 'date':
                return App::make(Parsers\DateParser::class);
            case 'int':
                return App::make(Parsers\IntParser::class);
            case 'string':
                return App::make(Parsers\StringParser::class, $input);
            case 'Application':
                return App::make(Parsers\ApplicationParser::class);
            case 'Center':
                return App::make(Parsers\CenterParser::class);
            case 'Course':
                return App::make(Parsers\CourseParser::class);
            case 'GlobalReport':
                return App::make(Parsers\GlobalReportParser::class);
            case 'LocalReport':
                return App::make(Parsers\LocalReportParser::class);
            case 'Quarter':
                return App::make(Parsers\QuarterParser::class);
            case 'Region':
                return App::make(Parsers\RegionParser::class);
            case 'TeamMember':
                return App::make(Parsers\TeamMemberParser::class);
            case 'WithdrawCode':
                return App::make(Parsers\WithdrawCodeParser::class);
            default:
                throw new ApiExceptions\ServerErrorException("Unknown parameter type {$type}");
        }
    }
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <parent>
        <groupId>org.wso2.appcloud</groupId>
        <artifactId>appcloud-parent</artifactId>
        <version>3.0.0-SNAPSHOT</version>
        <relativePath>../../../pom.xml</relativePath>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>tierapi</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>tierapi</name>

    <build>
        <finalName>tierapi</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.5.1</version>
                <inherited>true</inherited>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>org.glassfish.jersey</groupId>
            <artifactId>jersey-bom</artifactId>
            <version>2.22.1</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-moxy</artifactId>
        </dependency>
        <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat</groupId>
            <artifactId>tomcat-catalina</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.wso2.carbon</groupId>
            <artifactId>org.wso2.carbon.logging</artifactId>
        </dependency>
    </dependencies>
</project>


text:
import ast

from .exceptions import (
    InvalidTypeException,
    StructureException,
    VariableDeclarationException,
)
from .types import ByteArrayType
from .types import (
    canonicalize_type,
    get_size_of_type,
    parse_type,
)
from .utils import (
    fourbytes_to_int,
    is_varname_valid,
    sha3,
)

# Function argument
class VariableRecord():
    def __init__(self, name, pos, typ, mutable):
        self.name = name
        self.pos = pos
        self.typ = typ
        self.mutable = mutable

    @property
    def size(self):
        return get_size_of_type(self.typ)

# Function signature object
class FunctionSignature():
    def __init__(self, name, args, output_type, const, payable, internal, sig, method_id):
        self.name = name
        self.args = args
        self.output_type = output_type
        self.const = const
        self.payable = payable
        self.internal = internal
        self.sig = sig
        self.method_id = method_id
        self.gas = None

    # Get a signature from a function definition
    @classmethod
    def from_definition(cls, code):
        name = code.name
        pos = 0
        # Determine the arguments, expects something of the form def foo(arg1: num, arg2: num ...
        args = []
        for arg in code.args.args:
            typ = arg.annotation
            if not isinstance(arg.arg, str):
                raise VariableDeclarationException("Argument name invalid", arg)
            if not typ:
                raise InvalidTypeException("Argument must have type", arg)
            if not is_varname_valid(arg.arg):
                raise VariableDeclarationException("Argument name invalid or reserved: " + arg.arg, arg)
            if arg.arg in (x.name for x in args):
                raise VariableDeclarationException("Duplicate function argument name: " + arg.arg, arg)
            parsed_type = parse_type(typ, None)
            args.append(VariableRecord(arg.arg, pos, parsed_type, False))
            if isinstance(parsed_type, ByteArrayType):
                pos += 32
            else:
                pos += get_size_of_type(parsed_type) * 32

        # Apply decorators
        const, payable, internal = False, False, False
        for dec in code.decorator_list:
            if isinstance(dec, ast.Name) and dec.id == "constant":
                const = True
            elif isinstance(dec, ast.Name) and dec.id == "payable":
                payable = True
            elif isinstance(dec, ast.Name) and dec.id == "internal":
                internal = True
            else:
                raise StructureException("Bad decorator", dec)
        # Determine the return type and whether or not it's constant. Expects something
        # of the form:
        # def foo(): ...
        # def foo() -> num: ...
        # If there is no return type, ie. it's of the form def foo(): ...
        # and NOT def foo() -> type: ..., then it's null
        if not code.returns:
            output_type = None
        elif isinstance(code.returns, (ast.Name, ast.Compare, ast.Subscript, ast.Call)):
            output_type = parse_type(code.returns, None)
        else:
            raise InvalidTypeException("Output type invalid or unsupported: %r" % parse_type(code.returns, None), code.returns)
        # Output type must be canonicalizable
        if output_type is not None:
            assert canonicalize_type(output_type)
        # Get the canonical function signature
        sig = name + '(' + ','.join([canonicalize_type(parse_type(arg.annotation, None)) for arg in code.args.args]) + ')'
        # Take the first 4 bytes of the hash of the sig to get the method ID
        method_id = fourbytes_to_int(sha3(bytes(sig, 'utf-8'))[:4])
        return cls(name, args, output_type, const, payable, internal, sig, method_id)

    def to_abi_dict(self):
        return {
            "name": self.name,
            "outputs": [{"type": canonicalize_type(self.output_type), "name": "out"}] if self.output_type else [],
            "inputs": [{"type": canonicalize_type(arg.typ), "name": arg.name} for arg in self.args],
            "constant": self.const,
            "payable": self.payable,
            "type": "constructor" if self.name == "__init__" else "function"
        }


text:
package org.apache.commons.weaver.spi;

import org.apache.commons.weaver.model.Scanner;
import org.apache.commons.weaver.model.WeaveEnvironment;

/**
 * A {@link Weaver} implementation performs the byte code enhancement in the
 * classes.
 */
public interface Weaver {
    /**
     * Using the supplied {@link Scanner}, process a {@link WeaveEnvironment}.
     * @param environment to use
     * @param scanner to use
     * @return whether any work was done.
     */
    boolean process(WeaveEnvironment environment, Scanner scanner);
}


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Fear
{
    string key;
    string fearName;
    Sprite icon;

    public Fear(string key, string name)
    {
        this.key = key;
        fearName = name;
        icon = Resources.Load<Sprite>(key);
    }

    public void SetIcon(Sprite sprite)
    {
        icon = sprite;
    }

    public string FearName { get { return fearName; } }

    public Sprite Icon { get { return icon; } }

    void Start()
    {
        Debug.LogError("Fears should stay prefabs and never be instantiated.");
    }

    public string GetKey() { return key;  }
}


text:
//
//  RXAFNetworkingDefine.h
//  AFNetworking-RXExample
//
//  Created by ceshi on 16/5/30.
//  Copyright © 2016年 Rush. All rights reserved.
//

#ifndef RXAFNetworkingDefine_h
#define RXAFNetworkingDefine_h

// 输出url地址和参数
#ifndef k_RX_SwitchLog_URL_Parameter
#define k_RX_SwitchLog_URL_Parameter           1
#endif

// 输出调试信息
#ifndef k_RX_SwitchLog_Debug
#define k_RX_SwitchLog_Debug                    0
#endif

// 当网络出错的时候,输出Error信息,
#ifndef k_RX_SwitchLog_Error_Print
#define k_RX_SwitchLog_Error_Print                    1
#endif

#endif /* RXAFNetworkingDefine_h */


text:
$scope.message = "hi!";

('progress').hide();


text:
package com.yuqirong.koku.util;

import java.util.Calendar;
import java.util.Date;

/**
 * Created by Anyway on 2015/8/31.
 */
public class RelativeDateFormat {

    private static final long ONE_MINUTE = 60000L;
    private static final long ONE_HOUR = 3600000L;

    private static final String ONE_SECOND_AGO = "秒前";
    private static final String ONE_MINUTE_AGO = "分钟前";
    private static final String ONE_HOUR_AGO = "小时前";

    public static String format(Date date) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        long delta = System.currentTimeMillis() - date.getTime();
        if (delta < 1L * ONE_MINUTE) {
            long seconds = toSeconds(delta);
            return (seconds <= 0 ? 1 : seconds) + ONE_SECOND_AGO;
        }
        if (delta < 60L * ONE_MINUTE) {
            long minutes = toMinutes(delta);
            return (minutes <= 0 ? 1 : minutes) + ONE_MINUTE_AGO;
        }
        if (delta < 24L * ONE_HOUR) {
            long hours = toHours(delta);
            return (hours <= 0 ? 1 : hours) + ONE_HOUR_AGO;
        } else {
            String month = String.valueOf(c.get(Calendar.MONTH) + 1);
            String day = String.valueOf(c.get(Calendar.DAY_OF_MONTH));
            String hour = String.valueOf(c.get(Calendar.HOUR_OF_DAY));
            String minute = String.valueOf(c.get(Calendar.MINUTE));
//            String second = String.valueOf(c.get(Calendar.SECOND));
            if (c.get(Calendar.MONTH) + 1 < 10) {
                month = "0" + month;
            }
            if (c.get(Calendar.DAY_OF_MONTH) < 10) {
                day = "0" + day;
            }
            if (c.get(Calendar.HOUR_OF_DAY) < 10) {
                hour = "0" + hour;
            }
            if (c.get(Calendar.MINUTE) < 10) {
                minute = "0" + minute;
            }
//            if (c.get(Calendar.SECOND) < 10) {
//                second = "0" + second;
//            }
            return c.get(Calendar.YEAR) + "-" + month + "-" + day + " " + hour + ":" + minute;
        }
    }

    private static long toSeconds(long date) {
        return date / 1000L;
    }

    private static long toMinutes(long date) {
        return toSeconds(date) / 60L;
    }

    private static long toHours(long date) {
        return toMinutes(date) / 60L;
    }

}


text:
from singleseriesfns import *
from twoseriesfns import *

def bounded_roi(hd1, hd2, n=20, offset=20):
    """
    Calculates the average, bounded ROI for the proposed trade (assuming the symbol
    with the larger percent gain over offset+n:offset has been shorted).
    NOTE: offset must be greater than or equal to n
    """
    #Calculate percent gain in hd1 and hd2 to determine which would be shorted
    pg1 = (hd1.close[offset] - hd1.close[offset+n]) / hd1.close[offset+n]
    pg2 = (hd2.close[offset] - hd2.close[offset+n]) / hd2.close[offset+n]
    if pg1 > pg2:
        short = hd1
        long = hd2
    else:
        short = hd2
        long = hd1

    #Calculate ROI for shorted symbol
    roi_short = (short.close[offset] - short.close[offset-n]) / short.close[offset]

    #Calculate ROI for long symbol
    roi_long = (long.close[offset-n] - long.close[offset]) / long.close[offset]

    #Return the average of these ROI's, multiplied by 10 and bounded by tanh
    return sp.tanh(5 * (roi_short+roi_long))

def winning_trade_test(hd1, hd2, n=20, offset=20):
    """
    Alternative to bounded_roi for determing class of trade.
    Returns 1 iff the shorted position decreased AND the long position increased.
    """
    #Calculate percent gain in hd1 and hd2 to determine which would be shorted
    pg1 = (hd1.close[offset] - hd1.close[offset+n]) / hd1.close[offset+n]
    pg2 = (hd2.close[offset] - hd2.close[offset+n]) / hd2.close[offset+n]
    if pg1 > pg2:
        short = hd1
        long = hd2
    else:
        short = hd2
        long = hd1

    return 1 if ( short.close[offset] > short.close[offset-n] ) and ( long.close[offset-n] > long.close[offset] ) else 0

def mean_reversion_test(hd1, hd2, n=20, offset=20, hold_time=30, return_index=False):
    """
    Tests over the time period offset:offset-n to see if the pair reverts to the mean.
    Specifically, we are doing this by testing at each closing price in this time period
    to see if the long position is higher than its sma at the same time the short position
    is below its sma.
    """
    #Get short and long positions
    (short_pos, long_pos) = get_short_long(hd1, hd2, n, offset)

    #Calculate the simple moving average for each stock at time offset
    short_sma = sma(short_pos, offset=offset)
    long_sma = sma(long_pos, offset=offset)

    for i in xrange(offset, max(offset-hold_time, 0), -1):
        if short_pos.close[i] < short_sma and long_pos.close[i] > long_sma:
            if return_index:
                return i
            return 1

    #The pair has not reverted to the mean
    if return_index:
        return i
    return 0

def mean_ratio_reversion_test(hd1, hd2, n=20, offset=20, hold_time=30, return_index=False):
    """
    Tests over the time period offset:offset-hold_time to see if the price ratio of the
    price pair reverts to the mean.
    """
    #Get initial price ratio
    init_pr = hd1.close[offset]/hd2.close[offset]

    #Get mean for the pair
    pr_mean = mean_price_ratio(hd1, hd2, n=n, offset=offset)

    #Calculate coefficient to use to see if the price ratio switched sides of mean pr
    coeff = 1 if init_pr > pr_mean else -1

    for i in xrange(offset, max(offset-hold_time, 0), -1):
        if coeff*(hd1.close[i]/hd2.close[offset] - pr_mean) < 0:
            if return_index:
                return i
            return 1

    #The pair has not reverted to the mean
    if return_index:
        return i
    return 0


text:
exports.trailpack = require('./trailpack')
exports.locales = require('./locales')
exports.web = require('./web')


text:
package demo.hw.client;

import java.io.File;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import javax.xml.namespace.QName;
import javax.xml.ws.Response;

import org.apache.hello_world_async_soap_http.GreeterAsync;
import org.apache.hello_world_async_soap_http.SOAPService;
import org.apache.hello_world_async_soap_http.types.GreetMeSometimeResponse;

public final class Client {

    private static final QName SERVICE_NAME
        = new QName("http://apache.org/hello_world_async_soap_http", "SOAPService");

    private Client() {
    }

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

        if (args.length == 0) {
            System.out.println("please specify wsdl");
            System.exit(1);
        }
        URL url = null;
        File wsdl = new File(args[0]);
        if (wsdl.exists() && wsdl.isFile()) {
            url = wsdl.toURI().toURL();
        } else {
            url = new URL(args[0]);
        }

        SOAPService ss = new SOAPService(url, SERVICE_NAME);
        ExecutorService executor = Executors.newFixedThreadPool(5);
        ss.setExecutor(executor);
        GreeterAsync port = ss.getSoapPort();
        String resp;

        // callback method
        TestAsyncHandler testAsyncHandler = new TestAsyncHandler();
        System.out.println("Invoking greetMeSometimeAsync using callback object...");
        Future<?> response = port.greetMeSometimeAsync(System.getProperty("user.name"), testAsyncHandler);
        while (!response.isDone()) {
            Thread.sleep(100);
        }
        resp = testAsyncHandler.getResponse();
        System.out.println();
        System.out.println("Server responded through callback with: " + resp);
        System.out.println();

        //polling method
        System.out.println("Invoking greetMeSometimeAsync using polling...");
        Response<GreetMeSometimeResponse> greetMeSomeTimeResp =
            port.greetMeSometimeAsync(System.getProperty("user.name"));
        while (!greetMeSomeTimeResp.isDone()) {
            Thread.sleep(100);
        }
        GreetMeSometimeResponse reply = greetMeSomeTimeResp.get();
        System.out.println("Server responded through polling with: " + reply.getResponseType());

        System.exit(0);

    }

}


text:
require 'czech_name/version'

module CzechName
  autoload :NameFactory, 'czech_name/name_factory'
  autoload :MaleName,   'czech_name/male_name'
  autoload :FemaleName, 'czech_name/female_name'
  autoload :Database, 'czech_name/database'

  autoload :Configuration, 'czech_name/configuration'

  def self.detect(name)
    NameFactory.new(name).create
  end

  def self.fifth_case(name)
    name = NameFactory.new(name).create
    name && name.fifth_case
  end
end


text:
var React = require('react');
var SkipLinks = require('./SkipLinks');

var IntlMixin = require('../mixins/GrommetIntlMixin');
var Locale = require('../utils/Locale');

var App = React.createClass({

  propTypes: {
    centered: React.PropTypes.bool
  },

  mixins: [IntlMixin],

  getDefaultProps: function () {
    return {
      centered: true
    };
  },

  getInitialState: function () {
    return {
      lang: 'en-US'
    };
  },

  componentDidMount: function () {
    var lang = Locale.getCurrentLocale();
    if (this.props.lang) {
      lang = this.props.lang;
    }

    if (!document.documentElement.getAttribute('lang')) {
      document.documentElement.setAttribute('lang', lang);
    }

    this.setState({lang: lang});
  },

  render: function() {
    var classes = ["app"];
    if (this.props.centered) {
      classes.push("app--centered");
    }
    if (this.props.inline) {
      classes.push("app--inline");
    }

    if (this.props.className) {
      classes.push(this.props.className);
    }

    //remove this when React 0.14 is released. This is required because context props are not being propagated to children.
    var children = React.Children.map(this.props.children, function(child) {
      return React.isValidElement(child) ?
        React.cloneElement(child, this.getChildContext()) :
        child;
    }.bind(this));

    return (
      <div lang={this.state.lang} className={classes.join(' ')}>
        <SkipLinks/>
        {children}
      </div>
    );
  }
});

module.exports = App;


text:
package org.eclipse.gef.ui.parts;

import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;

import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Layout;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Sash;

import org.eclipse.draw2d.ColorConstants;

class Splitter extends Composite {

    public static final int DEFAULT_SASH_WIDTH = 5;
    private static final int DRAG_MINIMUM = 62;
    private static final String MAINTAIN_SIZE = "maintain size"; //$NON-NLS-1$

    private int fixedSize = 150;
    private int orientation = SWT.VERTICAL;
    private Sash[] sashes = new Sash[0];
    private Control[] controls = new Control[0];
    private Control maxControl = null;
    private Listener sashListener;
    private int sashWidth = DEFAULT_SASH_WIDTH;

    /**
     * PropertyChangeSupport
     */
    protected PropertyChangeSupport listeners = new PropertyChangeSupport(this);

    public void addFixedSizeChangeListener(PropertyChangeListener listener) {
        listeners.addPropertyChangeListener(listener);
    }

    protected void firePropertyChange(int oldValue, int newValue) {
        listeners.firePropertyChange(MAINTAIN_SIZE, oldValue, newValue);
    }

    public void removeFixedSizeChangeListener(PropertyChangeListener listener) {
        listeners.removePropertyChangeListener(listener);
    }

    public int getFixedSize() {
        return fixedSize;
    }

    public void setFixedSize(int newSize) {
        if (newSize == fixedSize) {
            return;
        }

        firePropertyChange(fixedSize, fixedSize = newSize);
    }

    class SashPainter implements Listener {
        @Override
        public void handleEvent(Event e) {
            paint((Sash) e.widget, e.gc);
        }
    }

    public Splitter(Composite parent, int style) {
        super(parent, checkStyle(style));

        if ((style & SWT.HORIZONTAL) != 0)
            orientation = SWT.HORIZONTAL;

        this.addListener(SWT.Resize, new Listener() {
            @Override
            public void handleEvent(Event e) {
                layout(true);
            }
        });

        sashListener = new Listener() {
            @Override
            public void handleEvent(Event e) {
                onDragSash(e);
            }
        };
    }

    private static int checkStyle(int style) {
        int mask = SWT.BORDER;
        return style & mask;
    }

    @Override
    public Point computeSize(int wHint, int hHint, boolean changed) {

        Control[] controls = getControls(true);
        if (controls.length == 0)
            return new Point(wHint, hHint);

        int width = 0;
        int height = 0;
        boolean vertical = (getStyle() & SWT.VERTICAL) != 0;
        if (vertical) {
            width = wHint;
            height += (controls.length - 1) * getSashWidth();
        } else {
            height = hHint;
            width += controls.length * getSashWidth();
        }
        for (int i = 0; i < controls.length; i++) {
            if (vertical) {
                Point size = controls[i].computeSize(wHint, SWT.DEFAULT);
                height += size.y;
            } else {
                Point size = controls[i].computeSize(SWT.DEFAULT, hHint);
                if (controls[i].getData(MAINTAIN_SIZE) != null) {
                    size.x = fixedSize;
                }
                width += size.x;
            }
        }
        // if (wHint != SWT.DEFAULT) width = wHint;
        // if (hHint != SWT.DEFAULT) height = hHint;

        return new Point(width, height);
    }

    /**
     * Answer SWT.HORIZONTAL if the controls in the SashForm are laid out side
     * by side. Answer SWT.VERTICAL if the controls in the SashForm are laid out
     * top to bottom.
     */
    @Override
    public int getOrientation() {
        return orientation;
    }

    public int getSashWidth() {
        return sashWidth;
    }

    /**
     * Answer the control that currently is maximized in the SashForm. This
     * value may be null.
     */
    public Control getMaximizedControl() {
        return this.maxControl;
    }

    private Control[] getControls(boolean onlyVisible) {
        Control[] children = getChildren();
        Control[] controls = new Control[0];
        for (int i = 0; i < children.length; i++) {
            if (children[i] instanceof Sash)
                continue;
            if (onlyVisible && !children[i].getVisible())
                continue;

            Control[] newControls = new Control[controls.length + 1];
            System.arraycopy(controls, 0, newControls, 0, controls.length);
            newControls[controls.length] = children[i];
            controls = newControls;
        }
        return controls;
    }

    @Override
    public void layout(boolean changed) {
        Rectangle area = getClientArea();
        if (area.width == 0 || area.height == 0)
            return;

        Control[] newControls = getControls(true);
        if (controls.length == 0 && newControls.length == 0)
            return;
        controls = newControls;

        if (maxControl != null && !maxControl.isDisposed()) {
            for (int i = 0; i < controls.length; i++) {
                if (controls[i] != maxControl) {
                    controls[i].setBounds(-200, -200, 0, 0);
                } else {
                    controls[i].setBounds(area);
                }
            }
            return;
        }

        // keep just the right number of sashes
        if (sashes.length < controls.length - 1) {
            Sash[] newSashes = new Sash[controls.length - 1];
            System.arraycopy(sashes, 0, newSashes, 0, sashes.length);
            int sashOrientation = (orientation == SWT.HORIZONTAL) ? SWT.VERTICAL
                    : SWT.HORIZONTAL;
            for (int i = sashes.length; i < newSashes.length; i++) {
                newSashes[i] = new Sash(this, sashOrientation);
                newSashes[i].setBackground(ColorConstants.button);
                newSashes[i].addListener(SWT.Paint, new SashPainter());
                newSashes[i].addListener(SWT.Selection, sashListener);
            }
            sashes = newSashes;
        }
        if (sashes.length > controls.length - 1) {
            if (controls.length == 0) {
                for (int i = 0; i < sashes.length; i++) {
                    sashes[i].dispose();
                }
                sashes = new Sash[0];
            } else {
                Sash[] newSashes = new Sash[controls.length - 1];
                System.arraycopy(sashes, 0, newSashes, 0, newSashes.length);
                for (int i = controls.length - 1; i < sashes.length; i++) {
                    sashes[i].dispose();
                }
                sashes = newSashes;
            }
        }

        if (controls.length == 0)
            return;

        // @TODO
        // This only works if the orientation is horizontal, there are two
        // children and one
        // of them has been set to maintain its size.
        int x = area.x;
        int width;
        for (int i = 0; i < controls.length; i++) {
            Control control = controls[i];
            if (control.getData(MAINTAIN_SIZE) != null) {
                width = fixedSize;
                if (width > area.width) {
                    width = area.width - getSashWidth();
                }
                control.setBounds(x, area.y, width, area.height);
                x += width + getSashWidth();
            } else {
                width = Math.max(area.width - fixedSize - getSashWidth(), 0);
                control.setBounds(x, area.y, width, area.height);
                x += (width + getSashWidth());
            }
        }
        if (sashes.length > 0)
            sashes[0].setBounds(
                    controls[0].getBounds().x + controls[0].getBounds().width,
                    area.y, getSashWidth(), area.height);
    }

    public void maintainSize(Control c) {
        Control[] controls = getControls(false);
        for (int i = 0; i < controls.length; i++) {
            Control ctrl = controls[i];
            if (ctrl == c) {
                ctrl.setData(MAINTAIN_SIZE, Boolean.valueOf(true));
                break;
            }
        }
    }

    void paint(Sash sash, GC gc) {
        if (getSashWidth() == 0)
            return;
        Point size = sash.getSize();
        if (getOrientation() == SWT.HORIZONTAL) {
            gc.setForeground(ColorConstants.buttonDarker);
            gc.drawLine(getSashWidth() - 1, 0, getSashWidth() - 1, size.y);
            gc.setForeground(ColorConstants.buttonLightest);
            gc.drawLine(0, 0, 0, size.y);
        } else {
            gc.setForeground(ColorConstants.buttonDarker);
            gc.drawLine(0, 0, size.x, 0);
            gc.drawLine(0, getSashWidth() - 1, size.x, getSashWidth() - 1);
            gc.setForeground(ColorConstants.buttonLightest);
            gc.drawLine(0, 1, size.x, 1);
        }
    }

    private void onDragSash(Event event) {
        if (event.detail == SWT.DRAG) {
            // constrain feedback
            Rectangle area = getClientArea();
            if (orientation == SWT.HORIZONTAL) {
                if (controls[0].getData(MAINTAIN_SIZE) != null) {
                    event.x = Math.max(event.x, DRAG_MINIMUM);
                } else {
                    event.x = Math.min(event.x, area.width - DRAG_MINIMUM
                            - getSashWidth());
                }
            } else {
                event.y = Math.min(event.y, area.height - DRAG_MINIMUM
                        - getSashWidth());
            }
            return;
        }

        Sash sash = (Sash) event.widget;
        int sashIndex = -1;
        for (int i = 0; i < sashes.length; i++) {
            if (sashes[i] == sash) {
                sashIndex = i;
                break;
            }
        }
        if (sashIndex == -1)
            return;

        Control c1 = controls[sashIndex];
        Control c2 = controls[sashIndex + 1];
        Rectangle b1 = c1.getBounds();
        Rectangle b2 = c2.getBounds();
        controls = getControls(false);

        Rectangle sashBounds = sash.getBounds();
        if (orientation == SWT.HORIZONTAL) {
            int shift = event.x - sashBounds.x;
            b1.width += shift;
            b2.x += shift;
            b2.width -= shift;
        } else {
            int shift = event.y - sashBounds.y;
            b1.height += shift;
            b2.y += shift;
            b2.height -= shift;
        }

        c1.setBounds(b1);
        sash.setBounds(event.x, event.y, event.width, event.height);
        c2.setBounds(b2);
        // @TODO
        // This will only work when you have two controls, one of whom is set to
        // maintain size
        if (c1.getData(MAINTAIN_SIZE) != null) {
            setFixedSize(c1.getBounds().width);
        } else {
            setFixedSize(c2.getBounds().width);
        }
    }

    /**
     * If orientation is SWT.HORIZONTAL, lay the controls in the SashForm out
     * side by side. If orientation is SWT.VERTICAL, lay the controls in the
     * SashForm out top to bottom.
     */
    @Override
    public void setOrientation(int orientation) {
        if (this.orientation == orientation)
            return;
        if (orientation != SWT.HORIZONTAL && orientation != SWT.VERTICAL) {
            SWT.error(SWT.ERROR_INVALID_ARGUMENT);
        }
        this.orientation = orientation;

        int sashOrientation = (orientation == SWT.HORIZONTAL) ? SWT.VERTICAL
                : SWT.HORIZONTAL;
        for (int i = 0; i < sashes.length; i++) {
            sashes[i].dispose();
            sashes[i] = new Sash(this, sashOrientation);
            sashes[i].setBackground(ColorConstants.buttonLightest);
            sashes[i].addListener(SWT.Selection, sashListener);
        }
        layout();
    }

    public void setSashWidth(int width) {
        sashWidth = width;
    }

    @Override
    public void setLayout(Layout layout) {
        // SashForm does not use Layout
    }

    /**
     * Specify the control that should take up the entire client area of the
     * SashForm. If one control has been maximized, and this method is called
     * with a different control, the previous control will be minimized and the
     * new control will be maximized.. if the value of control is null, the
     * SashForm will minimize all controls and return to the default layout
     * where all controls are laid out separated by sashes.
     */
    public void setMaximizedControl(Control control) {
        if (control == null) {
            if (maxControl != null) {
                this.maxControl = null;
                layout();
                for (int i = 0; i < sashes.length; i++) {
                    sashes[i].setVisible(true);
                }
            }
            return;
        }

        for (int i = 0; i < sashes.length; i++) {
            sashes[i].setVisible(false);
        }
        maxControl = control;
        layout();

    }

}


text:
#define MAC_IOSIZE 0x10000
#define NUM_RX_DMA 4       /* Au1x00 has 4 rx hardware descriptors */
#define NUM_TX_DMA 4       /* Au1x00 has 4 tx hardware descriptors */

#define NUM_RX_BUFFS 4
#define NUM_TX_BUFFS 4
#define MAX_BUF_SIZE 2048

#define ETH_TX_TIMEOUT (HZ/4)
#define MAC_MIN_PKT_SIZE 64

#define MULTICAST_FILTER_LIMIT 64

/*
 * Data Buffer Descriptor. Data buffers must be aligned on 32 byte
 * boundary for both, receive and transmit.
 */
struct db_dest {
	struct db_dest *pnext;
	u32 *vaddr;
	dma_addr_t dma_addr;
};

/*
 * The transmit and receive descriptors are memory
 * mapped registers.
 */
struct tx_dma {
	u32 status;
	u32 buff_stat;
	u32 len;
	u32 pad;
};

struct rx_dma {
	u32 status;
	u32 buff_stat;
	u32 pad[2];
};

/*
 * MAC control registers, memory mapped.
 */
struct mac_reg {
	u32 control;
	u32 mac_addr_high;
	u32 mac_addr_low;
	u32 multi_hash_high;
	u32 multi_hash_low;
	u32 mii_control;
	u32 mii_data;
	u32 flow_control;
	u32 vlan1_tag;
	u32 vlan2_tag;
};

struct au1000_private {
	struct db_dest *pDBfree;
	struct db_dest db[NUM_RX_BUFFS+NUM_TX_BUFFS];
	struct rx_dma *rx_dma_ring[NUM_RX_DMA];
	struct tx_dma *tx_dma_ring[NUM_TX_DMA];
	struct db_dest *rx_db_inuse[NUM_RX_DMA];
	struct db_dest *tx_db_inuse[NUM_TX_DMA];
	u32 rx_head;
	u32 tx_head;
	u32 tx_tail;
	u32 tx_full;

	int mac_id;

	int mac_enabled;       /* whether MAC is currently enabled and running
				* (req. for mdio)
				*/

	int old_link;          /* used by au1000_adjust_link */
	int old_speed;
	int old_duplex;

	struct phy_device *phy_dev;
	struct mii_bus *mii_bus;

	/* PHY configuration */
	int phy_static_config;
	int phy_search_highest_addr;
	int phy1_search_mac0;

	int phy_addr;
	int phy_busid;
	int phy_irq;

	/* These variables are just for quick access
	 * to certain regs addresses.
	 */
	struct mac_reg *mac;  /* mac registers                      */
	u32 *enable;     /* address of MAC Enable Register     */

	u32 vaddr;                /* virtual address of rx/tx buffers   */
	dma_addr_t dma_addr;      /* dma address of rx/tx buffers       */

	spinlock_t lock;       /* Serialise access to device */

	u32 msg_enable;
};


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.dialogflow.v2beta1.model;

/**
 * Defines the Automated Agent to connect to a conversation.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Dialogflow API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class GoogleCloudDialogflowV2beta1AutomatedAgentConfig extends com.google.api.client.json.GenericJson {

  /**
   * Required. ID of the Dialogflow agent environment to use. This project needs to either be the
   * same project as the conversation or you need to grant `service-@gcp-sa-
   * dialogflow.iam.gserviceaccount.com` the `Dialogflow API Service Agent` role in this project. -
   * For ES agents, use format: `projects//locations//agent/environments/`. If environment is not
   * specified, the default `draft` environment is used. Refer to [DetectIntentRequest](/dialogflow/
   * docs/reference/rpc/google.cloud.dialogflow.v2beta1#google.cloud.dialogflow.v2beta1.DetectIntent
   * Request) for more details. - For CX agents, use format
   * `projects//locations//agents//environments/`. If environment is not specified, the default
   * `draft` environment is used.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String agent;

  /**
   * Required. ID of the Dialogflow agent environment to use. This project needs to either be the
   * same project as the conversation or you need to grant `service-@gcp-sa-
   * dialogflow.iam.gserviceaccount.com` the `Dialogflow API Service Agent` role in this project. -
   * For ES agents, use format: `projects//locations//agent/environments/`. If environment is not
   * specified, the default `draft` environment is used. Refer to [DetectIntentRequest](/dialogflow/
   * docs/reference/rpc/google.cloud.dialogflow.v2beta1#google.cloud.dialogflow.v2beta1.DetectIntent
   * Request) for more details. - For CX agents, use format
   * `projects//locations//agents//environments/`. If environment is not specified, the default
   * `draft` environment is used.
   * @return value or {@code null} for none
   */
  public java.lang.String getAgent() {
    return agent;
  }

  /**
   * Required. ID of the Dialogflow agent environment to use. This project needs to either be the
   * same project as the conversation or you need to grant `service-@gcp-sa-
   * dialogflow.iam.gserviceaccount.com` the `Dialogflow API Service Agent` role in this project. -
   * For ES agents, use format: `projects//locations//agent/environments/`. If environment is not
   * specified, the default `draft` environment is used. Refer to [DetectIntentRequest](/dialogflow/
   * docs/reference/rpc/google.cloud.dialogflow.v2beta1#google.cloud.dialogflow.v2beta1.DetectIntent
   * Request) for more details. - For CX agents, use format
   * `projects//locations//agents//environments/`. If environment is not specified, the default
   * `draft` environment is used.
   * @param agent agent or {@code null} for none
   */
  public GoogleCloudDialogflowV2beta1AutomatedAgentConfig setAgent(java.lang.String agent) {
    this.agent = agent;
    return this;
  }

  @Override
  public GoogleCloudDialogflowV2beta1AutomatedAgentConfig set(String fieldName, Object value) {
    return (GoogleCloudDialogflowV2beta1AutomatedAgentConfig) super.set(fieldName, value);
  }

  @Override
  public GoogleCloudDialogflowV2beta1AutomatedAgentConfig clone() {
    return (GoogleCloudDialogflowV2beta1AutomatedAgentConfig) super.clone();
  }

}


text:
@interface MainViewController_OC ()<MainInfoViewTapGestureDelegate>{
    HealthManager *healthManager;
    enum MainVCState state;
}

@property CustomBarBtnItem_OC *stepBarItem;
@property CustomBarBtnItem_OC *runningBarItem;

@property (weak, nonatomic) IBOutlet MainInfomationView_OC *mainInfoView;
@property (weak, nonatomic) IBOutlet StepBarChartView_OC *stepBarChartView;
@property (weak, nonatomic) IBOutlet StartRunningButton_OC *startRunningBtn;

@end

@implementation MainViewController_OC

#pragma mark Life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    healthManager = [HealthManager sharedHealthManager];
    state = Running;

    [self.navigationController.navigationBar setBackgroundImage:[UIImage alloc] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage = [UIImage alloc];
    [self.navigationController.navigationBar setTranslucent:YES];
    self.navigationController.navigationBar.backIndicatorImage = [UIImage imageNamed:@"Back-22"];
    self.navigationController.navigationBar.backIndicatorTransitionMaskImage = [UIImage imageNamed:@"Back-22"];
    self.navigationController.navigationBar.titleTextAttributes = [NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:17] forKey:NSFontAttributeName];

    [healthManager authorizeWithCompletion:^(BOOL success,NSError *error){
        NSLog(@"Error == %@",error);
        NSLog(@"HealthKit authorize:%d",success);
    }];

    _mainInfoView.delegate = self;
    [self initStepBarChartView];

    _runningBarItem = [[CustomBarBtnItem_OC alloc] initWithButtonFrame:CGRectMake([Define sharedDefine].windowBounds.size.width/5*2-18-25, 0, 50, 22) title:@"运动" itemType:Left];
    [_runningBarItem addTarget:self action:@selector(swipeRight:progress:velocity:) for:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = _runningBarItem;

    _stepBarItem = [[CustomBarBtnItem_OC alloc] initWithButtonFrame:CGRectMake([Define sharedDefine].windowBounds.size.width/5*2-18-25, 0, 50, 22) title:@"记步" itemType:Right];
    [_stepBarItem addTarget:self action:@selector(swipeLeft:progress:velocity:) for:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = _stepBarItem;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [_mainInfoView refreshAnimation];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self updateCurrentDistance];
    [self updateCurrentStepCount];
}

#pragma mark - Navigation

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier  isEqual: @"ShowStepDetailVC"]) {
        StepDetailViewController_OC *stepDetailVC = segue.destinationViewController;
#ifdef __x86_64__

#else
#ifdef __i386__

#else
        [healthManager readStepCountWithPeriodDataType:Weekly withCompletion:^(NSArray<NSNumber *> *counts,NSError *error){
            if (counts != nil && error == nil) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    //                    stepDetailVC.
                });
            }
        }];
        [healthManager readDistanceWalkingRunningWithPeriodType:Weekly withCompletion:^(NSArray<NSNumber *> *distances,NSError *error){
            if (distances != nil && error == nil) {
                dispatch_async(dispatch_get_main_queue(), ^{

                });
            }
        }];
#endif
#endif

    } else {
        return;
    }
}

- (void)initStepBarChartView{
    _stepBarChartView.alpha = 0;
#ifdef __x86_64__

#else
#ifdef __i386__

#else
    [healthManager readStepCountWithPeriodDataType:Weekly withCompletion:^(NSArray<NSNumber *> *counts,NSError *error){
        if (counts != nil && error == nil) {
            dispatch_async(dispatch_get_main_queue(), ^{
                self.stepBarChartView.stepCounts = counts;
            });
        }
    }];
#endif
#endif
}

#pragma mark IBAction

- (IBAction)didPanInMainInfoView:(UIPanGestureRecognizer *)sender {
    CGFloat progress = [sender translationInView:_mainInfoView].x/_mainInfoView.frame.size.width;
    switch (sender.state) {
        case UIGestureRecognizerStateEnded:
        case UIGestureRecognizerStateCancelled:{
            CGFloat velocityX = [sender velocityInView:self.view].x;
            if (velocityX > 900) {
                [self swipeRight:sender progress:progress velocity:velocityX];
                break;
            }
            if (velocityX < -900) {
                [self swipeLeft:sender progress:progress velocity:velocityX];
                break;
            }
            if (progress > 0.4) {
                [self swipeRight:sender progress:progress velocity:velocityX];
            }else{
                if (progress < -0.4) {
                    [self swipeLeft:sender progress:progress velocity:velocityX];
                } else {
                    if (state == Running) {
                        [self swipeRight:sender progress:progress velocity:velocityX];
                    } else {
                        [self swipeLeft:sender progress:progress velocity:velocityX];
                    }
                }
            }
            break;
        }
        default:
            [_mainInfoView panAnimationWithProgress:progress currentState:state];
            [_stepBarChartView panAnimationWithProgress:progress currentState:state];
            [_startRunningBtn panAnimationWithProgress:progress currentState:state];
            break;
    }

}

#pragma mark Help func
- (void)swipeLeft:(id)sender progress:(CGFloat)progress velocity:(CGFloat)velocity{
    double duration;
    double baseDuration = 0.5;
    double pro = ABS(progress);
    double vel = ABS(velocity);
    if (vel > 900) {
        switch (state) {
            case Step:
                duration = baseDuration*pro*900/vel;
                break;
            case Running:
                duration = (baseDuration - baseDuration*pro)*900/vel;
            default:
                break;
        }
    }else{
        switch (state) {
            case Step:
                duration = baseDuration*pro;
                break;
            case Running:
                duration = baseDuration - baseDuration*pro;
            default:
                break;
        }
    }

    [UIView animateWithDuration:duration delay:0 options:UIViewAnimationOptionCurveEaseOut&UIViewAnimationOptionBeginFromCurrentState animations:^{
        [_mainInfoView panAnimationWithProgress:-1 currentState:state];
        _stepBarItem.enable = NO;
        _runningBarItem.enable = YES;
        [_stepBarChartView panAnimationWithProgress:-1 currentState:state];
        [_startRunningBtn panAnimationWithProgress:-1 currentState:state];
    } completion:nil];

    if (state == Running) {
        [self updateCurrentStepCount];
    }
    state = Step;
}

- (void)swipeRight:(id)sender progress:(CGFloat)progress velocity:(CGFloat)velocity{
    double duration;
    double baseDuration = 0.5;
    double pro = ABS(progress);
    double vel = ABS(velocity);
    if (vel > 900) {
        switch (state) {
            case Step:
                duration = baseDuration*pro*900/vel;
                break;
            case Running:
                duration = (baseDuration - baseDuration*pro)*900/vel;
            default:
                break;
        }
    }else{
        switch (state) {
            case Step:
                duration = baseDuration - baseDuration*pro;
                break;
            case Running:
                duration = baseDuration*pro;
            default:
                break;
        }
    }

    [UIView animateWithDuration:duration delay:0 options:UIViewAnimationOptionCurveEaseOut&UIViewAnimationOptionBeginFromCurrentState animations:^{
        [_mainInfoView panAnimationWithProgress:1 currentState:state];
        _stepBarItem.enable = YES;
        _runningBarItem.enable = NO;
        [_stepBarChartView panAnimationWithProgress:1 currentState:state];
        [_startRunningBtn panAnimationWithProgress:1 currentState:state];
    } completion:nil];

    if (state == Step) {
        [self updateCurrentDistance];
    }
    state = Running;
}

- (void)updateCurrentStepCount{
#ifdef __x86_64__
    _mainInfoView.stepCount = 1000;
#else
#ifdef __i386__
    _mainInfoView.stepCount = 1000;
#else
    [healthManager readStepCountWithPeriodDataType:Current withCompletion:^(NSArray<NSNumber *> *counts,NSError *error){
        if (counts != nil && error == nil) {
            dispatch_async(dispatch_get_main_queue(), ^{
                _mainInfoView.stepCount = counts[0].intValue;
                NSLog(@"%d", _mainInfoView.stepCount);
            });
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                _mainInfoView.stepCount = 0;
            });
        }
    }];
#endif
#endif
}

- (void)updateCurrentDistance{
#ifdef __x86_64__
    _mainInfoView.distance = 2000;
#else
#ifdef __i386__
    _mainInfoView.distance = 2000;
#else
    [healthManager readDistanceWalkingRunningWithPeriodType:Current withCompletion:^(NSArray<NSNumber *> *distances,NSError *error){
        if (distances != nil && error == nil) {
            dispatch_async(dispatch_get_main_queue(), ^{
                _mainInfoView.distance = distances[0].doubleValue;
            });
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                _mainInfoView.distance = 0;
            });
        }
    }];
#endif
#endif
}

#pragma mark MainInfoViewTapGestureDelegate
- (void)didTapInLabel:(UILabel *)label{
    if ([label isKindOfClass:[StepCountLabel_OC class]]) {
        [self performSegueWithIdentifier:@"ShowStepDetailVC" sender:label];
    } else {
        if ([label isKindOfClass:[DistanceWalkingRunningLabel_OC class]]) {
            [self performSegueWithIdentifier:@"ShowDistanceDetailVC" sender:label];
        }
    }
}

@end


text:
package com.jaren.easytranslate.service;

import android.app.Service;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.os.IBinder;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.jaren.easytranslate.R;

public class UiService extends Service {
    private static final String TAG = "UiService";
    private WindowManager windowManager;
    private WindowManager.LayoutParams wmParams;
    private LinearLayout linearLayout;

    private int layoutHeight = 0;
    private int layoutWidth = 0;
    private int wmXMin = 0;
    private int wmXMax = 0;
    private int wmYMin = 0;
    private int wmYMax = 0;
    private int imgWidth = 0;
    private int imgHeight = 0;
    private float touchX = 0;
    private float touchY = 0;

    ImageView imageView = null;

//    状态栏的高度
    private int statusBarHeight = 56;//wonder how to get statusbar's height!!!
    private boolean getSize = false;

    public UiService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        createWindow();
        if (imageView != null){
            setImgTouchListener();
        }
    }

    private void setImgTouchListener() {
        imageView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int action = event.getAction();
                switch (action) {
                    case MotionEvent.ACTION_DOWN: {
                        Log.d(TAG, "imageView get touch down!");
                        imageView.setBackgroundResource(R.mipmap.ic_light);
                    }
                    break;
                    case MotionEvent.ACTION_MOVE: {
                        Log.d(TAG, "imageView get touch move!");
                        updateWinManager(event);
                    }
                    break;
                    case MotionEvent.ACTION_UP: {
                        Log.d(TAG, "imageView get touch up!");
                        imageView.setBackgroundResource(R.mipmap.ic_mask);
                    }
                    break;
                    default: {
                        Log.e(TAG, "imageview get unkown touch event!");
                    }
                    break;
                }

                return true;
            }
        });
    }

    private void updateWinManager(MotionEvent event) {
        //x---48
        //y
        //|
        //|
        //48
        //new axes, 向量运算
//                let the image always behind finger
//                solution 1.
        this.touchX = (event.getRawX() - imgWidth / 2) + wmXMin;
        this.touchY = (event.getRawY() - imgHeight / 2) + wmYMin;
        wmParams.x = (int) this.touchX;
        wmParams.y = (int) this.touchY;
//                solution 2.
//                float imgX = event.getX();
//                float imgY = event.getY();
//                wmParams.x = (int) (wmParams.x + (imgX - imgWidth/2));
//                wmParams.y = (int) (wmParams.y + (imgY - imgHeight/2));

        //how about out of phone player size?
//                if using solution 2, this control must have
//                if (wmParams.x < wmXMin){
//                    wmParams.x = wmXMin;
//                }else if (wmParams.x > wmXMax){
//                    wmParams.x = wmXMax;
//                }
//                if (wmParams.y < wmYMin){
//                    wmParams.y = wmYMin;
//                }else if (wmParams.y > wmYMax){
//                    wmParams.y = wmYMax;
//                }

        windowManager.updateViewLayout(linearLayout, wmParams);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        super.onStartCommand(intent, flags, startId);

        Toast.makeText(this,"toast on service: service on startCommand!",Toast.LENGTH_LONG).show();
        return START_REDELIVER_INTENT;
    }

    private void createWindow() {
        windowManager = (WindowManager) getApplicationContext().getSystemService(getApplicationContext().WINDOW_SERVICE);
        wmParams = new WindowManager.LayoutParams();
        wmParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
        wmParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
        wmParams.type = WindowManager.LayoutParams.TYPE_PHONE;
        wmParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        wmParams.format = PixelFormat.RGBA_8888;

//        get screen size of phone, and set the right place of window
        Display defDisplay = windowManager.getDefaultDisplay();
        final DisplayMetrics metrics = new DisplayMetrics();
        defDisplay.getMetrics(metrics);
        layoutHeight = metrics.heightPixels;
        layoutWidth = metrics.widthPixels;

        LayoutInflater inflater = LayoutInflater.from(getApplication());
        linearLayout = (LinearLayout) inflater.inflate(R.layout.window_main,null);

//        get window measure
        imageView = (ImageView) linearLayout.findViewById(R.id.ic_win);
        imageView.setBackgroundResource(R.mipmap.ic_mask);

//        this listener will be called two times when windows create, and I don't know why.
        imageView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (getSize == false){
                    imgHeight = imageView.getWidth();
                    imgWidth = imageView.getHeight();
                    Log.d(TAG, "onGlobalLayout: " + "layoutWidth==" + layoutWidth + " layoutHeight==" + layoutHeight );
                    wmXMin = -layoutWidth/2 + imgWidth/2;
                    wmXMax = layoutWidth/2 - imgWidth/2;
                    wmYMin = (-layoutHeight - statusBarHeight)/2 + imgHeight/2;
                    wmYMax = (layoutHeight - statusBarHeight)/2 - imgHeight/2;
                    getSize = true;
                }
            }
        });

//        here is right & middle of the phone screen
        wmParams.x = Gravity.END;
//        wmParams.y = (wmYMax + wmYMin)/2;//middle position
        windowManager.addView(linearLayout, wmParams);

//        how can I get the move event?

    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }
}


text:
class TrustedApp < ActiveRecord::Base
  has_and_belongs_to_many :permissions
  has_many :consumers

  # Recording who updated the permit info
  has_many :people
  has_many :permits
  has_many :companies
  has_many :vehicles
  has_many :violations
  has_many :service_types

  validates :sha_hash, uniqueness: true
  validates :app_name, presence: true
end