text:
package java.nio;

import com.google.gwt.typedarrays.shared.ArrayBufferView;
import com.google.gwt.typedarrays.shared.Int16Array;
import com.google.gwt.typedarrays.shared.TypedArrays;

/** A buffer of shorts.
 *
 A short buffer can be created in either of the following ways:

 *

 *
{@link #allocate(int) Allocate} a new short array and create a buffer based on it;

 *
{@link #wrap(short[]) Wrap} an existing short array to create a new buffer;

 *
Use {@link java.nio.ByteBuffer#asShortBuffer() ByteBuffer.asShortBuffer} to create a short
 * buffer based on a byte buffer.

 *

 */
public final class ShortBuffer extends Buffer
  implements Comparable<ShortBuffer>, playn.html.HasArrayBufferView {

    private final ByteBuffer byteBuffer;
    private final Int16Array shortArray;

    static ShortBuffer wrap (ByteBuffer byteBuffer) {
      return new ShortBuffer(byteBuffer.slice());
    }

    /** Creates a short buffer based on a newly allocated short array.
     *
     * @param capacity the capacity of the new buffer.
     * @return the created short buffer.
     * @throws IllegalArgumentException if {@code capacity} is less than zero.
     */
    public static ShortBuffer allocate (int capacity) {
        if (capacity < 0) {
            throw new IllegalArgumentException();
        }
        ByteBuffer bb = ByteBuffer.allocateDirect(capacity * 2);
        bb.order(ByteOrder.nativeOrder());
        return bb.asShortBuffer();
    }

    ShortBuffer(ByteBuffer byteBuffer) {
      super((byteBuffer.capacity() >> 1));
      this.byteBuffer = byteBuffer;
      this.byteBuffer.clear();
      this.shortArray = TypedArrays.createInt16Array(
          byteBuffer.byteArray.buffer(),
          byteBuffer.byteArray.byteOffset(), capacity);
    }

    /** Compacts this short buffer.
     *
 The remaining shorts will be moved to the head of the buffer, starting from position
     * zero. Then the position is set to {@code remaining()}; the limit is set to capacity; the
     * mark is cleared.

     *
     * @return this buffer.
     * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer.
     */
    public ShortBuffer compact () {
      byteBuffer.limit(limit << 1);
      byteBuffer.position(position << 1);
      byteBuffer.compact();
      byteBuffer.clear();
      position = limit - position;
      limit = capacity;
      mark = UNSET_MARK;
      return this;
    }

    /** Compare the remaining shorts of this buffer to another short buffer's remaining shorts.
     *
     * @param otherBuffer another short buffer.
     * @return a negative value if this is less than {@code otherBuffer}; 0 if this equals to
     *         {@code otherBuffer}; a positive value if this is greater than {@code otherBuffer}.
     * @exception ClassCastException if {@code otherBuffer} is not a short buffer.
     */
    public int compareTo (ShortBuffer otherBuffer) {
        int compareRemaining = (remaining() < otherBuffer.remaining()) ?
          remaining() : otherBuffer.remaining();
        int thisPos = position;
        int otherPos = otherBuffer.position;
        short thisByte, otherByte;
        while (compareRemaining > 0) {
            thisByte = get(thisPos);
            otherByte = otherBuffer.get(otherPos);
            if (thisByte != otherByte) {
                return thisByte < otherByte ? -1 : 1;
            }
            thisPos++;
            otherPos++;
            compareRemaining--;
        }
        return remaining() - otherBuffer.remaining();
    }

    /** Returns a duplicated buffer that shares its content with this buffer.
     *
 The duplicated buffer's position, limit, capacity and mark are the same as this buffer.
     * The duplicated buffer's read-only property and byte order are the same as this buffer's.
     *

     *
 The new buffer shares its content with this buffer, which means either buffer's change
     * of content will be visible to the other. The two buffer's position, limit and mark are
     * independent.

     *
     * @return a duplicated buffer that shares its content with this buffer.
     */
    public ShortBuffer duplicate () {
      ShortBuffer buf = new ShortBuffer(byteBuffer.duplicate());
      buf.limit = limit;
      buf.position = position;
      buf.mark = mark;
      return buf;
    }

    /** Checks whether this short buffer is equal to another object.
     *
 If {@code other} is not a short buffer then {@code false} is returned. Two short buffers
     * are equal if and only if their remaining shorts are exactly the same. Position, limit,
     * capacity and mark are not considered.

     *
     * @param other the object to compare with this short buffer.
     * @return {@code true} if this short buffer is equal to {@code other}, {@code false} otherwise.
     */
    public boolean equals (Object other) {
        if (!(other instanceof ShortBuffer)) {
            return false;
        }
        ShortBuffer otherBuffer = (ShortBuffer)other;

        if (remaining() != otherBuffer.remaining()) {
            return false;
        }

        int myPosition = position;
        int otherPosition = otherBuffer.position;
        boolean equalSoFar = true;
        while (equalSoFar && (myPosition < limit)) {
            equalSoFar = get(myPosition++) == otherBuffer.get(otherPosition++);
        }

        return equalSoFar;
    }

    /** Returns the short at the current position and increases the position by 1.
     *
     * @return the short at the current position.
     * @exception BufferUnderflowException if the position is equal or greater than limit.
     */
    public short get () {
      // if (position == limit) {
      // throw new BufferUnderflowException();
       // }
      return shortArray.get(position++);
    }

    /** Reads shorts from the current position into the specified short array and increases the
     * position by the number of shorts read.
     *
 Calling this method has the same effect as {@code get(dest, 0, dest.length)}.

     *
     * @param dest the destination short array.
     * @return this buffer.
     * @exception BufferUnderflowException if {@code dest.length} is greater than {@code remaining()}.
     */
    public ShortBuffer get (short[] dest) {
        return get(dest, 0, dest.length);
    }

    /** Reads shorts from the current position into the specified short array, starting from the
     * specified offset, and increases the position by the number of shorts read.
     *
     * @param dest the target short array.
     * @param off the offset of the short array, must not be negative and not greater than {@code
     * dest.length}.
     * @param len the number of shorts to read, must be no less than zero and not greater than
     * {@code dest.length - off}.
     * @return this buffer.
     * @exception IndexOutOfBoundsException if either {@code off} or {@code len} is invalid.
     * @exception BufferUnderflowException if {@code len} is greater than {@code remaining()}.
     */
    public ShortBuffer get (short[] dest, int off, int len) {
        int length = dest.length;
        if (off < 0 || len < 0 || (long)off + (long)len > length) {
            throw new IndexOutOfBoundsException();
        }
        if (len > remaining()) {
            throw new BufferUnderflowException();
        }
        for (int i = off; i < off + len; i++) {
            dest[i] = get();
        }
        return this;
    }

    /** Returns the short at the specified index; the position is not changed.
     *
     * @param index the index, must not be negative and less than limit.
     * @return a short at the specified index.
     * @exception IndexOutOfBoundsException if index is invalid.
     */
    public short get (int index) {
      // if (index < 0 || index >= limit) {
      // throw new IndexOutOfBoundsException();
      // }
      return shortArray.get(index);
    }

    /** Indicates whether this buffer is based on a short array and is read/write.
     *
     * @return {@code true} if this buffer is based on a short array and provides read/write
     * access, {@code false} otherwise.
     */
    public final boolean hasArray () {
        return false;
    }

    /** Calculates this buffer's hash code from the remaining chars. The position, limit, capacity
     * and mark don't affect the hash code.
     *
     * @return the hash code calculated from the remaining shorts.
     */
    public int hashCode () {
        int myPosition = position;
        int hash = 0;
        while (myPosition < limit) {
            hash = hash + get(myPosition++);
        }
        return hash;
    }

    /** Indicates whether this buffer is direct. A direct buffer will try its best to take
     * advantage of native memory APIs and it may not stay in the Java heap, so it is not affected
     * by garbage collection.
     *
 A short buffer is direct if it is based on a byte buffer and the byte buffer is direct.
     *

     *
     * @return {@code true} if this buffer is direct, {@code false} otherwise.
     */
    public boolean isDirect () {
      return true;
    }

    /** Returns the byte order used by this buffer when converting shorts from/to bytes.
     *
 If this buffer is not based on a byte buffer, then always return the platform's native
     * byte order.

     *
     * @return the byte order used by this buffer when converting shorts from/to bytes.
     */
    public ByteOrder order () {
      return ByteOrder.nativeOrder();
    }

    /** Writes the given short to the current position and increases the position by 1.
     *
     * @param s the short to write.
     * @return this buffer.
     * @exception BufferOverflowException if position is equal or greater than limit.
     * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer.
     */
    public ShortBuffer put (short c) {
      // if (position == limit) {
      // throw new BufferOverflowException();
      // }
      shortArray.set(position++, c);
      return this;
    }

    /** Writes shorts from the given short array to the current position and increases the position
     * by the number of shorts written.
 Calling this method has the same effect as {@code
     * put(src, 0, src.length)}.

     *
     * @param src the source short array.
     * @return this buffer.
     * @exception BufferOverflowException if {@code remaining()} is less than {@code src.length}.
     * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer.
     */
    public final ShortBuffer put (short[] src) {
        return put(src, 0, src.length);
    }

    /** Writes shorts from the given short array, starting from the specified offset, to the
     * current position and increases the position by the number of shorts written.
     *
     * @param src the source short array.
     * @param off the offset of short array, must not be negative and not greater than {@code src.length}.
     * @param len the number of shorts to write, must be no less than zero and not greater than
     * {@code src.length - off}.
     * @return this buffer.
     * @exception BufferOverflowException if {@code remaining()} is less than {@code len}.
     * @exception IndexOutOfBoundsException if either {@code off} or {@code len} is invalid.
     * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer.
     */
    public ShortBuffer put (short[] src, int off, int len) {
        int length = src.length;
        if (off < 0 || len < 0 || (long)off + (long)len > length) {
            throw new IndexOutOfBoundsException();
        }

        if (len > remaining()) {
            throw new BufferOverflowException();
        }
        for (int i = off; i < off + len; i++) {
            put(src[i]);
        }
        return this;
    }

    /** Writes all the remaining shorts of the {@code src} short buffer to this buffer's current
     * position, and increases both buffers' position by the number of shorts copied.
     *
     * @param src the source short buffer.
     * @return this buffer.
     * @exception BufferOverflowException if {@code src.remaining()} is greater than this buffer's
     * {@code remaining()}.
     * @exception IllegalArgumentException if {@code src} is this buffer.
     * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer.
     */
    public ShortBuffer put (ShortBuffer src) {
        if (src == this) {
            throw new IllegalArgumentException();
        }
        if (src.remaining() > remaining()) {
            throw new BufferOverflowException();
        }
        short[] contents = new short[src.remaining()];
        src.get(contents);
        put(contents);
        return this;
    }

    /** Writes a short to the specified index of this buffer; the position is not changed.
     *
     * @param index the index, must not be negative and less than the limit.
     * @param s the short to write.
     * @return this buffer.
     * @exception IndexOutOfBoundsException if index is invalid.
     * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer.
     */
    public ShortBuffer put (int index, short c) {
      // if (index < 0 || index >= limit) {
      // throw new IndexOutOfBoundsException();
      // }
      shortArray.set(index, c);
      return this;
    }

    /** Returns a sliced buffer that shares its content with this buffer.
     *
 The sliced buffer's capacity will be this buffer's {@code remaining()}, and its zero
     * position will correspond to this buffer's current position. The new buffer's position will
     * be 0, limit will be its capacity, and its mark is cleared. The new buffer's read-only
     * property and byte order are same as this buffer's.

     *
 The new buffer shares its content with this buffer, which means either buffer's change
     * of content will be visible to the other. The two buffer's position, limit and mark are
     * independent.

     *
     * @return a sliced buffer that shares its content with this buffer.
     */
    public ShortBuffer slice () {
      byteBuffer.limit(limit << 1);
      byteBuffer.position(position << 1);
      ShortBuffer result = new ShortBuffer(byteBuffer.slice());
      byteBuffer.clear();
      return result;
    }

    /** Returns a string representing the state of this short buffer.
     *
     * @return a string representing the state of this short buffer.
     */
    public String toString () {
        StringBuffer buf = new StringBuffer();
        buf.append(getClass().getName());
        buf.append(", status: capacity="); //$NON-NLS-1$
        buf.append(capacity());
        buf.append(" position="); //$NON-NLS-1$
        buf.append(position());
        buf.append(" limit="); //$NON-NLS-1$
        buf.append(limit());
        return buf.toString();
    }

    public ArrayBufferView getTypedArray () {
      return shortArray;
    }

    public int getElementSize () {
      return 2;
    }

    public int getElementType() {
      return 0x1402; // GL_SHORT
    }

    public boolean isReadOnly() {
      return false;
    }
}


