Build the Knuth-Morris-Pratt table
343493
function buildTable(search) {
  // Based on https://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm#Description_of_pseudocode_for_the_table-building_algorithm
  var table = Array(search.length), pos = 2, cnd = 0, searchLen = search.length;
  table[0] = -1;
  table[1] = 0;
  while (pos < searchLen) {
    if (search[pos-1] === search[cnd]) {
      // the substring continues
      cnd++;
      table[pos] = cnd;
      pos++;
    } else if (cnd > 0) {
      // it doesn't, but we can fall back
      cnd = table[cnd];
    } else {
      // we have run part of candidates.  Note cnd = 0
      table[pos] = 0;
      pos++;
    }
  }
  return table;
}
290155
private static char[] buildTable() {
    char[] table = new char[26];
    for (int ix = 0; ix < table.length; ix++)
      table[ix] = '0';
    table['B' - 'A'] = '1';
    table['P' - 'A'] = '1';
    table['F' - 'A'] = '1';
    table['V' - 'A'] = '1';
    table['C' - 'A'] = '2';
    table['S' - 'A'] = '2';
    table['K' - 'A'] = '2';
    table['G' - 'A'] = '2';
    table['J' - 'A'] = '2';
    table['Q' - 'A'] = '2';
    table['X' - 'A'] = '2';
    table['Z' - 'A'] = '2';
    table['D' - 'A'] = '3';
    table['T' - 'A'] = '3';
    table['L' - 'A'] = '4';
    table['M' - 'A'] = '5';
    table['N' - 'A'] = '5';
    table['R' - 'A'] = '6';
    return table;
  }
219342
private void setU( DMatrixRMaj U, Vector3D_F64 a , Vector3D_F64 b ) {
		setColumn(U, 0, a);
		setColumn(U, 1, b);

		GeometryMath_F64.cross(a, b, tempV);
		setColumn(U, 2, tempV);
	}
1243878
function(array){
                array = array || [];
                var n = 0;
                for(i=0; i<this.vertices.length; i++){
                    var v = this.vertices[i];
                    array[n++] = v.normal.x;
                    array[n++] = v.normal.y;
                    array[n++] = v.normal.z;
                }

                return array;
            }
1235288
def _build_vertex_data(self):
        
        grid = self._grid
        w = 1.0 / grid[1]
        h = 1.0 / grid[0]

        quad = np.array([[0, 0, 0], [w, 0, 0], [w, h, 0],
                         [0, 0, 0], [w, h, 0], [0, h, 0]],
                        dtype=np.float32)
        quads = np.empty((grid[1], grid[0], 6, 3), dtype=np.float32)
        quads[:] = quad

        mgrid = np.mgrid[0.:grid[1], 0.:grid[0]].transpose(1, 2, 0)
        mgrid = mgrid[:, :, np.newaxis, :]
        mgrid[..., 0] *= w
        mgrid[..., 1] *= h

        quads[..., :2] += mgrid
        tex_coords = quads.reshape(grid[1]*grid[0]*6, 3)
        tex_coords = np.ascontiguousarray(tex_coords[:, :2])
        vertices = tex_coords * self.size

        self._subdiv_position.set_data(vertices.astype('float32'))
        self._subdiv_texcoord.set_data(tex_coords.astype('float32'))
811475
def _make_repr_table_from_sframe(X):
    

    assert isinstance(X, _SFrame)

    column_names = X.column_names()

    out_data = [ [None]*len(column_names) for i in range(X.num_rows())]

    column_sizes = [len(s) for s in column_names]

    for i, c in enumerate(column_names):
        for j, e in enumerate(X[c]):
            out_data[j][i] = str(e)
            column_sizes[i] = max(column_sizes[i], len(e))

    # now, go through and pad everything.
    out_data = ([ [cn.ljust(k, ' ') for cn, k in zip(column_names, column_sizes)],
                  ["-"*k for k in column_sizes] ]
                + [ [e.ljust(k, ' ') for e, k in zip(row, column_sizes)] for row in out_data] )

    return ['  '.join(row) for row in out_data]
