adapted from: https://gist.github.com/aemkei/1325937
432457
function(h, s, b){
	            h *= 6;
	            s = [
	                b += s *= b < .5 ? b : 1 - b,
	                b - h % 1 * s * 2,
	                b -= s *= 2,
	                b,
	                b + h % 1 * s,
	                b + s
	            ];

	            return [
	                s[ ~~h    % 6 ] * 255, // red
	                s[ (h|16) % 6 ] * 255, // green
	                s[ (h|8)  % 6 ] * 255  // blue
	            ];
	        }
232337
function shim () {
    if (!Function.prototype.bind) {
      Function.prototype.bind = function (oThis) {
        if (typeof this !== 'function') {
          // closest thing possible to the ECMAScript 5 internal IsCallable function
          throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
        }

        var aArgs = Array.prototype.slice.call(arguments, 1),
            fToBind = this,
            FNOP = function () {},
            fBound = function () {
              return fToBind.apply(this instanceof FNOP && oThis ?
                            this : oThis, aArgs.concat(Array.prototype.slice.call(arguments)));
            };

        FNOP.prototype = this.prototype;
        fBound.prototype = new FNOP();

        return fBound;
      };
    }

    if(!Array.isArray) {
      Array.isArray = function (vArg) {
        return Object.prototype.toString.call(vArg) === '[object Array]';
      };
    }

    if (!Array.prototype.indexOf) {
      Array.prototype.indexOf = function (searchElement, fromIndex) {
        var i,
            pivot = (fromIndex) ? fromIndex : 0,
            length;

        if (!this) {
          throw new TypeError();
        }

        length = this.length;

        if (length === 0 || pivot >= length) {
          return -1;
        }

        if (pivot < 0) {
          pivot = length - Math.abs(pivot);
        }

        for (i = pivot; i < length; i++) {
          if (this[i] === searchElement) {
            return i;
          }
        }
        return -1;
      };
    }

    if (!Array.prototype.map)
    {
      Array.prototype.map = function(fun /*, thisArg */)
      {
        'use strict';

        if (this === void 0 || this === null)
          throw new TypeError();

        var t = Object(this);
        var len = t.length >>> 0;
        if (typeof fun !== 'function') {
          throw new TypeError();
        }

        var res = new Array(len);
        var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
        for (var i = 0; i < len; i++)
        {
          // NOTE: Absolute correctness would demand Object.defineProperty
          //       be used.  But this method is fairly new, and failure is
          //       possible only if Object.prototype or Array.prototype
          //       has a property |i| (very unlikely), so use a less-correct
          //       but more portable alternative.
          if (i in t)
            res[i] = fun.call(thisArg, t[i], i, t);
        }

        return res;
      };
    }
  }
750377
function constrainedMDSLayout(areas, params) {
        params = params || {};
        var restarts = params.restarts || 10;

        // bidirectionally map sets to a rowid  (so we can create a matrix)
        var sets = [],
            setids = {},
            i;
        for (i = 0; i < areas.length; ++i) {
            var area = areas[i];
            if (area.sets.length == 1) {
                setids[area.sets[0]] = sets.length;
                sets.push(area);
            }
        }

        var matrices = getDistanceMatrices(areas, sets, setids),
            distances = matrices.distances,
            constraints = matrices.constraints;

        // keep distances bounded, things get messed up otherwise.
        // TODO: proper preconditioner?
        var norm = norm2(distances.map(norm2)) / distances.length;
        distances = distances.map(function (row) {
            return row.map(function (value) {
                return value / norm;
            });
        });

        var obj = function obj(x, fxprime) {
            return constrainedMDSGradient(x, fxprime, distances, constraints);
        };

        var best, current;
        for (i = 0; i < restarts; ++i) {
            var initial = zeros(distances.length * 2).map(Math.random);

            current = conjugateGradient(obj, initial, params);
            if (!best || current.fx < best.fx) {
                best = current;
            }
        }
        var positions = best.x;

        // translate rows back to (x,y,radius) coordinates
        var circles = {};
        for (i = 0; i < sets.length; ++i) {
            var set = sets[i];
            circles[set.sets[0]] = {
                x: positions[2 * i] * norm,
                y: positions[2 * i + 1] * norm,
                radius: Math.sqrt(set.size / Math.PI)
            };
        }

        if (params.history) {
            for (i = 0; i < params.history.length; ++i) {
                scale(params.history[i].x, norm);
            }
        }
        return circles;
    }
