Search is not available for this dataset
text
stringlengths
75
104k
def convert_items(self, items): """Generator like `convert_iterable`, but for 2-tuple iterators.""" return ((key, self.convert(value, self)) for key, value in items)
def convert_mapping(self, mapping): """Convenience method to track either a dict or a 2-tuple iterator.""" if isinstance(mapping, dict): return self.convert_items(iteritems(mapping)) return self.convert_items(mapping)
def changelist_view(self, request, extra_context=None): """ If we only have a single preference object redirect to it, otherwise display listing. """ model = self.model if model.objects.all().count() > 1: return super(PreferencesAdmin, self).changelist_view(re...
def md2rst(md_lines): 'Only converts headers' lvl2header_char = {1: '=', 2: '-', 3: '~'} for md_line in md_lines: if md_line.startswith('#'): header_indent, header_text = md_line.split(' ', 1) yield header_text header_char = lvl2header_char[len(header_indent)] ...
def aslist(generator): 'Function decorator to transform a generator into a list' def wrapper(*args, **kwargs): return list(generator(*args, **kwargs)) return wrapper
def get_package_release_from_pypi(pkg_name, version, pypi_json_api_url, allowed_classifiers): """ No classifier-based selection of Python packages is currently implemented: for now we don't fetch any .whl or .egg Eventually, we should select the best release available, based on the classifier & PEP 425: htt...
def extract_classifier_and_extension(pkg_name, filename): """ Returns a PEP425-compliant classifier (or 'py2.py3-none-any' if it cannot be extracted), and the file extension TODO: return a classifier 3-members namedtuple instead of a single string """ basename, _, extension = filename.rpartition...
def coerce(cls, key, value): """Convert plain dictionary to NestedMutable.""" if value is None: return value if isinstance(value, cls): return value if isinstance(value, dict): return NestedMutableDict.coerce(key, value) if isinstance(value, li...
def is_mod_function(mod, fun): """Checks if a function in a module was declared in that module. http://stackoverflow.com/a/1107150/3004221 Args: mod: the module fun: the function """ return inspect.isfunction(fun) and inspect.getmodule(fun) == mod
def is_mod_class(mod, cls): """Checks if a class in a module was declared in that module. Args: mod: the module cls: the class """ return inspect.isclass(cls) and inspect.getmodule(cls) == mod
def list_functions(mod_name): """Lists all functions declared in a module. http://stackoverflow.com/a/1107150/3004221 Args: mod_name: the module name Returns: A list of functions declared in that module. """ mod = sys.modules[mod_name] return [func.__name__ for func in mod....
def list_classes(mod_name): """Lists all classes declared in a module. Args: mod_name: the module name Returns: A list of functions declared in that module. """ mod = sys.modules[mod_name] return [cls.__name__ for cls in mod.__dict__.values() if is_mod_class(mod, cls...
def get_linenumbers(functions, module, searchstr='def {}(image):\n'): """Returns a dictionary which maps function names to line numbers. Args: functions: a list of function names module: the module to look the functions up searchstr: the string to search for Returns: A di...
def format_doc(fun): """Formats the documentation in a nicer way and for notebook cells.""" SEPARATOR = '=============================' func = cvloop.functions.__dict__[fun] doc_lines = ['{}'.format(l).strip() for l in func.__doc__.split('\n')] if hasattr(func, '__init__'): doc_lines.append...
def main(): """Main function creates the cvloop.functions example notebook.""" notebook = { 'cells': [ { 'cell_type': 'markdown', 'metadata': {}, 'source': [ '# cvloop functions\n\n', 'This notebook shows...
def prepare_axes(axes, title, size, cmap=None): """Prepares an axes object for clean plotting. Removes x and y axes labels and ticks, sets the aspect ratio to be equal, uses the size to determine the drawing area and fills the image with random colors as visual feedback. Creates an AxesImage to be...
def connect_event_handlers(self): """Connects event handlers to the figure.""" self.figure.canvas.mpl_connect('close_event', self.evt_release) self.figure.canvas.mpl_connect('pause_event', self.evt_toggle_pause)
def evt_toggle_pause(self, *args): # pylint: disable=unused-argument """Pauses and resumes the video source.""" if self.event_source._timer is None: # noqa: e501 pylint: disable=protected-access self.event_source.start() else: self.event_source.stop()
def print_info(self, capture): """Prints information about the unprocessed image. Reads one frame from the source to determine image colors, dimensions and data types. Args: capture: the source to read from. """ self.frame_offset += 1 ret, frame = ca...
def determine_size(self, capture): """Determines the height and width of the image source. If no dimensions are available, this method defaults to a resolution of 640x480, thus returns (480, 640). If capture has a get method it is assumed to understand `cv2.CAP_PROP_FRAME_WIDTH`...
def _init_draw(self): """Initializes the drawing of the frames by setting the images to random colors. This function is called by TimedAnimation. """ if self.original is not None: self.original.set_data(np.random.random((10, 10, 3))) self.processed.set_data(n...
def read_frame(self): """Reads a frame and converts the color if needed. In case no frame is available, i.e. self.capture.read() returns False as the first return value, the event_source of the TimedAnimation is stopped, and if possible the capture source released. Returns: ...
def annotate(self, framedata): """Annotates the processed axis with given annotations for the provided framedata. Args: framedata: The current frame number. """ for artist in self.annotation_artists: artist.remove() self.annotation_artists = [] ...
def _draw_frame(self, framedata): """Reads, processes and draws the frames. If needed for color maps, conversions to gray scale are performed. In case the images are no color images and no custom color maps are defined, the colormap `gray` is applied. This function is called by...
def update_info(self, custom=None): """Updates the figure's suptitle. Calls self.info_string() unless custom is provided. Args: custom: Overwrite it with this string, unless None. """ self.figure.suptitle(self.info_string() if custom is None else custom)
def info_string(self, size=None, message='', frame=-1): """Returns information about the stream. Generates a string containing size, frame number, and info messages. Omits unnecessary information (e.g. empty messages and frame -1). This method is primarily used to update the suptitle o...
def main(): """Sanitizes the loaded *.ipynb.""" with open(sys.argv[1], 'r') as nbfile: notebook = json.load(nbfile) # remove kernelspec (venvs) try: del notebook['metadata']['kernelspec'] except KeyError: pass # remove outputs and metadata, set execution counts to None ...
def create(self, comment, mentions=()): """ create comment :param comment: :param mentions: list of pair of code and type("USER", "GROUP", and so on) :return: """ data = { "app": self.app_id, "record": self.record_id, "comment"...
def _consume(iterator, n=None): """Advance the iterator n-steps ahead. If n is none, consume entirely.""" # Use functions that consume iterators at C speed. if n is None: # feed the entire iterator into a zero-length deque collections.deque(iterator, maxlen=0) else: # advance to ...
def _slice_required_len(slice_obj): """ Calculate how many items must be in the collection to satisfy this slice returns `None` for slices may vary based on the length of the underlying collection such as `lst[-1]` or `lst[::]` """ if slice_obj.step and slice_obj.step != 1: return None ...
def stylize(text, styles, reset=True): """conveniently styles your text as and resets ANSI codes at its end.""" terminator = attr("reset") if reset else "" return "{}{}{}".format("".join(styles), text, terminator)
def stylize_interactive(text, styles, reset=True): """stylize() variant that adds C0 control codes (SOH/STX) for readline safety.""" # problem: readline includes bare ANSI codes in width calculations. # solution: wrap nonprinting codes in SOH/STX when necessary. # see: https://github.com/dslackw/col...
def attribute(self): """Set or reset attributes""" paint = { "bold": self.ESC + "1" + self.END, 1: self.ESC + "1" + self.END, "dim": self.ESC + "2" + self.END, 2: self.ESC + "2" + self.END, "underlined": self.ESC + "4" + self.END, ...
def foreground(self): """Print 256 foreground colors""" code = self.ESC + "38;5;" if str(self.color).isdigit(): self.reverse_dict() color = self.reserve_paint[str(self.color)] return code + self.paint[color] + self.END elif self.color.startswith("#"): ...
def reverse_dict(self): """reverse dictionary""" self.reserve_paint = dict(zip(self.paint.values(), self.paint.keys()))
def reset(self, required=False): """ Perform a reset and check for presence pulse. :param bool required: require presence pulse """ reset = self._ow.reset() if required and reset: raise OneWireError("No presence pulse found. Check devices and wiring.") ...
def readinto(self, buf, *, start=0, end=None): """ Read into ``buf`` from the device. The number of bytes read will be the length of ``buf``. If ``start`` or ``end`` is provided, then the buffer will be sliced as if ``buf[start:end]``. This will not cause an allocation like ...
def write(self, buf, *, start=0, end=None): """ Write the bytes from ``buf`` to the device. If ``start`` or ``end`` is provided, then the buffer will be sliced as if ``buffer[start:end]``. This will not cause an allocation like ``buffer[start:end]`` will so it saves memory. ...
def scan(self): """Scan for devices on the bus and return a list of addresses.""" devices = [] diff = 65 rom = False count = 0 for _ in range(0xff): rom, diff = self._search_rom(rom, diff) if rom: count += 1 if count...
def crc8(data): """ Perform the 1-Wire CRC check on the provided data. :param bytearray data: 8 byte array representing 64 bit ROM code """ crc = 0 for byte in data: crc ^= byte for _ in range(8): if crc & 0x01: ...
def _deserialize(cls, json_body, get_value_and_type): """ deserialize json to model :param json_body: json data :param get_value_and_type: function(f: json_field) -> value, field_type_string(see FieldType) :return: """ instance = cls() is_set = False ...
def _serialize(self, convert_to_key_and_value, ignore_missing=False): """ serialize model object to dictionary :param convert_to_key_and_value: function(field_name, value, property_detail) -> key, value :return: """ serialized = {} properties = self._get_property...
def readinto(self, buf, *, start=0, end=None): """ Read into ``buf`` from the device. The number of bytes read will be the length of ``buf``. If ``start`` or ``end`` is provided, then the buffer will be sliced as if ``buf[start:end]``. This will not cause an allocation like ...
def write(self, buf, *, start=0, end=None): """ Write the bytes from ``buf`` to the device. If ``start`` or ``end`` is provided, then the buffer will be sliced as if ``buffer[start:end]``. This will not cause an allocation like ``buffer[start:end]`` will so it saves memory. ...
def preferences_class_prepared(sender, *args, **kwargs): """ Adds various preferences members to preferences.preferences, thus enabling easy access from code. """ cls = sender if issubclass(cls, Preferences): # Add singleton manager to subclasses. cls.add_to_class('singleton', Si...
def site_cleanup(sender, action, instance, **kwargs): """ Make sure there is only a single preferences object per site. So remove sites from pre-existing preferences objects. """ if action == 'post_add': if isinstance(instance, Preferences) \ and hasattr(instance.__class__, 'obje...
def get_queryset(self): """ Return the first preferences object for the current site. If preferences do not exist create it. """ queryset = super(SingletonManager, self).get_queryset() # Get current site current_site = None if getattr(settings, 'SITE_ID'...
def load_iterable(self, iterable, session=None): '''Load an ``iterable``. By default it returns a generator of data loaded via the :meth:`loads` method. :param iterable: an iterable over data to load. :param session: Optional :class:`stdnet.odm.Session`. :return: an ite...
def search_model(self, q, text, lookup=None): '''Implements :meth:`stdnet.odm.SearchEngine.search_model`. It return a new :class:`stdnet.odm.QueryElem` instance from the input :class:`Query` and the *text* to search.''' words = self.words_from_text(text, for_search=True) if not words: ...
def _search(self, words, include=None, exclude=None, lookup=None): '''Full text search. Return a list of queries to intersect.''' lookup = lookup or 'contains' query = self.router.worditem.query() if include: query = query.filter(model_type__in=include) if exclu...
def redis_client(address=None, connection_pool=None, timeout=None, parser=None, **kwargs): '''Get a new redis client. :param address: a ``host``, ``port`` tuple. :param connection_pool: optional connection pool. :param timeout: socket timeout. :param timeout: socket timeout. ''...
def to_bytes(s, encoding=None, errors='strict'): """Returns a bytestring version of 's', encoded as specified in 'encoding'.""" encoding = encoding or 'utf-8' if isinstance(s, bytes): if encoding != 'utf-8': return s.decode('utf-8', errors).encode(encoding, errors) else: ...
def to_string(s, encoding=None, errors='strict'): """Inverse of to_bytes""" encoding = encoding or 'utf-8' if isinstance(s, bytes): return s.decode(encoding, errors) if not is_string(s): s = string_type(s) return s
def date_decimal_hook(dct): '''The default JSON decoder hook. It is the inverse of :class:`stdnet.utils.jsontools.JSONDateDecimalEncoder`.''' if '__datetime__' in dct: return todatetime(dct['__datetime__']) elif '__date__' in dct: return todatetime(dct['__date__']).date() elif '__decimal...
def flat_to_nested(data, instance=None, attname=None, separator=None, loads=None): '''Convert a flat representation of a dictionary to a nested representation. Fields in the flat representation are separated by the *splitter* parameters. :parameter data: a flat dictionary of key value pairs. :pa...
def dict_flat_generator(value, attname=None, splitter=JSPLITTER, dumps=None, prefix=None, error=ValueError, recursive=True): '''Convert a nested dictionary into a flat dictionary representation''' if not isinstance(value, dict) or not recursive: if not pre...
def addmul_number_dicts(series): '''Multiply dictionaries by a numeric values and add them together. :parameter series: a tuple of two elements tuples. Each serie is of the form:: (weight,dictionary) where ``weight`` is a number and ``dictionary`` is a dictionary with numeric values. :parameter s...
def Download(campaign=0, queue='build', email=None, walltime=8, **kwargs): ''' Submits a cluster job to the build queue to download all TPFs for a given campaign. :param int campaign: The `K2` campaign to run :param str queue: The name of the queue to submit to. Default `build` :param str email...
def _Download(campaign, subcampaign): ''' Download all stars from a given campaign. This is called from ``missions/k2/download.pbs`` ''' # Are we doing a subcampaign? if subcampaign != -1: campaign = campaign + 0.1 * subcampaign # Get all star IDs for this campaign stars = [s[0...
def Run(campaign=0, EPIC=None, nodes=5, ppn=12, walltime=100, mpn=None, email=None, queue=None, **kwargs): ''' Submits a cluster job to compute and plot data for all targets in a given campaign. :param campaign: The K2 campaign number. If this is an :py:class:`int`, \ returns all tar...
def _Publish(campaign, subcampaign, strkwargs): ''' The actual function that publishes a given campaign; this must be called from ``missions/k2/publish.pbs``. ''' # Get kwargs from string kwargs = pickle.loads(strkwargs.replace('%%%', '\n').encode('utf-8')) # Check the cadence cadence...
def Status(season=range(18), model='nPLD', purge=False, injection=False, cadence='lc', **kwargs): ''' Shows the progress of the de-trending runs for the specified campaign(s). ''' # Mission compatibility campaign = season # Injection? if injection: return InjectionStatu...
def InjectionStatus(campaign=range(18), model='nPLD', purge=False, depths=[0.01, 0.001, 0.0001], **kwargs): ''' Shows the progress of the injection de-trending runs for the specified campaign(s). ''' if not hasattr(campaign, '__len__'): if type(campaign) is int: ...
def EverestModel(ID, model='nPLD', publish=False, csv=False, **kwargs): ''' A wrapper around an :py:obj:`everest` model for PBS runs. ''' if model != 'Inject': from ... import detrender # HACK: We need to explicitly mask short cadence planets if kwargs.get('cadence', 'lc') == ...
def PrimaryHDU(model): ''' Construct the primary HDU file containing basic header info. ''' # Get mission cards cards = model._mission.HDUCards(model.meta, hdu=0) if 'KEPMAG' not in [c[0] for c in cards]: cards.append(('KEPMAG', model.mag, 'Kepler magnitude')) # Add EVEREST info ...
def LightcurveHDU(model): ''' Construct the data HDU file containing the arrays and the observing info. ''' # Get mission cards cards = model._mission.HDUCards(model.meta, hdu=1) # Add EVEREST info cards.append(('COMMENT', '************************')) cards.append(('COMMENT', '* E...
def PixelsHDU(model): ''' Construct the HDU containing the pixel-level light curve. ''' # Get mission cards cards = model._mission.HDUCards(model.meta, hdu=2) # Add EVEREST info cards = [] cards.append(('COMMENT', '************************')) cards.append(('COMMENT', '* EVERES...
def ApertureHDU(model): ''' Construct the HDU containing the aperture used to de-trend. ''' # Get mission cards cards = model._mission.HDUCards(model.meta, hdu=3) # Add EVEREST info cards.append(('COMMENT', '************************')) cards.append(('COMMENT', '* EVEREST INFO ...
def ImagesHDU(model): ''' Construct the HDU containing sample postage stamp images of the target. ''' # Get mission cards cards = model._mission.HDUCards(model.meta, hdu=4) # Add EVEREST info cards.append(('COMMENT', '************************')) cards.append(('COMMENT', '* EVEREST...
def HiResHDU(model): ''' Construct the HDU containing the hi res image of the target. ''' # Get mission cards cards = model._mission.HDUCards(model.meta, hdu=5) # Add EVEREST info cards.append(('COMMENT', '************************')) cards.append(('COMMENT', '* EVEREST INFO *'...
def MakeFITS(model, fitsfile=None): ''' Generate a FITS file for a given :py:mod:`everest` run. :param model: An :py:mod:`everest` model instance ''' # Get the fits file name if fitsfile is None: outfile = os.path.join(model.dir, model._mission.FITSFile( model.ID, model.se...
def get_serializer(name, **options): '''Retrieve a serializer register as *name*. If the serializer is not available a ``ValueError`` exception will raise. A common usage pattern:: qs = MyModel.objects.query().sort_by('id') s = odm.get_serializer('json') s.dump(qs) ''' if name in _serializ...
def register_serializer(name, serializer): '''\ Register a new serializer to the library. :parameter name: serializer name (it can override existing serializers). :parameter serializer: an instance or a derived class of a :class:`stdnet.odm.Serializer` class or a callable. ''' if not isclass(serial...
def MaskSolve(A, b, w=5, progress=True, niter=None): ''' Finds the solution `x` to the linear problem A x = b for all contiguous `w`-sized masks applied to the rows and columns of `A` and to the entries of `b`. Returns an array `X` of shape `(N - w + 1, N - w)`, where t...
def MaskSolveSlow(A, b, w=5, progress=True, niter=None): ''' Identical to `MaskSolve`, but computes the solution the brute-force way. ''' # Number of data points N = b.shape[0] # How many iterations? Default is to go through # the entire dataset if niter is None: ...
def unmasked(self, depth=0.01): """Return the unmasked overfitting metric for a given transit depth.""" return 1 - (np.hstack(self._O2) + np.hstack(self._O3) / depth) / np.hstack(self._O1)
def show(self): """Show the overfitting PDF summary.""" try: if platform.system().lower().startswith('darwin'): subprocess.call(['open', self.pdf]) elif os.name == 'nt': os.startfile(self.pdf) elif os.name == 'posix': su...
def season(self): """ Return the current observing season. For *K2*, this is the observing campaign, while for *Kepler*, it is the current quarter. """ try: self._season except AttributeError: self._season = self._mission.Season(self.ID) ...
def fcor(self): ''' The CBV-corrected de-trended flux. ''' if self.XCBV is None: return None else: return self.flux - self._mission.FitCBVs(self)
def mask(self): ''' The array of indices to be masked. This is the union of the sets of outliers, bad (flagged) cadences, transit cadences, and :py:obj:`NaN` cadences. ''' return np.array(list(set(np.concatenate([self.outmask, self.badmask, self....
def X(self, i, j=slice(None, None, None)): ''' Computes the design matrix at the given *PLD* order and the given indices. The columns are the *PLD* vectors for the target at the corresponding order, computed as the product of the fractional pixel flux of all sets of :py:obj:`n` p...
def plot_info(self, dvs): ''' Plots miscellaneous de-trending information on the data validation summary figure. :param dvs: A :py:class:`dvs.DVS` figure instance ''' axl, axc, axr = dvs.title() axc.annotate("%s %d" % (self._mission.IDSTRING, self.ID), ...
def compute(self): ''' Compute the model for the current value of lambda. ''' # Is there a transit model? if self.transit_model is not None: return self.compute_joint() log.info('Computing the model...') # Loop over all chunks model = [None...
def compute_joint(self): ''' Compute the model in a single step, allowing for a light curve-wide transit model. This is a bit more expensive to compute. ''' # Init log.info('Computing the joint model...') A = [None for b in self.breakpoints] B = [None fo...
def apply_mask(self, x=None): ''' Returns the outlier mask, an array of indices corresponding to the non-outliers. :param numpy.ndarray x: If specified, returns the masked version of \ :py:obj:`x` instead. Default :py:obj:`None` ''' if x is None: ...
def get_chunk(self, b, x=None, pad=True): ''' Returns the indices corresponding to a given light curve chunk. :param int b: The index of the chunk to return :param numpy.ndarray x: If specified, applies the mask to array \ :py:obj:`x`. Default :py:obj:`None` ''' ...
def get_weights(self): ''' Computes the PLD weights vector :py:obj:`w`. ..warning :: Deprecated and not thoroughly tested. ''' log.info("Computing PLD weights...") # Loop over all chunks weights = [None for i in range(len(self.breakpoints))] for b, brk...
def get_cdpp_arr(self, flux=None): ''' Returns the CDPP value in *ppm* for each of the chunks in the light curve. ''' if flux is None: flux = self.flux return np.array([self._mission.CDPP(flux[self.get_masked_chunk(b)], cadence=self.c...
def get_cdpp(self, flux=None): ''' Returns the scalar CDPP for the light curve. ''' if flux is None: flux = self.flux return self._mission.CDPP(self.apply_mask(flux), cadence=self.cadence)
def plot_aperture(self, axes, labelsize=8): ''' Plots the aperture and the pixel images at the beginning, middle, and end of the time series. Also plots a high resolution image of the target, if available. ''' log.info('Plotting the aperture...') # Get colormap...
def overfit(self, tau=None, plot=True, clobber=False, w=9, **kwargs): r""" Compute the masked & unmasked overfitting metrics for the light curve. This routine injects a transit model given by `tau` at every cadence in the light curve and recovers the transit depth when (1) leaving ...
def lnlike(self, model, refactor=False, pos_tol=2.5, neg_tol=50., full_output=False): r""" Return the likelihood of the astrophysical model `model`. Returns the likelihood of `model` marginalized over the PLD model. :param ndarray model: A vector of the same shape as `se...
def Inject(ID, inj_model='nPLD', t0=None, per=None, dur=0.1, depth=0.001, mask=False, trn_win=5, poly_order=3, make_fits=False, **kwargs): ''' Run one of the :py:obj:`everest` models with injected transits and attempt to recover the transit depth at the end with a simple linear regression wit...
def object(self, session): '''Instance of :attr:`model_type` with id :attr:`object_id`.''' if not hasattr(self, '_object'): pkname = self.model_type._meta.pkname() query = session.query(self.model_type).filter(**{pkname: ...
def GetData(ID, season = None, cadence = 'lc', clobber = False, delete_raw = False, aperture_name = None, saturated_aperture_name = None, max_pixels = None, download_only = False, saturation_tolerance = None, bad_bits = None, **kwargs): ''' Returns a :py:obj:`DataContainer` ins...
def GetNeighbors(ID, model = None, neighbors = None, mag_range = None, cdpp_range = None, aperture_name = None, cadence = 'lc', **kwargs): ''' Return `neighbors` random bright stars on the same module as `EPIC`. :param int ID: The target ID number :param str model: The :py...
def get(ID, pipeline='everest2', campaign=None): ''' Returns the `time` and `flux` for a given EPIC `ID` and a given `pipeline` name. ''' log.info('Downloading %s light curve for %d...' % (pipeline, ID)) # Dev version hack if EVEREST_DEV: if pipeline.lower() == 'everest2' or pipel...
def plot(ID, pipeline='everest2', show=True, campaign=None): ''' Plots the de-trended flux for the given EPIC `ID` and for the specified `pipeline`. ''' # Get the data time, flux = get(ID, pipeline=pipeline, campaign=campaign) # Remove nans mask = np.where(np.isnan(flux))[0] time ...
def get_cdpp(campaign, pipeline='everest2'): ''' Computes the CDPP for a given `campaign` and a given `pipeline`. Stores the results in a file under "/missions/k2/tables/". ''' # Imports from .k2 import CDPP from .utils import GetK2Campaign # Check pipeline assert pipeline.lower()...
def get_outliers(campaign, pipeline='everest2', sigma=5): ''' Computes the number of outliers for a given `campaign` and a given `pipeline`. Stores the results in a file under "/missions/k2/tables/". :param int sigma: The sigma level at which to clip outliers. Default 5 ''' # Imports ...