/*
Anomaly detection
779968
public boolean isAnomaly(Instance instance,
			double uniVariateAnomalyProbabilityThreshold,
			double multiVariateAnomalyProbabilityThreshold,
			int numberOfInstanceesForAnomaly) {
		//AMRUles is equipped with anomaly detection. If on, compute the anomaly value.
		long perceptronIntancesSeen=this.perceptron.getInstancesSeen();
		if ( perceptronIntancesSeen>= numberOfInstanceesForAnomaly) {
			double attribSum;
			double attribSquaredSum;
			double D = 0.0;
			double N = 0.0;
			double anomaly;

			for (int x = 0; x < instance.numAttributes() - 1; x++) {
				// Perceptron is initialized each rule.
				// this is a local anomaly.
				int instAttIndex = modelAttIndexToInstanceAttIndex(x, instance);
				attribSum = this.perceptron.perceptronattributeStatistics.getValue(x);
				attribSquaredSum = this.perceptron.squaredperceptronattributeStatistics.getValue(x);
				double mean = attribSum / perceptronIntancesSeen;
				double sd = computeSD(attribSquaredSum, attribSum, perceptronIntancesSeen);
				double probability = computeProbability(mean, sd, instance.value(instAttIndex));

				if (probability > 0.0) {
					D = D + Math.abs(Math.log(probability));
					if (probability < uniVariateAnomalyProbabilityThreshold) {//0.10
						N = N + Math.abs(Math.log(probability));
					}
				} 
			}

			anomaly = 0.0;
			if (D != 0.0) {
				anomaly = N / D;
			}
			if (anomaly >= multiVariateAnomalyProbabilityThreshold) {
				//debuganomaly(instance,
				//		uniVariateAnomalyProbabilityThreshold,
				//		multiVariateAnomalyProbabilityThreshold,
				//		anomaly);
				return true;
			}
		}
		return false;
	}
1181774
function isEscapeingAt(string, index) {
	if (index === 0) { return false; }
	let i = index - 1;
	while (
		i >= 0 && string[i] === '\\'
	) { --i; }
	return (index - i) % 2 === 0;
}
571905
def get_anomalies(smoothed_errors, y_true, z, window, all_anomalies, error_buffer):
    

    mu = np.mean(smoothed_errors)
    sigma = np.std(smoothed_errors)

    epsilon = mu + (z * sigma)

    # compare to epsilon
    errors_seq, anomaly_indices, max_error_below_e = group_consecutive_anomalies(
        smoothed_errors,
        epsilon,
        y_true,
        error_buffer,
        window,
        all_anomalies
    )

    if len(errors_seq) > 0:
        anomaly_indices = prune_anomalies(
            errors_seq,
            smoothed_errors,
            max_error_below_e,
            anomaly_indices
        )

    return anomaly_indices
680543
private Stack grahamScan(Coordinate[] c) {
        Coordinate p;
        Stack ps = new Stack();
        p = (Coordinate) ps.push(c[0]);
        p = (Coordinate) ps.push(c[1]);
        p = (Coordinate) ps.push(c[2]);
        for (int i = 3; i < c.length; i++) {
            p = (Coordinate) ps.pop();
            // check for empty stack to guard against robustness problems
            while (
                    ! ps.empty() &&
                            CGAlgorithms.computeOrientation((Coordinate) ps.peek(), p, c[i]) > 0) {
                p = (Coordinate) ps.pop();
            }
            p = (Coordinate) ps.push(p);
            p = (Coordinate) ps.push(c[i]);
        }
        p = (Coordinate) ps.push(c[0]);
        return ps;
    }
875400
function NeuQuant(pixels, samplefac) {
  var network; // int[netsize][4]
  var netindex; // for network lookup - really 256

  // bias and freq arrays for learning
  var bias;
  var freq;
  var radpower;

  /*
    Private Method: init

    sets up arrays
  */
  function init() {
    network = [];
    netindex = new Int32Array(256);
    bias = new Int32Array(netsize);
    freq = new Int32Array(netsize);
    radpower = new Int32Array(netsize >> 3);

    var i, v;
    for (i = 0; i < netsize; i++) {
      v = (i << (netbiasshift + 8)) / netsize;
      network[i] = new Float64Array([v, v, v, 0]);
      //network[i] = [v, v, v, 0]
      freq[i] = intbias / netsize;
      bias[i] = 0;
    }
  }

  /*
    Private Method: unbiasnet

    unbiases network to give byte values 0..255 and record position i to prepare for sort
  */
  function unbiasnet() {
    for (var i = 0; i < netsize; i++) {
      network[i][0] >>= netbiasshift;
      network[i][1] >>= netbiasshift;
      network[i][2] >>= netbiasshift;
      network[i][3] = i; // record color number
    }
  }

  /*
    Private Method: altersingle

    moves neuron *i* towards biased (b,g,r) by factor *alpha*
  */
  function altersingle(alpha, i, b, g, r) {
    network[i][0] -= (alpha * (network[i][0] - b)) / initalpha;
    network[i][1] -= (alpha * (network[i][1] - g)) / initalpha;
    network[i][2] -= (alpha * (network[i][2] - r)) / initalpha;
  }

  /*
    Private Method: alterneigh

    moves neurons in *radius* around index *i* towards biased (b,g,r) by factor *alpha*
  */
  function alterneigh(radius, i, b, g, r) {
    var lo = Math.abs(i - radius);
    var hi = Math.min(i + radius, netsize);

    var j = i + 1;
    var k = i - 1;
    var m = 1;

    var p, a;
    while ((j < hi) || (k > lo)) {
      a = radpower[m++];

      if (j < hi) {
        p = network[j++];
        p[0] -= (a * (p[0] - b)) / alpharadbias;
        p[1] -= (a * (p[1] - g)) / alpharadbias;
        p[2] -= (a * (p[2] - r)) / alpharadbias;
      }

      if (k > lo) {
        p = network[k--];
        p[0] -= (a * (p[0] - b)) / alpharadbias;
        p[1] -= (a * (p[1] - g)) / alpharadbias;
        p[2] -= (a * (p[2] - r)) / alpharadbias;
      }
    }
  }

  /*
    Private Method: contest

    searches for biased BGR values
  */
  function contest(b, g, r) {
    /*
      finds closest neuron (min dist) and updates freq
      finds best neuron (min dist-bias) and returns position
      for frequently chosen neurons, freq[i] is high and bias[i] is negative
      bias[i] = gamma * ((1 / netsize) - freq[i])
    */

    var bestd = ~(1 << 31);
    var bestbiasd = bestd;
    var bestpos = -1;
    var bestbiaspos = bestpos;

    var i, n, dist, biasdist, betafreq;
    for (i = 0; i < netsize; i++) {
      n = network[i];

      dist = Math.abs(n[0] - b) + Math.abs(n[1] - g) + Math.abs(n[2] - r);
      if (dist < bestd) {
        bestd = dist;
        bestpos = i;
      }

      biasdist = dist - ((bias[i]) >> (intbiasshift - netbiasshift));
      if (biasdist < bestbiasd) {
        bestbiasd = biasdist;
        bestbiaspos = i;
      }

      betafreq = (freq[i] >> betashift);
      freq[i] -= betafreq;
      bias[i] += (betafreq << gammashift);
    }

    freq[bestpos] += beta;
    bias[bestpos] -= betagamma;

    return bestbiaspos;
  }

  /*
    Private Method: inxbuild

    sorts network and builds netindex[0..255]
  */
  function inxbuild() {
    var i, j, p, q, smallpos, smallval, previouscol = 0, startpos = 0;
    for (i = 0; i < netsize; i++) {
      p = network[i];
      smallpos = i;
      smallval = p[1]; // index on g
      // find smallest in i..netsize-1
      for (j = i + 1; j < netsize; j++) {
        q = network[j];
        if (q[1] < smallval) { // index on g
          smallpos = j;
          smallval = q[1]; // index on g
        }
      }
      q = network[smallpos];
      // swap p (i) and q (smallpos) entries
      if (i != smallpos) {
        j = q[0];   q[0] = p[0];   p[0] = j;
        j = q[1];   q[1] = p[1];   p[1] = j;
        j = q[2];   q[2] = p[2];   p[2] = j;
        j = q[3];   q[3] = p[3];   p[3] = j;
      }
      // smallval entry is now in position i

      if (smallval != previouscol) {
        netindex[previouscol] = (startpos + i) >> 1;
        for (j = previouscol + 1; j < smallval; j++)
          netindex[j] = i;
        previouscol = smallval;
        startpos = i;
      }
    }
    netindex[previouscol] = (startpos + maxnetpos) >> 1;
    for (j = previouscol + 1; j < 256; j++)
      netindex[j] = maxnetpos; // really 256
  }

  /*
    Private Method: inxsearch

    searches for BGR values 0..255 and returns a color index
  */
  function inxsearch(b, g, r) {
    var a, p, dist;

    var bestd = 1000; // biggest possible dist is 256*3
    var best = -1;

    var i = netindex[g]; // index on g
    var j = i - 1; // start at netindex[g] and work outwards

    while ((i < netsize) || (j >= 0)) {
      if (i < netsize) {
        p = network[i];
        dist = p[1] - g; // inx key
        if (dist >= bestd) i = netsize; // stop iter
        else {
          i++;
          if (dist < 0) dist = -dist;
          a = p[0] - b; if (a < 0) a = -a;
          dist += a;
          if (dist < bestd) {
            a = p[2] - r; if (a < 0) a = -a;
            dist += a;
            if (dist < bestd) {
              bestd = dist;
              best = p[3];
            }
          }
        }
      }
      if (j >= 0) {
        p = network[j];
        dist = g - p[1]; // inx key - reverse dif
        if (dist >= bestd) j = -1; // stop iter
        else {
          j--;
          if (dist < 0) dist = -dist;
          a = p[0] - b; if (a < 0) a = -a;
          dist += a;
          if (dist < bestd) {
            a = p[2] - r; if (a < 0) a = -a;
            dist += a;
            if (dist < bestd) {
              bestd = dist;
              best = p[3];
            }
          }
        }
      }
    }

    return best;
  }

  /*
    Private Method: learn

    "Main Learning Loop"
  */
  function learn() {
    var i;

    var lengthcount = pixels.length;
    var alphadec = 30 + ((samplefac - 1) / 3);
    var samplepixels = lengthcount / (3 * samplefac);
    var delta = ~~(samplepixels / ncycles);
    var alpha = initalpha;
    var radius = initradius;

    var rad = radius >> radiusbiasshift;

    if (rad <= 1) rad = 0;
    for (i = 0; i < rad; i++)
      radpower[i] = alpha * (((rad * rad - i * i) * radbias) / (rad * rad));

    var step;
    if (lengthcount < minpicturebytes) {
      samplefac = 1;
      step = 3;
    } else if ((lengthcount % prime1) !== 0) {
      step = 3 * prime1;
    } else if ((lengthcount % prime2) !== 0) {
      step = 3 * prime2;
    } else if ((lengthcount % prime3) !== 0)  {
      step = 3 * prime3;
    } else {
      step = 3 * prime4;
    }

    var b, g, r, j;
    var pix = 0; // current pixel

    i = 0;
    while (i < samplepixels) {
      b = (pixels[pix] & 0xff) << netbiasshift;
      g = (pixels[pix + 1] & 0xff) << netbiasshift;
      r = (pixels[pix + 2] & 0xff) << netbiasshift;

      j = contest(b, g, r);

      altersingle(alpha, j, b, g, r);
      if (rad !== 0) alterneigh(rad, j, b, g, r); // alter neighbours

      pix += step;
      if (pix >= lengthcount) pix -= lengthcount;

      i++;

      if (delta === 0) delta = 1;
      if (i % delta === 0) {
        alpha -= alpha / alphadec;
        radius -= radius / radiusdec;
        rad = radius >> radiusbiasshift;

        if (rad <= 1) rad = 0;
        for (j = 0; j < rad; j++)
          radpower[j] = alpha * (((rad * rad - j * j) * radbias) / (rad * rad));
      }
    }
  }

  /*
    Method: buildColormap

    1. initializes network
    2. trains it
    3. removes misconceptions
    4. builds colorindex
  */
  function buildColormap() {
    init();
    learn();
    unbiasnet();
    inxbuild();
  }
  this.buildColormap = buildColormap;

  /*
    Method: getColormap

    builds colormap from the index

    returns array in the format:

    >
    > [r, g, b, r, g, b, r, g, b, ..]
    >
  */
  function getColormap() {
    var map = [];
    var index = [];

    for (var i = 0; i < netsize; i++)
      index[network[i][3]] = i;

    var k = 0;
    for (var l = 0; l < netsize; l++) {
      var j = index[l];
      map[k++] = (network[j][0]);
      map[k++] = (network[j][1]);
      map[k++] = (network[j][2]);
    }
    return map;
  }
  this.getColormap = getColormap;

  /*
    Method: lookupRGB

    looks for the closest *r*, *g*, *b* color in the map and
    returns its index
  */
  this.lookupRGB = inxsearch;
}
113831
function detectSubsampling( img ) {
                var iw = img.naturalWidth,
                    ih = img.naturalHeight,
                    canvas, ctx;

                // subsampling may happen overmegapixel image
                if ( iw * ih > 1024 * 1024 ) {
                    canvas = document.createElement('canvas');
                    canvas.width = canvas.height = 1;
                    ctx = canvas.getContext('2d');
                    ctx.drawImage( img, -iw + 1, 0 );

                    // subsampled image becomes half smaller in rendering size.
                    // check alpha channel value to confirm image is covering
                    // edge pixel or not. if alpha value is 0
                    // image is not covering, hence subsampled.
                    return ctx.getImageData( 0, 0, 1, 1 ).data[ 3 ] === 0;
                } else {
                    return false;
                }
            }
