Internal function to calculate and cache the posterior
969104
def _posterior(self, x):
        
        yedge = self._nuis_pdf.marginalization_bins()
        yc = 0.5 * (yedge[1:] + yedge[:-1])
        yw = yedge[1:] - yedge[:-1]

        like_array = self.like(x[:, np.newaxis], yc[np.newaxis, :]) * yw
        like_array /= like_array.sum()

        self._post = like_array.sum(1)
        self._post_interp = castro.Interpolator(x, self._post)
        return self._post
1155885
def posterior_predictive_to_xarray(self):
        """"""
        data = {k: np.expand_dims(v, 0) for k, v in self.posterior_predictive.items()}
        return dict_to_dataset(data, library=self.pymc3, coords=self.coords, dims=self.dims)
465059
protected void		calcLocal(Bone bone, int parentId)
    {
        if (parentId < 0)
        {
            bone.LocalMatrix.set(bone.WorldMatrix);
            return;
        }
	/*
	 * WorldMatrix = WorldMatrix(parent) * LocalMatrix
	 * LocalMatrix = INVERSE[ WorldMatrix(parent) ] * WorldMatrix
	 */
        getWorldMatrix(parentId, mTempMtxA);	// WorldMatrix(par)
        mTempMtxA.invert();					    // INVERSE[ WorldMatrix(parent) ]
        mTempMtxA.mul(bone.WorldMatrix, bone.LocalMatrix);  // LocalMatrix = INVERSE[ WorldMatrix(parent) ] * WorldMatrix
    }
39071
def cache_finite_samples(f):
	''''''
	cache = {}
	def wrap(*args):
		key = FRAME_RATE, args
		if key not in cache:
			cache[key] = [sample for sample in f(*args)]
		return (sample for sample in cache[key])
	return wrap
669522
def posterior_to_xarray(self):
        """"""
        posterior = self.posterior
        # filter posterior_predictive and log_likelihood
        posterior_predictive = self.posterior_predictive
        if posterior_predictive is None:
            posterior_predictive = []
        elif isinstance(posterior_predictive, str):
            posterior_predictive = [posterior_predictive]
        log_likelihood = self.log_likelihood
        if not isinstance(log_likelihood, str):
            log_likelihood = []
        else:
            log_likelihood = [log_likelihood]

        ignore = posterior_predictive + log_likelihood + ["lp__"]

        data = get_draws(posterior, ignore=ignore)

        return dict_to_dataset(data, library=self.pystan, coords=self.coords, dims=self.dims)
307513
def compute(self):
        """"""
        self._compute_window_size()
        smooth = []
        residual = []

        x, y = self.x, self.y

        # step through x and y data with a window window_size wide.
        self._update_values_in_window()
        self._update_mean_in_window()
        self._update_variance_in_window()
        for i, (xi, yi) in enumerate(zip(x, y)):
            if ((i - self._neighbors_on_each_side) > 0.0 and
                    (i + self._neighbors_on_each_side) < len(x)):
                self._advance_window()
            smooth_here = self._compute_smooth_during_construction(xi)
            residual_here = self._compute_cross_validated_residual_here(xi, yi, smooth_here)
            smooth.append(smooth_here)
            residual.append(residual_here)

        self._store_unsorted_results(smooth, residual)
1308294
def posterior(self, x, sigma=1.):
        """"""
        pr0 = 1. / self.scale**2  # prior precision
        prd = x.size / sigma**2  # data precision
        varp = 1. / (pr0 + prd)  # posterior variance
        mu = varp * (pr0 * self.loc + prd * x.mean())
        return Normal(loc=mu, scale=np.sqrt(varp))