text:
package com.opengamma.analytics.financial.model.finitedifference;

import org.apache.commons.lang.NotImplementedException;
import org.apache.commons.lang.Validate;

import com.opengamma.analytics.math.function.Function1D;
import com.opengamma.analytics.math.surface.Surface;

/**
 * Crank-Nicolson scheme using SOR algorithm to solve the matrix system at each time step.
 * <b>Note</b> this is for testing purposes and is not recommended for actual use. Use ThetaMethodFiniteDifference for production.
 */
public class CrankNicolsonFiniteDifferenceSOR implements ConvectionDiffusionPDESolver {

  private final double _theta;

  /**
   * Sets up a standard Crank-Nicolson scheme
   */
  public CrankNicolsonFiniteDifferenceSOR() {
    _theta = 0.5;
  }

  /**
   * Sets up a scheme that is the weighted average of an explicit and an implicit scheme
   * @param theta The weight. theta = 0 - fully explicit, theta = 0.5 - Crank-Nicolson, theta = 1.0 - fully implicit
   */
  public CrankNicolsonFiniteDifferenceSOR(final double theta) {
    Validate.isTrue(theta >= 0 && theta <= 1.0, "theta must be in the range 0 to 1");
    _theta = theta;
  }

  @SuppressWarnings("deprecation")
  @Override
  public PDEResults1D solve(final ZZConvectionDiffusionPDEDataBundle pdeData, final int tSteps, final int xSteps, final double tMax, final BoundaryCondition lowerBoundary,
      final BoundaryCondition upperBoundary) {
    return solve(pdeData, tSteps, xSteps, tMax, lowerBoundary, upperBoundary, null);
  }

  @SuppressWarnings("deprecation")
  @Override
  public PDEResults1D solve(final ZZConvectionDiffusionPDEDataBundle pdeData, final int tSteps, final int xSteps, final double tMax, final BoundaryCondition lowerBoundary,
      final BoundaryCondition upperBoundary, final Surface<Double, Double, Double> freeBoundary) {
    return solve(pdeData.getCoefficients(), pdeData.getInitialCondition(), tSteps, xSteps, tMax, lowerBoundary, upperBoundary, freeBoundary);
  }

  @Override
  public PDEResults1D solve(PDE1DDataBundle<ConvectionDiffusionPDE1DCoefficients> pdeData) {
    throw new NotImplementedException();
  }

  @Override
  public PDEResults1D solve(ConvectionDiffusionPDE1DStandardCoefficients pdeData, Function1D<Double, Double> initialCondition, int tSteps, int xSteps, double tMax, BoundaryCondition lowerBoundary,
      BoundaryCondition upperBoundary) {
    return solve(pdeData, initialCondition, tSteps, xSteps, tMax, lowerBoundary, upperBoundary, null);
  }

  @Override
  public PDEResults1D solve(ConvectionDiffusionPDE1DStandardCoefficients pdeData, Function1D<Double, Double> initialCondition, int tSteps, int xSteps, double tMax, BoundaryCondition lowerBoundary,
      BoundaryCondition upperBoundary, Surface<Double, Double, Double> freeBoundary) {
    // simple test code - doesn't use a PDEGrid1D
    final PDEGrid1D grid = new PDEGrid1D(tSteps + 1, xSteps + 1, tMax, lowerBoundary.getLevel(), upperBoundary.getLevel());

    final double dt = tMax / (tSteps);
    final double dx = (upperBoundary.getLevel() - lowerBoundary.getLevel()) / (xSteps);
    final double dtdx2 = dt / dx / dx;
    final double dtdx = dt / dx;

    final double[] f = new double[xSteps + 1];
    final double[] x = new double[xSteps + 1];
    final double[] q = new double[xSteps + 1];
    final double[][] m = new double[xSteps + 1][xSteps + 1];
    // double[] coefficients = new double[3];

    double currentX = lowerBoundary.getLevel();

    double a, b, c, aa, bb, cc;

    for (int i = 0; i <= xSteps; i++) {
      currentX = lowerBoundary.getLevel() + i * dx;
      x[i] = currentX;
      final double value = initialCondition.evaluate(currentX);
      f[i] = value;
    }

    double t = 0.0;

    for (int n = 0; n < tSteps; n++) {
      t += dt;

      for (int i = 1; i < xSteps; i++) {
        a = pdeData.getA(t - dt, x[i]);
        b = pdeData.getB(t - dt, x[i]);
        c = pdeData.getC(t - dt, x[i]);

        double rho = a;
        // double bdx = (b * dx / 2);
        // if (Math.abs(bdx) > 10 * Math.abs(a)) {
        // rho = Math.abs(bdx);
        // } else if (Math.abs(a) > 10 * Math.abs(bdx)) {
        // rho = a;
        // } else {
        // rho = bdx / Math.tanh(bdx / a);
        // }

        aa = (1 - _theta) * (-dtdx2 * rho + 0.5 * dtdx * b);
        bb = 1 + (1 - _theta) * (2 * dtdx2 * rho - dt * c);
        cc = (1 - _theta) * (-dtdx2 * rho - 0.5 * dtdx * b);
        q[i] = aa * f[i - 1] + bb * f[i] + cc * f[i + 1];

        // TODO could store these
        a = pdeData.getA(t, x[i]);
        b = pdeData.getB(t, x[i]);
        c = pdeData.getC(t, x[i]);

        rho = a;
        // bdx = (b * dx / 2);
        // if (Math.abs(bdx) > 10 * Math.abs(a)) {
        // rho = Math.abs(bdx);
        // } else if (Math.abs(a) > 10 * Math.abs(bdx)) {
        // rho = a;
        // } else {
        // rho = bdx / Math.tanh(bdx / a);
        // }

        aa = (-dtdx2 * rho + 0.5 * dtdx * b);
        bb = (2 * dtdx2 * rho - dt * c);
        cc = (-dtdx2 * rho - 0.5 * dtdx * b);
        m[i][i - 1] = -_theta * aa;
        m[i][i] = 1 - _theta * bb;
        m[i][i + 1] = -_theta * cc;
      }

      double[] temp = lowerBoundary.getLeftMatrixCondition(pdeData, grid, t);
      for (int k = 0; k < temp.length; k++) {
        m[0][k] = temp[k];
      }
      temp = upperBoundary.getLeftMatrixCondition(pdeData, grid, t);
      for (int k = 0; k < temp.length; k++) {
        m[xSteps][xSteps - k] = temp[k];
      }

      temp = lowerBoundary.getRightMatrixCondition(pdeData, grid, t);
      double sum = 0;
      for (int k = 0; k < temp.length; k++) {
        sum += temp[k] * f[k];
      }
      q[0] = sum + lowerBoundary.getConstant(pdeData, t);

      temp = upperBoundary.getRightMatrixCondition(pdeData, grid, t);
      sum = 0;
      for (int k = 0; k < temp.length; k++) {
        sum += temp[k] * f[xSteps - k];
      }
      q[xSteps] = sum + upperBoundary.getConstant(pdeData, t);

      // SOR
      final double omega = 1.0;
      double scale = 1.0;
      double errorSqr = Double.POSITIVE_INFINITY;
      while (errorSqr / (scale + 1e-10) > 1e-18) {
        errorSqr = 0.0;
        scale = 0.0;
        for (int j = 0; j <= xSteps; j++) {
          sum = 0;
          for (int k = 0; k <= xSteps; k++) {
            sum += m[j][k] * f[k];
          }
          double correction = omega / m[j][j] * (q[j] - sum);
          if (freeBoundary != null) {
            correction = Math.max(correction, freeBoundary.getZValue(t, x[j]) - f[j]);
          }
          errorSqr += correction * correction;
          f[j] += correction;
          scale += f[j] * f[j];
        }
      }

    }

    return new PDETerminalResults1D(grid, f);
  }