1312407
function Detector() {
      var _this;

      var ua = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
      var values = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
      var cssFlags = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
      var cssFlagsPrefix = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 'djs';

      _classCallCheck(this, Detector);

      _this = _possibleConstructorReturn(this, _getPrototypeOf(Detector).call(this, ua));
      _this._values = values;
      _this._cssFlags = !!cssFlags ? [] : null;
      _this._cssFlagsPrefix = cssFlagsPrefix + (!!cssFlagsPrefix ? '--' : ''); //! Features

      _this.checkFeature(); //! Software


      _this.checkEngine();

      _this.checkBrowser();

      _this.checkOS(); //! Hardware
      // this.checkDevice();


      _this.checkCPU();

      _this.checkGPU();

      _this.checkPlatform();

      _this.setCssFlags(); // remove unnecessary memory usage


      delete _this._booleanFlagsValuePropertyName;
      delete _this._values;
      delete _this._cssFlags;
      delete _this._cssFlagsPrefix;
      delete _this._root;
      delete _this._process;
      delete _this._navigator;
      delete _this._document;
      delete _this._ua;
      console.warn('DetectorJS initialized', _this.toFlags());
      return _this;
    }
462745
public boolean detect( T input ) {

		detections.reset();

		detector.process(input);

		FastQueue<FoundFiducial> found = detector.getFound();

		for (int i = 0; i < found.size(); i++) {
			FoundFiducial fid = found.get(i);

			int gridIndex = isExpected(fid.id);
			if( gridIndex >= 0 ) {
				Detection d = lookupDetection(fid.id,gridIndex);
				d.location.set(fid.distortedPixels);
				d.numDetected++;
			}
		}

		for (int i = detections.size-1; i >= 0; i--) {
			if( detections.get(i).numDetected != 1 ) {
				detections.remove(i);
			}
		}

		return detections.size > 0;
	}