176736
function(arr, seg, poly, pDist, coef) 
{
    var dta = vcross(seg.tn, seg.ta);
    var dtb = vcross(seg.tn, seg.tb);
    var n = vmult(seg.tn, coef);
    
    var verts = poly.tVerts;
    for(var i=0; i<verts.length; i+=2){
        var vx = verts[i];
        var vy = verts[i+1];
        if(vdot2(vx, vy, n.x, n.y) < vdot(seg.tn, seg.ta)*coef + seg.r){
            var dt = vcross2(seg.tn.x, seg.tn.y, vx, vy);
            if(dta >= dt && dt >= dtb){
                arr.push(new Contact(new Vect(vx, vy), n, pDist, hashPair(poly.hashid, i)));
            }
        }
    }
}
1156187
def memoize(fn):
    ''''''

    cache = {}

    @wraps(fn)
    def wrapped_function(*args):
        if args in cache:
            return cache[args]

        else:
            result = fn(*args)
            cache[args] = result
            return result

    return wrapped_function
1342079
function byLevel (a, b) {
    if (no(cachedLevelOf[a])) cachedLevelOf[a] = computeLevelOf(a)

    if (no(cachedLevelOf[b])) cachedLevelOf[b] = computeLevelOf(b)

    return cachedLevelOf[a] - cachedLevelOf[b]
  }
1043989
def _cdf(self, xloc, dist, length, cache):
        
        output = evaluation.evaluate_forward(
            dist, xloc.reshape(1, -1)).reshape(length, -1)
        assert xloc.shape == output.shape
        return output
505573
def cache_results(function):
    """"""
    def save_to_permacache():
        """Save the in-memory cache data to the permacache.

        There is a race condition here between two processes updating at the
        same time. It's perfectly acceptable to lose and/or corrupt the
        permacache information as each process's in-memory cache will remain
        in-tact.

        """
        update_from_permacache()
        try:
            with open(filename, 'wb') as fp:
                pickle.dump(cache, fp, pickle.HIGHEST_PROTOCOL)
        except IOError:
            pass  # Ignore permacache saving exceptions

    def update_from_permacache():
        """Attempt to update newer items from the permacache."""
        try:
            with open(filename, 'rb') as fp:
                permacache = pickle.load(fp)
        except Exception:  # TODO: Handle specific exceptions
            return  # It's okay if it cannot load
        for key, value in permacache.items():
            if key not in cache or value[0] > cache[key][0]:
                cache[key] = value

    cache = {}
    cache_expire_time = 3600
    try:
        filename = os.path.join(gettempdir(), 'update_checker_cache.pkl')
        update_from_permacache()
    except NotImplementedError:
        filename = None

    @wraps(function)
    def wrapped(obj, package_name, package_version, **extra_data):
        """Return cached results if available."""
        now = time.time()
        key = (package_name, package_version)
        if not obj.bypass_cache and key in cache:  # Check the in-memory cache
            cache_time, retval = cache[key]
            if now - cache_time < cache_expire_time:
                return retval
        retval = function(obj, package_name, package_version, **extra_data)
        cache[key] = now, retval
        if filename:
            save_to_permacache()
        return retval
    return wrapped
298128
def _mom(self, k, dist, cache):
        """"""
        return (-1)**numpy.sum(k)*evaluation.evaluate_moment(
            dist, k, cache=cache)
1054975
def compute(self):
        """"""
        self.smooth_result = run_freidman_supsmu(self.x, self.y)
        self._store_unsorted_results(self.smooth_result, numpy.zeros(len(self.smooth_result)))
958098
def _inference_tip_cached(func, instance, args, kwargs, _cache={}):
    """"""
    node = args[0]
    try:
        return iter(_cache[func, node])
    except KeyError:
        result = func(*args, **kwargs)
        # Need to keep an iterator around
        original, copy = itertools.tee(result)
        _cache[func, node] = list(copy)
        return original