1240381
def q12d(grid, spacing=None, E=1e5, nu=0.3, dirichlet_boundary=True,
         format=None):
    
    X, Y = tuple(grid)

    if X < 1 or Y < 1:
        raise ValueError('invalid grid shape')

    if dirichlet_boundary:
        X += 1
        Y += 1

    pts = np.mgrid[0:X+1, 0:Y+1]
    pts = np.hstack((pts[0].T.reshape(-1, 1) - X / 2.0,
                     pts[1].T.reshape(-1, 1) - Y / 2.0))

    if spacing is None:
        DX, DY = 1, 1
    else:
        DX, DY = tuple(spacing)
        pts *= [DX, DY]

    # compute local stiffness matrix
    lame = E * nu / ((1 + nu) * (1 - 2*nu))  # Lame's first parameter
    mu = E / (2 + 2*nu)                   # shear modulus

    vertices = np.array([[0, 0], [DX, 0], [DX, DY], [0, DY]])
    K = q12d_local(vertices, lame, mu)

    nodes = np.arange((X+1)*(Y+1)).reshape(X+1, Y+1)
    LL = nodes[:-1, :-1]
    Id = (2*LL).repeat(K.size).reshape(-1, 8, 8)
    J = Id.copy()
    Id += np.tile([0, 1, 2, 3, 2*X + 4, 2*X + 5, 2*X + 2, 2*X + 3], (8, 1))
    J += np.tile([0, 1, 2, 3, 2*X + 4, 2*X + 5, 2*X + 2, 2*X + 3], (8, 1)).T
    V = np.tile(K, (X*Y, 1))

    Id = np.ravel(Id)
    J = np.ravel(J)
    V = np.ravel(V)

    # sum duplicates
    A = coo_matrix((V, (Id, J)), shape=(pts.size, pts.size)).tocsr()
    A = A.tobsr(blocksize=(2, 2))

    del Id, J, V, LL, nodes

    B = np.zeros((2 * (X+1)*(Y+1), 3))
    B[0::2, 0] = 1
    B[1::2, 1] = 1
    B[0::2, 2] = -pts[:, 1]
    B[1::2, 2] = pts[:, 0]

    if dirichlet_boundary:
        mask = np.zeros((X+1, Y+1), dtype='bool')
        mask[1:-1, 1:-1] = True
        mask = np.ravel(mask)
        data = np.zeros(((X-1)*(Y-1), 2, 2))
        data[:, 0, 0] = 1
        data[:, 1, 1] = 1
        indices = np.arange((X-1)*(Y-1))
        indptr = np.concatenate((np.array([0]), np.cumsum(mask)))
        P = bsr_matrix((data, indices, indptr),
                       shape=(2*(X+1)*(Y+1), 2*(X-1)*(Y-1)))
        Pt = P.T
        A = P.T * A * P

        B = Pt * B

    return A.asformat(format), B
983148
function powColVector(x, power) {
                var result = x.clone();
                for (var i = 0; i < x.rows; ++i) {
                    result[i][0] = Math.pow(result[i][0], power);
                }
                return result;
            }
630779
def _make_table(values):
        """"""
        import collections
        table = collections.deque()
        start, end = values[0], values[0]
        for num, value in enumerate(values):
            if num == 0:
                table.append((value, value,))
                continue
            start, end = table.pop()
            if end == value - 1:
                table.append((start, value,))
            else:
                table.append((start, end,))
                table.append((value, value,))
        return tuple(table)