1195924
function ensureExists(path, mask, cb) {
    if (typeof mask == 'function') {
        cb = mask;
        mask = 0777;
    }

    filesystem.mkdir(path, mask, function(err) {
        if (err) {
            if (err.code == 'EEXIST') cb(null);
            else cb(err);
        } else cb(null);
    });
}
1201057
@Override
  public OutlierResult run(Database db, Relation<V> relation) {
    ArrayDBIDs ids = DBIDUtil.ensureArray(relation.getDBIDs());
    DBIDArrayIter pB = ids.iter(), pC = ids.iter();
    SimilarityQuery<V> sq = db.getSimilarityQuery(relation, kernelFunction);
    KernelMatrix kernelMatrix = new KernelMatrix(sq, relation, ids);

    // Output storage.
    WritableDoubleDataStore abodvalues = DataStoreUtil.makeDoubleStorage(ids, DataStoreFactory.HINT_STATIC);
    DoubleMinMax minmaxabod = new DoubleMinMax();
    double max = 0.;

    // Storage for squared distances (will be reused!)
    WritableDoubleDataStore sqDists = DataStoreUtil.makeDoubleStorage(ids, DataStoreFactory.HINT_TEMP | DataStoreFactory.HINT_HOT);
    // Nearest neighbor heap (will be reused!)
    KNNHeap nn = DBIDUtil.newHeap(k);

    // Priority queue for candidates
    ModifiableDoubleDBIDList candidates = DBIDUtil.newDistanceDBIDList(relation.size());
    // get Candidate Ranking
    for(DBIDIter pA = relation.iterDBIDs(); pA.valid(); pA.advance()) {
      // Compute nearest neighbors and distances.
      nn.clear();
      double simAA = kernelMatrix.getSimilarity(pA, pA);
      // Sum of 1./(|AB|) and 1./(|AB|^2); for computing R2.
      double sumid = 0., sumisqd = 0.;
      for(pB.seek(0); pB.valid(); pB.advance()) {
        if(DBIDUtil.equal(pB, pA)) {
          continue;
        }
        double simBB = kernelMatrix.getSimilarity(pB, pB);
        double simAB = kernelMatrix.getSimilarity(pA, pB);
        double sqdAB = simAA + simBB - simAB - simAB;
        sqDists.putDouble(pB, sqdAB);
        final double isqdAB = 1. / sqdAB;
        sumid += FastMath.sqrt(isqdAB);
        sumisqd += isqdAB;
        // Update heap
        nn.insert(sqdAB, pB);
      }

      // Compute FastABOD approximation, adjust for lower bound.
      // LB-ABOF is defined via a numerically unstable formula.
      // Variance as E(X^2)-E(X)^2 suffers from catastrophic cancellation!
      // TODO: ensure numerical precision!
      double nnsum = 0., nnsumsq = 0., nnsumisqd = 0.;
      KNNList nl = nn.toKNNList();
      DoubleDBIDListIter iB = nl.iter(), iC = nl.iter();
      for(; iB.valid(); iB.advance()) {
        double sqdAB = iB.doubleValue();
        double simAB = kernelMatrix.getSimilarity(pA, iB);
        if(!(sqdAB > 0.)) {
          continue;
        }
        for(iC.seek(iB.getOffset() + 1); iC.valid(); iC.advance()) {
          double sqdAC = iC.doubleValue();
          double simAC = kernelMatrix.getSimilarity(pA, iC);
          if(!(sqdAC > 0.)) {
            continue;
          }
          // Exploit bilinearity of scalar product:
          // <B-A, C-A> = <B, C-A> - <A,C-A>
          // = <B,C> - <B,A> - <A,C> + <A,A>
          double simBC = kernelMatrix.getSimilarity(iB, iC);
          double numerator = simBC - simAB - simAC + simAA;
          double sqweight = 1. / (sqdAB * sqdAC);
          double weight = FastMath.sqrt(sqweight);
          double val = numerator * sqweight;
          nnsum += val * weight;
          nnsumsq += val * val * weight;
          nnsumisqd += sqweight;
        }
      }
      // Remaining weight, term R2:
      double r2 = sumisqd * sumisqd - 2. * nnsumisqd;
      double tmp = (2. * nnsum + r2) / (sumid * sumid);
      double lbabof = 2. * nnsumsq / (sumid * sumid) - tmp * tmp;

      // Track maximum?
      if(lbabof > max) {
        max = lbabof;
      }
      abodvalues.putDouble(pA, lbabof);
      candidates.add(lbabof, pA);
    }
    minmaxabod.put(max); // Put maximum from approximate values.
    candidates.sort();

    // refine Candidates
    int refinements = 0;
    DoubleMinHeap topscores = new DoubleMinHeap(l);
    MeanVariance s = new MeanVariance();
    for(DoubleDBIDListIter pA = candidates.iter(); pA.valid(); pA.advance()) {
      // Stop refining
      if(topscores.size() >= k && pA.doubleValue() > topscores.peek()) {
        break;
      }
      final double abof = computeABOF(kernelMatrix, pA, pB, pC, s);
      // Store refined score:
      abodvalues.putDouble(pA, abof);
      minmaxabod.put(abof);
      // Update the heap tracking the top scores.
      if(topscores.size() < k) {
        topscores.add(abof);
      }
      else {
        if(topscores.peek() > abof) {
          topscores.replaceTopElement(abof);
        }
      }
      refinements += 1;
    }
    if(LOG.isStatistics()) {
      LoggingConfiguration.setVerbose(Level.VERYVERBOSE);
      LOG.statistics(new LongStatistic("lb-abod.refinements", refinements));
    }
    // Build result representation.
    DoubleRelation scoreResult = new MaterializedDoubleRelation("Angle-based Outlier Detection", "abod-outlier", abodvalues, ids);
    OutlierScoreMeta scoreMeta = new InvertedOutlierScoreMeta(minmaxabod.getMin(), minmaxabod.getMax(), 0.0, Double.POSITIVE_INFINITY);
    return new OutlierResult(scoreMeta, scoreResult);
  }
