text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 = [] for annotation in self.annotations: if annotation[2] > framedata: return if annotation[2] == framedata: pos = annotation[0:2] s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
original = self.read_frame() if original is None: self.update_info(self.info_string(message='Finished.', frame=framedata)) return if self.original is not None: processed = self.process_frame(original.copy()) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 st...
self.figure.suptitle(self.info_string() if custom is None else custom)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def info_string(self, size=None, message='', frame=-1): """Returns information about the stream. Generates a string containing size, frame number, and info messa...
info = [] if size is not None: info.append('Size: {1}x{0}'.format(*size)) elif self.size is not None: info.append('Size: {1}x{0}'.format(*self.size)) if frame >= 0: info.append('Frame: {}'.format(frame)) if message != '': info.appe...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ...
if slice_obj.step and slice_obj.step != 1: return None # (None, None, *) requires the entire list if slice_obj.start is None and slice_obj.stop is None: return None # Negative indexes are hard without knowing the collection length if slice_obj.start and slice_obj.start < 0: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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, 4: self.ESC + "4" + self.END, "blink": self.ES...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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("#"): return code + str(self.HEX) + self.END else...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.") return not reset
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 > self.maximum_devices: raise RuntimeError( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: crc = (crc >> 1) ^ 0x8C else: crc >>= 1 crc &= 0xFF return crc
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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', SingletonManager()) # Add property for preferences object to preferences.preferences. setattr(preferences.Preferences, cls._meta.object_name, property(lambda x: cls...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def site_cleanup(sender, action, instance, **kwargs): """ Make sure there is only a single preferences object per site. So remove sites from pre-existing prefere...
if action == 'post_add': if isinstance(instance, Preferences) \ and hasattr(instance.__class__, 'objects'): site_conflicts = instance.__class__.objects.filter( sites__in=instance.sites.all() ).only('id').distinct() for conflict in site_confli...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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', None) is not None: current_site = Site.objects.get_current() # If site found limit queryset to site. if current_site is not None:...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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. ''...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 *'...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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': subprocess.call(['xdg-open', self.pdf]) else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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) if hasattr(self._season, '__len__'): raise AttributeError( "Please choose a campaign/season for this target: %s." % self._sea...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def fcor(self): ''' The CBV-corrected de-trended flux. ''' if self.XCBV is None: return None else: return self.flux - self._mission.FitCBVs(self)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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), ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_outliers(self): ''' Performs iterative sigma clipping to get outliers. ''' log.info("Clipping outliers...") log.info('Iter %d/%d: %d outliers' % (0, self.oiter, len(self.outmask))) def M(x): return np.delete(x, np.concatenate( [self...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_ylim(self): ''' Computes the ideal y-axis limits for the light curve plot. Attempts to set the limits equal to those of the raw light curve, but if more than 1% of the flux lies either above or below these limits, auto-expands to include those points. At the end, adds 5% ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def plot_cbv(self, ax, flux, info, show_cbv=False): ''' Plots the final CBV-corrected light curve. ''' # Plot the light curve bnmask = np.array( list(set(np.concatenate([self.badmask, self.nanmask]))), dtype=int) def M(x): return np.delete(x, bnmask) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def load_tpf(self): ''' Loads the target pixel file. ''' if not self.loaded: if self._data is not None: data = self._data else: data = self._mission.GetData( self.ID, season=self.season, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def load_model(self, name=None): ''' Loads a saved version of the model. ''' if self.clobber: return False if name is None: name = self.name file = os.path.join(self.dir, '%s.npz' % name) if os.path.exists(file): if not self....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def save_model(self): ''' Saves all of the de-trending information to disk in an `npz` file and saves the DVS as a `pdf`. ''' # Save the data log.info("Saving data to '%s.npz'..." % self.name) d = dict(self.__dict__) d.pop('_weights', None) d.pop...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def exception_handler(self, pdb): ''' A custom exception handler. :param pdb: If :py:obj:`True`, enters PDB post-mortem \ mode for debugging. ''' # Grab the exception exctype, value, tb = sys.exc_info() # Log the error and create a .err file ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def init_kernel(self): ''' Initializes the covariance matrix with a guess at the GP kernel parameters. ''' if self.kernel_params is None: X = self.apply_mask(self.fpix / self.flux.reshape(-1, 1)) y = self.apply_mask(self.flux) - np.dot(X, np.linalg.solve...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def run(self): ''' Runs the de-trending step. ''' try: # Load raw data log.info("Loading target data...") self.load_tpf() self.mask_planets() self.plot_aperture([self.dvs.top_right() for i in range(4)]) self.init_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def publish(self, **kwargs): ''' Correct the light curve with the CBVs, generate a cover page for the DVS figure, and produce a FITS file for publication. ''' try: # HACK: Force these params for publication self.cbv_win = 999 self.cb...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def run(self): ''' Runs the de-trending. ''' try: # Plot original self.plot_aperture([self.dvs.top_right() for i in range(4)]) self.plot_lc(self.dvs.left(), info_right='nPLD', color='k') # Cross-validate self.cross_validate(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def validation_scatter(self, log_lam, b, masks, pre_v, gp, flux, time, med): ''' Computes the scatter in the validation set. ''' # Update the lambda matrix self.lam[b] = 10 ** log_lam # Validation set scatter scatter = [None for i in ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def iterdirty(self): '''Ordered iterator over dirty elements.''' return iter(chain(itervalues(self._new), itervalues(self._modified)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def commit(self, callback=None): '''Close the transaction and commit session to the backend.''' if self.executed: raise InvalidTransaction('Invalid operation. ' 'Transaction already executed.') session = self.session self.session = N...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def load_related(self, meta, fname, data, fields, encoding): '''Parse data for related objects.''' field = meta.dfields[fname] if field in meta.multifields: fmeta = field.structure_class()._meta if fmeta.name in ('hashtable', 'zset'): return ((native...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _execute_query(self): '''Execute the query without fetching data. Returns the number of elements in the query.''' pipe = self.pipe if not self.card: if self.meta.ordering: self.ismember = getattr(self.backend.client, 'zrank') self.card = get...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def order(self, last): '''Perform ordering with respect model fields.''' desc = last.desc field = last.name nested = last.nested nested_args = [] while nested: meta = nested.model._meta nested_args.extend((self.backend.basekey(meta), nested...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def related_lua_args(self): '''Generator of load_related arguments''' related = self.queryelem.select_related if related: meta = self.meta for rel in related: field = meta.dfields[rel] relmodel = field.relmodel bk = ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def pop_range(self, start, stop=None, withscores=True, **options): '''Remove and return a range from the ordered set by score.''' return self.backend.execute( self.client.zpopbyscore(self.id, start, stop, withscores=withscores, **options), ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def execute_session(self, session_data): '''Execute a session in redis.''' pipe = self.client.pipeline() for sm in session_data: # loop through model sessions meta = sm.meta if sm.structures: self.flush_structure(sm, pipe) delquery = No...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def flush(self, meta=None): '''Flush all model keys from the database''' pattern = self.basekey(meta) if meta else self.namespace return self.client.delpattern('%s*' % pattern)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def GetCovariance(kernel, kernel_params, time, errors): ''' Returns the covariance matrix for a given light curve segment. :param array_like kernel_params: A list of kernel parameters \ (white noise amplitude, red noise amplitude, and red noise timescale) :param array_like time: The time ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def NegLnLike(x, time, flux, errors, kernel): ''' Returns the negative log-likelihood function and its gradient. ''' gp = GP(kernel, x, white=True) gp.compute(time, errors) if OLDGEORGE: nll = -gp.lnlikelihood(flux) # NOTE: There was a bug on this next line! Used to be ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def missing_intervals(startdate, enddate, start, end, dateconverter=None, parseinterval=None, intervals=None): '''Given a ``startdate`` and an ``enddate`` dates, evaluate the date intervals from which data is not available. It return a list of ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def InitLog(file_name=None, log_level=logging.DEBUG, screen_level=logging.CRITICAL, pdb=False): ''' A little routine to initialize the logging functionality. :param str file_name: The name of the file to log to. \ Default :py:obj:`None` (set internally by :py:mod:`everest`) :para...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def ExceptionHook(exctype, value, tb): ''' A custom exception handler that logs errors to file. ''' for line in traceback.format_exception_only(exctype, value): log.error(line.replace('\n', '')) for line in traceback.format_tb(tb): log.error(line.replace('\n', '')) sys.__except...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def prange(*x): ''' Progress bar range with `tqdm` ''' try: root = logging.getLogger() if len(root.handlers): for h in root.handlers: if (type(h) is logging.StreamHandler) and \ (h.level != logging.CRITICAL): from ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def back(self, *fields): '''Return the back pair of the structure''' ts = self.irange(-1, -1, fields=fields) if ts: return ts.end(), ts[0]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Search(ID, mission='k2'): """Why is my target not in the EVEREST database?"""
# Only K2 supported for now assert mission == 'k2', "Only the K2 mission is supported for now." print("Searching for target %d..." % ID) # First check if it is in the database season = missions.k2.Season(ID) if season in [91, 92, [91, 92]]: print("Campaign 9 is currently not part of th...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _get_norm(self): ''' Computes the PLD flux normalization array. ..note :: `iPLD` model **only**. ''' log.info('Computing the PLD normalization...') # Loop over all chunks mod = [None for b in self.breakpoints] for b, brkpt in enumerate(self.breakpo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def plot_pipeline(self, pipeline, *args, **kwargs): ''' Plots the light curve for the target de-trended with a given pipeline. :param str pipeline: The name of the pipeline (lowercase). Options \ are 'everest2', 'everest1', and other mission-specific \ pipelines. F...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_pipeline(self, *args, **kwargs): ''' Returns the `time` and `flux` arrays for the target obtained by a given pipeline. Options :py:obj:`args` and :py:obj:`kwargs` are passed directly to the :py:func:`pipelines.get` function of the mission. ''' return ge...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _save_npz(self): ''' Saves all of the de-trending information to disk in an `npz` file ''' # Save the data d = dict(self.__dict__) d.pop('_weights', None) d.pop('_A', None) d.pop('_B', None) d.pop('_f', None) d.pop('_mK', None) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def Interpolate(time, mask, y): ''' Masks certain elements in the array `y` and linearly interpolates over them, returning an array `y'` of the same length. :param array_like time: The time array :param array_like mask: The indices to be interpolated over :param array_like y: The dependent ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def Smooth(x, window_len=100, window='hanning'): ''' Smooth data by convolving on a given timescale. :param ndarray x: The data array :param int window_len: The size of the smoothing window. Default `100` :param str window: The window type. Default `hanning` ''' if window_len == 0: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def SavGol(y, win=49): ''' Subtracts a second order Savitsky-Golay filter with window size `win` and returns the result. This acts as a high pass filter. ''' if len(y) >= win: return y - savgol_filter(y, win, 2) + np.nanmedian(y) else: return y
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def NumRegressors(npix, pld_order, cross_terms=True): ''' Return the number of regressors for `npix` pixels and PLD order `pld_order`. :param bool cross_terms: Include pixel cross-terms? Default :py:obj:`True` ''' res = 0 for k in range(1, pld_order + 1): if cross_terms: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def Downbin(x, newsize, axis=0, operation='mean'): ''' Downbins an array to a smaller size. :param array_like x: The array to down-bin :param int newsize: The new size of the axis along which to down-bin :param int axis: The axis to operate on. Default 0 :param str operation: The operation to p...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lookup(var_name, contexts=(), start=0): """lookup the value of the var_name on the stack of contexts :var_name: TODO :contexts: TODO :returns: None if not fo...
start = len(contexts) if start >=0 else start for context in reversed(contexts[:start]): try: if var_name in context: return context[var_name] except TypeError as te: # we may put variable on the context, skip it continue return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delimiters_to_re(delimiters): """convert delimiters to corresponding regular expressions"""
# caching delimiters = tuple(delimiters) if delimiters in re_delimiters: re_tag = re_delimiters[delimiters] else: open_tag, close_tag = delimiters # escape open_tag = ''.join([c if c.isalnum() else '\\' + c for c in open_tag]) close_tag = ''.join([c if c.isalnu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _escape(self, text): """Escape text according to self.escape"""
ret = EMPTYSTRING if text is None else str(text) if self.escape: return html_escape(ret) else: return ret
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _lookup(self, dot_name, contexts): """lookup value for names like 'a.b.c' and handle filters as well"""
# process filters filters = [x for x in map(lambda x: x.strip(), dot_name.split('|'))] dot_name = filters[0] filters = filters[1:] # should support paths like '../../a.b.c/../d', etc. if not dot_name.startswith('.'): dot_name = './' + dot_name path...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _render_children(self, contexts, partials): """Render the children tokens"""
ret = [] for child in self.children: ret.append(child._render(contexts, partials)) return EMPTYSTRING.join(ret)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _render(self, contexts, partials): """render inverted section"""
val = self._lookup(self.value, contexts) if val: return EMPTYSTRING return self._render_children(contexts, partials)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def Setup(): ''' Called when the code is installed. Sets up directories and downloads the K2 catalog. ''' if not os.path.exists(os.path.join(EVEREST_DAT, 'k2', 'cbv')): os.makedirs(os.path.join(EVEREST_DAT, 'k2', 'cbv')) GetK2Stars(clobber=False)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def CDPP(flux, mask=[], cadence='lc'): ''' Compute the proxy 6-hr CDPP metric. :param array_like flux: The flux array to compute the CDPP for :param array_like mask: The indices to be masked :param str cadence: The light curve cadence. Default `lc` ''' # 13 cadences is 6.5 hours rmswi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def HasShortCadence(EPIC, season=None): ''' Returns `True` if short cadence data is available for this target. :param int EPIC: The EPIC ID number :param int season: The campaign number. Default :py:obj:`None` ''' if season is None: season = Campaign(EPIC) if season is None: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def DVSFile(ID, season, cadence='lc'): ''' Returns the name of the DVS PDF for a given target. :param ID: The target ID :param int season: The target season number :param str cadence: The cadence type. Default `lc` ''' if cadence == 'sc': strcadence = '_sc' else: strca...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def GetTargetCBVs(model): ''' Returns the design matrix of CBVs for the given target. :param model: An instance of the :py:obj:`everest` model for the target ''' # Get the info season = model.season name = model.name # We use the LC light curves as CBVs; there aren't # enough SC ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def StatsToCSV(campaign, model='nPLD'): ''' Generate the CSV file used in the search database for the documentation. ''' statsfile = os.path.join(EVEREST_SRC, 'missions', 'k2', 'tables', 'c%02d_%s.cdpp' % (campaign, model)) csvfile = os.path.join(os.path.dirname(EVEREST_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_pending_lookups(event, sender, **kwargs): """Handle any pending relations to the sending model. Sent from class_prepared."""
key = (sender._meta.app_label, sender._meta.name) for callback in pending_lookups.pop(key, []): callback(sender)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def Many2ManyThroughModel(field): '''Create a Many2Many through model with two foreign key fields and a CompositeFieldId depending on the two foreign keys.''' from stdnet.odm import ModelType, StdModel, ForeignKey, CompositeIdField name_model = field.model._meta.name name_relmodel = field.relmodel....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def makeMany2ManyRelatedManager(formodel, name_relmodel, name_formodel): '''formodel is the model which the manager .''' class _Many2ManyRelatedManager(Many2ManyRelatedManager): pass _Many2ManyRelatedManager.formodel = formodel _Many2ManyRelatedManager.name_relmodel = name_relmodel ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def metaphone_processor(words): '''Double metaphone word processor.''' for word in words: for w in double_metaphone(word): if w: w = w.strip() if w: yield w
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def tolerant_metaphone_processor(words): '''Double metaphone word processor slightly modified so that when no words are returned by the algorithm, the original word is returned.''' for word in words: r = 0 for w in double_metaphone(word): if w: w = w.strip() ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def stemming_processor(words): '''Porter Stemmer word processor''' stem = PorterStemmer().stem for word in words: word = stem(word, 0, len(word)-1) yield word
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def Pool(pool='AnyPool', **kwargs): ''' Chooses between the different pools. If ``pool == 'AnyPool'``, chooses based on availability. ''' if pool == 'MPIPool': return MPIPool(**kwargs) elif pool == 'MultiPool': return MultiPool(**kwargs) elif pool == 'SerialPool': r...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wait(self): """ If this isn't the master process, wait for instructions. """
if self.is_master(): raise RuntimeError("Master node told to await jobs.") status = MPI.Status() while True: # Event loop. # Sit here and await instructions. if self.debug: print("Worker {0} waiting for task.".format(self.rank)) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def commit_when_no_transaction(f): '''Decorator for committing changes when the instance session is not in a transaction.''' def _(self, *args, **kwargs): r = f(self, *args, **kwargs) return self.session.add(self) if self.session is not None else r _.__name__ = f.__name__ _.__doc_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def irange(self, start=0, end=-1, callback=None, withscores=True, **options): '''Return the range by rank between start and end.''' backend = self.read_backend res = backend.structure(self).irange(start, end, withscores=withscores,...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def pop_front(self): '''Remove the first element from of the list.''' backend = self.backend return backend.execute(backend.structure(self).pop_front(), self.value_pickler.loads)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def block_pop_back(self, timeout=10): '''Remove the last element from of the list. If no elements are available, blocks for at least ``timeout`` seconds.''' value = yield self.backend_structure().block_pop_back(timeout) if value is not None: yield self.value_pickler.loads(value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def block_pop_front(self, timeout=10): '''Remove the first element from of the list. If no elements are available, blocks for at least ``timeout`` seconds.''' value = yield self.backend_structure().block_pop_front(timeout) if value is not None: yield self.value_pickler.loads(val...