456989
def ckMAO(self,data,s=5,pm=False):
    
    c = data[-s:]

    if pm:
      ckvalue = max(c)
      preckvalue = max(c) > 0
    else:
      ckvalue = min(c)
      preckvalue = max(c) < 0

    return [s - c.index(ckvalue) < 4 and c.index(ckvalue) != s-1 and preckvalue, s - c.index(ckvalue) - 1, ckvalue]
179588
function(aKeyIndexes, newIndex) {
    if(lang.isArray(aKeyIndexes) && lang.isNumber(newIndex) && this._elColgroup && (this._elColgroup.childNodes.length > aKeyIndexes[aKeyIndexes.length-1])) {
        var i,
            tmpCols = [];
        // Remove COL
        for(i=aKeyIndexes.length-1; i>-1; i--) {
            tmpCols.push(this._elColgroup.removeChild(this._elColgroup.childNodes[aKeyIndexes[i]]));
        }
        // Insert COL
        var nextSibling = this._elColgroup.childNodes[newIndex] || null;
        for(i=tmpCols.length-1; i>-1; i--) {
            this._elColgroup.insertBefore(tmpCols[i], nextSibling);
        }
    }
}
336661
function arffToInputs(arffData, targetAttributes, patternAttributes, options = {}) {
  // set the target to the last attribute if no target attributes are given
  if (!Array.isArray(targetAttributes) || targetAttributes.length === 0) {
    targetAttributes = [arffData.attributes[arffData.attributes.length - 1]];
  }
  // get all the columns that represent the targets and place them in one place
  let targetColumns = targetAttributes.map((attribute) => {
    return arffData.data.map((dataRow) => {
      return dataRow[attribute];
    });
  });
  
  // set the patternAttributes to all
  if (!Array.isArray(patternAttributes) || patternAttributes.length === 0) {
    patternAttributes = arffData.attributes;
  }
  if (!options.skipTargetFilter) {
    // filter out the target attributes to get the input attributes
    patternAttributes = patternAttributes.filter((attribute) => {
      return targetAttributes.indexOf(attribute) === -1;
    });
  }
  
  // grab all the input attributes out of each data row to form the set of inputs/patterns
  let patterns = arffData.data.map((dataRow) => {
    return patternAttributes.map((attribute) => {
      return dataRow[attribute];
    });
  });
  
  return {
    targetColumns: targetColumns,
    patterns: patterns,
    patternAttributes: patternAttributes,
    targetAttributes: targetAttributes
  };
}
1020213
function buildValueColumns(
  item,
  loadedDimensions,
  columnCombinations,
  dataSets
) {
  var thisColumnOptions = clone(item._columnOptions);
  thisColumnOptions.tableStructure = item._tableStructure;
  var columns = [];
  var hasNoConcepts = item._concepts.length === 0;
  var regionDimension = getDimensionById(
    loadedDimensions,
    item.regionDimensionId
  );
  var regionDimensionIndex = getDimensionIndexById(
    loadedDimensions,
    item.regionDimensionId
  );
  var timePeriodDimension = getDimensionById(
    loadedDimensions,
    item.timePeriodDimensionId
  );
  var timePeriodDimensionIndex = getDimensionIndexById(
    loadedDimensions,
    item.timePeriodDimensionId
  );

  var regionCount = defined(regionDimension)
    ? regionDimension.values.length
    : 1;
  var timePeriodCount = defined(timePeriodDimension)
    ? timePeriodDimension.values.length
    : 1;

  for (
    var combinationIndex = 0;
    combinationIndex < columnCombinations.ids.length;
    combinationIndex++
  ) {
    var ids = columnCombinations.ids[combinationIndex];
    var dimensionIndices = mapDimensionValueIdsToKeyValues(
      item,
      loadedDimensions,
      ids
    );
    // The name is just the joined names of all the columns involved, or 'value' if no columns still have names.
    var combinationName =
      columnCombinations.names[combinationIndex]
        .filter(function(name) {
          return !!name;
        })
        .join(" ") || "Value";
    var combinationId = ids.join(" ") || "Value";
    var values = [];
    for (
      var timePeriodIndex = 0;
      timePeriodIndex < timePeriodCount;
      timePeriodIndex++
    ) {
      for (var regionIndex = 0; regionIndex < regionCount; regionIndex++) {
        if (defined(regionDimensionIndex)) {
          dimensionIndices[regionDimensionIndex] =
            regionDimension.values[regionIndex].id;
        }
        if (defined(timePeriodDimensionIndex)) {
          dimensionIndices[timePeriodDimensionIndex] =
            timePeriodDimension.values[timePeriodIndex].id;
        }
        values.push(
          getObsValue(item, loadedDimensions, dimensionIndices, dataSets)
        );
      }
    }
    thisColumnOptions.id = combinationId; // So we can refer to the dimension in a template by a sequence of ids or names.
    var column = new TableColumn(combinationName, values, thisColumnOptions);
    if (hasNoConcepts) {
      // If there are no concepts displayed to the user, there is only one value column, and we won't add a "total" column.
      // So make this column active.
      column.isActive = true;
    }
    columns.push(column);
  }
  return columns;
}
892835
function(oRoadMap, iNewPos, bSkipAnim, fEndCallBack){
		var jStepArea = oRoadMap.$("steparea");
		jStepArea.stop(false, true);

		if (iNewPos == "next") {
			iNewPos = jStepArea.scrollLeft() + oRoadMap.iStepWidth * getRTLFactor();
		} else if (iNewPos == "prev") {
			iNewPos = jStepArea.scrollLeft() - oRoadMap.iStepWidth * getRTLFactor();
		} else if (iNewPos == "keep") {
			iNewPos = jStepArea.scrollLeft();
		} else {
			iNewPos = iNewPos * getRTLFactor();
		}

		var fDoAfterScroll = function(){
			updateDelimiters(oRoadMap);

			if (fEndCallBack) {
				var jFirstVisibleRef = RoadMapRenderer.getFirstVisibleRef(oRoadMap);
				fEndCallBack(jFirstVisibleRef.attr("id"));
			}
		};

		if (!jQuery.fx.off && !bSkipAnim) {
			jStepArea.animate({scrollLeft: iNewPos}, "fast", fDoAfterScroll);
		} else {
			jStepArea.scrollLeft(iNewPos);
			fDoAfterScroll();
		}
	}
