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 add(self, sid, token): """ Add new sensor to the database Parameters sid : str SensorId token : str """
try: self.dbcur.execute(SQL_SENSOR_INS, (sid, token)) except sqlite3.IntegrityError: # sensor entry exists pass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove(self, sid): """ Remove sensor from the database Parameters sid : str SensorID """
self.dbcur.execute(SQL_SENSOR_DEL, (sid,)) self.dbcur.execute(SQL_TMPO_DEL, (sid,))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list(self, *sids): """ List all tmpo-blocks in the database Parameters sids : list of str SensorID's for which to list blocks Optional, leave empty to get th...
if sids == (): sids = [sid for (sid,) in self.dbcur.execute(SQL_SENSOR_ALL)] slist = [] for sid in sids: tlist = [] for tmpo in self.dbcur.execute(SQL_TMPO_ALL, (sid,)): tlist.append(tmpo) sid, rid, lvl, bid, ext, ctd, blk = tm...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def series(self, sid, recycle_id=None, head=None, tail=None, datetime=True): """ Create data Series Parameters sid : str recycle_id : optional head : int | panda...
if head is None: head = 0 else: head = self._2epochs(head) if tail is None: tail = EPOCHS_MAX else: tail = self._2epochs(tail) if recycle_id is None: self.dbcur.execute(SQL_TMPO_RID_MAX, (sid,)) recycle_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 dataframe(self, sids, head=0, tail=EPOCHS_MAX, datetime=True): """ Create data frame Parameters sids : list[str] head : int | pandas.Timestamp, optional Star...
if head is None: head = 0 else: head = self._2epochs(head) if tail is None: tail = EPOCHS_MAX else: tail = self._2epochs(tail) series = [self.series(sid, head=head, tail=tail, datetime=False) for sid in sids] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def first_timestamp(self, sid, epoch=False): """ Get the first available timestamp for a sensor Parameters sid : str SensorID epoch : bool default False If True ...
first_block = self.dbcur.execute(SQL_TMPO_FIRST, (sid,)).fetchone() if first_block is None: return None timestamp = first_block[2] if not epoch: timestamp = pd.Timestamp.utcfromtimestamp(timestamp) timestamp = timestamp.tz_localize('UTC') 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 last_timestamp(self, sid, epoch=False): """ Get the theoretical last timestamp for a sensor Parameters sid : str SensorID epoch : bool default False If True ...
timestamp, value = self.last_datapoint(sid, epoch) return timestamp
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addKwdArgsToSig(sigStr, kwArgsDict): """ Alter the passed function signature string to add the given kewords """
retval = sigStr if len(kwArgsDict) > 0: retval = retval.strip(' ,)') # open up the r.h.s. for more args for k in kwArgsDict: if retval[-1] != '(': retval += ", " retval += str(k)+"="+str(kwArgsDict[k]) retval += ')' retval = retval return retval
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _gauss_funct(p, fjac=None, x=None, y=None, err=None, weights=None): """ Defines the gaussian function to be used as the model. """
if p[2] != 0.0: Z = (x - p[1]) / p[2] model = p[0] * np.e ** (-Z ** 2 / 2.0) else: model = np.zeros(np.size(x)) status = 0 if weights is not None: if err is not None: print("Warning: Ignoring errors and using weights.\n") return [status, (y - model)...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gfit1d(y, x=None, err=None, weights=None, par=None, parinfo=None, maxiter=200, quiet=0): """ Return the gaussian fit as an object. Parameters y: 1D Numpy arr...
y = y.astype(np.float) if weights is not None: weights = weights.astype(np.float) if err is not None: err = err.astype(np.float) if x is None and len(y.shape) == 1: x = np.arange(len(y)).astype(np.float) if x.shape != y.shape: print("input arrays X and Y must be of e...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def filter(self, *args, **kwargs): """filter lets django managers use `objects.filter` on a hashable object."""
obj = kwargs.pop(self.object_property_name, None) if obj is not None: kwargs['object_hash'] = self.model._compute_hash(obj) return super().filter(*args, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _extract_model_params(self, defaults, **kwargs): """this method allows django managers use `objects.get_or_create` and `objects.update_or_create` on a hashab...
obj = kwargs.pop(self.object_property_name, None) if obj is not None: kwargs['object_hash'] = self.model._compute_hash(obj) lookup, params = super()._extract_model_params(defaults, **kwargs) if obj is not None: params[self.object_property_name] = obj ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def persist(self): """a private method that persists an estimator object to the filesystem"""
if self.object_hash: data = dill.dumps(self.object_property) f = ContentFile(data) self.object_file.save(self.object_hash, f, save=False) f.close() self._persisted = True return self._persisted
<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(self): """a private method that loads an estimator object from the filesystem"""
if self.is_file_persisted: self.object_file.open() temp = dill.loads(self.object_file.read()) self.set_object(temp) self.object_file.close()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_from_file(cls, filename): """Return an Estimator object given the path of the file, relative to the MEDIA_ROOT"""
obj = cls() obj.object_file = filename obj.load() return obj
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getAppDir(): """ Return our application dir. Create it if it doesn't exist. """
# Be sure the resource dir exists theDir = os.path.expanduser('~/.')+APP_NAME.lower() if not os.path.exists(theDir): try: os.mkdir(theDir) except OSError: print('Could not create "'+theDir+'" to save GUI settings.') theDir = "./"+APP_NAME.lower() retu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getEmbeddedKeyVal(cfgFileName, kwdName, dflt=None): """ Read a config file and pull out the value of a given keyword. """
# Assume this is a ConfigObj file. Use that s/w to quickly read it and # put it in dict format. Assume kwd is at top level (not in a section). # The input may also be a .cfgspc file. # # Only use ConfigObj here as a tool to generate a dict from a file - do # not use the returned object as a C...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getCfgFilesInDirForTask(aDir, aTask, recurse=False): """ This is a specialized function which is meant only to keep the same code from needlessly being much ...
if recurse: flist = irafutils.rglob(aDir, '*.cfg') else: flist = glob.glob(aDir+os.sep+'*.cfg') if aTask: retval = [] for f in flist: try: if aTask == getEmbeddedKeyVal(f, TASK_NAME_KEY, ''): retval.append(f) 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 getUsrCfgFilesForPyPkg(pkgName): """ See if the user has one of their own local .cfg files for this task, such as might be created automatically during the s...
# Get the python package and it's .cfg file thePkg, theFile = findCfgFileForPkg(pkgName, '.cfg') # See if the user has any of their own local .cfg files for this task tname = getEmbeddedKeyVal(theFile, TASK_NAME_KEY) flist = getCfgFilesInDirForTask(getAppDir(), tname) return flist
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def checkSetReadOnly(fname, raiseOnErr = False): """ See if we have write-privileges to this file. If we do, and we are not supposed to, then fix that case. """
if os.access(fname, os.W_OK): # We can write to this but it is supposed to be read-only. Fix it. # Take away usr-write, leave group and other alone, though it # may be simpler to just force/set it to: r--r--r-- or r-------- irafutils.setWritePrivs(fname, False, ignoreErrors= not rai...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def isHiddenName(astr): """ Return True if this string name denotes a hidden par or section """
if astr is not None and len(astr) > 2 and astr.startswith('_') and \ astr.endswith('_'): return True else: return 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 syncParamList(self, firstTime, preserve_order=True): """ Set or reset the internal param list from the dict's contents. """
# See the note in setParam about this design. # Get latest par values from dict. Make sure we do not # change the id of the __paramList pointer here. new_list = self._getParamsFromConfigDict(self, initialPass=firstTime) # dumpCfgspcTo=sys...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getDefaultParList(self): """ Return a par list just like ours, but with all default values. """
# The code below (create a new set-to-dflts obj) is correct, but it # adds a tenth of a second to startup. Clicking "Defaults" in the # GUI does not call this. But this can be used to set the order seen. # But first check for rare case of no cfg file name if self.filename is ...
<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, *args, **kw): """ This may be overridden by a subclass. """
if self._runFunc is not None: # remove the two args sent by EditParDialog which we do not use if 'mode' in kw: kw.pop('mode') if '_save' in kw: kw.pop('_save') return self._runFunc(self, *args, **kw) else: raise taskpars.NoExecError('No way to...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def triggerLogicToStr(self): """ Print all the trigger logic to a string and return it. """
try: import json except ImportError: return "Cannot dump triggers/dependencies/executes (need json)" retval = "TRIGGERS:\n"+json.dumps(self._allTriggers, indent=3) retval += "\nDEPENDENCIES:\n"+json.dumps(self._allDepdcs, indent=3) retval += "\nTO EXECUTE...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _findAssociatedConfigSpecFile(self, cfgFileName): """ Given a config file, find its associated config-spec file, and return the full pathname of the file. ""...
# Handle simplest 2 cases first: co-located or local .cfgspc file retval = "."+os.sep+self.__taskName+".cfgspc" if os.path.isfile(retval): return retval retval = os.path.dirname(cfgFileName)+os.sep+self.__taskName+".cfgspc" if os.path.isfile(retval): return retval # A...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getPosArgs(self): """ Return a list, in order, of any parameters marked with "pos=N" in the .cfgspc file. """
if len(self._posArgs) < 1: return [] # The first item in the tuple is the index, so we now sort by it self._posArgs.sort() # Build a return list retval = [] for idx, scope, name in self._posArgs: theDict, val = findScopedPar(self, scope, name) 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 dottedQuadToNum(ip): """ Convert decimal dotted quad string to long integer 1 16777218 16908291 16909060 4294967295 Traceback (most recent call last): Value...
# import here to avoid it when ip_addr values are not used import socket, struct try: return struct.unpack('!L', socket.inet_aton(ip.strip()))[0] except socket.error: raise ValueError('Not a good dotted-quad IP: %s' % ip) return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def numToDottedQuad(num): """ Convert long int to dotted quad string Traceback (most recent call last): ValueError: Not a good numeric IP: -1 '0.0.0.1' '1.0.0.2...
# import here to avoid it when ip_addr values are not used import socket, struct # no need to intercept here, 4294967295 is fine if num > 4294967295 or num < 0: raise ValueError('Not a good numeric IP: %s' % num) try: return socket.inet_ntoa( struct.pack('!L', long(num...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _is_num_param(names, values, to_float=False): """ Return numbers from inputs or raise VdtParamError. Lets ``None`` pass through. Pass in keyword argument ``t...
fun = to_float and float or int out_params = [] for (name, val) in zip(names, values): if val is None: out_params.append(val) elif isinstance(val, number_or_string_types): try: out_params.append(fun(val)) except ValueError: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_boolean(value): """ Check if the value represents a boolean. 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 Traceback (most recent call last): VdtTypeError: the value "...
if isinstance(value, string_types): try: return bool_dict[value.lower()] except KeyError: raise VdtTypeError(value) # we do an equality test rather than an identity test # this ensures Python 2.2 compatibilty # and allows 0 and 1 to represent True and False i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_ip_addr(value): """ Check that the supplied value is an Internet Protocol address, v.4, represented by a dotted-quad string, i.e. '1.2.3.4'. '1' '1.2' '1....
if not isinstance(value, string_types): raise VdtTypeError(value) value = value.strip() try: dottedQuadToNum(value) except ValueError: raise VdtValueError(value) return 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 is_list(value, min=None, max=None): """ Check that the value is a list of values. You can optionally specify the minimum and maximum number of members. It do...
(min_len, max_len) = _is_num_param(('min', 'max'), (min, max)) if isinstance(value, string_types): raise VdtTypeError(value) try: num_members = len(value) except TypeError: raise VdtTypeError(value) if min_len is not None and num_members < min_len: raise VdtValueTooS...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_int_list(value, min=None, max=None): """ Check that the value is a list of integers. You can optionally specify the minimum and maximum number of members....
return [is_integer(mem) for mem in is_list(value, min, max)]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_bool_list(value, min=None, max=None): """ Check that the value is a list of booleans. You can optionally specify the minimum and maximum number of members...
return [is_boolean(mem) for mem in is_list(value, min, max)]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_float_list(value, min=None, max=None): """ Check that the value is a list of floats. You can optionally specify the minimum and maximum number of members....
return [is_float(mem) for mem in is_list(value, min, max)]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_string_list(value, min=None, max=None): """ Check that the value is a list of strings. You can optionally specify the minimum and maximum number of member...
if isinstance(value, string_types): raise VdtTypeError(value) return [is_string(mem) for mem in is_list(value, min, max)]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_ip_addr_list(value, min=None, max=None): """ Check that the value is a list of IP addresses. You can optionally specify the minimum and maximum number of ...
return [is_ip_addr(mem) for mem in is_list(value, min, max)]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def force_list(value, min=None, max=None): """ Check that a value is a list, coercing strings into a list with one member. Useful where users forget the trailing...
if not isinstance(value, (list, tuple)): value = [value] return is_list(value, min, max)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_mixed_list(value, *args): """ Check that the value is a list. Allow specifying the type of each member. Work on lists of specific lengths. You specify eac...
try: length = len(value) except TypeError: raise VdtTypeError(value) if length < len(args): raise VdtValueTooShortError(value) elif length > len(args): raise VdtValueTooLongError(value) try: return [fun_dict[arg](val) for arg, val in zip(args, value)] exc...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_option(value, *options): """ This check matches the value to any of a set of options. 'yoda' Traceback (most recent call last): VdtValueError: the value ...
if not isinstance(value, string_types): raise VdtTypeError(value) if not value in options: raise VdtValueError(value) return 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 _unquote(self, val): """Unquote a value if necessary."""
if (len(val) >= 2) and (val[0] in ("'", '"')) and (val[0] == val[-1]): val = val[1:-1] return val
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def match_header(cls, header): """A constant value HDU will only be recognized as such if the header contains a valid PIXVALUE and NAXIS == 0. """
pixvalue = header.get('PIXVALUE') naxis = header.get('NAXIS', 0) return (super(_ConstantValueImageBaseHDU, cls).match_header(header) and (isinstance(pixvalue, float) or _is_int(pixvalue)) and naxis == 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 _check_constant_value_data(self, data): """Verify that the HDU's data is a constant value array."""
arrayval = data.flat[0] if np.all(data == arrayval): return arrayval 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 dumps(columns): ''' Serialize ``columns`` to a JSON formatted ``bytes`` object. ''' fp = BytesIO() dump(columns, fp) fp.seek(0) return fp.read()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def readall(cls, member, size): ''' Parse variable metadata for a XPORT file member. ''' fp = member.library.fp LINE = member.library.LINE n = cls.header_match(fp.read(LINE)) namestrs = [fp.read(size) for i in range(n)] # Each namestr field is 140 bytes ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def to_jd(year, month, day): '''Determine Julian day count from Islamic date''' return (day + ceil(29.5 * (month - 1)) + (year - 1) * 354 + trunc((3 + (11 * year)) / 30) + EPOCH) - 1
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def from_jd(jd): '''Calculate Islamic date from Julian day''' jd = trunc(jd) + 0.5 year = trunc(((30 * (jd - EPOCH)) + 10646) / 10631) month = min(12, ceil((jd - (29 + to_jd(year, 1, 1))) / 29.5) + 1) day = int(jd - to_jd(year, month, 1)) + 1 return (year, month, day)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def freshenFocus(self): """ Did something which requires a new look. Move scrollbar up. This often needs to be delayed a bit however, to let other events in the ...
self.top.update_idletasks() self.top.after(10, self.setViewAtTop)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mwl(self, event): """Mouse Wheel - under tkinter we seem to need Tk v8.5+ for this """
if event.num == 4: # up on Linux self.top.f.canvas.yview_scroll(-1*self._tmwm, 'units') elif event.num == 5: # down on Linux self.top.f.canvas.yview_scroll(1*self._tmwm, 'units') else: # assume event.delta has the direction, but reversed sign self.top.f.canva...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def focusNext(self, event): """Set focus to next item in sequence"""
try: event.widget.tk_focusNext().focus_set() except TypeError: # see tkinter equivalent code for tk_focusNext to see # commented original version name = event.widget.tk.call('tk_focusNext', event.widget._w) event.widget._nametowidget(str(name)...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def focusPrev(self, event): """Set focus to previous item in sequence"""
try: event.widget.tk_focusPrev().focus_set() except TypeError: # see tkinter equivalent code for tk_focusPrev to see # commented original version name = event.widget.tk.call('tk_focusPrev', event.widget._w) event.widget._nametowidget(str(name)...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def doScroll(self, event): """Scroll the panel down to ensure widget with focus to be visible Tracks the last widget that doScroll was called for and ignores rep...
canvas = self.top.f.canvas widgetWithFocus = event.widget if widgetWithFocus is self.lastFocusWidget: return FALSE self.lastFocusWidget = widgetWithFocus if widgetWithFocus is None: return TRUE # determine distance of widget from top & bottom edge...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _handleParListMismatch(self, probStr, extra=False): """ Handle the situation where two par lists do not match. This is meant to allow subclasses to override....
errmsg = 'ERROR: mismatch between default and current par lists ' + \ 'for task "'+self.taskName+'"' if probStr: errmsg += '\n\t'+probStr errmsg += '\n(try: "unlearn '+self.taskName+'")' print(errmsg) return 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 _setupDefaultParamList(self): """ This creates self.defaultParamList. It also does some checks on the paramList, sets its order if needed, and deletes any ex...
# Obtain the default parameter list self.defaultParamList = self._taskParsObj.getDefaultParList() theParamList = self._taskParsObj.getParList() # Lengths are probably equal but this isn't necessarily an error # here, so we check for differences below. if len(self.defau...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def saveAs(self, event=None): """ Save the parameter settings to a user-specified file. Any changes here must be coordinated with the corresponding tpar save_as ...
self.debug('Clicked Save as...') # On Linux Pers..Dlg causes the cwd to change, so get a copy of current curdir = os.getcwd() # The user wishes to save to a different name writeProtChoice = self._writeProtectOnSaveAs if capable.OF_TKFD_IN_EPAR: # Prompt usi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def htmlHelp(self, helpString=None, title=None, istask=False, tag=None): """ Pop up the help in a browser window. By default, this tries to show the help for the...
# Check the help string. If it turns out to be a URL, launch that, # if not, dump it to a quick and dirty tmp html file to make it # presentable, and pass that file name as the URL. if not helpString: helpString = self.getHelpString(self.pkgName+'.'+self.taskName) i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getValue(self, name, scope=None, native=False): """ Return current par value from the GUI. This does not do any validation, and it it not necessarily the sam...
# Get model data, the list of pars theParamList = self._taskParsObj.getParList() # NOTE: If par scope is given, it will be used, otherwise it is # assumed to be unneeded and the first name-match is returned. fullName = basicpar.makeFullName(scope, name) # Loop over 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 _pushMessages(self): """ Internal callback used to make sure the msg list keeps moving. """
# This continues to get itself called until no msgs are left in list. self.showStatus('') if len(self._statusMsgsToShow) > 0: self.top.after(200, self._pushMessages)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def teal(theTask, parent=None, loadOnly=False, returnAs="dict", canExecute=True, strict=False, errorsToTerm=False, autoClose=True, defaults=False): # overrides=N...
if loadOnly: # this forces returnAs="dict" obj = None try: obj = cfgpars.getObjectFromTaskArg(theTask, strict, defaults) # obj.strictUpdate(overrides) # ! would need to re-verify after this ! except Exception as re: # catches RuntimeError and KeyError and ... ...
<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(theTask, canExecute=True, strict=True, defaults=False): """ Shortcut to load TEAL .cfg files for non-GUI access where loadOnly=True. """
return teal(theTask, parent=None, loadOnly=True, returnAs="dict", canExecute=canExecute, strict=strict, errorsToTerm=True, defaults=defaults)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cfgGetBool(theObj, name, dflt): """ Get a stringified val from a ConfigObj obj and return it as bool """
strval = theObj.get(name, None) if strval is None: return dflt return strval.lower().strip() == 'true'
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _overrideMasterSettings(self): """ Override so that we can run in a different mode. """
# config-obj dict of defaults cod = self._getGuiSettings() # our own GUI setup self._appName = APP_NAME self._appHelpString = tealHelpString self._useSimpleAutoClose = self._do_usac self._showExtraHelpButton = False self._saveAndCl...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _doActualSave(self, fname, comment, set_ro=False, overwriteRO=False): """ Override this so we can handle case of file not writable, as well as to make our _l...
self.debug('Saving, file name given: '+str(fname)+', set_ro: '+\ str(set_ro)+', overwriteRO: '+str(overwriteRO)) cantWrite = False inInstArea = False if fname in (None, ''): fname = self._taskParsObj.getFilename() # now do some final checks then save t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _defineEditedCallbackObjectFor(self, parScope, parName): """ Override to allow us to use an edited callback. """
# We know that the _taskParsObj is a ConfigObjPars triggerStrs = self._taskParsObj.getTriggerStrings(parScope, parName) # Some items will have a trigger, but likely most won't if triggerStrs and len(triggerStrs) > 0: return self else: 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 updateTitle(self, atitle): """ Override so we can append read-only status. """
if atitle and os.path.exists(atitle): if _isInstalled(atitle): atitle += ' [installed]' elif not os.access(atitle, os.W_OK): atitle += ' [read only]' super(ConfigObjEparDialog, self).updateTitle(atitle)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def edited(self, scope, name, lastSavedVal, newVal, action): """ This is the callback function invoked when an item is edited. This is only called for those item...
# Get name(s) of any triggers that this par triggers triggerNamesTup = self._taskParsObj.getTriggerStrings(scope, name) assert triggerNamesTup is not None and len(triggerNamesTup) > 0, \ 'Empty trigger name for: "'+name+'", consult the .cfgspc file.' # Loop through all ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _setTaskParsObj(self, theTask): """ Overridden version for ConfigObj. theTask can be either a .cfg file name or a ConfigObjPars object. """
# Create the ConfigObjPars obj self._taskParsObj = cfgpars.getObjectFromTaskArg(theTask, self._strict, False) # Tell it that we can be used for catching debug lines self._taskParsObj.setDebugLogger(self) # Immediately make a copy of it's un-t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _getSaveAsFilter(self): """ Return a string to be used as the filter arg to the save file dialog during Save-As. """
# figure the dir to use, start with the one from the file absRcDir = os.path.abspath(self._rcDir) thedir = os.path.abspath(os.path.dirname(self._taskParsObj.filename)) # skip if not writeable, or if is _rcDir if thedir == absRcDir or not os.access(thedir, os.W_OK): t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _getOpenChoices(self): """ Go through all possible sites to find applicable .cfg files. Return as an iterable. """
tsk = self._taskParsObj.getName() taskFiles = set() dirsSoFar = [] # this helps speed this up (skip unneeded globs) # last dir aDir = os.path.dirname(self._taskParsObj.filename) if len(aDir) < 1: aDir = os.curdir dirsSoFar.append(aDir) taskFiles.update(c...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pfopen(self, event=None): """ Load the parameter settings from a user-specified file. """
# Get the selected file name fname = self._openMenuChoice.get() # Also allow them to simply find any file - do not check _task_name_... # (could use tkinter's FileDialog, but this one is prettier) if fname[-3:] == '...': if capable.OF_TKFD_IN_EPAR: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _handleParListMismatch(self, probStr, extra=False): """ Override to include ConfigObj filename and specific errors. Note that this only handles "missing" par...
# keep down the duplicate errors if extra: return True # the base class is already stating it will be ignored # find the actual errors, and then add that to the generic message errmsg = 'Warning: ' if self._strict: errmsg = 'ERROR: ' errmsg = er...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _setToDefaults(self): """ Load the default parameter settings into the GUI. """
# Create an empty object, where every item is set to it's default value try: tmpObj = cfgpars.ConfigObjPars(self._taskParsObj.filename, associatedPkg=\ self._taskParsObj.getAssocPkg(), ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getDict(self): """ Retrieve the current parameter settings from the GUI."""
# We are going to have to return the dict so let's # first make sure all of our models are up to date with the values in # the GUI right now. badList = self.checkSetSaveEntries(doSave=False) if badList: self.processBadEntries(badList, self.taskName, canCancel=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 loadDict(self, theDict): """ Load the parameter settings from a given dict into the GUI. """
# We are going to have to merge this info into ourselves so let's # first make sure all of our models are up to date with the values in # the GUI right now. badList = self.checkSetSaveEntries(doSave=False) if badList: if not self.processBadEntries(badList, self.taskN...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _applyTriggerValue(self, triggerName, outval): """ Here we look through the entire .cfgspc to see if any parameters are affected by this trigger. For those t...
# First find which items are dependent upon this trigger (cached) # e.g. { scope1.name1 : dep'cy-type, scope2.name2 : dep'cy-type, ... } depParsDict = self._taskParsObj.getParsWhoDependOn(triggerName) if not depParsDict: return if 0: print("Dependent parameters:\n"+str(depParsD...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def readShiftFile(self, filename): """ Reads a shift file from disk and populates a dictionary. """
order = [] fshift = open(filename,'r') flines = fshift.readlines() fshift.close() common = [f.strip('#').strip() for f in flines if f.startswith('#')] c=[line.split(': ') for line in common] # Remove any line comments in the shift file - lines starting with '#'...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def writeShiftFile(self, filename="shifts.txt"): """ Writes a shift file object to a file on disk using the convention for shift file format. """
lines = ['# frame: ', self['frame'], '\n', '# refimage: ', self['refimage'], '\n', '# form: ', self['form'], '\n', '# units: ', self['units'], '\n'] for o in self['order']: ss = " " for shift in self[o]: ss += 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 weave_instance(instance, aspect, methods=NORMAL_METHODS, lazy=False, bag=BrokenBag, **options): """ Low-level weaver for instances. .. warning:: You should n...
if bag.has(instance): return Nothing entanglement = Rollback() method_matches = make_method_matcher(methods) logdebug("weave_instance (module=%r, aspect=%s, methods=%s, lazy=%s, **options=%s)", instance, aspect, methods, lazy, options) def fixup(func): return func.__g...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def weave_module(module, aspect, methods=NORMAL_METHODS, lazy=False, bag=BrokenBag, **options): """ Low-level weaver for "whole module weaving". .. warning:: You...
if bag.has(module): return Nothing entanglement = Rollback() method_matches = make_method_matcher(methods) logdebug("weave_module (module=%r, aspect=%s, methods=%s, lazy=%s, **options=%s)", module, aspect, methods, lazy, options) for attr in dir(module): func = getatt...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def patch_module(module, name, replacement, original=UNSPECIFIED, aliases=True, location=None, **_bogus_options): """ Low-level attribute patcher. :param module ...
rollback = Rollback() seen = False original = getattr(module, name) if original is UNSPECIFIED else original location = module.__name__ if hasattr(module, '__name__') else type(module).__module__ target = module.__name__ if hasattr(module, '__name__') else type(module).__name__ try: rep...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def patch_module_function(module, target, aspect, force_name=None, bag=BrokenBag, **options): """ Low-level patcher for one function from a specified module. .. ...
logdebug("patch_module_function (module=%s, target=%s, aspect=%s, force_name=%s, **options=%s", module, target, aspect, force_name, options) name = force_name or target.__name__ return patch_module(module, name, _checked_apply(aspect, target, module=module), original=target, **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 unstuff(packet): """ Remove byte stuffing from a TSIP packet. :param packet: TSIP packet with byte stuffing. The packet must already have been stripped or `V...
if is_framed(packet): raise ValueError('packet contains leading DLE and trailing DLE/ETX') else: return packet.replace(CHR_DLE + CHR_DLE, CHR_DLE)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def open(self): """ Opens the file for subsequent access. """
if self.handle is None: self.handle = fits.open(self.fname, mode='readonly') if self.extn: if len(self.extn) == 1: hdu = self.handle[self.extn[0]] else: hdu = self.handle[self.extn[0],self.extn[1]] else: hdu = sel...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reloadCompletedMeasurements(self): """ Reloads the completed measurements from the backing store. """
from pathlib import Path reloaded = [self.load(x.resolve()) for x in Path(self.dataDir).glob('*/*/*') if x.is_dir()] logger.info('Reloaded ' + str(len(reloaded)) + ' completed measurements') self.completeMeasurements = [x for x in reloaded if x is not None and x.status == MeasurementSta...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_exptime(filelist): """ Removes files with EXPTIME==0 from filelist. """
toclose = False removed_files = [] for f in filelist: if isinstance(f, str): f = fits.open(f) toclose = True try: exptime = f[0].header['EXPTIME'] except KeyError: removed_files.append(f) print("Warning: There are files 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 convert2fits(sci_ivm): """ Checks if a file is in WAIVER of GEIS format and converts it to MEF """
removed_files = [] translated_names = [] newivmlist = [] for file in sci_ivm: #find out what the input is # if science file is not found on disk, add it to removed_files for removal try: imgfits,imgtype = fileutil.isFits(file[0]) except IOError: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def journals(self): """ Retrieve journals attribute for this very Issue """
try: target = self._item_path json_data = self._redmine.get(target % str(self.id), parms={'include': 'journals'}) data = self._redmine.unwrap_json(None, json_data) journals = [Journal(redmine=self._redmine, ...
<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(self, notes=None): '''Save all changes back to Redmine with optional notes.''' # Capture the notes if given if notes: self._changes['notes'] = notes # Call the base-class save function super(Issue, self).save()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def set_status(self, new_status, notes=None): '''Save all changes and set to the given new_status''' self.status_id = new_status try: self.status['id'] = self.status_id # We don't have the id to name mapping, so blank the name self.status['name'] = 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 resolve(self, notes=None): '''Save all changes and resolve this issue''' self.set_status(self._redmine.ISSUE_STATUS_ID_RESOLVED, notes=notes)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def close(self, notes=None): '''Save all changes and close this issue''' self.set_status(self._redmine.ISSUE_STATUS_ID_CLOSED, notes=notes)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def new(self, page_name, **dict): ''' Create a new item with the provided dict information at the given page_name. Returns the new item. As of version 2.2 of Redmine, this doesn't seem to function. ''' self._item_new_path = '/projects/%s/wiki/%s.json' % \ (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 _set_version(self, version): ''' Set up this object based on the capabilities of the known versions of Redmine ''' # Store the version we are evaluating self.version = version or None # To evaluate the version capabilities, # assume the best-case if 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 interpret_bits_value(val): """ Converts input bits value from string to a single integer value or None. If a comma- or '+'-separated set of values are provid...
if isinstance(val, int) or val is None: return val else: val = str(val).strip() if val.startswith('~'): flip_bits = True val = val[1:].lstrip() else: flip_bits = False if val.startswith('('): if val.endswith(')'): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def output_influx(data): """Print data using influxDB format."""
for contract in data: # Pop yesterdays data yesterday_data = data[contract]['yesterday_hourly_consumption'] del data[contract]['yesterday_hourly_consumption'] # Print general data out = "pyhydroquebec,contract=" + contract + " " for index, key in enumerate(data[co...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def to_jd(year, month, day): '''Determine Julian day from Bahai date''' gy = year - 1 + EPOCH_GREGORIAN_YEAR if month != 20: m = 0 else: if isleap(gy + 1): m = -14 else: m = -15 return gregorian.to_jd(gy, 3, 20) + (19 * (month - 1)) + m + day
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def from_jd(jd): '''Calculate Bahai date from Julian day''' jd = trunc(jd) + 0.5 g = gregorian.from_jd(jd) gy = g[0] bstarty = EPOCH_GREGORIAN_YEAR if jd <= gregorian.to_jd(gy, 3, 20): x = 1 else: x = 0 # verify this next line... bys = gy - (bstarty + (((gregorian....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def to_jd(baktun, katun, tun, uinal, kin): '''Determine Julian day from Mayan long count''' return EPOCH + (baktun * 144000) + (katun * 7200) + (tun * 360) + (uinal * 20) + kin
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def from_jd(jd): '''Calculate Mayan long count from Julian day''' d = jd - EPOCH baktun = trunc(d / 144000) d = (d % 144000) katun = trunc(d / 7200) d = (d % 7200) tun = trunc(d / 360) d = (d % 360) uinal = trunc(d / 20) kin = int((d % 20)) return (baktun, katun, tun, uinal,...