  @SuppressWarnings("deprecation")
  public PDEResults1D solve(final ZZConvectionDiffusionPDEDataBundle pdeData, final double[] timeGrid, final double[] spaceGrid, final BoundaryCondition lowerBoundary,
      final BoundaryCondition upperBoundary, final Surface<Double, Double, Double> freeBoundary) {
    Validate.notNull(pdeData, "pde data");

    final PDEGrid1D grid = new PDEGrid1D(timeGrid, spaceGrid);

    final int tNodes = timeGrid.length;
    final int xNodes = spaceGrid.length;
    Validate.isTrue(tNodes > 1, "need at least 2 time nodes");
    Validate.isTrue(xNodes > 2, "need at least 3 space nodes");

    // TODO would like more sophistication that simply checking to the grid is consistent with the boundary level
    Validate.isTrue(Math.abs(spaceGrid[0] - lowerBoundary.getLevel()) < 1e-7, "space grid not consistent with boundary level");
    Validate.isTrue(Math.abs(spaceGrid[xNodes - 1] - upperBoundary.getLevel()) < 1e-7, "space grid not consistent with boundary level");

    final double[] dt = new double[tNodes - 1];
    for (int n = 0; n < tNodes - 1; n++) {
      dt[n] = timeGrid[n + 1] - timeGrid[n];
      Validate.isTrue(dt[n] > 0, "time steps must be increasing");
    }

    final double[] dx = new double[xNodes - 1];
    for (int i = 0; i < xNodes - 1; i++) {
      dx[i] = spaceGrid[i + 1] - spaceGrid[i];
      Validate.isTrue(dx[i] > 0, "space steps must be increasing");
    }

    final double[] f = new double[xNodes];
    final double[] q = new double[xNodes];
    final double[][] m = new double[xNodes][xNodes];

    double a, b, c, aa, bb, cc;

    for (int i = 0; i < xNodes; i++) {
      f[i] = pdeData.getInitialValue(spaceGrid[i]);
    }

    for (int n = 1; n < tNodes; n++) {

      for (int i = 1; i < xNodes - 1; i++) {
        a = pdeData.getA(timeGrid[n - 1], spaceGrid[i]);
        b = pdeData.getB(timeGrid[n - 1], spaceGrid[i]);
        c = pdeData.getC(timeGrid[n - 1], spaceGrid[i]);

        aa = (1 - _theta) * dt[n - 1] * (-2 / dx[i - 1] / (dx[i - 1] + dx[i]) * a + dx[i] / dx[i - 1] / (dx[i - 1] + dx[i]) * b);
        bb = 1 + (1 - _theta) * dt[n - 1] * (2 / dx[i - 1] / dx[i] * a - (dx[i] - dx[i - 1]) / dx[i - 1] / dx[i] * b - c);
        cc = (1 - _theta) * dt[n - 1] * (-2 / dx[i] / (dx[i - 1] + dx[i]) * a - dx[i - 1] / dx[i] / (dx[i - 1] + dx[i]) * b);
        q[i] = aa * f[i - 1] + bb * f[i] + cc * f[i + 1];

        // TODO could store these
        a = pdeData.getA(timeGrid[n], spaceGrid[i]);
        b = pdeData.getB(timeGrid[n], spaceGrid[i]);
        c = pdeData.getC(timeGrid[n], spaceGrid[i]);
        aa = dt[n - 1] * (-2 / dx[i - 1] / (dx[i - 1] + dx[i]) * a + dx[i] / dx[i - 1] / (dx[i - 1] + dx[i]) * b);
        bb = dt[n - 1] * (2 / dx[i - 1] / dx[i] * a - (dx[i] - dx[i - 1]) / dx[i - 1] / dx[i] * b - c);
        cc = dt[n - 1] * (-2 / dx[i] / (dx[i - 1] + dx[i]) * a - dx[i - 1] / dx[i] / (dx[i - 1] + dx[i]) * b);
        m[i][i - 1] = -_theta * aa;
        m[i][i] = 1 - _theta * bb;
        m[i][i + 1] = -_theta * cc;
      }

      double[] temp = lowerBoundary.getLeftMatrixCondition(pdeData.getCoefficients(), grid, timeGrid[n]);
      for (int k = 0; k < temp.length; k++) {
        m[0][k] = temp[k];
      }

      temp = upperBoundary.getLeftMatrixCondition(pdeData.getCoefficients(), grid, timeGrid[n]);
      for (int k = 0; k < temp.length; k++) {
        m[xNodes - 1][xNodes - 1 - k] = temp[k];
      }
      // debug
      // m[xNodes - 1][xNodes - 3] = 2 / dx[xNodes - 3] / (dx[xNodes - 3] + dx[xNodes - 2]);
      // m[xNodes - 1][xNodes - 2] = -2 / dx[xNodes - 3] / dx[xNodes - 2];
      // m[xNodes - 1][xNodes - 1] = 2 / dx[xNodes - 2] / (dx[xNodes - 3] + dx[xNodes - 2]);

      temp = lowerBoundary.getRightMatrixCondition(pdeData.getCoefficients(), grid, timeGrid[n]);
      double sum = 0;
      for (int k = 0; k < temp.length; k++) {
        sum += temp[k] * f[k];
      }
      q[0] = sum + lowerBoundary.getConstant(pdeData.getCoefficients(), timeGrid[n]); // TODO need to change how boundary are calculated - dx[0] wrong for non-constant grid

      temp = upperBoundary.getRightMatrixCondition(pdeData.getCoefficients(), grid, timeGrid[n]);
      sum = 0;
      for (int k = 0; k < temp.length; k++) {
        sum += temp[k] * f[xNodes - 1 - k];
      }

      q[xNodes - 1] = sum + upperBoundary.getConstant(pdeData.getCoefficients(), timeGrid[n]);

      // SOR
      final double omega = 1.0;
      double scale = 1.0;
      double errorSqr = Double.POSITIVE_INFINITY;
      while (errorSqr / (scale + 1e-10) > 1e-18) {
        errorSqr = 0.0;
        scale = 0.0;
        for (int j = 0; j < xNodes; j++) {
          sum = 0;
          for (int k = 0; k < xNodes; k++) {
            sum += m[j][k] * f[k];
          }
          double correction = omega / m[j][j] * (q[j] - sum);
          if (freeBoundary != null) {
            correction = Math.max(correction, freeBoundary.getZValue(timeGrid[n], spaceGrid[j]) - f[j]);
          }
          errorSqr += correction * correction;
          f[j] += correction;
          scale += f[j] * f[j];
        }
      }

    }

    return new PDETerminalResults1D(grid, f);

  }

  @SuppressWarnings("deprecation")
  @Override
  public PDEResults1D solve(final ZZConvectionDiffusionPDEDataBundle pdeData, final PDEGrid1D grid, final BoundaryCondition lowerBoundary, final BoundaryCondition upperBoundary) {
    throw new NotImplementedException("This is a simple test implimentation of Crank-Nicolson. If you do what to run this scheme, use ThetaMethodFiniteDifference with theta = 0.5");
  }

  @SuppressWarnings("deprecation")
  @Override
  public PDEResults1D solve(final ZZConvectionDiffusionPDEDataBundle pdeData, final PDEGrid1D grid, final BoundaryCondition lowerBoundary, final BoundaryCondition upperBoundary,
      final Surface<Double, Double, Double> freeBoundary) {
    throw new NotImplementedException("This is a simple test implimentation of Crank-Nicolson. If you do what to run this scheme, use ThetaMethodFiniteDifference with theta = 0.5");
  }

}

redpajama_set_name: RedPajamaGithub


text:
DIR="$( cd "$( dirname "$0" )" && pwd )"
while getopts ":d:s:t:" opt; do
    case $opt in
        d)
            DB_NAME="$OPTARG"
            ;;
        s)
            SCHEMA_NAME="$OPTARG"
            ;;
        t)
            TABLE_NAME="$OPTARG"
            ;;
        \?) # fall-through
            ;&
        :)
            echo "USAGE: `basename $0` [-d <database name>] [-s <schema name>] [-t <table name>]" >&2
            echo "Example: `basename $0` -d osm_bugs -s keepright -t errors" >&2
            exit 1
            ;;
    esac
done

if [ -z $DB_NAME ] ; then
    DB_NAME="osm_bugs"
fi

if [ -z $SCHEMA_NAME ] ; then
    SCHEMA_NAME="keepright"
fi

if [ -z $TABLE_NAME ] ; then
    TABLE_NAME="errors"
fi

# add geometry to table
echo "Add geometry column to $SCHEMA_NAME.$TABLE_NAME"
echo "select AddGeometryColumn ('$SCHEMA_NAME','$TABLE_NAME','geom', 4326,'POINT',2)"
psql -d $DB_NAME -c "CREATE EXTENSION IF NOT EXISTS postgis;"
psql -d $DB_NAME -c "select AddGeometryColumn ('$SCHEMA_NAME','$TABLE_NAME','geom', 4326,'POINT',2);"

# update table
echo "Generate geometry objects based on lat/lng values"
psql -d $DB_NAME -c "update $SCHEMA_NAME.$TABLE_NAME set geom = ST_SetSRID(ST_Point(lon/10000000.0,lat/10000000.0),4326);"

# create spatial index
#echo "Create spatial index"
#psql -d $DB_NAME -c "create index geom_idx on $SCHEMA_NAME.$TABLE_NAME using gist(geom);"


text:
"""
    The Plaid API

    The Plaid REST API. Please see https://plaid.com/docs/api for more details.  # noqa: E501
    Generated by: https://openapi-generator.tech
"""

import re  # noqa: F401
import sys  # noqa: F401

from plaid.model_utils import (  # noqa: F401
    ApiTypeError,
    ModelComposed,
    ModelNormal,
    ModelSimple,
    cached_property,
    change_keys_js_to_python,
    convert_js_args_to_python_args,
    date,
    datetime,
    file_type,
    none_type,
    validate_get_composed_info,
)

def lazy_import():
    from plaid.model.partner_end_customer import PartnerEndCustomer
    from plaid.model.partner_end_customer_secrets import PartnerEndCustomerSecrets
    from plaid.model.partner_end_customer_status import PartnerEndCustomerStatus
    from plaid.model.partner_end_customer_with_secrets_all_of import PartnerEndCustomerWithSecretsAllOf
    globals()['PartnerEndCustomer'] = PartnerEndCustomer
    globals()['PartnerEndCustomerSecrets'] = PartnerEndCustomerSecrets
    globals()['PartnerEndCustomerStatus'] = PartnerEndCustomerStatus
    globals()['PartnerEndCustomerWithSecretsAllOf'] = PartnerEndCustomerWithSecretsAllOf