611321
function readNextSpendableMcIndex(conn, type, address, arrConflictingUnits, handleNextSpendableMcIndex){
	conn.query(
		"SELECT to_main_chain_index FROM inputs CROSS JOIN units USING(unit) \n\
		WHERE type=? AND address=? AND sequence='good' "+(
			(arrConflictingUnits && arrConflictingUnits.length > 0) 
			? " AND unit NOT IN("+arrConflictingUnits.map(function(unit){ return db.escape(unit); }).join(", ")+") " 
			: ""
		)+" \n\
		ORDER BY to_main_chain_index DESC LIMIT 1", 
		[type, address],
		function(rows){
			var mci = (rows.length > 0) ? (rows[0].to_main_chain_index+1) : 0;
		//	readNextUnspentMcIndex(conn, type, address, function(next_unspent_mci){
		//		if (next_unspent_mci !== mci)
		//			throw Error("next unspent mci !== next spendable mci: "+next_unspent_mci+" !== "+mci+", address "+address);
				handleNextSpendableMcIndex(mci);
		//	});
		}
	);
}
424756
def _m_to_e(cls, e, M):
        

        k1 = 3 * np.pi + 2
        k2 = np.pi - 1
        k3 = 6 * np.pi - 1
        A = 3 * k2 ** 2 / k1
        B = k3 ** 2 / (6 * k1)

        m1 = float(M)
        if abs(m1) < 1 / 6:
            E = m1 + e * (6 * m1) ** (1 / 3) - m1
        elif m1 < 0:
            w = np.pi + m1
            E = m1 + e * (A * w / (B - w) - np.pi - m1)
        else:
            w = np.pi - m1
            E = m1 + e * (np.pi - A * w / (B - w) - m1)

        e1 = 1 - e
        risk_disabler = (e1 + E ** 2 / 6) >= 0.1

        for i in range(2):
            fdd = e * sin(E)
            fddd = e * cos(E)

            if risk_disabler:
                f = (E - fdd) - m1
                fd = 1 - fddd
            else:
                f = cls._e_e_sin_e(e, E) - m1
                s = sin(E / 2)
                fd = e1 + 2 * e * s ** 2
            dee = f * fd / (0.5 * f * fdd - fd ** 2)

            w = fd + 0.5 * dee * (fdd + dee * fddd / 3)
            fd += dee * (fdd + 0.5 * dee * fddd)
            E -= (f - dee * (fd - w)) / fd

        E += M - m1

        return E
