Full artillery :-)
            - Find saturated stars
            - Run maxiter L.A.Cosmic iterations (stops if no more cosmics are found)
    
        Stops if no cosmics are found or if maxiter is reached.
491513
def run(self, maxiter = 4, verbose = False):
        
            
        if self.satlevel > 0 and self.satstars == None:
            self.findsatstars(verbose=True)
            
        print "Starting %i L.A.Cosmic iterations ..." % maxiter
        for i in range(1, maxiter+1):
            print "Iteration %i" % i
            
            iterres = self.lacosmiciteration(verbose=verbose)
            print "%i cosmic pixels (%i new)" % (iterres["niter"], iterres["nnew"])
            
            #self.clean(mask = iterres["mask"]) # No, we want clean to operate on really clean pixels only !
            # Thus we always apply it on the full mask, as lacosmic does :
            self.clean(verbose=verbose)
            # But note that for huge cosmics, one might want to revise this.
            # Thats why I added a feature to skip saturated stars !
            
            if iterres["niter"] == 0:
                break
128732
def deep_run(self):
        """"""
        # Lomb-Scargle period finding.
        self.get_period_LS(self.date, self.mag, self.n_threads, self.min_period)

        # Features based on a phase-folded light curve
        # such as Eta, slope-percentile, etc.
        # Should be called after the getPeriodLS() is called.

        # Created phased a folded light curve.
        # We use period * 2 to take eclipsing binaries into account.
        phase_folded_date = self.date % (self.period * 2.)
        sorted_index = np.argsort(phase_folded_date)

        folded_date = phase_folded_date[sorted_index]
        folded_mag = self.mag[sorted_index]

        # phase Eta
        self.phase_eta = self.get_eta(folded_mag, self.weighted_std)

        # Slope percentile.
        self.slope_per10, self.slope_per90 = \
            self.slope_percentile(folded_date, folded_mag)

        # phase Cusum
        self.phase_cusum = self.get_cusum(folded_mag)
1323976
def GetStars(campaign, module, model='nPLD', **kwargs):
    '''
    

    '''

    # Get the channel numbers
    channels = Channels(module)
    assert channels is not None, "No channels available on this module."

    # Get the EPIC numbers
    all = GetK2Campaign(campaign)
    stars = np.array([s[0] for s in all if s[2] in channels and
                      os.path.exists(
        os.path.join(EVEREST_DAT, 'k2', 'c%02d' % int(campaign),
                     ('%09d' % s[0])[:4] + '00000',
                     ('%09d' % s[0])[4:], model + '.npz'))], dtype=int)
    N = len(stars)
    assert N > 0, "No light curves found for campaign %d, module %d." % (
        campaign, module)

    # Loop over all stars and store the fluxes in a list
    fluxes = []
    errors = []
    kpars = []

    for n in range(N):

        # De-trended light curve file name
        nf = os.path.join(EVEREST_DAT, 'k2', 'c%02d' % int(campaign),
                          ('%09d' % stars[n])[:4] + '00000',
                          ('%09d' % stars[n])[4:], model + '.npz')

        # Get the data
        data = np.load(nf)
        t = data['time']
        if n == 0:
            time = t
            breakpoints = data['breakpoints']

        # Get de-trended light curve
        y = data['fraw'] - data['model']
        err = data['fraw_err']

        # De-weight outliers and bad timestamps
        m = np.array(list(set(np.concatenate([data['outmask'], data['badmask'],
                                              data['nanmask'],
                                              data['transitmask']]))),
                     dtype=int)

        # Interpolate over the outliers
        y = np.interp(t, np.delete(t, m), np.delete(y, m))
        err = np.interp(t, np.delete(t, m), np.delete(err, m))

        # Append to our running lists
        fluxes.append(y)
        errors.append(err)
        kpars.append(data['kernel_params'])

    return time, breakpoints, np.array(fluxes), \
           np.array(errors), np.array(kpars)