class PartnerEndCustomerWithSecrets(ModelComposed):
    """NOTE: This class is auto generated by OpenAPI Generator.
    Ref: https://openapi-generator.tech

    Do not edit the class manually.

    Attributes:
      allowed_values (dict): The key is the tuple path to the attribute
          and the for var_name this is (var_name,). The value is a dict
          with a capitalized key describing the allowed value and an allowed
          value. These dicts store the allowed enum values.
      attribute_map (dict): The key is attribute name
          and the value is json key in definition.
      discriminator_value_class_map (dict): A dict to go from the discriminator
          variable value to the discriminator class name.
      validations (dict): The key is the tuple path to the attribute
          and the for var_name this is (var_name,). The value is a dict
          that stores validations for max_length, min_length, max_items,
          min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
          inclusive_minimum, and regex.
      additional_properties_type (tuple): A tuple of classes accepted
          as additional properties values.
    """

    allowed_values = {
    }

    validations = {
    }

    @cached_property
    def additional_properties_type():
        """
        This must be a method because a model may have properties that are
        of type self, this must run after the class is loaded
        """
        lazy_import()
        return (bool, date, datetime, dict, float, int, list, str, none_type,)  # noqa: E501

    _nullable = False

    @cached_property
    def openapi_types():
        """
        This must be a method because a model may have properties that are
        of type self, this must run after the class is loaded

        Returns
            openapi_types (dict): The key is attribute name
                and the value is attribute type.
        """
        lazy_import()
        return {
            'client_id': (str,),  # noqa: E501
            'company_name': (str,),  # noqa: E501
            'status': (PartnerEndCustomerStatus,),  # noqa: E501
            'secrets': (PartnerEndCustomerSecrets,),  # noqa: E501
        }

    @cached_property
    def discriminator():
        return None

    attribute_map = {
        'client_id': 'client_id',  # noqa: E501
        'company_name': 'company_name',  # noqa: E501
        'status': 'status',  # noqa: E501
        'secrets': 'secrets',  # noqa: E501
    }

    required_properties = set([
        '_data_store',
        '_check_type',
        '_spec_property_naming',
        '_path_to_item',
        '_configuration',
        '_visited_composed_classes',
        '_composed_instances',
        '_var_name_to_model_instances',
        '_additional_properties_model_instances',
    ])

    @convert_js_args_to_python_args
    def __init__(self, *args, **kwargs):  # noqa: E501
        """PartnerEndCustomerWithSecrets - a model defined in OpenAPI

        Keyword Args:
            _check_type (bool): if True, values for parameters in openapi_types
                                will be type checked and a TypeError will be
                                raised if the wrong type is input.
                                Defaults to True
            _path_to_item (tuple/list): This is a list of keys or values to
                                drill down to the model in received_data
                                when deserializing a response
            _spec_property_naming (bool): True if the variable names in the input data
                                are serialized names, as specified in the OpenAPI document.
                                False if the variable names in the input data
                                are pythonic names, e.g. snake case (default)
            _configuration (Configuration): the instance to use when
                                deserializing a file_type parameter.
                                If passed, type conversion is attempted
                                If omitted no type conversion is done.
            _visited_composed_classes (tuple): This stores a tuple of
                                classes that we have traveled through so that
                                if we see that class again we will not use its
                                discriminator again.
                                When traveling through a discriminator, the
                                composed schema that is
                                is traveled through is added to this set.
                                For example if Animal has a discriminator
                                petType and we pass in "Dog", and the class Dog
                                allOf includes Animal, we move through Animal
                                once using the discriminator, and pick Dog.
                                Then in Dog, we will make an instance of the
                                Animal class but this time we won't travel
                                through its discriminator because we passed in
                                _visited_composed_classes = (Animal,)
            client_id (str): [optional]  # noqa: E501
            company_name (str): [optional]  # noqa: E501
            status (PartnerEndCustomerStatus): [optional]  # noqa: E501
            secrets (PartnerEndCustomerSecrets): [optional]  # noqa: E501
        """

        _check_type = kwargs.pop('_check_type', True)
        _spec_property_naming = kwargs.pop('_spec_property_naming', False)
        _path_to_item = kwargs.pop('_path_to_item', ())
        _configuration = kwargs.pop('_configuration', None)
        _visited_composed_classes = kwargs.pop('_visited_composed_classes', ())

        if args:
            raise ApiTypeError(
                "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % (
                    args,
                    self.__class__.__name__,
                ),
                path_to_item=_path_to_item,
                valid_classes=(self.__class__,),
            )

        self._data_store = {}
        self._check_type = _check_type
        self._spec_property_naming = _spec_property_naming
        self._path_to_item = _path_to_item
        self._configuration = _configuration
        self._visited_composed_classes = _visited_composed_classes + (self.__class__,)

        constant_args = {
            '_check_type': _check_type,
            '_path_to_item': _path_to_item,
            '_spec_property_naming': _spec_property_naming,
            '_configuration': _configuration,
            '_visited_composed_classes': self._visited_composed_classes,
        }
        required_args = {
        }
        model_args = {}
        model_args.update(required_args)
        model_args.update(kwargs)
        composed_info = validate_get_composed_info(
            constant_args, model_args, self)
        self._composed_instances = composed_info[0]
        self._var_name_to_model_instances = composed_info[1]
        self._additional_properties_model_instances = composed_info[2]
        unused_args = composed_info[3]

        for var_name, var_value in required_args.items():
            setattr(self, var_name, var_value)
        for var_name, var_value in kwargs.items():
            if var_name in unused_args and \
                        self._configuration is not None and \
                        self._configuration.discard_unknown_keys and \
                        not self._additional_properties_model_instances:
                # discard variable.
                continue
            setattr(self, var_name, var_value)

    @cached_property
    def _composed_schemas():
        # we need this here to make our import statements work
        # we must store _composed_schemas in here so the code is only run
        # when we invoke this method. If we kept this at the class
        # level we would get an error beause the class level
        # code would be run when this module is imported, and these composed
        # classes don't exist yet because their module has not finished
        # loading
        lazy_import()
        return {
          'anyOf': [
          ],
          'allOf': [
              PartnerEndCustomer,
              PartnerEndCustomerWithSecretsAllOf,
          ],
          'oneOf': [
          ],
        }


text:
from .base import *  # noqa
from .base import env

# GENERAL
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#secret-key
SECRET_KEY = env("DJANGO_SECRET_KEY")
# https://docs.djangoproject.com/en/dev/ref/settings/#allowed-hosts
ALLOWED_HOSTS = env.list("DJANGO_ALLOWED_HOSTS", default=["nozesnabrita.github.io"])

# DATABASES
# ------------------------------------------------------------------------------
DATABASES["default"] = env.db("DATABASE_URL")  # noqa F405
DATABASES["default"]["ATOMIC_REQUESTS"] = True  # noqa F405
DATABASES["default"]["CONN_MAX_AGE"] = env.int("CONN_MAX_AGE", default=60)  # noqa F405

# CACHES
# ------------------------------------------------------------------------------
CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": env("REDIS_URL"),
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
            # Mimicing memcache behavior.
            # http://jazzband.github.io/django-redis/latest/#_memcached_exceptions_behavior
            "IGNORE_EXCEPTIONS": True,
        },
    }
}

# SECURITY
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#secure-proxy-ssl-header
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
# https://docs.djangoproject.com/en/dev/ref/settings/#secure-ssl-redirect
SECURE_SSL_REDIRECT = env.bool("DJANGO_SECURE_SSL_REDIRECT", default=True)
# https://docs.djangoproject.com/en/dev/ref/settings/#session-cookie-secure
SESSION_COOKIE_SECURE = True
# https://docs.djangoproject.com/en/dev/ref/settings/#csrf-cookie-secure
CSRF_COOKIE_SECURE = True
# https://docs.djangoproject.com/en/dev/topics/security/#ssl-https
# https://docs.djangoproject.com/en/dev/ref/settings/#secure-hsts-seconds
# TODO: set this to 60 seconds first and then to 518400 once you prove the former works
SECURE_HSTS_SECONDS = 60
# https://docs.djangoproject.com/en/dev/ref/settings/#secure-hsts-include-subdomains
SECURE_HSTS_INCLUDE_SUBDOMAINS = env.bool(
    "DJANGO_SECURE_HSTS_INCLUDE_SUBDOMAINS", default=True
)
# https://docs.djangoproject.com/en/dev/ref/settings/#secure-hsts-preload
SECURE_HSTS_PRELOAD = env.bool("DJANGO_SECURE_HSTS_PRELOAD", default=True)
# https://docs.djangoproject.com/en/dev/ref/middleware/#x-content-type-options-nosniff
SECURE_CONTENT_TYPE_NOSNIFF = env.bool(
    "DJANGO_SECURE_CONTENT_TYPE_NOSNIFF", default=True
)

# STATIC
# ------------------------
STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"
# MEDIA
# ------------------------------------------------------------------------------

# TEMPLATES
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#templates
TEMPLATES[-1]["OPTIONS"]["loaders"] = [  # type: ignore[index] # noqa F405
    (
        "django.template.loaders.cached.Loader",
        [
            "django.template.loaders.filesystem.Loader",
            "django.template.loaders.app_directories.Loader",
        ],
    )
]

# EMAIL
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#default-from-email
DEFAULT_FROM_EMAIL = env(
    "DJANGO_DEFAULT_FROM_EMAIL", default="Big Future <noreply@nozesnabrita.github.io>"
)
# https://docs.djangoproject.com/en/dev/ref/settings/#server-email
SERVER_EMAIL = env("DJANGO_SERVER_EMAIL", default=DEFAULT_FROM_EMAIL)
# https://docs.djangoproject.com/en/dev/ref/settings/#email-subject-prefix
EMAIL_SUBJECT_PREFIX = env(
    "DJANGO_EMAIL_SUBJECT_PREFIX", default="[Big Future]"
)

# ADMIN
# ------------------------------------------------------------------------------
# Django Admin URL regex.
ADMIN_URL = env("DJANGO_ADMIN_URL")

# Anymail
# ------------------------------------------------------------------------------
# https://anymail.readthedocs.io/en/stable/installation/#installing-anymail
INSTALLED_APPS += ["anymail"]  # noqa F405
# https://docs.djangoproject.com/en/dev/ref/settings/#email-backend
# https://anymail.readthedocs.io/en/stable/installation/#anymail-settings-reference
# https://anymail.readthedocs.io/en/stable/esps/mailgun/
EMAIL_BACKEND = "anymail.backends.mailgun.EmailBackend"
ANYMAIL = {
    "MAILGUN_API_KEY": env("MAILGUN_API_KEY"),
    "MAILGUN_SENDER_DOMAIN": env("MAILGUN_DOMAIN"),
    "MAILGUN_API_URL": env("MAILGUN_API_URL", default="https://api.mailgun.net/v3"),
}

# django-compressor
# ------------------------------------------------------------------------------
# https://django-compressor.readthedocs.io/en/latest/settings/#django.conf.settings.COMPRESS_ENABLED
COMPRESS_ENABLED = env.bool("COMPRESS_ENABLED", default=True)
# https://django-compressor.readthedocs.io/en/latest/settings/#django.conf.settings.COMPRESS_STORAGE
COMPRESS_STORAGE = "compressor.storage.GzipCompressorFileStorage"
# https://django-compressor.readthedocs.io/en/latest/settings/#django.conf.settings.COMPRESS_URL
COMPRESS_URL = STATIC_URL  # noqa F405
# https://django-compressor.readthedocs.io/en/latest/settings/#django.conf.settings.COMPRESS_OFFLINE
COMPRESS_OFFLINE = True  # Offline compression is required when using Whitenoise
# https://django-compressor.readthedocs.io/en/latest/settings/#django.conf.settings.COMPRESS_FILTERS
COMPRESS_FILTERS = {
    "css": [
        "compressor.filters.css_default.CssAbsoluteFilter",
        "compressor.filters.cssmin.rCSSMinFilter",
    ],
    "js": ["compressor.filters.jsmin.JSMinFilter"],
}

# LOGGING
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#logging
# See https://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "filters": {"require_debug_false": {"()": "django.utils.log.RequireDebugFalse"}},
    "formatters": {
        "verbose": {
            "format": "%(levelname)s %(asctime)s %(module)s "
            "%(process)d %(thread)d %(message)s"
        }
    },
    "handlers": {
        "mail_admins": {
            "level": "ERROR",
            "filters": ["require_debug_false"],
            "class": "django.utils.log.AdminEmailHandler",
        },
        "console": {
            "level": "DEBUG",
            "class": "logging.StreamHandler",
            "formatter": "verbose",
        },
    },
    "root": {"level": "INFO", "handlers": ["console"]},
    "loggers": {
        "django.request": {
            "handlers": ["mail_admins"],
            "level": "ERROR",
            "propagate": True,
        },
        "django.security.DisallowedHost": {
            "level": "ERROR",
            "handlers": ["console", "mail_admins"],
            "propagate": True,
        },
    },
}

# Your stuff...
# ------------------------------------------------------------------------------


text:
package org.eclipse.bpel.apache.ode.deploy.model.dd.impl;

import javax.xml.namespace.QName;

import org.eclipse.bpel.apache.ode.deploy.model.dd.TService;
import org.eclipse.bpel.apache.ode.deploy.model.dd.ddPackage;

import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;

import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;

import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.impl.EObjectImpl;

import org.eclipse.emf.ecore.util.BasicFeatureMap;
import org.eclipse.emf.ecore.util.FeatureMap;
import org.eclipse.emf.ecore.util.InternalEList;