765570
private ValFrame rowwise(Env env, Frame fr, final AstPrimitive fun) {
    final String[] names = fr._names;

    final AstFunction scope = env._scope;  // Current execution scope; needed to lookup variables

    // do a single row of the frame to determine the size of the output.
    double[] ds = new double[fr.numCols()];
    for (int col = 0; col < fr.numCols(); ++col)
      ds[col] = fr.vec(col).at(0);
    int noutputs = fun.apply(env, env.stk(), new AstRoot[]{fun, new AstRow(ds, fr.names())}).getRow().length;

    Frame res = new MRTask() {
      @Override
      public void map(Chunk chks[], NewChunk[] nc) {
        double ds[] = new double[chks.length]; // Working row
        AstRoot[] asts = new AstRoot[]{fun, new AstRow(ds, names)}; // Arguments to be called; they are reused endlessly
        Session ses = new Session();                      // Session, again reused endlessly
        Env env = new Env(ses);
        env._scope = scope;                               // For proper namespace lookup
        for (int row = 0; row < chks[0]._len; row++) {
          for (int col = 0; col < chks.length; col++) // Fill the row
            ds[col] = chks[col].atd(row);
          try (Env.StackHelp stk_inner = env.stk()) {
            double[] valRow = fun.apply(env, stk_inner, asts).getRow(); // Make the call per-row
            for (int newCol = 0; newCol < nc.length; ++newCol)
              nc[newCol].addNum(valRow[newCol]);
          }
        }
        ses.end(null);        // Mostly for the sanity checks
      }
    }.doAll(noutputs, Vec.T_NUM, fr).outputFrame();
    return new ValFrame(res);
  }