752390
private double update(double[][] data, double T, int k, double[][] centroids, double[][] posteriori, double[] priori) {
        int n = data.length;
        int d = data[0].length;

        double D = 0.0;
        double H = 0.0;

        int iter = 0;
        double currentDistortion = Double.MAX_VALUE;
        double newDistortion = Double.MAX_VALUE / 2;
        while (iter < 100 && currentDistortion > newDistortion) {
            currentDistortion = newDistortion;

            D = Double.NaN;
            H = 0.0;

            if (tasks != null) {
                try {
                    D = 0.0;
                    for (UpdateThread t : tasks) {
                        t.k = k;
                        t.T = T;
                    }
                    
                    for (UpdateThread t : MulticoreExecutor.run(tasks)) {
                        D += t.D;
                        H += t.H;
                    }
                } catch (Exception ex) {
                    logger.error("Failed to run Deterministic Annealing on multi-core", ex);

                    D = Double.NaN;
                }
            }

            if (Double.isNaN(D)) {
                D = 0.0;
                double[] dist = new double[k];

                for (int i = 0; i < n; i++) {
                    double p = 0.0;

                    for (int j = 0; j < k; j++) {
                        dist[j] = Math.squaredDistance(data[i], centroids[j]);
                        posteriori[i][j] = priori[j] * Math.exp(-dist[j] / T);
                        p += posteriori[i][j];
                    }

                    double r = 0.0;
                    for (int j = 0; j < k; j++) {
                        posteriori[i][j] /= p;
                        D += posteriori[i][j] * dist[j];
                        r += -posteriori[i][j] * Math.log(posteriori[i][j]);
                    }
                    H += r;
                }
            }
            
            for (int i = 0; i < k; i++) {
                priori[i] = 0;
                for (int j = 0; j < n; j++) {
                    priori[i] += posteriori[j][i];
                }
                priori[i] /= n;
            }

            boolean parallel = false;
            if (ctasks != null) {
                try {
                    for (CentroidThread t : ctasks) {
                        t.k = k;
                    }
                    
                    MulticoreExecutor.run(ctasks);
                    parallel = true;
                } catch (Exception ex) {
                    logger.error("Failed to run Deterministic Annealing on multi-core", ex);

                    parallel = false;
                }
            }

            if (!parallel) {
                for (int i = 0; i < k; i++) {
                    Arrays.fill(centroids[i], 0.0);
                    for (int j = 0; j < d; j++) {
                        for (int m = 0; m < n; m++) {
                            centroids[i][j] += data[m][j] * posteriori[m][i];
                        }
                        centroids[i][j] /= (n * priori[i]);
                    }
                }
            }

            newDistortion = D - T * H;
            iter++;
        }

        logger.info(String.format("Deterministic Annealing clustering entropy after %3d iterations at temperature %.4f and k = %d: %.5f (soft distortion = %.5f )%n", iter, T, k / 2, H, D));

        return currentDistortion;
    }
489312
public static void calculateFromPrior(LPC lpc, long[] R, LPC priorLPC) {
    int coeffCount = lpc.order;

    //calculate first iteration directly
    double[] A = lpc.rawCoefficients;
    for(int i = 0; i < coeffCount+1; i++) A[i] = 0.0;
    A[0] = 1;
    double E = R[0];
    int startIter = 0;
    if(priorLPC != null && priorLPC.order < lpc.order) {
      startIter = priorLPC.order;
      E = priorLPC.rawError;
      System.arraycopy(priorLPC.rawCoefficients, 0, A, 0, startIter+1);
    }
    //calculate remaining iterations
    if(R[0] == 0) {
      for(int i = 0; i < coeffCount+1; i++)
        A[i] = 0.0;
    }
    else {
      double[] ATemp = lpc.tempCoefficients;
      for(int i = 0; i < coeffCount+1; i++) ATemp[i] = 0.0;

      for(int k = startIter; k < coeffCount; k++) {
        double lambda = 0.0;
        double temp = 0.0;
        for(int j = 0; j <= k; j++) {
          temp -= A[j]*R[k-j+1];
        }
        lambda = temp/E;

        for(int i = 0; i <= k+1; i++) {
          ATemp[i] = A[i]+lambda*A[k+1-i];
        }
        System.arraycopy(ATemp, 0, A, 0, coeffCount+1);
        E = (1-lambda*lambda)*E;
      }
    }
    lpc.rawError = E;
  }