/**
 *
 * An implementation of the model object 'TService'.
 *
 *

 * The following features are implemented:
 *

 *
{@link org.eclipse.bpel.apache.ode.deploy.model.dd.impl.TServiceImpl#getAny Any}

 *
{@link org.eclipse.bpel.apache.ode.deploy.model.dd.impl.TServiceImpl#getName Name}

 *
{@link org.eclipse.bpel.apache.ode.deploy.model.dd.impl.TServiceImpl#getPort Port}

 *

 *

 *
 * @generated
 */
public class TServiceImpl extends EObjectImpl implements TService {
	/**
	 * The cached value of the '{@link #getAny() Any}' attribute list.
	 *
	 *
	 * @see #getAny()
	 * @generated
	 * @ordered
	 */
	protected FeatureMap any;

	/**
	 * The default value of the '{@link #getName() Name}' attribute.
	 *
	 *
	 * @see #getName()
	 * @generated
	 * @ordered
	 */
	protected static final QName NAME_EDEFAULT = null;

	/**
	 * The cached value of the '{@link #getName() Name}' attribute.
	 *
	 *
	 * @see #getName()
	 * @generated
	 * @ordered
	 */
	protected QName name = NAME_EDEFAULT;

	/**
	 * The default value of the '{@link #getPort() Port}' attribute.
	 *
	 *
	 * @see #getPort()
	 * @generated
	 * @ordered
	 */
	protected static final String PORT_EDEFAULT = null;

	/**
	 * The cached value of the '{@link #getPort() Port}' attribute.
	 *
	 *
	 * @see #getPort()
	 * @generated
	 * @ordered
	 */
	protected String port = PORT_EDEFAULT;