168750
protected void maximization() {
		// discard previous parameters by zeroing
		for (int i = 0; i < mixture.size; i++) {
			mixture.get(i).zero();
		}

		// compute the new mean
		for (int i = 0; i < info.size; i++) {
			PointInfo p = info.get(i);

			for (int j = 0; j < mixture.size; j++) {
				mixture.get(j).addMean(p.point,p.weights.get(j));
			}
		}
		for (int i = 0; i < mixture.size; i++) {
			GaussianGmm_F64 g = mixture.get(i);
			if( g.weight > 0 )
				CommonOps_DDRM.divide(g.mean,g.weight);
		}

		// compute new covariance
		for (int i = 0; i < info.size; i++) {
			PointInfo pp = info.get(i);
			double[] p = pp.point;

			for (int j = 0; j < mixture.size; j++) {
				GaussianGmm_F64 g = mixture.get(j);

				for (int k = 0; k < p.length; k++) {
					dx[k] = p[k]-g.mean.data[k];
				}

				mixture.get(j).addCovariance(dx, pp.weights.get(j));
			}
		}
		double totalMixtureWeight = 0;
		for (int i = 0; i < mixture.size; i++) {
			GaussianGmm_F64 g = mixture.get(i);
			if( g.weight > 0 ) {
				CommonOps_DDRM.divide(g.covariance, g.weight);
				totalMixtureWeight += g.weight;
			}
		}

		// update the weight
		for (int i = 0; i < mixture.size; i++) {
			mixture.get(i).weight /= totalMixtureWeight;
		}
	}
489056
def _fit_star(self, epsf, star, fitter, fitter_kwargs,
                  fitter_has_fit_info, fit_boxsize):
        

        if fit_boxsize is not None:
            try:
                xcenter, ycenter = star.cutout_center
                large_slc, small_slc = overlap_slices(star.shape,
                                                      fit_boxsize,
                                                      (ycenter, xcenter),
                                                      mode='strict')
            except (PartialOverlapError, NoOverlapError):
                warnings.warn('The star at ({0}, {1}) cannot be fit because '
                              'its fitting region extends beyond the star '
                              'cutout image.'.format(star.center[0],
                                                     star.center[1]),
                              AstropyUserWarning)

                star = copy.deepcopy(star)
                star._fit_error_status = 1

                return star

            data = star.data[large_slc]
            weights = star.weights[large_slc]

            # define the origin of the fitting region
            x0 = large_slc[1].start
            y0 = large_slc[0].start
        else:
            # use the entire cutout image
            data = star.data
            weights = star.weights

            # define the origin of the fitting region
            x0 = 0
            y0 = 0

        scaled_data = data / np.prod(epsf._oversampling)

        # define positions in the ePSF oversampled grid
        yy, xx = np.indices(data.shape, dtype=np.float)
        xx = (xx - (star.cutout_center[0] - x0)) * epsf._oversampling[0]
        yy = (yy - (star.cutout_center[1] - y0)) * epsf._oversampling[1]

        # define the initial guesses for fitted flux and shifts
        epsf.flux = star.flux
        epsf.x_0 = 0.0
        epsf.y_0 = 0.0

        # create copy to avoid overwriting original oversampling factor
        _epsf = epsf.copy()
        _epsf._oversampling = np.array([1., 1.])

        try:
            fitted_epsf = fitter(model=_epsf, x=xx, y=yy, z=scaled_data,
                                 weights=weights, **fitter_kwargs)
        except TypeError:
            # fitter doesn't support weights
            fitted_epsf = fitter(model=_epsf, x=xx, y=yy, z=scaled_data,
                                 **fitter_kwargs)

        fit_error_status = 0
        if fitter_has_fit_info:
            fit_info = copy.copy(fitter.fit_info)

            if 'ierr' in fit_info and fit_info['ierr'] not in [1, 2, 3, 4]:
                fit_error_status = 2    # fit solution was not found
        else:
            fit_info = None

        # compute the star's fitted position
        x_center = (star.cutout_center[0] +
                    (fitted_epsf.x_0.value / epsf._oversampling[0]))
        y_center = (star.cutout_center[1] +
                    (fitted_epsf.y_0.value / epsf._oversampling[1]))

        star = copy.deepcopy(star)
        star.cutout_center = (x_center, y_center)

        # set the star's flux to the ePSF-fitted flux
        star.flux = fitted_epsf.flux.value

        star._fit_info = fit_info
        star._fit_error_status = fit_error_status

        return star
