INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Return the number of extname extensions defaulting to counting the number of SCI extensions.
def countExtn(fimg, extname='SCI'): """ Return the number of 'extname' extensions, defaulting to counting the number of SCI extensions. """ closefits = False if isinstance(fimg, string_types): fimg = fits.open(fimg) closefits = True n = 0 for e in fimg: if 'extn...
Returns the PyFITS extension corresponding to extension specified in filename.
def getExtn(fimg, extn=None): """ Returns the PyFITS extension corresponding to extension specified in filename. Defaults to returning the first extension with data or the primary extension, if none have data. If a non-existent extension has been specified, it raises a `KeyError` exception. ...
Search a directory for full filename with optional path.
def findFile(input): """Search a directory for full filename with optional path.""" # If no input name is provided, default to returning 'no'(FALSE) if not input: return no # We use 'osfn' here to insure that any IRAF variables are # expanded out before splitting out the path... _fdir,...
Checks to see if file specified exists in current or specified directory.
def checkFileExists(filename, directory=None): """ Checks to see if file specified exists in current or specified directory. Default is current directory. Returns 1 if it exists, 0 if not found. """ if directory is not None: fname = os.path.join(directory,filename) else: fname...
Copy a file whole from input to output.
def copyFile(input, output, replace=None): """Copy a file whole from input to output.""" _found = findFile(output) if not _found or (_found and replace): shutil.copy2(input, output)
Utility function for deleting a list of files or a single file.
def removeFile(inlist): """ Utility function for deleting a list of files or a single file. This function will automatically delete both files of a GEIS image, just like 'iraf.imdelete'. """ if not isinstance(inlist, string_types): # We do have a list, so delete all filenames in list. ...
This function will return the index of the extension in a multi - extension FITS file which contains the desired keyword with the given value.
def findKeywordExtn(ft, keyword, value=None): """ This function will return the index of the extension in a multi-extension FITS file which contains the desired keyword with the given value. """ i = 0 extnum = -1 # Search through all the extensions in the FITS object for chip in ft: ...
Returns the list number of the extension corresponding to EXTNAME given.
def findExtname(fimg, extname, extver=None): """ Returns the list number of the extension corresponding to EXTNAME given. """ i = 0 extnum = None for chip in fimg: hdr = chip.header if 'EXTNAME' in hdr: if hdr['EXTNAME'].strip() == extname.upper(): if...
Returns the next non - blank line in an ASCII file.
def rAsciiLine(ifile): """Returns the next non-blank line in an ASCII file.""" _line = ifile.readline().strip() while len(_line) == 0: _line = ifile.readline().strip() return _line
List IRAF variables.
def listVars(prefix="", equals="\t= ", **kw): """List IRAF variables.""" keylist = getVarList() if len(keylist) == 0: print('No IRAF variables defined') else: keylist.sort() for word in keylist: print("%s%s%s%s" % (prefix, word, equals, envget(word)))
Undo Python conversion of CL parameter or variable name.
def untranslateName(s): """Undo Python conversion of CL parameter or variable name.""" s = s.replace('DOT', '.') s = s.replace('DOLLAR', '$') # delete 'PY' at start of name components if s[:2] == 'PY': s = s[2:] s = s.replace('.PY', '.') return s
Get value of IRAF or OS environment variable.
def envget(var, default=None): """Get value of IRAF or OS environment variable.""" if 'pyraf' in sys.modules: #ONLY if pyraf is already loaded, import iraf into the namespace from pyraf import iraf else: # else set iraf to None so it knows to not use iraf's environment iraf ...
Convert IRAF virtual path name to OS pathname.
def osfn(filename): """Convert IRAF virtual path name to OS pathname.""" # Try to emulate the CL version closely: # # - expands IRAF virtual file names # - strips blanks around path components # - if no slashes or relative paths, return relative pathname # - otherwise return absolute pathna...
Returns true if CL variable is defined.
def defvar(varname): """Returns true if CL variable is defined.""" if 'pyraf' in sys.modules: #ONLY if pyraf is already loaded, import iraf into the namespace from pyraf import iraf else: # else set iraf to None so it knows to not use iraf's environment iraf = None if i...
Set IRAF environment variables.
def set(*args, **kw): """Set IRAF environment variables.""" if len(args) == 0: if len(kw) != 0: # normal case is only keyword,value pairs for keyword, value in kw.items(): keyword = untranslateName(keyword) svalue = str(value) _var...
Print value of IRAF or OS environment variables.
def show(*args, **kw): """Print value of IRAF or OS environment variables.""" if len(kw): raise TypeError('unexpected keyword argument: %r' % list(kw)) if args: for arg in args: print(envget(arg)) else: # print them all listVars(prefix=" ", equals="=")
Unset IRAF environment variables.
def unset(*args, **kw): """ Unset IRAF environment variables. This is not a standard IRAF task, but it is obviously useful. It makes the resulting variables undefined. It silently ignores variables that are not defined. It does not change the os environment variables. """ if len(kw) != ...
Expand a string with embedded IRAF variables ( IRAF virtual filename ).
def Expand(instring, noerror=0): """ Expand a string with embedded IRAF variables (IRAF virtual filename). Allows comma-separated lists. Also uses os.path.expanduser to replace '~' symbols. Set the noerror flag to silently replace undefined variables with just the variable name or null (so Ex...
Expand a string with embedded IRAF variables ( IRAF virtual filename ).
def _expand1(instring, noerror): """Expand a string with embedded IRAF variables (IRAF virtual filename).""" # first expand names in parentheses # note this works on nested names too, expanding from the # inside out (just like IRAF) mm = __re_var_paren.search(instring) while mm is not None: ...
Check if this is a legal date in the Julian calendar
def legal_date(year, month, day): '''Check if this is a legal date in the Julian calendar''' daysinmonth = month_length(year, month) if not (0 < day <= daysinmonth): raise ValueError("Month {} doesn't have a day {}".format(month, day)) return True
Calculate Julian calendar date from Julian day
def from_jd(jd): '''Calculate Julian calendar date from Julian day''' jd += 0.5 z = trunc(jd) a = z b = a + 1524 c = trunc((b - 122.1) / 365.25) d = trunc(365.25 * c) e = trunc((b - d) / 30.6001) if trunc(e < 14): month = e - 1 else: month = e - 13 if trun...
Convert to Julian day using astronomical years ( 0 = 1 BC - 1 = 2 BC )
def to_jd(year, month, day): '''Convert to Julian day using astronomical years (0 = 1 BC, -1 = 2 BC)''' legal_date(year, month, day) # Algorithm as given in Meeus, Astronomical Algorithms, Chapter 7, page 61 if month <= 2: year -= 1 month += 12 return (trunc((365.25 * (year + 471...
Test for delay of start of new year and to avoid
def delay_1(year): '''Test for delay of start of new year and to avoid''' # Sunday, Wednesday, and Friday as start of the new year. months = trunc(((235 * year) - 234) / 19) parts = 12084 + (13753 * months) day = trunc((months * 29) + parts / 25920) if ((3 * (day + 1)) % 7) < 3: day += ...
Check for delay in start of new year due to length of adjacent years
def delay_2(year): '''Check for delay in start of new year due to length of adjacent years''' last = delay_1(year - 1) present = delay_1(year) next_ = delay_1(year + 1) if next_ - present == 356: return 2 elif present - last == 382: return 1 else: return 0
How many days are in a given month of a given year
def month_days(year, month): '''How many days are in a given month of a given year''' if month > 13: raise ValueError("Incorrect month index") # First of all, dispose of fixed-length 29 day months if month in (IYYAR, TAMMUZ, ELUL, TEVETH, VEADAR): return 29 # If it's not a leap yea...
Input GEIS files input will be read and converted to a new GEIS file whose byte - order has been swapped from its original state.
def byteswap(input,output=None,clobber=True): """Input GEIS files "input" will be read and converted to a new GEIS file whose byte-order has been swapped from its original state. Parameters ---------- input - str Full filename with path of input GEIS image header file output - str ...
Initialises the device if required then enters a read loop taking data from the provider and passing it to the handler. It will continue until either breakRead is true or the duration ( if provided ) has passed.: return:
def start(self, measurementId, durationInSeconds=None): """ Initialises the device if required then enters a read loop taking data from the provider and passing it to the handler. It will continue until either breakRead is true or the duration (if provided) has passed. :return: ...
Yields the analysed wav data.: param targetId:: return:
def get(self, targetId): """ Yields the analysed wav data. :param targetId: :return: """ result = self._targetController.analyse(targetId) if result: if len(result) == 2: if result[1] == 404: return result ...
stores a new target.: param targetId: the target to store.: return:
def put(self, targetId): """ stores a new target. :param targetId: the target to store. :return: """ json = request.get_json() if 'hinge' in json: logger.info('Storing target ' + targetId) if self._targetController.storeFromHinge(targetId, ...
Return a datetime for the input floating point Julian Day Count
def to_datetime(jdc): '''Return a datetime for the input floating point Julian Day Count''' year, month, day = gregorian.from_jd(jdc) # in jdc: 0.0 = noon, 0.5 = midnight # the 0.5 changes it to 0.0 = midnight, 0.5 = noon frac = (jdc + 0.5) % 1 hours = int(24 * frac) mfrac = frac * 24 - h...
Slightly introverted parser for lists of dot - notation nested fields i. e. period. di period. fhr = > { period: { di: {} fhr: {} }}
def dict_from_qs(qs): ''' Slightly introverted parser for lists of dot-notation nested fields i.e. "period.di,period.fhr" => {"period": {"di": {}, "fhr": {}}} ''' entries = qs.split(',') if qs.strip() else [] entries = [entry.strip() for entry in entries] def _dict_from_qs(line, d): ...
Same as dict_from_qs but in reverse i. e. { period: { di: {} fhr: {} }} = > period. di period. fhr
def qs_from_dict(qsdict, prefix=""): ''' Same as dict_from_qs, but in reverse i.e. {"period": {"di": {}, "fhr": {}}} => "period.di,period.fhr" ''' prefix = prefix + '.' if prefix else "" def descend(qsd): for key, val in sorted(qsd.items()): if val: yield qs_...
Set up connection before executing function commit and close connection afterwards. Unless a connection already has been created.
def dbcon(func): """Set up connection before executing function, commit and close connection afterwards. Unless a connection already has been created.""" @wraps(func) def wrapper(*args, **kwargs): self = args[0] if self.dbcon is None: # set up connection self.dbco...
Add new sensor to the database
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 exi...
Remove sensor from the database
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,))
Synchronise data
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)] ...
List all tmpo - blocks in the database
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]] """ ...
Create data Series
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 ...
Create data frame
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.Ti...
Get the first available timestamp for a sensor
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 ...
Get the theoretical last timestamp for a sensor
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 ...
Parameters ---------- sid: str SensorId epoch: bool default False If True return as epoch If False return as pd. Timestamp
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,...
Numpy: Modifying Array Values http:// docs. scipy. org/ doc/ numpy/ reference/ arrays. nditer. html
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
Take a check function signature ( string ) and parse it to get a dict of the keyword args and their values.
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 ...
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 )
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 STA...
Alter the passed function signature string to add the given kewords
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 += ", " ...
Defines the gaussian function to be used as the model.
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)) statu...
Return the gaussian fit as an object.
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 m...
filter lets django managers use objects. filter on a hashable object.
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)
this method allows django managers use objects. get_or_create and objects. update_or_create on a hashable object.
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'] ...
a private method that persists an estimator object to the filesystem
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() se...
a private method that loads an estimator object from the filesystem
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()
Return an Estimator object given the path of the file relative to the MEDIA_ROOT
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
Return our application dir. Create it if it doesn t exist.
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 ...
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 ConfigObjPars () ctor setAllToDefaults - bool - if theTask is a pkg name ...
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, pass...
Read a config file and pull out the value of a given keyword.
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...
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 task name is known it is given as taskName otherwise one is determined usin...
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 '....
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 }
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'): retv...
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. If recurse is True it will check subdirectories. If aTask is N...
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 f...
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 exists a ~/. teal/ <taskname >. cfg file 3 - ...
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 match...
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.
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 = findCfgFileFo...
See if we have write - privileges to this file. If we do and we are not supposed to then fix that case.
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 grou...
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.
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 = {} ...
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.
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,...
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.
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] # ...
Find the given par. Return tuple: ( its own ( sub - ) dict its value ).
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 goe...
Sets a par s value without having to give its scope/ section.
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
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 than once in configObj ( e. g. within two diff...
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 key...
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.
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 (...
Return True if this string name denotes a hidden par or section
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
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::
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 ...
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.
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. """ ...
Set or reset the internal param list from the dict s contents.
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. ...
Return a par list just like ours but with all default values.
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 se...
Find the ConfigObj entry. Update the __paramList.
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] ...
Write parameter data to filename ( string or filehandle )
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 ...
This may be overridden by a subclass.
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(s...
Print all the trigger logic to a string and return it.
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) ...
Given a config file find its associated config - spec file and return the full pathname of the file.
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 o...
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.
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...
For a given item ( scope + name ) return all strings ( in a tuple ) that it is meant to trigger if any exist. Returns None is none.
def getTriggerStrings(self, parScope, parName): """ For a given item (scope + name), return all strings (in a tuple) that it is meant to trigger, if any exist. Returns None is none. """ # The data structure of _allTriggers was chosen for how easily/quickly # this particular access can b...
For a given item ( scope + name ) return all strings ( in a tuple ) that it is meant to execute if any exist. Returns None is none.
def getExecuteStrings(self, parScope, parName): """ For a given item (scope + name), return all strings (in a tuple) that it is meant to execute, if any exist. Returns None is none. """ # The data structure of _allExecutes was chosen for how easily/quickly # this particular access can b...
Return a list in order of any parameters marked with pos = N in the. cfgspc file.
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 r...
Return a dict of all normal dict parameters - that is all parameters NOT marked with pos = N in the. cfgspc file. This will also exclude all hidden parameters ( metadata rules etc ).
def getKwdArgs(self, flatten = False): """ Return a dict of all normal dict parameters - that is, all parameters NOT marked with "pos=N" in the .cfgspc file. This will also exclude all hidden parameters (metadata, rules, etc). """ # Start with a full deep-copy. What complicate...
For the given item name ( and scope ) we are being asked to try the given value to see if it would pass validation. We are not to set it but just try it. We return a tuple: If it fails we return: ( False the last known valid value ). On success we return: ( True None ).
def tryValue(self, name, val, scope=''): """ For the given item name (and scope), we are being asked to try the given value to see if it would pass validation. We are not to set it, but just try it. We return a tuple: If it fails, we return: (False, the last known valid va...
Use ConfigObj s get_extra_values () call to find any extra/ unknown parameters we may have loaded. Return a string similar to findTheLost. If deleteAlso is True this will also delete any extra/ unknown items.
def listTheExtras(self, deleteAlso): """ Use ConfigObj's get_extra_values() call to find any extra/unknown parameters we may have loaded. Return a string similar to findTheLost. If deleteAlso is True, this will also delete any extra/unknown items. """ # get list of extras ...
Reloads the measurements from the backing store.: return: 200 if success.
def get(self): """ Reloads the measurements from the backing store. :return: 200 if success. """ try: self._measurementController.reloadCompletedMeasurements() return None, 200 except: logger.exception("Failed to reload measurements") ...
Writes each sample to a csv file.: param data: the samples.: return:
def handle(self, data): """ Writes each sample to a csv file. :param data: the samples. :return: """ self.logger.debug("Handling " + str(len(data)) + " data items") for datum in data: if isinstance(datum, dict): # these have to wrapped ...
Posts to the target to tell it a named measurement is starting.: param measurementId:
def start(self, measurementId): """ Posts to the target to tell it a named measurement is starting. :param measurementId: """ self.sendURL = self.rootURL + measurementId + '/' + self.deviceName self.startResponseCode = self._doPut(self.sendURL)
puts the data in the target.: param data: the data to post.: return:
def handle(self, data): """ puts the data in the target. :param data: the data to post. :return: """ self.dataResponseCode.append(self._doPut(self.sendURL + '/data', data=data))
informs the target the named measurement has completed: param measurementId: the measurement that has completed.: return:
def stop(self, measurementId, failureReason=None): """ informs the target the named measurement has completed :param measurementId: the measurement that has completed. :return: """ if failureReason is None: self.endResponseCode = self._doPut(self.sendURL + "/c...
Convert decimal dotted quad string to long integer
def dottedQuadToNum(ip): """ Convert decimal dotted quad string to long integer >>> int(dottedQuadToNum('1 ')) 1 >>> int(dottedQuadToNum(' 1.2')) 16777218 >>> int(dottedQuadToNum(' 1.2.3 ')) 16908291 >>> int(dottedQuadToNum('1.2.3.4')) 16909060 >>> dottedQuadToNum('255.255.2...
Convert long int to dotted quad string
def numToDottedQuad(num): """ Convert long int to dotted quad string >>> numToDottedQuad(long(-1)) Traceback (most recent call last): ValueError: Not a good numeric IP: -1 >>> numToDottedQuad(long(1)) '0.0.0.1' >>> numToDottedQuad(long(16777218)) '1.0.0.2' >>> numToDottedQuad(lo...
Return numbers from inputs or raise VdtParamError.
def _is_num_param(names, values, to_float=False): """ Return numbers from inputs or raise VdtParamError. Lets ``None`` pass through. Pass in keyword argument ``to_float=True`` to use float for the conversion rather than int. >>> _is_num_param(('', ''), (0, 1.0)) [0, 1] >>> _is_num_para...
A check that tests that a given value is an integer ( int or long ) and optionally between bounds. A negative value is accepted while a float will fail.
def is_integer(value, min=None, max=None): """ A check that tests that a given value is an integer (int, or long) and optionally, between bounds. A negative value is accepted, while a float will fail. If the value is a string, then the conversion is done - if possible. Otherwise a VdtError is r...
A check that tests that a given value is a float ( an integer will be accepted ) and optionally - that it is between bounds.
def is_float(value, min=None, max=None): """ A check that tests that a given value is a float (an integer will be accepted), and optionally - that it is between bounds. If the value is a string, then the conversion is done - if possible. Otherwise a VdtError is raised. This can accept negative...
Check if the value represents a boolean.
def is_boolean(value): """ Check if the value represents a boolean. >>> vtor = Validator() >>> vtor.check('boolean', 0) 0 >>> vtor.check('boolean', False) 0 >>> vtor.check('boolean', '0') 0 >>> vtor.check('boolean', 'off') 0 >>> vtor.check('boolean', 'false') 0 >...
Check that the supplied value is an Internet Protocol address v. 4 represented by a dotted - quad string i. e. 1. 2. 3. 4.
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'. >>> vtor = Validator() >>> vtor.check('ip_addr', '1 ') '1' >>> vtor.check('ip_addr', ' 1.2') '1.2' >>> vtor.check('ip_addr', ' 1.2.3 ')...
Check that the value is a list of values.
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 does no check on list members. >>> vtor = Validator() >>> vtor.check('list', ()) [] >>> vtor.check('list', []) [] >>> ...
Check that the value is a list of integers.
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. Each list member is checked that it is an integer. >>> vtor = Validator() >>> vtor.check('int_list', ()) [] >>> vtor.check(...