1149227
function nelderMead(f, x0, parameters) {
        parameters = parameters || {};

        var maxIterations = parameters.maxIterations || x0.length * 200,
            nonZeroDelta = parameters.nonZeroDelta || 1.05,
            zeroDelta = parameters.zeroDelta || 0.001,
            minErrorDelta = parameters.minErrorDelta || 1e-6,
            minTolerance = parameters.minErrorDelta || 1e-5,
            rho = parameters.rho !== undefined ? parameters.rho : 1,
            chi = parameters.chi !== undefined ? parameters.chi : 2,
            psi = parameters.psi !== undefined ? parameters.psi : -0.5,
            sigma = parameters.sigma !== undefined ? parameters.sigma : 0.5,
            maxDiff;

        // initialize simplex.
        var N = x0.length,
            simplex = new Array(N + 1);
        simplex[0] = x0;
        simplex[0].fx = f(x0);
        simplex[0].id = 0;
        for (var i = 0; i < N; ++i) {
            var point = x0.slice();
            point[i] = point[i] ? point[i] * nonZeroDelta : zeroDelta;
            simplex[i + 1] = point;
            simplex[i + 1].fx = f(point);
            simplex[i + 1].id = i + 1;
        }

        function updateSimplex(value) {
            for (var i = 0; i < value.length; i++) {
                simplex[N][i] = value[i];
            }
            simplex[N].fx = value.fx;
        }

        var sortOrder = function sortOrder(a, b) {
            return a.fx - b.fx;
        };

        var centroid = x0.slice(),
            reflected = x0.slice(),
            contracted = x0.slice(),
            expanded = x0.slice();

        for (var iteration = 0; iteration < maxIterations; ++iteration) {
            simplex.sort(sortOrder);

            if (parameters.history) {
                // copy the simplex (since later iterations will mutate) and
                // sort it to have a consistent order between iterations
                var sortedSimplex = simplex.map(function (x) {
                    var state = x.slice();
                    state.fx = x.fx;
                    state.id = x.id;
                    return state;
                });
                sortedSimplex.sort(function (a, b) {
                    return a.id - b.id;
                });

                parameters.history.push({ x: simplex[0].slice(),
                    fx: simplex[0].fx,
                    simplex: sortedSimplex });
            }

            maxDiff = 0;
            for (i = 0; i < N; ++i) {
                maxDiff = Math.max(maxDiff, Math.abs(simplex[0][i] - simplex[1][i]));
            }

            if (Math.abs(simplex[0].fx - simplex[N].fx) < minErrorDelta && maxDiff < minTolerance) {
                break;
            }

            // compute the centroid of all but the worst point in the simplex
            for (i = 0; i < N; ++i) {
                centroid[i] = 0;
                for (var j = 0; j < N; ++j) {
                    centroid[i] += simplex[j][i];
                }
                centroid[i] /= N;
            }

            // reflect the worst point past the centroid  and compute loss at reflected
            // point
            var worst = simplex[N];
            weightedSum(reflected, 1 + rho, centroid, -rho, worst);
            reflected.fx = f(reflected);

            // if the reflected point is the best seen, then possibly expand
            if (reflected.fx < simplex[0].fx) {
                weightedSum(expanded, 1 + chi, centroid, -chi, worst);
                expanded.fx = f(expanded);
                if (expanded.fx < reflected.fx) {
                    updateSimplex(expanded);
                } else {
                    updateSimplex(reflected);
                }
            }

            // if the reflected point is worse than the second worst, we need to
            // contract
            else if (reflected.fx >= simplex[N - 1].fx) {
                    var shouldReduce = false;

                    if (reflected.fx > worst.fx) {
                        // do an inside contraction
                        weightedSum(contracted, 1 + psi, centroid, -psi, worst);
                        contracted.fx = f(contracted);
                        if (contracted.fx < worst.fx) {
                            updateSimplex(contracted);
                        } else {
                            shouldReduce = true;
                        }
                    } else {
                        // do an outside contraction
                        weightedSum(contracted, 1 - psi * rho, centroid, psi * rho, worst);
                        contracted.fx = f(contracted);
                        if (contracted.fx < reflected.fx) {
                            updateSimplex(contracted);
                        } else {
                            shouldReduce = true;
                        }
                    }

                    if (shouldReduce) {
                        // if we don't contract here, we're done
                        if (sigma >= 1) break;

                        // do a reduction
                        for (i = 1; i < simplex.length; ++i) {
                            weightedSum(simplex[i], 1 - sigma, simplex[0], sigma, simplex[i]);
                            simplex[i].fx = f(simplex[i]);
                        }
                    }
                } else {
                    updateSimplex(reflected);
                }
        }

        simplex.sort(sortOrder);
        return { fx: simplex[0].fx,
            x: simplex[0] };
    }
697645
function constrainedMDSGradient(x, fxprime, distances, constraints) {
        var loss = 0, i;
        for (i = 0; i < fxprime.length; ++i) {
            fxprime[i] = 0;
        }

        for (i = 0; i < distances.length; ++i) {
            var xi = x[2 * i], yi = x[2 * i + 1];
            for (var j = i + 1; j < distances.length; ++j) {
                var xj = x[2 * j], yj = x[2 * j + 1],
                    dij = distances[i][j],
                    constraint = constraints[i][j];

                var squaredDistance = (xj - xi) * (xj - xi) + (yj - yi) * (yj - yi),
                    distance$$1 = Math.sqrt(squaredDistance),
                    delta = squaredDistance - dij * dij;

                if (((constraint > 0) && (distance$$1 <= dij)) ||
                    ((constraint < 0) && (distance$$1 >= dij))) {
                    continue;
                }

                loss += 2 * delta * delta;

                fxprime[2*i]     += 4 * delta * (xi - xj);
                fxprime[2*i + 1] += 4 * delta * (yi - yj);

                fxprime[2*j]     += 4 * delta * (xj - xi);
                fxprime[2*j + 1] += 4 * delta * (yj - yi);
            }
        }
        return loss;
    }