132503
function(){
			spy.history = [];
			spy.args = [];
			spy.count = 0;
			spy.scope = null;
			spy.trace = null;

			return spy;
		}
646833
def _detect_anomalies(self):
        
        anom_scores = self.anom_scores
        max_anom_score = anom_scores.max()
        anomalies = []

        if max_anom_score:
            threshold = self.threshold or max_anom_score * self.score_percent_threshold
            # Find all the anomaly intervals.
            intervals = []
            start, end = None, None
            for timestamp, value in anom_scores.iteritems():
                if value > threshold:
                    end = timestamp
                    if not start:
                        start = timestamp
                elif start and end is not None:
                    intervals.append([start, end])
                    start = None
                    end = None
            if start is not None:
                intervals.append([start, end])

            # Locate the exact anomaly point within each anomaly interval.
            for interval_start, interval_end in intervals:
                interval_series = anom_scores.crop(interval_start, interval_end)

                self.refine_algorithm_params['time_series'] = interval_series
                refine_algorithm = self.refine_algorithm(**self.refine_algorithm_params)
                scores = refine_algorithm.run()
                max_refine_score = scores.max()

                # Get the timestamp of the maximal score.
                max_refine_timestamp = scores.timestamps[scores.values.index(max_refine_score)]
                anomaly = Anomaly(interval_start, interval_end, interval_series.max(), max_refine_timestamp)
                anomalies.append(anomaly)

        self.anomalies = anomalies