	/**
	 *
	 *
	 * @generated
	 */
	protected TServiceImpl() {
		super();
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	protected EClass eStaticClass() {
		return ddPackage.Literals.TSERVICE;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public FeatureMap getAny() {
		if (any == null) {
			any = new BasicFeatureMap(this, ddPackage.TSERVICE__ANY);
		}
		return any;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public QName getName() {
		return name;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public void setName(QName newName) {
		QName oldName = name;
		name = newName;
		if (eNotificationRequired())
			eNotify(new ENotificationImpl(this, Notification.SET, ddPackage.TSERVICE__NAME, oldName, name));
	}

	/**
	 *
	 *
	 * @generated
	 */
	public String getPort() {
		return port;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public void setPort(String newPort) {
		String oldPort = port;
		port = newPort;
		if (eNotificationRequired())
			eNotify(new ENotificationImpl(this, Notification.SET, ddPackage.TSERVICE__PORT, oldPort, port));
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
		switch (featureID) {
			case ddPackage.TSERVICE__ANY:
				return ((InternalEList<?>)getAny()).basicRemove(otherEnd, msgs);
		}
		return super.eInverseRemove(otherEnd, featureID, msgs);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public Object eGet(int featureID, boolean resolve, boolean coreType) {
		switch (featureID) {
			case ddPackage.TSERVICE__ANY:
				if (coreType) return getAny();
				return ((FeatureMap.Internal)getAny()).getWrapper();
			case ddPackage.TSERVICE__NAME:
				return getName();
			case ddPackage.TSERVICE__PORT:
				return getPort();
		}
		return super.eGet(featureID, resolve, coreType);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public void eSet(int featureID, Object newValue) {
		switch (featureID) {
			case ddPackage.TSERVICE__ANY:
				((FeatureMap.Internal)getAny()).set(newValue);
				return;
			case ddPackage.TSERVICE__NAME:
				setName((QName)newValue);
				return;
			case ddPackage.TSERVICE__PORT:
				setPort((String)newValue);
				return;
		}
		super.eSet(featureID, newValue);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public void eUnset(int featureID) {
		switch (featureID) {
			case ddPackage.TSERVICE__ANY:
				getAny().clear();
				return;
			case ddPackage.TSERVICE__NAME:
				setName(NAME_EDEFAULT);
				return;
			case ddPackage.TSERVICE__PORT:
				setPort(PORT_EDEFAULT);
				return;
		}
		super.eUnset(featureID);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public boolean eIsSet(int featureID) {
		switch (featureID) {
			case ddPackage.TSERVICE__ANY:
				return any != null && !any.isEmpty();
			case ddPackage.TSERVICE__NAME:
				return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name);
			case ddPackage.TSERVICE__PORT:
				return PORT_EDEFAULT == null ? port != null : !PORT_EDEFAULT.equals(port);
		}
		return super.eIsSet(featureID);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public String toString() {
		if (eIsProxy()) return super.toString();

		StringBuffer result = new StringBuffer(super.toString());
		result.append(" (any: ");
		result.append(any);
		result.append(", name: ");
		result.append(name);
		result.append(", port: ");
		result.append(port);
		result.append(')');
		return result.toString();
	}

} //TServiceImpl


text:
require File.dirname(__FILE__) + '/../../spec_helper.rb'

module Spec
  module Extensions
    describe Main do
      include SandboxedOptions
      before(:each) do
        @main = Class.new do; include Main; end
      end

      after(:each) do
        $rspec_story_steps = @original_rspec_story_steps
      end

      specify {@main.should respond_to(:describe)}
      specify {@main.should respond_to(:context)}

      it "should raise when no block given to describe" do
        lambda { @main.describe "foo" }.should raise_error(ArgumentError)
      end

      it "should raise when no description given to describe" do
        lambda { @main.describe do; end }.should raise_error(ArgumentError)
      end

      it "should registered ExampleGroups by default" do
        example_group = @main.describe("The ExampleGroup") do end
        Spec::Runner.options.example_groups.should include(example_group)
      end

      it "should not run unregistered ExampleGroups" do
        example_group = @main.describe("The ExampleGroup") do
          unregister
        end

        Spec::Runner.options.example_groups.should_not include(example_group)
      end

      it "should create a shared ExampleGroup with share_examples_for" do
        group = @main.share_examples_for "all things" do end
        group.should be_an_instance_of(Spec::Example::SharedExampleGroup)
      end

      describe "#share_as" do
        before(:each) do
          $share_as_examples_example_module_number ||= 1
          $share_as_examples_example_module_number += 1
          t = Time.new.to_i
          @group_name = "Group#{$share_as_examples_example_module_number}"
        end

        it "should create a shared ExampleGroup" do
          group = @main.share_as @group_name do end
          group.should be_an_instance_of(Spec::Example::SharedExampleGroup)
        end

        it "should create a constant that points to a Module" do
          group = @main.share_as @group_name do end
          Object.const_get(@group_name).should equal(group)
        end

        it "should bark if you pass it something not-constantizable" do
          lambda do
            @group = @main.share_as "Non Constant" do end
          end.should raise_error(NameError, /The first argument to share_as must be a legal name for a constant/)
        end

      end
    end
  end
end


text:
title: Children of Blood and Bone
written_by: Tomi Adeyemi
available: 'March 6th, 2018'
isbn: '9781250170972'
binding: Hardcover
link_to_buy_page:
image_path: 'https://images.booksense.com/images/972/170/9781250170972.jpg'
link:
---


text:
<?php
namespace FS\SolrBundle\Tests\Doctrine\Annotation\Entities;

class InvalidEntityRepository
{
    /**
     * @Solr\Id
     */
    private $id;
}


text:
export const labelPressEnterToAccept = 'Press Enter to accept';
export const labelSave = 'Save';
export const labelSaving = 'Saving...';
export const labelSaved = 'Saved';
export const labelReset = 'Reset';
export const labelDisplayThePassword = 'Display the password';
export const labelHideThePassword = 'Hide the password';


text:
<meta charset="UTF-8">
<title>Sku.description - RichUtils</title>
<link rel="stylesheet" href="../../../style.css">

RichUtils / pyxis.uzuki.live.richutilskt.module.iap / Sku / description

description

var description: String


text:
namespace operations_research {
namespace glop {

bool LoadMPModelProtoFromModelOrRequest(const std::string& input_file_path,
                                        MPModelProto* model) {
  MPModelProto model_proto;
  MPModelRequest request_proto;
  ReadFileToProto(input_file_path, &model_proto);
  ReadFileToProto(input_file_path, &request_proto);
  // If the input proto is in binary format, both ReadFileToProto could return
  // true. Instead use the actual number of variables found to test the
  // correct format of the input.
  const bool is_model_proto = model_proto.variable_size() > 0;
  const bool is_request_proto = request_proto.model().variable_size() > 0;
  if (!is_model_proto && !is_request_proto) {
    LOG(ERROR) << "Failed to parse '" << input_file_path
               << "' as an MPModelProto or an MPModelRequest.";
    return false;
  } else {
    if (is_model_proto && is_request_proto) {
      LOG(ERROR) << input_file_path
                 << " is parsing as both MPModelProto and MPModelRequest";
      return false;
    }
    if (is_request_proto) {
      VLOG(1) << "Read input proto as an MPModelRequest.";
      model_proto.Swap(request_proto.mutable_model());
    } else {
      VLOG(1) << "Read input proto as an MPModelProto.";
    }
  }
  model->Swap(&model_proto);
  return true;
}

bool LoadLinearProgramFromModelOrRequest(const std::string& input_file_path,
                                         LinearProgram* linear_program) {
  MPModelProto model_proto;
  if (LoadMPModelProtoFromModelOrRequest(input_file_path, &model_proto)) {
    MPModelProtoToLinearProgram(model_proto, linear_program);
    return true;
  }
  return false;
}

}  // namespace glop
}  // namespace operations_research


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Foundation;
using UIKit;

namespace HandlingRotation.Screens.iPad.Home {
	public partial class HomeScreenPad : UIViewController {
		#region Constructors

		// The IntPtr and initWithCoder constructors are required for controllers that need
		// to be able to be created from a xib rather than from managed code

		public HomeScreenPad (IntPtr handle) : base(handle)
		{
			Initialize ();
		}

		[Export("initWithCoder:")]
		public HomeScreenPad (NSCoder coder) : base(coder)
		{
			Initialize ();
		}

		public HomeScreenPad () : base("HomeScreen", null)
		{
			Initialize ();
		}

		void Initialize ()
		{
		}

		#endregion

		public override void ViewWillAppear (bool animated)
		{
			base.ViewWillAppear (animated);
			// we don't want the nav bar to appear on the home page, so we hide it
			// when the page appears. if it's an animated appearance, we likewise
			// animate the disappearance of the nav bar
			NavigationController.SetNavigationBarHidden (true, animated);
		}

		public override void ViewWillDisappear (bool animated)
		{
			base.ViewWillDisappear (animated);
			// when page is going away because we're showing another page, we
			// bring the nav bar back
			NavigationController.SetNavigationBarHidden (false, animated);
		}

		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();

			// wire up our button TouchUpInside handlers
			btnMethod1.TouchUpInside += delegate { NavigationController.PushViewController (new Method1Autosize.AutosizeScreenPad (), true); };
			btnMethod2.TouchUpInside += delegate { NavigationController.PushViewController (new Method2MoveControls.Controller (), true); };
			btnMethod3.TouchUpInside += delegate { NavigationController.PushViewController (new Method3SwapViews.Controller (), true); };
		}

		/// <summary>
		/// When the device rotates, the OS calls this method to determine if it should try and rotate the
		/// application and then call WillAnimateRotation
		/// </summary>
		public override bool ShouldAutorotateToInterfaceOrientation (UIInterfaceOrientation toInterfaceOrientation)
		{
			// we're passed to orientation that it will rotate to. in our case, we could
			// just return true, but this switch illustrates how you can test for the
			// different cases
			switch (toInterfaceOrientation) {
				case UIInterfaceOrientation.LandscapeLeft:
				case UIInterfaceOrientation.LandscapeRight:
				case UIInterfaceOrientation.Portrait:
				case UIInterfaceOrientation.PortraitUpsideDown:
				default:
					return true;
			}
		}
	}
}


text:
'use strict';
describe('rootCtrl', function() {
	var scope;
	var ctrl;

	// You need to load modules that you want to test,
	// it loads only the "ng" module by default.
	beforeEach(module('app'));
	beforeEach(inject(function ($rootScope, $controller) {
		scope = $rootScope.$new();
		ctrl = $controller('rootCtrl', {$scope: scope});
	}));

	it('should have a working method for deleting scope.query',
		function () {
			expect(scope.val).toEqual('for test');
		}
	);

});


text:
struct Rom
{
    std::vector<uint8_t> binaryData = {};

    explicit Rom(std::string filePath);
};

#endif //CHIP8_ROM_HPP


text:
require 'spec_helper'

describe PicturesController do
  render_views

  context "with public picture" do
    before do
      @public_picture = create(:public_picture)
    end

    describe "when not authenticated" do
      it "should redirect to login" do
        get :index
        response.should redirect_to(:new_user_session)
      end

      it "should render receiver's index with public picture included" do
        get :index, :user_id => @public_picture.post_activity.receiver.to_param
        response.should be_success
        response.body.should =~ /attachment_tile/
        response.body.should =~ /rails.png/
      end

      it "should render receiver's show" do
        get :show, :id => @public_picture.to_param
        response.should be_success
        response.headers["Content-Type"].should include('text/html')
      end

      it "should render receiver's content" do
        get :show, :id => @public_picture.to_param, :format=>:png
        response.should be_success
        response.headers["Content-Type"].should include('image/png')
      end
    end

    describe "when authenticated" do
      before do
        sign_in create(:user)
      end

      it "should render index" do
        get :index, :user_id => @public_picture.post_activity.receiver.to_param
        response.should be_success
        response.body.should =~ /attachment_tile/
        response.body.should =~ /rails.png/
      end

      it "should render show" do
        get :show, :id => @public_picture.to_param
        response.should be_success
        response.headers["Content-Type"].should include('text/html')
      end

      it "should render content" do
        get :show, :id => @public_picture.to_param, :format=>:png
        response.should be_success
        response.headers["Content-Type"].should include('image/png')
      end
    end
  end #end of the context

  context "with private picture" do
    before do
      @private_picture = create(:private_picture)
    end
    describe "when not authenticated" do
      it "should render receiver's index without private picture" do
        get :index, :user_id => @private_picture.post_activity.receiver.to_param
        response.should be_success
        response.body.should_not =~ /attachment_tile/
        response.body.should_not =~ /privado.png/
      end
    end

    describe "when authenticated" do
      before do
        sign_in create(:user)
      end
      it "should render index" do
        get :index, :user_id => @private_picture.post_activity.receiver.to_param
        response.should be_success
        response.body.should_not =~ /attachment_tile/
        response.body.should_not =~ /privado.png/
      end

      it "should render show" do
        lambda {get :show, :id => @private_picture.to_param}.should raise_error(CanCan::AccessDenied)
      end
    end
  end
end


text:
typedef NS_ENUM(NSUInteger, BZMethodType) {
    Unknown,
    GET,
    POST,
    Stream
};


text:
using System.Net;
using System.Text;

namespace Mono.Nat.Upnp
{
    static class DiscoverDeviceMessage
    {
        internal static readonly string[] SupportedServiceTypes = new[] {
            "urn:schemas-upnp-org:device:InternetGatewayDevice:1",
            "urn:schemas-upnp-org:device:InternetGatewayDevice:2",
            "urn:schemas-upnp-org:device:InternetGatewayDevice:",
        };

        static readonly string[] SearchServiceTypes = new[] {
            "all",
            "urn:schemas-upnp-org:device:InternetGatewayDevice:1",
            "urn:schemas-upnp-org:device:InternetGatewayDevice:2",
        };

        /// <summary>
        /// The message sent to discover all uPnP devices on the network
        /// </summary>
        /// <returns></returns>
        public static byte[][] EncodeSSDP ()
        {
            var results = new byte[SearchServiceTypes.Length][];
            for (int i = 0; i < SearchServiceTypes.Length; i++) {
                var s = "M-SEARCH * HTTP/1.1\r\n"
                        + "HOST: 239.255.255.250:1900\r\n"
                        + "MAN: \"ssdp:discover\"\r\n"
                        + "MX: 3\r\n"
                        + string.Format ("ST: ssdp:{0}\r\n\r\n", SearchServiceTypes[i]);
                results[i] = Encoding.ASCII.GetBytes (s);
            }
            return results;
        }

        public static byte[][] EncodeUnicast (IPAddress gatewayAddress)
        {
            //Format obtained from http://upnp.org/specs/arch/UPnP-arch-DeviceArchitecture-v1.1.pdf pg 31
            //This method only works with upnp 1.1 routers... unfortunately
            var results = new byte[SearchServiceTypes.Length][];
            for (int i = 0; i < SearchServiceTypes.Length; i++) {
                string s = "M-SEARCH * HTTP/1.1\r\n"
                        + "HOST: " + gatewayAddress + ":1900\r\n"
                        + "MAN: \"ssdp:discover\"\r\n"
                        + string.Format ("ST: ssdp:{0}\r\n\r\n", SearchServiceTypes[i]);
                results[i] = Encoding.ASCII.GetBytes (s);
            }
            return results;
        }
    }
}


text:
package com.unicorn.easygo.db;

/**
 * Created by guojishan on 2017/6/20.
 */

public class account {
    private int id;
    private int userId;
    private String sex;
    private String vip;
    private double money;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getVip() {
        return vip;
    }

    public void setVip(String vip) {
        this.vip = vip;
    }

    public double getMoney() {
        return money;
    }

    public void setMoney(double money) {
        this.money = money;
    }

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }
}


text:
<!--
  - Copyright 1999-2012 Alibaba Group.
  -
  -   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.
  -->
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
       xmlns="http://www.springframework.org/schema/beans"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
       http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd">

    <dubbo:application name="heartbeat-provider"/>

    <!--<dubbo:registry address="127.0.0.1:9090"/>-->

    <dubbo:protocol name="dubbo" port="20880"/>

    <bean id="helloService" class="com.alibaba.dubbo.examples.remoting.heartbeat.impl.HelloServiceImpl"/>

    <dubbo:service registry="N/A" interface="com.alibaba.dubbo.examples.remoting.heartbeat.api.HelloService"
                   ref="helloService">
        <dubbo:parameter key="heartbeat" value="3000"/>
    </dubbo:service>

</beans>


text:
import React, {Component} from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';

import { PaginationContainer } from '../PaginationContainer';
import { LoadingContainer } from '../LoadingContainer';
import { LogTableRow } from '../../components/admin/LogTableRow';
import * as AdminActions from '../../actions/AdminActions';
import { SearchBar } from '../../components/admin/SearchBar';

class LogOverview extends Component {

  onSearchQueryChange (newQuery) {
    // trigger change, if needed
    // update url query
    if (this.props.logOverview.pagesQuery.q === newQuery) {
      return;
    }
  }

  onSearchClick (query) {
    this.props.changeLogsSearch(query);
  }

  onResetSearchClick () {
    this.props.changeLogsSearch('');
  }

  renderSearch () {
    return (<SearchBar
      placeholderText="Nach Log suchen..."
      searchClickHandler={this.onSearchClick.bind(this)}
      changeSearchQuery={this.onSearchQueryChange.bind(this)}
      resetSearchHandler={this.onResetSearchClick.bind(this)}
      searchQuery={this.props.logOverview.pagesQuery.q} />);
  }

  renderTable() {
    return (

            Event
            Nachricht
            Typ
            Zusätzliche Daten
            Zeitpunkt

          {this.props.logOverview.logs.map((log, index) => {
            return <LogTableRow key={index} data={log} />;
          })}

    );
  }

  render () {
    const content = this.renderTable();
    return (
      <PaginationContainer
          changePage={this.props.changeLogsPage}
          requestPage={this.props.requestLogsPage}
          pages={this.props.logOverview.pages}
          pagesQuery={this.props.logOverview.pagesQuery}
          location={this.props.location}>

Letzte Events ({this.props.logOverview.count})

        {this.renderSearch()}
        <LoadingContainer isLoading={this.props.logOverview.isFetching}>
          {content}
        </LoadingContainer>
      </PaginationContainer>
    );
  }
}

export default connect(state => ({
  logOverview: state.logOverview
}),
  dispatch => bindActionCreators(AdminActions, dispatch)
)(LogOverview);


text:
require 'set'
require 'parslet/atoms/visitor'

class Parslet::Parser
  module Visitors
    class Citrus
      attr_reader :context, :output
      def initialize(context)
        @context = context
      end

      def visit_str(str)
        "\"#{str.inspect[1..-2]}\""
      end
      def visit_re(match)
        match.to_s
      end

      def visit_entity(name, block)
        context.deferred(name, block)

        "(#{context.mangle_name(name)})"
      end
      def visit_named(name, parslet)
        parslet.accept(self)
      end

      def visit_sequence(parslets)
        '(' <<
        parslets.
          map { |el| el.accept(self) }.
          join(' ') <<
        ')'
      end
      def visit_repetition(tag, min, max, parslet)
        parslet.accept(self) << "#{min}*#{max}"
      end
      def visit_alternative(alternatives)
        '(' <<
        alternatives.
          map { |el| el.accept(self) }.
          join(' | ') <<
        ')'
      end

      def visit_lookahead(positive, bound_parslet)
        (positive ? '&' : '!') <<
        bound_parslet.accept(self)
      end
    end

    class Treetop < Citrus
      def visit_repetition(tag, min, max, parslet)
        parslet.accept(self) << "#{min}..#{max}"
      end

      def visit_alternative(alternatives)
        '(' <<
        alternatives.
          map { |el| el.accept(self) }.
          join(' / ') <<
        ')'
      end
    end
  end

  # A helper class that formats Citrus and Treetop grammars as a string.
  #
  class PrettyPrinter
    attr_reader :visitor
    def initialize(visitor_klass)
      @visitor = visitor_klass.new(self)
    end

    # Pretty prints the given parslet using the visitor that has been
    # configured in initialize. Returns the string representation of the
    # Citrus or Treetop grammar.
    #
    def pretty_print(name, parslet)
      output = "grammar #{name}\n"

      output << rule('root', parslet)

      seen = Set.new
      loop do
        # @todo is constantly filled by the visitor (see #deferred). We
        # keep going until it is empty.
        break if @todo.empty?
        name, block = @todo.shift

        # Track what rules we've already seen. This breaks loops.
        next if seen.include?(name)
        seen << name

        output << rule(name, block.call)
      end

      output << "end\n"
    end

    # Formats a rule in either dialect.
    #
    def rule(name, parslet)
      "  rule #{mangle_name name}\n" <<
      "    " << parslet.accept(visitor) << "\n" <<
      "  end\n"
    end

    # Whenever the visitor encounters an rule in a parslet, it defers the
    # pretty printing of the rule by calling this method.
    #
    def deferred(name, content)
      @todo ||= []
      @todo << [name, content]
    end

    # Mangles names so that Citrus and Treetop can live with it. This mostly
    # transforms some of the things that Ruby allows into other patterns. If
    # there is collision, we will not detect it for now.
    #
    def mangle_name(str)
      str.to_s.sub(/\?$/, '_p')
    end
  end

  # Exports the current parser instance as a string in the Citrus dialect.
  #
  # Example:
  #
  #   require 'parslet/export'
  #   class MyParser < Parslet::Parser
  #     root(:expression)
  #     rule(:expression) { str('foo') }
  #   end
  #
  #   MyParser.new.to_citrus # => a citrus grammar as a string
  #
  def to_citrus
    PrettyPrinter.new(Visitors::Citrus).
      pretty_print(self.class.name, root)
  end

  # Exports the current parser instance as a string in the Treetop dialect.
  #
  # Example:
  #
  #   require 'parslet/export'
  #   class MyParser < Parslet::Parser
  #     root(:expression)
  #     rule(:expression) { str('foo') }
  #   end
  #
  #   MyParser.new.to_treetop # => a treetop grammar as a string
  #
  def to_treetop
    PrettyPrinter.new(Visitors::Treetop).
      pretty_print(self.class.name, root)
  end
end


text:
#ifndef _IENGINE_H
#define _IENGINE_H

/**
 * The engine interface -- each engine must provide
 *	1) an ignition sequence
 *	2) what each cycle is to do
 *	3) the shutdown sequence
 */

enum status_code { UNINITIALIZED, INITIALIZED, RUNNING, STOPPED };

class Engine {
	public:
		Engine();
		~Engine();

		virtual void ignite();
		virtual void cycle();
		virtual void shutdown();

		int get_status();
		int get_signal();

	private:
		int status;

		/**
		 * initialize signal to 1 -- if signal == 0 while in .cycle(), call .shutdown()
		 */
		int signal;
};

#endif


text:
package main

import (
	"errors"
	"flag"
	"fmt"
	"os"
	"path/filepath"
	"strconv"
	"strings"
)

type folder struct {
	name  string
	depth int
}

type folders []folder

func (a *folders) String() string {
	return fmt.Sprintf("%+v", *a)
}

func (a *folders) Set(x string) error {
	p := strings.Split(x, ",")
	if len(p) > 2 {
		return errors.New("too many occurances of , in argument")
	}
	n := -1
	if len(p) == 2 {
		var err error
		n, err = strconv.Atoi(p[1])
		if err != nil {
			return err
		}
	}
	*a = append(*a, folder{name: p[0], depth: n})
	return nil
}

var flagFolders folders

func main() {
	flag.Var(&flagFolders, "p", "path[,depth]; may be specified multiple times.")
	flag.Parse()

	for _, folder := range flagFolders {
		for _, path := range Find(folder.name, folder.depth) {
			rel, err := filepath.Rel(folder.name, path)
			if err != nil {
				panic(err)
			}
			fmt.Printf("%s,%s\n", folder.name, rel)
		}
	}
}

// Find git repositories.
func Find(name string, depth int) []string {
	var repos []string
	filepath.Walk(name, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return filepath.SkipDir
		}

		if !info.IsDir() {
			return nil
		}

		if _, err := os.Stat(filepath.Join(path, ".git")); err == nil {
			repos = append(repos, path)
			return filepath.SkipDir
		}

		rel, err := filepath.Rel(name, path)
		if err != nil {
			panic(err)
		}

		if depth == 0 && rel == "." {
			return filepath.SkipDir
		}

		if depth > 0 && rel != "." {
			p := strings.Split(rel, string(filepath.Separator))
			if len(p) >= depth {
				return filepath.SkipDir
			}
		}

		return nil
	})
	return repos
}


text:
This example demonstrates using Jupyter JS Services from the browser using
Webpack. The python script `main.py` is used to start a Jupyter Notebook Server
and serve the Webpack bundle.

The base url of the notebook server is to the HTML template as part of a JSON
script tag. The script starts a python notebook session and interacts
with it, printing messages to the browser console.

The example can be installed as `npm install` and run as `python main.py`.

Notes:

- The example is written in _TypeScript_ using _ES6_ syntax.
- The TypeScript compiler config is in `tsconfig.json`.
- A typings file and a polyfill are required for ES6 promises.
- The example requires version 4.1+ of the Jupyter Notebook.
- This example `require`s its dependencies from the root directory of the
  repo, but typically the requirements would be directly in `package.json`


text:
<form class="form">

            Enviar para participantes da promoção:

                <input type="checkbox" value="true" ng-model="promotionAtacheds[promotion.id]"> {{promotion.name}}

                   de {{promotion.start_date | date:"dd/MM/yyyy"}} ate {{promotion.end_date | date:"dd/MM/yyyy"}}

</form>


text:
require 'fog/vcloud/models/compute/network'

module Fog
  module Vcloud
    class Compute
      class Networks < Fog::Vcloud::Collection
        undef_method :create

        model Fog::Vcloud::Compute::Network

        attribute :href

        def all
          self.href = service.default_vdc_href unless self.href
          data = nil
          if self.href =~ /\/vdc\//
            check_href!("Vdc")
            data = [service.get_vdc(self.href).available_networks].flatten.compact.reject{|n| n == '' }
          elsif self.href =~ /\/org\//
            check_href!("Org")
            data = service.get_organization(self.href).links.select{|l| l[:type] == network_type_id }
          elsif self.href =~ /\/vApp\//
            check_href!("Vapp")
            data = [(service.get_vapp(self.href).network_configs||{})[:NetworkConfig]].flatten.compact.map{|n| n[:Configuration][:ParentNetwork] unless n[:Configuration].nil? }.compact
          end
          load([*data]) unless data.nil?
        end

        def get(uri)
          service.get_network(uri)
        rescue Fog::Errors::NotFound
          nil
        end

        private
        def network_type_id
          if service.version == '1.0'
            'application/vnd.vmware.vcloud.network+xml'
          else
            'application/vnd.vmware.vcloud.orgNetwork+xml'
          end
        end
      end
    end
  end
end


text:
namespace tensorflow {

// Message-text conversion for tensorflow.GraphDef
string ProtoDebugString(
    const ::tensorflow::GraphDef& msg);
string ProtoShortDebugString(
    const ::tensorflow::GraphDef& msg);
bool ProtoParseFromString(
    const string& s,
    ::tensorflow::GraphDef* msg)
        TF_MUST_USE_RESULT;

// Message-text conversion for tensorflow.NodeDef
string ProtoDebugString(
    const ::tensorflow::NodeDef& msg);
string ProtoShortDebugString(
    const ::tensorflow::NodeDef& msg);
bool ProtoParseFromString(
    const string& s,
    ::tensorflow::NodeDef* msg)
        TF_MUST_USE_RESULT;

}  // namespace tensorflow

#endif  // tensorflow_core_framework_graph_proto_H_


text:
<title>OGRE: OgreTimer.h Source File - OGRE Documentation</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link type="text/css" rel="stylesheet" href="doxygen.css">
<link type="text/css" rel="stylesheet" href="tabs.css">

Main Page

Related Pages

Modules

Namespaces

Classes

Files

Directories

File List

File Members

OgreMain » include

OgreTimer.h
Go to the documentation of this file.

00001
00028 #ifndef __OgreCommonTimer_H__
00029 #define __OgreCommonTimer_H__
00030
00031 #include "OgrePrerequisites.h"
00032 #include "OgrePlatform.h"
00033
00034 //Bring in the specific platform's header file
00035 #if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
00036 # include "WIN32/OgreTimerImp.h"
00037 #elif OGRE_PLATFORM == OGRE_PLATFORM_LINUX
00038 # include "GLX/OgreTimerImp.h"
00039 #elif OGRE_PLATFORM == OGRE_PLATFORM_NACL
00040 # include "NaCl/OgreTimerImp.h"
00041 #elif OGRE_PLATFORM == OGRE_PLATFORM_APPLE
00042 # include "OSX/OgreTimerImp.h"
00043 #elif OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS
00044 # include "iOS/OgreTimerImp.h"
00045 #elif OGRE_PLATFORM == OGRE_PLATFORM_ANDROID
00046 # include "Android/OgreTimerImp.h"
00047 #endif
00048
00049 #endif

Copyright © 2012 Torus Knot Software Ltd

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.

Last modified Sun Sep 2 08:16:11 2012


text:
package cat.nyaa.nyaabank.signs;

import cat.nyaa.nyaabank.CommonAction;
import cat.nyaa.nyaabank.I18n;
import cat.nyaa.nyaabank.NyaaBank;
import cat.nyaa.nyaabank.database.enums.BankStatus;
import cat.nyaa.nyaabank.database.enums.TransactionType;
import cat.nyaa.nyaabank.database.tables.BankRegistration;
import cat.nyaa.nyaabank.database.tables.SignRegistration;
import cat.nyaa.nyaacore.orm.WhereClause;
import org.bukkit.ChatColor;
import org.bukkit.OfflinePlayer;
import org.bukkit.block.Sign;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.SignChangeEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.scheduler.BukkitRunnable;

import static cat.nyaa.nyaabank.signs.SignHelper.stringEqIgnoreColor;

public class SignListener implements Listener {
    public final static String SIGN_MAGIC_FALLBACK = "[BANK]";
    private final ChatInputCallbacks callbacks;
    private final NyaaBank plugin;

    public SignListener(NyaaBank plugin) {
        this.plugin = plugin;
        plugin.getServer().getPluginManager().registerEvents(this, plugin);
        callbacks = new ChatInputCallbacks(plugin);
    }

    /**
     * Apply commission fee, move from player to bank.
     * amount can be negative
     */
    private void applyCommission(Player player, BankRegistration bank, double amount) {
        OfflinePlayer banker = plugin.getServer().getOfflinePlayer(bank.ownerId);
        if (amount > 0) {
            plugin.eco.withdrawPlayer(player, amount);
            plugin.eco.depositPlayer(banker, amount);
            plugin.dbm.log(TransactionType.COMMISSION).from(player.getUniqueId()).to(bank.bankId)
                    .capital(amount).insert();
        } else if (amount < 0) {
            plugin.eco.depositPlayer(player, -amount);
            plugin.eco.withdrawPlayer(banker, amount);
            plugin.dbm.log(TransactionType.COMMISSION).from(player.getUniqueId()).to(bank.bankId)
                    .capital(amount).insert();
        } // do nothing if zero commission
    }

    @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
    public void onPlayerRightClickSign(PlayerInteractEvent ev) {
        if (!ev.hasBlock()) return;
        if (ev.getAction() != Action.RIGHT_CLICK_BLOCK) return;
        if (!SignHelper.isSignBlock(ev.getClickedBlock())) return;
        Sign sign = (Sign) ev.getClickedBlock().getState();
        String magicLine = ChatColor.stripColor(sign.getLine(0));
        if (stringEqIgnoreColor(magicLine, plugin.cfg.signMagic, false) ||
                stringEqIgnoreColor(magicLine, SIGN_MAGIC_FALLBACK, false)) {
            Player p = ev.getPlayer();
            if (callbacks.callbacks.containsKey(p.getUniqueId())) return;
            SignRegistration sr = SignHelper.getSign(plugin, ev.getClickedBlock().getLocation());
            if (sr == null) {
                p.sendMessage(I18n.format("user.sign.invalid_sign"));
                return;
            }
            BankRegistration bank = plugin.dbm.getUniqueBank(sr.bankId.toString());
            if (bank == null) {
                p.sendMessage(I18n.format("user.sign.invalid_sign"));
                return;
            }
            if (bank.status == BankStatus.BANKRUPT) {
                p.sendMessage(I18n.format("user.sign.bankrupted"));
                return;
            }
            if (sr.type == TransactionType.LOAN && sr.loanAmount <= 0) {
                p.sendMessage(I18n.format("user.sign.invalid_sign"));
                return;
            }
            switch (sr.type) {
                case DEPOSIT:
                    if (!p.hasPermission("nb.deposit")) {
                        p.sendMessage(I18n.format("user.sign.use_no_permission"));
                        break;
                    }
                    p.sendMessage(I18n.format("user.sign.input_prompt_deposit", plugin.cfg.signTimeout));
                    callbacks.register(ev.getPlayer().getUniqueId(),
                            new ChatInputCallbacks.InputCallback() {
                                @Override
                                public void onDoubleInput(Player p, double input, boolean isAll) {
                                    try {
                                        if (isAll)
                                            throw new CommonAction.TransactionException("user.sign.invalid_number");
                                        CommonAction.deposit(plugin, p, bank, input);
                                        p.sendMessage(I18n.format("user.sign.input_accepted"));
                                    } catch (CommonAction.TransactionException ex) {
                                        p.sendMessage(I18n.format(ex.getMessage()));
                                    }
                                }
                            });
                    break;
                case WITHDRAW:
                    if (!p.hasPermission("nb.withdraw")) {
                        p.sendMessage(I18n.format("user.sign.use_no_permission"));
                        break;
                    }
                    p.sendMessage(I18n.format("user.sign.input_prompt_withdraw", plugin.cfg.signTimeout));
                    callbacks.register(ev.getPlayer().getUniqueId(),
                            new ChatInputCallbacks.InputCallback() {
                                @Override
                                public void onDoubleInput(Player p, double input, boolean isAll) {
                                    try {
                                        CommonAction.withdraw(plugin, p, bank, input, isAll);
                                        applyCommission(p, bank, sr.commissionFee);
                                        p.sendMessage(I18n.format("user.sign.input_accepted"));

                                    } catch (CommonAction.TransactionException ex) {
                                        p.sendMessage(I18n.format(ex.getMessage()));
                                    }
                                }
                            });
                    break;
                case LOAN:
                    if (!p.hasPermission("nb.loan")) {
                        p.sendMessage(I18n.format("user.sign.use_no_permission"));
                        break;
                    }
                    p.sendMessage(I18n.format("user.sign.input_prompt_loan", plugin.cfg.signTimeout));
                    callbacks.register(ev.getPlayer().getUniqueId(),
                            new ChatInputCallbacks.InputCallback() {
                                @Override
                                public void onDoubleInput(Player p, double input, boolean isAll) {
                                    try {
                                        if (!isAll)
                                            throw new CommonAction.TransactionException("user.sign.loan_cancelled");
                                        CommonAction.loan(plugin, p, bank, sr.loanAmount);
                                        p.sendMessage(I18n.format("user.sign.input_accepted"));
                                    } catch (CommonAction.TransactionException ex) {
                                        p.sendMessage(I18n.format(ex.getMessage()));
                                    }
                                }
                            });
                    break;
                case REPAY:
                    if (!p.hasPermission("nb.repay")) {
                        p.sendMessage(I18n.format("user.sign.use_no_permission"));
                        break;
                    }
                    p.sendMessage(I18n.format("user.sign.input_prompt_repay", plugin.cfg.signTimeout));
                    callbacks.register(ev.getPlayer().getUniqueId(),
                            new ChatInputCallbacks.InputCallback() {
                                @Override
                                public void onDoubleInput(Player p, double input, boolean isAll) {
                                    try {
                                        CommonAction.repay(plugin, p, bank, input, isAll);
                                        applyCommission(p, bank, sr.commissionFee);
                                        p.sendMessage(I18n.format("user.sign.input_accepted"));
                                    } catch (CommonAction.TransactionException ex) {
                                        p.sendMessage(I18n.format(ex.getMessage()));
                                    }
                                }
                            });
                    break;
                default:
                    p.sendMessage(I18n.format("user.sign.invalid_sign"));
                    return; // do not update if an invalid sign
            }
            new BukkitRunnable() {
                @Override
                public void run() {
                    SignHelper.updateSignBlock(plugin, ev.getClickedBlock().getLocation(), sr);
                }
            }.runTaskLater(plugin, 1L); // update block after click;
        }
    }

    @EventHandler(ignoreCancelled = true)
    public void onPlayerCreateSign(SignChangeEvent ev) {
        if (!ev.getPlayer().hasPermission("nb.sign_create")) return;
        String firstLine = ev.getLine(0);
        if (!SignHelper.stringEqIgnoreColor(firstLine, SIGN_MAGIC_FALLBACK, true) &&
                !SignHelper.stringEqIgnoreColor(firstLine, plugin.cfg.signMagic, true))
            return; // not a bank sign
        SignRegistration sr = SignHelper.getSign(plugin, ev.getBlock().getLocation());
        boolean newSign = false;
        if (sr == null) newSign = true;
        sr = SignHelper.parseSign(plugin, ev.getLines(), sr, ev.getBlock().getLocation());
        if (sr == null) {
            ev.getPlayer().sendMessage(I18n.format("user.sign.create_fail"));
            return;
        }
        if (!ev.getPlayer().hasPermission("nb.sign_create_admin")) { // skip bank owner check for admins
            BankRegistration bank = plugin.dbm.getUniqueBank(sr.bankId);
            if (bank == null || !ev.getPlayer().getUniqueId().equals(bank.ownerId)) {
                ev.getPlayer().sendMessage(I18n.format("user.sign.create_fail"));
                return;
            }
        }
        if (newSign) {
            ;
            plugin.dbm.tableSignRegistration.insert(sr);
        } else {
            ;
            plugin.dbm.tableSignRegistration.update(sr, WhereClause.EQ(SignRegistration.N_SIGN_ID, sr.signId));
        }
        ev.getPlayer().sendMessage(I18n.format("user.sign.create_success"));

        // update sign next tick
        final SignRegistration fsr = sr;
        new BukkitRunnable() {
            @Override
            public void run() {
                SignHelper.updateSignBlock(plugin, ev.getBlock().getLocation(), fsr);
            }
        }.runTaskLater(plugin, 1);
    }

    @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
    public void onPlayerBreakSign(BlockBreakEvent ev) {
        if (!SignHelper.isSignBlock(ev.getBlock())) return;
        SignRegistration sr = SignHelper.getSign(plugin, ev.getBlock().getLocation());
        if (sr == null) return;
        if (!ev.getPlayer().hasPermission("nb.sign_break")) {
            ev.getPlayer().sendMessage(I18n.format("user.sign.break_no_permission"));
            ev.setCancelled(true);
            return;
        }
        if (!ev.getPlayer().hasPermission("nb.sign_break_admin")) { // skip owner check for admin
            BankRegistration bank = plugin.dbm.getUniqueBank(sr.bankId);
            if (bank != null && !ev.getPlayer().getUniqueId().equals(bank.ownerId)) {
                ev.getPlayer().sendMessage(I18n.format("user.sign.break_no_permission"));
                ev.setCancelled(true);
                return;
            }
        }
        plugin.dbm.tableSignRegistration.delete(WhereClause.EQ(SignRegistration.N_SIGN_ID, sr.signId));
        ev.getPlayer().sendMessage(I18n.format("user.sign.break_success"));
    }
}


text:
class vtkStructuredPoints;

class WatershedCorrector {
 public:
  static vtkStructuredPoints *correct(
      vtkStructuredPoints *scalar_field,
      vtkStructuredPoints *label_field);
};

#endif  // WATERSHED_CORRECTOR_H_


text:
package org.apache.skywalking.oap.server.receiver.otel;

import org.apache.skywalking.oap.server.library.module.ModuleDefine;

public class OtelMetricReceiverModule extends ModuleDefine {
    public static final String NAME = "receiver-otel";

    public OtelMetricReceiverModule() {
        super(NAME);
    }

    @Override
    public Class[] services() {
        return new Class[0];
    }
}


text:
<ion-tabs>
  <ion-tab tabIcon="water" tabTitle="Home" [root]="tab1Root"></ion-tab>
  <ion-tab tabIcon="leaf" tabTitle="About" [root]="tab2Root"></ion-tab>
  <ion-tab tabIcon="flame" tabTitle="Contact" [root]="tab3Root"></ion-tab>
</ion-tabs>


text:
package cn.androiddevelop.phonelocation.ui;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.LinearLayout;
import android.widget.TextView;
import cn.androiddevelop.phonelocation.R;
import cn.androiddevelop.phonelocation.component.MyService;

public class LocationUi extends LinearLayout implements OnTouchListener {
	private TextView locationInfo;
	public static int x = 0;
	public static int y = 0;
	private int xxStart, xxEnd; // 拖动位置
	private int yyStart, yyEnd; // 拖动位置

	public LocationUi(Context context) {
		super(context);
		LayoutInflater.from(context).inflate(R.layout.location, this);
		locationInfo = (TextView) findViewById(R.id.location);
		locationInfo.setOnTouchListener(this);
	}

	/**
	 * 设置归属地信息
	 *
	 * @param text
	 */
	public void setText(String text) {
		locationInfo.setText(text);
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			xxStart = (int) event.getX();
			yyStart = (int) event.getY();
		} else if (event.getAction() == MotionEvent.ACTION_MOVE) {
			xxEnd = (int) event.getX();
			yyEnd = (int) event.getY();
//			System.out.println("------->xxEnd=" + xxEnd + " yyEnd=" + yyEnd);
			int offsetX = xxEnd - xxStart;
			int offsetY = yyEnd - yyStart;
			if (offsetX * offsetX + offsetY * offsetY > 1600) {
				x = x + offsetX;
				y = y + offsetY;
				xxStart = xxEnd;
				yyStart = yyEnd;
				MyService.refreshLocation();
			}
		} else if (event.getAction() == MotionEvent.ACTION_UP) {
		}
		return true;
	}

}


text:
namespace ALS.Glance.Models.Core.Interfaces
{
    public interface IHaveVersionAsLong : IHaveVersion<long>
    {
    }
}


text:
package at.ac.tuwien.infosys.jcloudscale.migration.annotations;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import at.ac.tuwien.infosys.jcloudscale.annotations.CloudObject;

/**
 * {@link CloudObject}'s methods annotated with PostMigration are executed after
 * a successful migration.
 *

 * If multiple methods are annotated they will be executed sequential in no
 * particular order, unless a priority value is specified.
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface PostMigration {

	/**
	 * Specifies the execution priority of the annotated method. Methods with a
	 * lower priority value are executed first.
	 */
	int priority() default Integer.MAX_VALUE;

}