1010078
function encodeMetaEvent(event) {
    var length, cursor, eventData, value, rates;

    rates = [24, 25, 30, 30];

    switch (event.type) {
    case MetaEvent.TYPE.SEQUENCE_NUMBER:
        eventData = new BufferCursor(new buffer.Buffer(2));
        eventData.writeUInt16LE(event.number);
        break;
    case MetaEvent.TYPE.TEXT:
    case MetaEvent.TYPE.COPYRIGHT_NOTICE:
    case MetaEvent.TYPE.SEQUENCE_NAME:
    case MetaEvent.TYPE.INSTRUMENT_NAME:
    case MetaEvent.TYPE.LYRICS:
    case MetaEvent.TYPE.MARKER:
    case MetaEvent.TYPE.CUE_POINT:
    case MetaEvent.TYPE.PROGRAM_NAME:
    case MetaEvent.TYPE.DEVICE_NAME:
        eventData = new BufferCursor(new buffer.Buffer(
            buffer.Buffer.byteLength(event.text, 'utf8')
        ));
        eventData.write(event.text, 'utf8');
        break;
    case MetaEvent.TYPE.MIDI_CHANNEL:
        eventData = new BufferCursor(new buffer.Buffer(1));
        eventData.writeUInt8(event.channel);
        break;
    case MetaEvent.TYPE.MIDI_PORT:
        eventData = new BufferCursor(new buffer.Buffer(1));
        eventData.writeUInt8(event.port);
        break;
    case MetaEvent.TYPE.END_OF_TRACK:
        eventData = new BufferCursor(new buffer.Buffer(0));
        break;
    case MetaEvent.TYPE.SET_TEMPO:
        eventData = new BufferCursor(new buffer.Buffer(3));
        value = 60000000 / event.tempo;

        eventData.writeUInt8(value >> 16);
        eventData.writeUInt8((value >> 8) & 0xFF);
        eventData.writeUInt8(value & 0xFF);
        break;
    case MetaEvent.TYPE.SMPTE_OFFSET:
        eventData = new BufferCursor(new buffer.Buffer(5));

        eventData.writeUInt8(
            (rates.indexOf(event.rate) << 6) + (event.hours & 0x3F)
        );
        eventData.writeUInt8(event.minutes);
        eventData.writeUInt8(event.seconds);
        eventData.writeUInt8(event.frames);
        eventData.writeUInt8(event.subframes);
        break;
    case MetaEvent.TYPE.TIME_SIGNATURE:
        eventData = new BufferCursor(new buffer.Buffer(4));

        eventData.writeUInt8(event.numerator);
        eventData.writeUInt8(Math.log(event.denominator) / Math.LN2);
        eventData.writeUInt8(event.metronome);
        eventData.writeUInt8(192 / event.clockSignalsPerBeat);
        break;
    case MetaEvent.TYPE.KEY_SIGNATURE:
        eventData = new BufferCursor(new buffer.Buffer(2));

        eventData.writeUInt8(event.note);
        eventData.writeUInt8(+!event.major);
        break;
    case MetaEvent.TYPE.SEQUENCER_SPECIFIC:
        eventData = new BufferCursor(new buffer.Buffer(event.data.length));
        eventData.copy(event.data);
        break;
    default:
        throw new error.MIDIEncoderError(
            event.type,
            'known MetaEvent type'
        );
    }

    length = encodeVarInt(eventData.length);
    cursor = new BufferCursor(new buffer.Buffer(
        2 + length.length + eventData.length
    ));

    cursor.writeUInt8(0xFF);
    cursor.writeUInt8(event.type);
    cursor.copy(length);
    cursor.copy(eventData.buffer);

    return cursor.buffer;
}
1103840
private static void induceSA(BaseArray T, int[] SA, BaseArray C, BaseArray B, int n, int k) {
        int b, i, j;
        int c0, c1;
    /* compute SAl */
        if (C == B) {
            getCounts(T, C, n, k);
        }
        getBuckets(C, B, k, false); /* find starts of buckets */
        j = n - 1;
        b = B.get(c1 = T.get(j));
        SA[b++] = ((0 < j) && (T.get(j - 1) < c1)) ? ~j : j;
        for (i = 0; i < n; ++i) {
            j = SA[i];
            SA[i] = ~j;
            if (0 < j) {
                if ((c0 = T.get(--j)) != c1) {
                    B.set(c1, b);
                    b = B.get(c1 = c0);
                }
                SA[b++] = ((0 < j) && (T.get(j - 1) < c1)) ? ~j : j;
            }
        }
    /* compute SAs */
        if (C == B) {
            getCounts(T, C, n, k);
        }
        getBuckets(C, B, k, true); /* find ends of buckets */
        for (i = n - 1, b = B.get(c1 = 0); 0 <= i; --i) {
            if (0 < (j = SA[i])) {
                if ((c0 = T.get(--j)) != c1) {
                    B.set(c1, b);
                    b = B.get(c1 = c0);
                }
                SA[--b] = ((j == 0) || (T.get(j - 1) > c1)) ? ~j : j;
            } else {
                SA[i] = ~j;
            }
        }
    }