480158
function find_errors(lambda) {
		var errloc = [];

		for (var i = 1; i <= 31; i++) {
			var sum = 0;

			for (var j = 0; j < 5; j++) {
				sum ^= gmult(gexp[(j * i) % 31], lambda[j]);
			}

			if (sum === 0) {
				var pos = 31 - i;
				if (pos > 12 && pos < 27) return [];

				errloc[errloc.length] = pos;
			}
		}

		return errloc;
	}
900145
function alterneigh(rad, i, b, g, r) {

    var j;
    var k;
    var lo;
    var hi;
    var a;
    var m;
    var p;

    lo = i - rad;
    if (lo < -1) lo = -1;

    hi = i + rad;
    if (hi > netsize) hi = netsize;

    j = i + 1;
    k = i - 1;
    m = 1;

    while ((j < hi) || (k > lo)) {
      a = radpower[m++];

      if (j < hi) {
        p = network[j++];

        try {
          p[0] -= (a * (p[0] - b)) / alpharadbias;
          p[1] -= (a * (p[1] - g)) / alpharadbias;
          p[2] -= (a * (p[2] - r)) / alpharadbias;
        } catch (e) { } // prevents 1.3 miscompilation
      }

      if (k > lo) {
        p = network[k--];

        try {
          p[0] -= (a * (p[0] - b)) / alpharadbias;
          p[1] -= (a * (p[1] - g)) / alpharadbias;
          p[2] -= (a * (p[2] - r)) / alpharadbias;
        } catch (e) { }
      }
    }
  }