824530
function Box(sx, sy, sz) {
  sx = sx != null ? sx : 1;
  sy = sy != null ? sy : sx != null ? sx : 1;
  sz = sz != null ? sz : sx != null ? sx : 1;

  Geometry.call(this, { vertices: true, faces: true });

  var vertices = this.vertices;
  var faces = this.faces;

  var x = sx/2;
  var y = sy/2;
  var z = sz/2;

  //bottom
  vertices.push(new Vec3(-x, -y, -z));
  vertices.push(new Vec3(-x, -y,  z));
  vertices.push(new Vec3( x, -y,  z));
  vertices.push(new Vec3( x, -y, -z));

  //top
  vertices.push(new Vec3(-x,  y, -z));
  vertices.push(new Vec3(-x,  y,  z));
  vertices.push(new Vec3( x,  y,  z));
  vertices.push(new Vec3( x,  y, -z));

  //     4----7
  //    /:   /|
  //   5----6 |
  //   | 0..|.3
  //   |,   |/
  //   1----2

  faces.push([0, 3, 2, 1]); //bottom
  faces.push([4, 5, 6, 7]); //top
  faces.push([0, 1, 5, 4]); //left
  faces.push([2, 3, 7, 6]); //right
  faces.push([1, 2, 6, 5]); //front
  faces.push([3, 0, 4, 7]); //back

  this.computeNormals();
}
999879
private ValFrame slow_table(Vec v1, Vec v2, String[] colnames, boolean dense) {


    // For simplicity, repeat v1 if v2 is missing; this will end up filling in
    // only the diagonal of a 2-D array (in what is otherwise a 1-D array).
    // This should be nearly the same cost as a 1-D array, since everything is
    // sparsely filled in.

    // If this is the 1-column case (all counts on the diagonals), just build a
    // 1-d result.
    if (v2 == null) {


      // Slow-pass group counting, very sparse hashtables.  Note that Vec v2 is
      // used as the left-most arg, or OUTER dimension - which will be columns in
      // the final result.
      AstTable.SlowCnt sc = new AstTable.SlowCnt().doAll(v1, v1);

      // Get the column headers as sorted doubles
      double dcols[] = collectDomain(sc._col0s);

      Frame res = new Frame();
      Vec rowlabel = Vec.makeVec(dcols, Vec.VectorGroup.VG_LEN1.addVec());
      rowlabel.setDomain(v1.domain());
      res.add(colnames[0], rowlabel);
      long cnts[] = new long[dcols.length];
      for (int col = 0; col < dcols.length; col++) {
        long lkey = Double.doubleToRawLongBits(dcols[col]);
        NonBlockingHashMapLong<AtomicLong> colx = sc._col0s.get(lkey);
        AtomicLong al = colx.get(lkey);
        cnts[col] = al.get();
      }
      Vec vec = Vec.makeVec(cnts, null, Vec.VectorGroup.VG_LEN1.addVec());
      res.add("Counts", vec);
      return new ValFrame(res);
    }

    // 2-d table result.
    Frame res = new Frame();
    if (!dense) {

      // Slow-pass group counting, very sparse hashtables.  Note that Vec v2 is
      // used as the left-most arg, or OUTER dimension - which will be columns in
      // the final result.
      AstTable.SlowCnt sc = new AstTable.SlowCnt().doAll(v2, v1);

      // Get the column headers as sorted doubles
      double dcols[] = collectDomain(sc._col0s);

      // Need the row headers as sorted doubles also, but these are scattered
      // throughout the nested tables.  Fold 'em into 1 table.
      NonBlockingHashMapLong<AtomicLong> rows = new NonBlockingHashMapLong<>();
      for (NonBlockingHashMapLong.IteratorLong i = iter(sc._col0s); i.hasNext(); )
        rows.putAll(sc._col0s.get(i.nextLong()));
      double drows[] = collectDomain(rows);

      // Now walk the columns one by one, building a Vec per column, building a
      // Frame result.  Rowlabel for first column.

      Vec rowlabel = Vec.makeVec(drows, Vec.VectorGroup.VG_LEN1.addVec());
      rowlabel.setDomain(v1.domain());
      res.add(colnames[0], rowlabel);
      long cnts[] = new long[drows.length];
      for (int col = 0; col < dcols.length; col++) {
        NonBlockingHashMapLong<AtomicLong> colx = sc._col0s.get(Double.doubleToRawLongBits(dcols[col]));
        for (int row = 0; row < drows.length; row++) {
          AtomicLong al = colx.get(Double.doubleToRawLongBits(drows[row]));
          cnts[row] = al == null ? 0 : al.get();
        }
        Vec vec = Vec.makeVec(cnts, null, Vec.VectorGroup.VG_LEN1.addVec());
        res.add(v2.isCategorical() ? v2.domain()[col] : Double.toString(dcols[col]), vec);
      }
    } else {

      AstTable.SlowCnt sc = new AstTable.SlowCnt().doAll(v1, v2);

      double dcols[] = collectDomain(sc._col0s);

      NonBlockingHashMapLong<AtomicLong> rows = new NonBlockingHashMapLong<>();
      for (NonBlockingHashMapLong.IteratorLong i = iter(sc._col0s); i.hasNext(); )
        rows.putAll(sc._col0s.get(i.nextLong()));
      double drows[] = collectDomain(rows);

      int x = 0;
      int sz = 0;
      for (NonBlockingHashMapLong.IteratorLong i = iter(sc._col0s); i.hasNext(); ) {
        sz += sc._col0s.get(i.nextLong()).size();
      }
      long cnts[] = new long[sz];
      double[] left_categ = new double[sz];
      double[] right_categ = new double[sz];

      for (double dcol : dcols) {
        NonBlockingHashMapLong<AtomicLong> colx = sc._col0s.get(Double.doubleToRawLongBits(dcol));
        for (double drow : drows) {
          AtomicLong al = colx.get(Double.doubleToRawLongBits(drow));
          if (al != null) {
            left_categ[x] = dcol;
            right_categ[x] = drow;
            cnts[x] = al.get();
            x++;
          }
        }
      }

      Vec vec = Vec.makeVec(left_categ, Vec.VectorGroup.VG_LEN1.addVec());
      if (v1.isCategorical()) vec.setDomain(v1.domain());
      res.add(colnames[0], vec);
      vec = Vec.makeVec(right_categ, Vec.VectorGroup.VG_LEN1.addVec());
      if (v2.isCategorical()) vec.setDomain(v2.domain());
      res.add(colnames[1], vec);
      vec = Vec.makeVec(cnts, null, Vec.VectorGroup.VG_LEN1.addVec());
      res.add("Counts", vec);
    }
    return new ValFrame(res);
  }