589592
@Override
  public Val apply(Env env, Env.StackHelp stk, AstRoot asts[]) {
    // Argument parsing and sanity checking
    // Whole frame being imputed
    Frame fr = stk.track(asts[1].exec(env)).getFrame();

    // Column within frame being imputed
    final String method = asts[2].exec(env).getStr();
    if (!(Arrays.asList("forward","backward")).contains(method.toLowerCase()))
      throw new IllegalArgumentException("Method must be forward or backward");

    final int axis = (int) asts[3].exec(env).getNum();
    if (!(Arrays.asList(0,1)).contains(axis))
      throw new IllegalArgumentException("Axis must be 0 for columnar 1 for row");
    final int limit = (int) asts[4].exec(env).getNum();

    assert limit >= 0:"The maxlen/limit parameter should be >= 0.";
    if (limit == 0) // fast short cut to do nothing if user set zero limit
      return new ValFrame(fr.deepCopy(Key.make().toString()));

    Frame res;

    if (axis == 0) {
      res = (METHOD_BACKWARD.equalsIgnoreCase(method.trim()))?
              new FillBackwardTaskCol(limit, fr.anyVec().nChunks()).doAll(fr.numCols(), Vec.T_NUM, fr).outputFrame():
              new FillForwardTaskCol(limit).doAll(fr.numCols(), Vec.T_NUM, fr).outputFrame();
    } else {
      res = (METHOD_BACKWARD.equalsIgnoreCase(method.trim()))?
              new FillBackwardTaskRow(limit).doAll(fr.numCols(), Vec.T_NUM, fr).outputFrame():
              new FillForwardTaskRow(limit).doAll(fr.numCols(), Vec.T_NUM, fr).outputFrame();
    }
    res._key = Key.<Frame>make();
    return new ValFrame(res);
  }
992712
function (scope, iAttrs, newValue) {
    'use strict';
    var ngModelArr = iAttrs.ngModel.split('.');
    // console.log(JSON.stringify(ngModelArr, null, 2));


    switch (ngModelArr.length) {
    case 1:
        scope.$apply(function () {scope[ngModelArr[0]] = newValue;});
        break;
    case 2:
        scope.$apply(function () {scope[ngModelArr[0]][ngModelArr[1]] = newValue;});
        break;
    case 3:
        scope.$apply(function () {scope[ngModelArr[0]][ngModelArr[1]][ngModelArr[2]] = newValue;});
        break;
    case 4:
        scope.$apply(function () {scope[ngModelArr[0]][ngModelArr[1]][ngModelArr[2]][ngModelArr[3]] = newValue;});
        break;
    case 5:
        scope.$apply(function () {scope[ngModelArr[0]][ngModelArr[1]][ngModelArr[2]][ngModelArr[3]][ngModelArr[4]] = newValue;});
        break;
    default:
        scope.$apply(function () {scope[iAttrs.ngModel] = newValue;});
    }

}