939758
private void verifyChunkedSums(
      byte[] data, int dataOff, int dataLen,
      byte[] checksums, int checksumsOff, String fileName,
      long basePos) throws ChecksumException {
    
    int remaining = dataLen;
    int dataPos = 0;
    while (remaining > 0) {
      int n = Math.min(remaining, bytesPerChecksum);
      
      summer.reset();
      summer.update(data, dataOff + dataPos, n);
      dataPos += n;
      remaining -= n;
      
      int calculated = (int)summer.getValue();
      int stored = (checksums[checksumsOff] << 24 & 0xff000000) |
        (checksums[checksumsOff + 1] << 16 & 0xff0000) |
        (checksums[checksumsOff + 2] << 8 & 0xff00) |
        checksums[checksumsOff + 3] & 0xff;
      checksumsOff += 4;
      if (calculated != stored) {
        long errPos = basePos + dataPos - n;
        throw new ChecksumException(
            "Checksum error: "+ fileName + " at "+ errPos +
            " exp: " + stored + " got: " + calculated, errPos);
      }
    }
  }
1211212
function detect() {
  // Two types of detection:
  //  1. Object detection
  //    e.g. detect("(java)");
  //    e.g. detect("!(document.addEventListener)");
  //  2. Platform detection (browser sniffing)
  //    e.g. detect("MSIE");
  //    e.g. detect("MSIE|opera");

  var jscript = NaN/*@cc_on||@_jscript_version@*/; // http://dean.edwards.name/weblog/2007/03/sniff/#comment85164
  var javaEnabled = global.java ? true : false;
  if (global.navigator) { // browser
    var MSIE = /MSIE[\d.]+/g;
    var element = document.createElement("span");
    // Close up the space between name and version number.
    //  e.g. MSIE 6 -> MSIE6
    var userAgent = navigator.userAgent.replace(/([a-z])[\s\/](\d)/gi, "$1$2");
    // Fix opera's (and others) user agent string.
    if (!jscript) userAgent = userAgent.replace(MSIE, "");
    if (MSIE.test(userAgent)) userAgent = userAgent.match(MSIE)[0] + " " + userAgent.replace(MSIE, "");
    base2.userAgent = navigator.platform + " " + userAgent.replace(/like \w+/gi, "");
    javaEnabled &= navigator.javaEnabled();
//} else if (java) { // rhino
//  var System = java.lang.System;
//  base2.userAgent = "Rhino " + System.getProperty("os.arch") + " " + System.getProperty("os.name") + " " + System.getProperty("os.version");
//} else if (jscript) { // Windows Scripting Host
//  base2.userAgent = "WSH";
  }

  var _cache = {};
  detect = function(expression) {
    if (_cache[expression] == null) {
      var returnValue = false, test = expression;
      var not = test.charAt(0) == "!";
      if (not) test = test.slice(1);
      if (test.charAt(0) == "(") {
        try {
          returnValue = new Function("element,jscript,java,global", "return !!" + test)(element, jscript, javaEnabled, global);
        } catch (ex) {
          // the test failed
        }
      } else {
        // Browser sniffing.
        returnValue = new RegExp("(" + test + ")", "i").test(base2.userAgent);
      }
      _cache[expression] = !!(not ^ returnValue);
    }
    return _cache[expression];
  };
  
  return detect(arguments[0]);
}
1187331
function(s) {
                //TODO: validate array length
		//TODO: return unwanted subset as new Px object

                var counts = this.valCounts(),
                multipliers = [];

                _.each(s, function(d, i) {
                    if (d[0] === '*') {
                        s[i] = _.range(0, counts[i] - 1);
                    }
                });

                for (var i = 0, l = counts.length; i < l - 1; i++) {
                    multipliers[i] = _.reduce(counts.slice(i+1), function(a, b) { return a * b; });
                }
                multipliers.push(1);

                for (var j = 0, k = s.length; j < k; j++) {
                    
                    // drop the values
                    this.metadata.VALUES[this.variables()[j]] = 
                        _.filter(this.metadata.VALUES[this.variables()[j]], function(e, m) {
                            return _.indexOf(s[j], m) !== -1;
                        });
                }

                var keepIdxs = [];
                var pattern = function pattern(c,m,w,p) {
                    if (c.length > 1) {
                        p = typeof p !== 'undefined' ? p : 1;
                        var count = c.pop(),
                            multiple = m.pop(),
                            want = w.pop();

                        var patt = _.flatten(_.map(_.range(0, count), function(d) { 
                            return _.include(want, d) ? p : _arrayOfZeroes(multiple);
                        }));

                        pattern(c, m, w, patt);
                    }
                    keepIdxs.push(_.flatten(p));
                };
                pattern(counts,multipliers,s);
                keepIdxs = keepIdxs[0];

                var indices = [];
                _.each(s[0], function(d) {
                    var start = d * multipliers[0];
                    var end = start + multipliers[0];
                    indices.push(_.filter(_.range(start, end), function(d, i) {return keepIdxs[i] === 1;}));
                });
                indices = _.flatten(indices);
                this.data = _.filter(this.data, function(d, i) {return _.indexOf(indices, i) !== -1;});
            }