code
stringlengths
1
18.2k
def sync(self, *sids): """ Synchronise data Parameters ---------- sids : list of str SensorIDs to sync Optional, leave empty to sync everything """ if sids == (): sids = [sid for (sid,) in self.dbcur.execute(SQL_SENSOR_ALL)] for sid in sids: self.dbcur.execute(SQL_TMPO_LAST, (sid,)) last = self.dbcur.fetchone() if last...
256: return else: rid, lvl, bid = 0, 0, 0 self._req_sync(sid, rid, lvl, bid)
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 them all Returns ------- list[list[tuple]] """ if sids == (): sids = [sid for (sid,) in self.dbcur.execute(SQL_SENSOR_ALL)] slist = [] for sid in sids...
bid, ext, ctd, blk = tmpo self._dprintf(DBG_TMPO_WRITE, ctd, sid, rid, lvl, bid, len(blk)) slist.append(tlist) return slist
def series(self, sid, recycle_id=None, head=None, tail=None, datetime=True): """ Create data Series Parameters ---------- sid : str recycle_id : optional head : int | pandas.Timestamp, optional Start of the interval default earliest available tail : int | pandas.Timestamp, optional End of the interval default max epoch...
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 = self.dbcur.fetchone()[0] tlist = self.list(sid)[0] srlist = [] for _sid, rid, lvl, bid, ext, ctd, blk in tlist: if (recycle_id == rid an...
pd.concat(srlist) ts.name = sid if datetime is True: ts.index = pd.to_datetime(ts.index, unit="s", utc=True) return ts else: return pd.Series([], name=sid)
def dataframe(self, sids, head=0, tail=EPOCHS_MAX, datetime=True): """ Create data frame Parameters ---------- sids : list[str] head : int | pandas.Timestamp, optional Start of the interval default earliest available tail : int | pandas.Timestamp, optional End of the interval default max epoch datetime : bool convert i...
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] df = pd.concat(series, axis=1) if datetime is True: df.index = pd.to_datetime(df.index, unit="s", utc=True) return df
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 return as epoch If False return as pd.Timestamp Returns ------- pd.Timestamp | int """ first_block = self.dbcur.execute(SQL_TMPO_FIRST, (sid,)).fetc...
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 return as epoch If False return as pd.Timestamp Returns ------- pd.Timestamp | int """ timestamp, value = self.last_datapoint(sid, epoch) return tim...
def last_datapoint(self, sid, epoch=False): """ Parameters ---------- sid : str SensorId epoch : bool default False If True return as epoch If False return as pd.Timestamp Returns ------- pd.Timestamp | int, float """ block = self._last_block(sid) if block is None: return None, None header = block['h'] timestamp, value...
def _npdelta(self, a, delta): """Numpy: Modifying Array Values http://docs.scipy.org/doc/numpy/reference/arrays.nditer.html""" for x in np.nditer(a, op_flags=["readwrite"]): delta += x x[...] = delta return a
def sigStrToKwArgsDict(checkFuncSig): """ Take a check function signature (string), and parse it to get a dict of the keyword args and their values. """ p1 = checkFuncSig.find('(') p2 = checkFuncSig.rfind(')') assert p1 > 0 and p2 > 0 and p2 > p1, "Invalid signature: "+checkFuncSig argParts = irafutils.csvSplit(checkFu...
argSpl = argPair.split('=', 1) if len(argSpl) > 1: if argSpl[0] in retval: if isinstance(retval[argSpl[0]], (list,tuple)): retval[argSpl[0]]+=(irafutils.stripQuotes(argSpl[1]),) # 3rd else: # 2nd in, so convert to tuple retval[argSpl[0]] = (retval[argSpl[0]], irafutils.stripQuotes(argSpl[1]),) else: retval[argSpl[0]] =...
def separateKeywords(kwArgsDict): """ Look through the keywords passed and separate the special ones we have added from the legal/standard ones. Return both sets as two dicts (in a tuple), as (standardKws, ourKws) """ standardKws = {} ourKws = {} for k in kwArgsDict: if k in STANDARD_KEYS: standardKws[k]=kwArgsDict[k] ...
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]) r...
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: Ig...
return [status, (y - model) * weights] elif err is not None: return [status, (y - model) / err] else: return [status, y - model]
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 array The data to be fitted x: 1D Numpy array (optional) The x values of the y array. x and y must have the same shape. err: 1D Numpy array (optional) ...
y weights: 1D Numpy array (optiional) 1D array with weights, must be the same shape as y par: List (optional) Starting values for the parameters to be fitted parinfo: Dictionary of lists (optional) provides additional information for the parameters. For a detailed description see nmpfit.py. Parinfo can be used to limit...
to perform Default: 200 quiet: number if set to 1, nmpfit does not print to the screen Default: 0 Examples -------- >>> x = np.arange(10,20, 0.1) >>> y= 10*np.e**(-(x-15)**2/4) >>> print(gfit1d(y,x=x, maxiter=20,quiet=1).params) [10. 15. 1.41421356] """ y = y.astype(np.float) if weights is not None: weights = weights.a...
= np.arange(len(y)).astype(np.float) if x.shape != y.shape: print("input arrays X and Y must be of equal shape.\n") return fa = {'x': x, 'y': y, 'err': err, 'weights': weights} if par is not None: p = par else: ysigma = y.std() ind = np.nonzero(y > ysigma)[0] if len(ind) != 0: xind = int(ind.mean()) p2 = x[xind] p1 = y...
ymin = y.min() ymean= y.mean() if (ymax - ymean) > (abs(ymin - ymean)): p1 = ymax else: p1 = ymin ind = (np.nonzero(y == p1))[0] p2 = x.mean() p3 = 1. p = [p1, p2, p3] m = nmpfit.mpfit(_gauss_funct, p,parinfo = parinfo, functkw=fa, maxiter=maxiter, quiet=quiet) if (m.status <= 0): print('error message = ', m.errmsg) re...
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)
def _extract_model_params(self, defaults, **kwargs): """this method allows django managers use `objects.get_or_create` and `objects.update_or_create` 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) lookup, params = sup...
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
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()
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
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_NA...
def getObjectFromTaskArg(theTask, strict, setAllToDefaults): """ Take the arg (usually called theTask), which can be either a subclass of ConfigObjPars, or a string package name, or a .cfg filename - no matter what it is - take it and return a ConfigObjPars object. strict - bool - warning severity, passed to the Config...
all to defaults """ # Already in the form we need (instance of us or of subclass) if isinstance(theTask, ConfigObjPars): if setAllToDefaults: raise RuntimeError('Called getObjectFromTaskArg with existing'+\ ' object AND setAllToDefaults - is unexpected use case.') # If it is an existing object, make sure it's internal ...
# edited the dict before calling us. theTask.syncParamList(False) # use strict somehow? # Note - some validation is done here in IrafPar creation, but it is # not the same validation done by the ConfigObj s/w (no check funcs). # Do we want to do that too here? return theTask # For example, a .cfg file if os.path.isfile...
KeyError: # this might just be caused by a file sitting in the local cwd with # the same exact name as the package we want to import, let's see if theTask.find('.') > 0: # it has an extension, like '.cfg' raise # this really was an error # else we drop down to the next step - try it as a pkg name
# Else it must be a Python package name to load if isinstance(theTask, str) and setAllToDefaults: # NOTE how we pass the task name string in setAllToDefaults return ConfigObjPars('', setAllToDefaults=theTask, strict=strict) else: return getParsObjForPyPkg(theTask, strict)
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 us...
here as a tool to generate a dict from a file - do # not use the returned object as a ConfigObj per se. As such, we can call # with "simple" format, ie. no cfgspc, no val'n, and "list_values"=False. try: junkObj = configobj.ConfigObj(cfgFileName, list_values=False) except: if kwdName == TASK_NAME_KEY: raise KeyError('C...
KeyError('Unfound key "'+kwdName+'" while parsing: '+ \ '\n\t'+os.path.realpath(cfgFileName)) if kwdName in junkObj: retval = junkObj[kwdName] del junkObj return retval # Not found if dflt is not None: del junkObj return dflt else: if kwdName == TASK_NAME_KEY: raise KeyError('Can not parse as a parameter config file: '...
def findCfgFileForPkg(pkgName, theExt, pkgObj=None, taskName=None): """ Locate the configuration files for/from/within a given python package. pkgName is a string python package name. This is used unless pkgObj is given, in which case pkgName is taken from pkgObj.__name__. theExt is either '.cfg' or '.cfgspc'. If the t...
of (package-object, cfg-file-name). """ # arg check ext = theExt if ext[0] != '.': ext = '.'+theExt # Do the import, if needed pkgsToTry = {} if pkgObj: pkgsToTry[pkgObj.__name__] = pkgObj else: # First try something simple like a regular or dotted import try: fl = [] if pkgName.find('.') > 0: fl = [ pkgName[:pkgName.r...
# One last case to try is something like "csc_kill" from # "acstools.csc_kill", but this convenience capability will only be # allowed if the parent pkg (acstools) has already been imported. if isinstance(pkgName, string_types) and pkgName.find('.') < 0: matches = [x for x in sys.modules.keys() \ if x.endswith("."+pkgN...
package or "+ext+" file via: "+\ "import "+str(pkgName)) # Now that we have the package object (or a few of them to try), for each # one find the .cfg or .cfgspc file, and return # Return as soon as ANY match is found. for aPkgName in pkgsToTry: aPkg = pkgsToTry[aPkgName] path = os.path.dirname(aPkg.__file__) if len(pa...
"*"+ext) if len(flist) < 1: continue # Go through these and find the first one for the assumed or given task # name. The task name for 'BigBlackBox.drizzle' would be 'drizzle'. if taskName is None: taskName = aPkgName.split(".")[-1] flist.sort() for f in flist: # A .cfg file gets checked for _task_name_=val, but a .cfg...
the val. if ext == '.cfg': itsTask = getEmbeddedKeyVal(f, TASK_NAME_KEY, '') else: # .cfgspc sigStr = getEmbeddedKeyVal(f, TASK_NAME_KEY, '') # .cfgspc file MUST have an entry for TASK_NAME_KEY w/ a default itsTask = vtor_checks.sigStrToKwArgsDict(sigStr)['default'] if itsTask == taskName: # We've found the correct fil...
still here? raise NoCfgFileError('No valid '+ext+' files found in package: "'+ \ str(pkgName)+'" for task: "'+str(taskName)+'"')
def findAllCfgTasksUnderDir(aDir): """ Finds all installed tasks by examining any .cfg files found on disk at and under the given directory, as an installation might be. This returns a dict of { file name : task name } """ retval = {} for f in irafutils.rglob(aDir, '*.cfg'): retval[f] = getEmbeddedKeyVal(f, TASK_NAME_K...
def getCfgFilesInDirForTask(aDir, aTask, recurse=False): """ This is a specialized function which is meant only to keep the same code from needlessly being much repeated throughout this application. This must be kept as fast and as light as possible. This checks a given directory for .cfg files matching a given task. I...
all files and ignores aTask. """ 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 Exception as e: print('Warning: '+str(e)) return retval else: return fl...
def getParsObjForPyPkg(pkgName, strict): """ Locate the appropriate ConfigObjPars (or subclass) within the given package. NOTE this begins the same way as getUsrCfgFilesForPyPkg(). Look for .cfg file matches in these places, in this order: 1 - any named .cfg file in current directory matching given task 2 - if there ex...
task 4 - the installed default .cfg file (with the given package) """ # Get the python package and it's .cfg file - need this no matter what installedPkg, installedFile = findCfgFileForPkg(pkgName, '.cfg') theFile = None tname = getEmbeddedKeyVal(installedFile, TASK_NAME_KEY) # See if the user has any of their own .cfg...
getCfgFilesInDirForTask(os.getcwd(), tname) if len(flist) > 0: if len(flist) == 1: # can skip file times sort theFile = flist[0] else: # There are a few different choices. In the absence of # requirements to the contrary, just take the latest. Set up a # list of tuples of (mtime, fname) so we can sort by mtime. ftups =...
flist] ftups.sort() theFile = ftups[-1][1] # See if the user has any of their own app-dir .cfg files for this task if theFile is None: flist = getCfgFilesInDirForTask(getAppDir(), tname) # verifies tname flist = [f for f in flist if os.path.basename(f) == tname+'.cfg'] if len(flist) > 0: theFile = flist[0] assert len(f...
an env. var defined area? (speak to users first) # Did we find one yet? If not, use the installed version useInstVer = False if theFile is None: theFile = installedFile useInstVer = True # Create a stand-in instance from this file. Force a read-only situation # if we are dealing with the installed, (expected to be) unw...
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 save of a read-only package, and return their names. """ # Get the python package and it's .cfg file thePkg, theFile = findCfgFileForPkg(pkgName, '.cfg') # See ...
this task tname = getEmbeddedKeyVal(theFile, TASK_NAME_KEY) flist = getCfgFilesInDirForTask(getAppDir(), tname) return flist
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 ...
it to: r--r--r-- or r-------- irafutils.setWritePrivs(fname, False, ignoreErrors= not raiseOnErr)
def flattenDictTree(aDict): """ Takes a dict of vals and dicts (so, a tree) as input, and returns a flat dict (only one level) as output. All key-vals are moved to the top level. Sub-section dict names (keys) are ignored/dropped. If there are name collisions, an error is raised. """ retval = {} for k in aDict: val = aD...
val is a dict, get its data (recursively) into a flat dict subDict = flattenDictTree(val) # Merge its dict of data into ours, watching for NO collisions rvKeySet = set(retval.keys()) sdKeySet = set(subDict.keys()) intr = rvKeySet.intersection(sdKeySet) if len(intr) > 0: raise DuplicateKeyError("Flattened dict already h...
has key: "+\ k+" - cannot flatten this.") else: retval[k] = val return retval
def countKey(theDict, name): """ Return the number of times the given par exists in this dict-tree, since the same key name may be used in different sections/sub-sections. """ retval = 0 for key in theDict: val = theDict[key] if isinstance(val, dict): retval += countKey(val, name) # recurse else: if key == name: retval...
other items on # this level will not be named "name", but child dicts # may have further counts return retval
def findFirstPar(theDict, name, _depth=0): """ Find the given par. Return tuple: (its own (sub-)dict, its value). Returns the first match found, without checking whether the given key name is unique or whether it is used in multiple sections. """ for key in theDict: val = theDict[key] # print _depth*' ', key, str(val)[...
is not None: return retval # else keep looking else: if key == name: return theDict, theDict[name] # else keep looking # if we get here then we have searched this whole (sub)-section and its # descendants, and found no matches. only raise if we are at the top. if _depth == 0: raise KeyError(name) else: return None
def findScopedPar(theDict, scope, name): """ Find the given par. Return tuple: (its own (sub-)dict, its value). """ # Do not search (like findFirstPar), but go right to the correct # sub-section, and pick it up. Assume it is there as stated. if len(scope): theDict = theDict[scope] # ! only goes one level deep - enhance...
def setPar(theDict, name, value): """ Sets a par's value without having to give its scope/section. """ section, previousVal = findFirstPar(theDict, name) # "section" is the actual object, not a copy section[name] = value
def mergeConfigObj(configObj, inputDict): """ Merge the inputDict values into an existing given configObj instance. The inputDict is a "flat" dict - it has no sections/sub-sections. The configObj may have sub-sections nested to any depth. This will raise a DuplicateKeyError if one of the inputDict keys is used more tha...
astrodrizzle # Verify that all inputDict keys in configObj are unique within configObj for key in inputDict: if countKey(configObj, key) > 1: raise DuplicateKeyError(key) # Now update configObj with each inputDict item for key in inputDict: setPar(configObj, key, inputDict[key])
def findTheLost(config_file, configspec_file, skipHidden=True): """ Find any lost/missing parameters in this cfg file, compared to what the .cfgspc says should be there. This method is recommended by the ConfigObj docs. Return a stringified list of item errors. """ # do some sanity checking, but don't (yet) make this a...
os.path.exists(configspec_file): print("ERROR: Configspec file not found: "+configspec_file) return [] tmpObj = configobj.ConfigObj(config_file, configspec=configspec_file) simval = configobj.SimpleVal() test = tmpObj.validate(simval) if test == True: return [] # If we get here, there is a dict returned of {key1: bool,...
pars. missing = [] flattened = configobj.flatten_errors(tmpObj, test) # But, before we move on, skip/eliminate any 'hidden' items from our list, # since hidden items are really supposed to be missing from the .cfg file. if len(flattened) > 0 and skipHidden: keepers = [] for tup in flattened: keep = True # hidden sectio...
(in a section, or at the top level) elif tup[1] is not None and isHiddenName(tup[1]): keep = False if keep: keepers.append(tup) flattened = keepers flatStr = flattened2str(flattened, missing=True) return flatStr
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
def flattened2str(flattened, missing=False, extra=False): """ Return a pretty-printed multi-line string version of the output of flatten_errors. Know that flattened comes in the form of a list of keys that failed. Each member of the list is a tuple:: ([list of sections...], key, result) so we turn that into a string. S...
extra to True if all the input problems are from extra items. """ if flattened is None or len(flattened) < 1: return '' retval = '' for sections, key, result in flattened: # Name the section and item, to start the message line if sections is None or len(sections) == 0: retval += '\t"'+key+'"' elif len(sections) == 1: i...
whole section is missing at the top-level; see if hidden junk = sections[0] if isHiddenName(junk): continue # this missing or extra section is not an error else: retval += '\tSection "'+sections[0]+'"' else: retval += '\t"'+sections[0]+'.'+key+'"' else: # len > 1 joined = '.'.join(sections) joined = '"'+joined+'"' if k...
line with "what seems to be the trouble" with this one if missing and result==False: retval += ' is missing.' elif extra: if result: retval += ' is an unexpected section. Is your file out of date?' else: retval += ' is an unexpected parameter. Is your file out of date?' elif isinstance(result, bool): retval += ' has an...
' is invalid, '+result.message retval += '\n\n' return retval.rstrip()
def getDefaultSaveFilename(self, stub=False): """ Return name of file where we are expected to be saved if no files for this task have ever been saved, and the user wishes to save. If stub is True, the result will be <dir>/<taskname>_stub.cfg instead of <dir>/<taskname>.cfg. """ if stub: return self._rcDir+os.sep+self....
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(s...
of the GUI (still?) if self._forUseWithEpar: new_list.append(basicpar.IrafParS(['$nargs','s','h','N'])) if len(self.__paramList) > 0 and preserve_order: # Here we have the most up-to-date data from the actual data # model, the ConfigObj dict, and we need to use it to fill in # our param list. BUT, we need to preserve t...
[p.fullName() for p in self.__paramList] assert len(namesInOrder) == len(new_list), \ 'Mismatch in num pars, had: '+str(len(namesInOrder))+ \ ', now we have: '+str(len(new_list))+', '+ \ str([p.fullName() for p in new_list]) self.__paramList[:] = [] # clear list, keep same pointer # create a flat dict view of new_list,...
for par in new_list: new_list_dict[par.fullName()] = par # populate for fn in namesInOrder: self.__paramList.append(new_list_dict[fn]) else: # Here we just take the data in whatever order it came. self.__paramList[:] = new_list
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 chec...
case of no cfg file name if self.filename is None: # this is a .cfgspc-only kind of object so far self.filename = self.getDefaultSaveFilename(stub=True) return copy.deepcopy(self.__paramList) tmpObj = ConfigObjPars(self.filename, associatedPkg=self.__assocPkg, setAllToDefaults=True, strict=False) return tmpObj.getParLi...
def setParam(self, name, val, scope='', check=1, idxHint=None): """ Find the ConfigObj entry. Update the __paramList. """ theDict, oldVal = findScopedPar(self, scope, name) # Set the value, even if invalid. It needs to be set before # the validation step (next). theDict[name] = val # If need be, check the proposed valu...
now, the best # shortcut is to only validate this section. if check: ans=self.validate(self._vtor, preserve_errors=True, section=theDict) if ans != True: flatStr = "All values are invalid!" if ans != False: flatStr = flattened2str(configobj.flatten_errors(self, ans)) raise RuntimeError("Validation error: "+flatStr) # N...
rely on the idxHint arg so we don't have to search the __paramList # every time this is called, which could really slows things down. assert idxHint is not None, "ConfigObjPars relies on a valid idxHint" assert name == self.__paramList[idxHint].name, \ 'Error in setParam, name: "'+name+'" != name at idxHint: "'+\ self....
def saveParList(self, *args, **kw): """Write parameter data to filename (string or filehandle)""" if 'filename' in kw: filename = kw['filename'] if not filename: filename = self.getFilename() if not filename: raise ValueError("No filename specified to save parameters") if hasattr(filename,'write'): fh = filename absFil...
numpars -= 1 if not self.final_comment: self.final_comment = [''] # force \n at EOF # Empty the ConfigObj version of section.defaults since that is based # on an assumption incorrect for us, and override with our own list. # THIS IS A BIT OF MONKEY-PATCHING! WATCH FUTURE VERSION CHANGES! # See Trac ticket #762. while l...
in self._neverWrite: self.defaults.append(key) # Note also that we are only overwriting the top/main section's # "defaults" list, but EVERY [sub-]section has such an attribute... # Now write to file, delegating work to ConfigObj (note that ConfigObj # write() skips any items listed by name in the self.defaults list) se...
# reset our own ConfigObj filename attr self.debug('Keys not written: '+str(self.defaults)) return retval
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 ru...
\ 'ConfigObjPars subclass, or you must supply a "run" '+ \ 'function in your package.')
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...
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 retv...
try and see if there is a matching .cfgspc file in/under an # associated package, if one is defined. if self.__assocPkg is not None: x, theFile = findCfgFileForPkg(None, '.cfgspc', pkgObj = self.__assocPkg, taskName = self.__taskName) return theFile # Finally try to import the task name and see if there is a .cfgspc # ...
self.__taskName) if os.path.exists(theFile): return theFile # unfound raise NoCfgFileError('Unfound config-spec file for task: "'+ \ self.__taskName+'"')
def _getParamsFromConfigDict(self, cfgObj, scopePrefix='', initialPass=False, dumpCfgspcTo=None): """ Walk the given ConfigObj dict pulling out IRAF-like parameters into a list. Since this operates on a dict this can be called recursively. This is also our chance to find and pull out triggers and such dependencies. """...
# FOR SECURITY: the following 3 chunks of data, # _allTriggers, _allDepdcs, _allExecutes, # are collected ONLY from the .cfgspc file self._allTriggers = {} self._allDepdcs = {} self._allExecutes = {} # start walking ("tell yer story walkin, buddy") # NOTE: this relies on the "in" operator returning keys in the # order ...