980517
def __find_star_in_col(self, col):
        
        row = -1
        for i in range(self.n):
            if self.marked[i][col] == 1:
                row = i
                break

        return row
485170
def full_like(a, **kwargs):
    """"""
    _like_args(a, kwargs)
    if isinstance(a, Array):
        kwargs.setdefault('fill_value', a.fill_value)
    return full(**kwargs)
785962
def isEmpty(self):
        
        if self.isRectangular:
            return False
        eps = 1e-5
        ul = Point()
        ur = (self.ur - self.ul).abs_unit
        lr = (self.lr - self.ul).abs_unit
        ll = (self.ll - self.ul).abs_unit
        if max(ur.y, lr.y, ll.y) - min(ur.y, lr.y, ll.y) < eps:
            return True
        return False
1213162
public boolean saturate(IBond[] bonds, IAtomContainer atomContainer) throws CDKException {
        logger.debug("Saturating bond set of size: ", bonds.length);
        boolean bondsAreFullySaturated = false;
        if (bonds.length > 0) {
            IBond bond = bonds[0];

            // determine bonds left
            int leftBondCount = bonds.length - 1;
            IBond[] leftBonds = new IBond[leftBondCount];
            System.arraycopy(bonds, 1, leftBonds, 0, leftBondCount);

            // examine this bond
            logger.debug("Examining this bond: ", bond);
            if (isSaturated(bond, atomContainer)) {
                logger.debug("OK, bond is saturated, now try to saturate remaining bonds (if needed)");
                bondsAreFullySaturated = saturate(leftBonds, atomContainer);
            } else if (isUnsaturated(bond, atomContainer)) {
                logger.debug("Ok, this bond is unsaturated, and can be saturated");
                // two options now:
                // 1. saturate this one directly
                // 2. saturate this one by saturating the rest
                logger.debug("Option 1: Saturating this bond directly, then trying to saturate rest");
                // considering organic bonds, the max order is 3, so increase twice
                boolean bondOrderIncreased = saturateByIncreasingBondOrder(bond, atomContainer);
                bondsAreFullySaturated = bondOrderIncreased && saturate(bonds, atomContainer);
                if (bondsAreFullySaturated) {
                    logger.debug("Option 1: worked");
                } else {
                    logger.debug("Option 1: failed. Trying option 2.");
                    logger.debug("Option 2: Saturing this bond by saturating the rest");
                    // revert the increase (if succeeded), then saturate the rest
                    if (bondOrderIncreased) unsaturateByDecreasingBondOrder(bond);
                    bondsAreFullySaturated = saturate(leftBonds, atomContainer) && isSaturated(bond, atomContainer);
                    if (!bondsAreFullySaturated) logger.debug("Option 2: failed");
                }
            } else {
                logger.debug("Ok, this bond is unsaturated, but cannot be saturated");
                // try recursing and see if that fixes things
                bondsAreFullySaturated = saturate(leftBonds, atomContainer) && isSaturated(bond, atomContainer);
            }
        } else {
            bondsAreFullySaturated = true; // empty is saturated by default
        }
        return bondsAreFullySaturated;
    }
211653
function (numStars) {
    if (!this.stars){
      this.stars = document.createElement('a-entity');
      this.stars.id= 'stars';
      this.createStars();
      this.el.appendChild(this.stars);
    }
    numStars = Math.floor(Math.min(2000, Math.max(0, numStars)));
    this.stars.getObject3D('mesh').geometry.setDrawRange(0, numStars);
  }
601405
def getsatstars(self, verbose = None):
        
        if verbose == None:
            verbose = self.verbose
        if not self.satlevel > 0:
            raise RuntimeError, "Cannot determine satstars : you gave satlevel <= 0 !" 
        if self.satstars == None:
            self.findsatstars(verbose = verbose)
        return self.satstars