119501
def surface(n_x=20,n_y=20):
		
	x=[float(np.random.randint(0,100))]
	for i in range(n_x):
		x.append(x[:1][0]+np.random.randn()*np.random.randint(1,10))
	df=pd.DataFrame(x)
	for i in range(n_y):
		df[i+1]=df[i].map(lambda x:x+np.random.randn()*np.random.randint(1,10))
	return df
1154267
protected static void constructM(List<Point2D_F64> obsPts,
									 DMatrixRMaj alphas, DMatrixRMaj M)
	{
		int N = obsPts.size();
		M.reshape(3*alphas.numCols,2*N,false);

		for( int i = 0; i < N; i++ ) {
			Point2D_F64 p2 = obsPts.get(i);

			int row = i*2;

			for( int j = 0; j < alphas.numCols; j++ ) {
				int col = j*3;

				double alpha = alphas.unsafe_get(i, j);
				M.unsafe_set(col, row, alpha);
				M.unsafe_set(col + 1, row, 0);
				M.unsafe_set(col + 2, row, -alpha * p2.x);
				M.unsafe_set(col    , row + 1, 0);
				M.unsafe_set(col + 1, row + 1, alpha);
				M.unsafe_set(col + 2, row + 1, -alpha * p2.y);
			}
		}
	}
976685
def cubic_bezier(document, coords):
	""
	element = document.createElement('path')
	points  = [(coords[i], coords[i+1]) for i  in range(0, len(coords), 2)]
	path    = ["M%s %s" %points[0]]
	for n in xrange(1, len(points), 3):
		A, B, C = points[n:n+3]
		path.append("C%s,%s %s,%s %s,%s" % (A[0], A[1], B[0], B[1], C[0], C[1]))
	element.setAttribute('d', ' '.join(path))
	return element
74100
function hessenbergQRStep (M) {
  const n = M.dimension;
  const me = M.elements;
  const csr = [0, 0, 0];
  const cs = [];
  for (let k = 0; k < n - 1; ++k) {
    const row1 = k;
    const row2 = k + 1;
    const colK = k * n;
    const a = me[row1 + colK];
    const b = me[row2 + colK];
    rotg(a, b, csr);
    const c = csr[0];
    const s = csr[1];
    const r = csr[2];
    cs[k] = [c, s];
    for (let x = k; x < n; ++x) {
      const colX = x * n;
      const tmp1 = me[row1 + colX];
      const tmp2 = me[row2 + colX];
      me[row1 + colX] = c * tmp1 + s * tmp2;
      me[row2 + colX] = -s * tmp1 + c * tmp2;
    }
    me[row1 + colK] = r;
    me[row2 + colK] = 0;
  }
  for (let k = 0; k < n - 1; ++k) {
    const col1 = k * n;
    const col2 = (k + 1) * n;
    const [c, s] = cs[k];
    for (let x = 0; x <= k + 1; ++x) {
      const rowX = x;
      const tmp1 = me[rowX + col1];
      const tmp2 = me[rowX + col2];
      me[rowX + col1] = tmp1 * c + tmp2 * s;
      me[rowX + col2] = -tmp1 * s + tmp2 * c;
    }
  }
  return M;
}
189533
function buildRowMapping(mapping, columns, yOffset) {
  for (let i = 0; i < columns.length; i++) {
    const {icon, xOffset} = columns[i];
    const id = getIconId(icon);
    mapping[id] = Object.assign({}, icon, {
      x: xOffset,
      y: yOffset
    });
  }
}
1187633
public void addTris (float[] xys, int xysOffset, int xysLen, float tw, float th,
                       int[] indices, int indicesOffset, int indicesLen, int indexBase) {
    int vertIdx = beginPrimitive(xysLen/2, indicesLen), offset = vertPos;
    float[] verts = vertices, stables = stableAttrs;
    for (int ii = xysOffset, ll = ii+xysLen; ii < ll; ii += 2) {
      float x = xys[ii], y = xys[ii+1];
      offset = add(verts, add(verts, offset, stables), x, y, x/tw, y/th);
    }
    vertPos = offset;

    addElems(vertIdx, indices, indicesOffset, indicesLen, indexBase);
  }