898004
public boolean isFull()
	{
		return !itemStack.isEmpty() && itemStack.getCount() == Math.min(itemStack.getMaxStackSize(), getSlotStackLimit());
	}
949296
@Override
    public void saturate(IAtomContainer atomContainer) throws CDKException {
        logger.info("Saturating atomContainer by adjusting bond orders...");
        boolean allSaturated = allSaturated(atomContainer);
        if (!allSaturated) {
            logger.info("Saturating bond orders is needed...");
            IBond[] bonds = new IBond[atomContainer.getBondCount()];
            for (int i = 0; i < bonds.length; i++)
                bonds[i] = atomContainer.getBond(i);
            boolean succeeded = saturate(bonds, atomContainer);
            if (!succeeded) {
                throw new CDKException("Could not saturate this atomContainer!");
            }
        }
    }
463650
def finder(self, figsize=(7,7), **kwargs):
        '''
        
        '''

        try:
            center = self.meta['center']
            radius = self.meta['radius']
        except KeyError:
            return self.allskyfinder(**kwargs)

        plt.figure(figsize=figsize)
        scatter = self.plot(**kwargs)
        plt.xlabel(r'Right Ascension ($^\circ$)'); plt.ylabel(r'Declination ($^\circ$)')
        #plt.title('{} in {:.1f}'.format(self.name, epoch))
        r = radius.to('deg').value
        plt.xlim(center.ra.deg + r/np.cos(center.dec), center.ra.deg - r/np.cos(center.dec))
        plt.ylim(center.dec.deg - r, center.dec.deg + r)
        ax = plt.gca()
        ax.set_aspect(1.0/np.cos(center.dec))

        return scatter
231908
def from_sky(cls, magnitudelimit=None):
        '''
        
        '''


        # define a query for cone search surrounding this center

        criteria = {}
        if magnitudelimit is not None:
            criteria[cls.defaultfilter + 'mag'] = '<{}'.format(magnitudelimit)

        v = Vizier(columns=cls.columns,
                   column_filters=criteria)
        v.ROW_LIMIT = -1

        # run the query
        print('querying Vizier for {}, for {}<{}'.format(cls.name, cls.defaultfilter, magnitudelimit))

        table = v.query_constraints(catalog=cls.catalog, **criteria)[0]

        # store the search parameters in this object
        c = cls(cls.standardize_table(table))
        c.standardized.meta['catalog'] = cls.catalog
        c.standardized.meta['criteria'] = criteria
        c.standardized.meta['magnitudelimit'] = magnitudelimit or c.magnitudelimit
        #c.magnitudelimit = magnitudelimit or c.magnitudelimit
        return c
406060
@Override
	public ESat isEntailed() {
		boolean done = true;
		for (int i = 0; i < n; i++) {
			if ((!degrees[i].contains(0)) && !g.getPotentialNodes().contains(i)) {
				return ESat.FALSE;
			}
			ISet env = target.getPotSet(g, i);
			ISet ker = target.getMandSet(g, i);
			if (degrees[i].getLB() > env.size()
					|| degrees[i].getUB() < ker.size()) {
				return ESat.FALSE;
			}
			if (env.size() != ker.size() || !degrees[i].isInstantiated()) {
				done = false;
			}
		}
		if (!done) {
			return ESat.UNDEFINED;
		}
		return ESat.TRUE;
	}
364183
def process_star(filename, output, *, extension, star_name, period, shift,
                 parameters, period_label, shift_label, **kwargs):
    
    if star_name is None:
        basename = path.basename(filename)
        if basename.endswith(extension):
            star_name = basename[:-len(extension)]
        else:
            # file has wrong extension
            return
    if parameters is not None:
        if period is None:
            try:
                period = parameters[period_label][star_name]
            except KeyError:
                pass
            if shift is None:
                try:
                    shift = parameters.loc[shift_label][star_name]
                except KeyError:
                    pass

    result = get_lightcurve_from_file(filename, name=star_name,
                                      period=period, shift=shift,
                                      **kwargs)
    if result is None:
        return
    if output is not None:
        plot_lightcurve(star_name, result['lightcurve'], result['period'],
                        result['phased_data'], output=output, **kwargs)

    return result