INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
stores a chunk of new file this is a nop if the file already exists.: param filename: the filename.: param chunkIdx: the chunk idx.: param totalChunks: the no of chunks expected.: return: the no of bytes written and 200 or 400 if nothing was written.
def put(self, filename, chunkIdx, totalChunks): """ stores a chunk of new file, this is a nop if the file already exists. :param filename: the filename. :param chunkIdx: the chunk idx. :param totalChunks: the no of chunks expected. :return: the no of bytes written and 200...
Deletes the named file.: param name: the name.: return: 200 if it was deleted 404 if it doesn t exist or 500 for anything else.
def delete(self, name): """ Deletes the named file. :param name: the name. :return: 200 if it was deleted, 404 if it doesn't exist or 500 for anything else. """ try: result = self._uploadController.delete(name) return None, 200 if result is not Non...
Stores a new target.: param name: the name.: param start: start time.: param end: end time.: return:
def put(self, name, start, end): """ Stores a new target. :param name: the name. :param start: start time. :param end: end time. :return: """ entry = self._uploadController.getEntry(name) if entry is not None: return None, 200 if self._...
: param name:: param start:: param end:: param resolution:: param window:: return: an analysed file.
def get(self, name, start, end, resolution, window): """ :param name: :param start: :param end: :param resolution: :param window: :return: an analysed file. """ logger.info( 'Analysing ' + name + ' from ' + start + ' to ' + end + ' at '...
Completes the specified upload.: param filename: the filename.: param totalChunks: the no of chunks.: param status: the status of the upload.: return: 200.
def put(self, filename, totalChunks, status): """ Completes the specified upload. :param filename: the filename. :param totalChunks: the no of chunks. :param status: the status of the upload. :return: 200. """ logger.info('Completing ' + filename + ' - ' +...
Patches the metadata associated with the new measurement if this impacts the measurement length then a new measurement is created otherwise it just updates it in place.: param measurementId:: return:
def patch(self, measurementId): """ Patches the metadata associated with the new measurement, if this impacts the measurement length then a new measurement is created otherwise it just updates it in place. :param measurementId: :return: """ data = request.get_j...
Initiates a new measurement. Accepts a json payload with the following attributes ;
def put(self, measurementId): """ Initiates a new measurement. Accepts a json payload with the following attributes; * duration: in seconds * startTime OR delay: a date in YMD_HMS format or a delay in seconds * description: some free text information about the measurement ...
Calculates an absolute start time from the json payload. This is either the given absolute start time ( + 2s ) or the time in delay seconds time. If the resulting date is in the past then now is returned instead.: param json: the payload from the UI: return: the absolute start time.
def _calculateStartTime(self, json): """ Calculates an absolute start time from the json payload. This is either the given absolute start time (+2s) or the time in delay seconds time. If the resulting date is in the past then now is returned instead. :param json: the payload from the UI ...
Adds the delay in seconds to the start time.: param start:: param delay:: return: a datetimem for the specified point in time.
def _getAbsoluteTime(self, start, delay): """ Adds the delay in seconds to the start time. :param start: :param delay: :return: a datetimem for the specified point in time. """ return start + datetime.timedelta(days=0, seconds=delay)
Deletes the named measurement.: return: 200 if something was deleted 404 if the measurement doesn t exist 500 in any other case.
def delete(self, measurementId): """ Deletes the named measurement. :return: 200 if something was deleted, 404 if the measurement doesn't exist, 500 in any other case. """ message, count, deleted = self._measurementController.delete(measurementId) if count == 0: ...
Initialises the measurement session from the given device.: param measurementId:: param deviceId:: return:
def put(self, measurementId, deviceId): """ Initialises the measurement session from the given device. :param measurementId: :param deviceId: :return: """ logger.info('Starting measurement ' + measurementId + ' for ' + deviceId) if self._measurementControl...
Store a bunch of data for this measurement session.: param measurementId:: param deviceId:: return:
def put(self, measurementId, deviceId): """ Store a bunch of data for this measurement session. :param measurementId: :param deviceId: :return: """ data = request.get_json() if data is not None: parsedData = json.loads(data) logger....
Fails the measurement for this device.: param measurementId: the measurement name.: param deviceId: the device name.: return: 200 if
def put(self, measurementId, deviceId): """ Fails the measurement for this device. :param measurementId: the measurement name. :param deviceId: the device name. :return: 200 if """ payload = request.get_json() failureReason = json.loads(payload).get('failu...
Puts a new device into the device store: param deviceId:: return:
def put(self, deviceId): """ Puts a new device into the device store :param deviceId: :return: """ device = request.get_json() logger.debug("Received /devices/" + deviceId + " - " + str(device)) self._deviceController.accept(deviceId, device) retur...
Print a list of strings centered in columns. Determine the number of columns and lines on the fly. Return the result ready to print. in_strings is a list/ tuple/ iterable of strings min_pad is number of spaces to appear on each side of a single string ( so you will see twice this many spaces between 2 strings )
def printColsAuto(in_strings, term_width=80, min_pad=1): """ Print a list of strings centered in columns. Determine the number of columns and lines on the fly. Return the result, ready to print. in_strings is a list/tuple/iterable of strings min_pad is number of spaces to appear on each side of a sing...
Print elements of list in cols columns
def printCols(strlist,cols=5,width=80): """Print elements of list in cols columns""" # This may exist somewhere in the Python standard libraries? # Should probably rewrite this, it is pretty crude. nlines = (len(strlist)+cols-1)//cols line = nlines*[""] for i in range(len(strlist)): c...
Strip single or double quotes off string ; remove embedded quote pairs
def stripQuotes(value): """Strip single or double quotes off string; remove embedded quote pairs""" if value[:1] == '"': value = value[1:] if value[-1:] == '"': value = value[:-1] # replace "" with " value = re.sub(_re_doubleq2, '"', value) elif value[:1] == "'"...
Take a string as input ( e. g. a line in a csv text file ) and break it into tokens separated by commas while ignoring commas embedded inside quoted sections. This is exactly what the csv module is meant for so we * should * be using it save that it has two bugs ( described next ) which limit our use of it. When these ...
def csvSplit(line, delim=',', allowEol=True): """ Take a string as input (e.g. a line in a csv text file), and break it into tokens separated by commas while ignoring commas embedded inside quoted sections. This is exactly what the 'csv' module is meant for, so we *should* be using it, save that it has...
Same thing as glob. glob but recursively checks subdirs.
def rglob(root, pattern): """ Same thing as glob.glob, but recursively checks subdirs. """ # Thanks to Alex Martelli for basics on Stack Overflow retlist = [] if None not in (pattern, root): for base, dirs, files in os.walk(root): goodfiles = fnmatch.filter(files, pattern) ...
Set a file named fname to be writable ( or not ) by user with the option to ignore errors. There is nothing ground - breaking here but I was annoyed with having to repeate this little bit of code.
def setWritePrivs(fname, makeWritable, ignoreErrors=False): """ Set a file named fname to be writable (or not) by user, with the option to ignore errors. There is nothing ground-breaking here, but I was annoyed with having to repeate this little bit of code. """ privs = os.stat(fname).st_mode try: ...
Remove escapes from in front of quotes ( which IRAF seems to just stick in for fun sometimes. ) Remove \ - newline too. If quoted is true removes all blanks following \ - newline ( which is a nasty thing IRAF does for continuations inside quoted strings. ) XXX Should we remove \\ too?
def removeEscapes(value, quoted=0): """Remove escapes from in front of quotes (which IRAF seems to just stick in for fun sometimes.) Remove \-newline too. If quoted is true, removes all blanks following \-newline (which is a nasty thing IRAF does for continuations inside quoted strings.) XXX S...
Convert CL parameter or variable name to Python - acceptable name
def translateName(s, dot=0): """Convert CL parameter or variable name to Python-acceptable name Translate embedded dollar signs to 'DOLLAR' Add 'PY' prefix to components that are Python reserved words Add 'PY' prefix to components start with a number If dot != 0, also replaces '.' with 'DOT' "...
In case the _default_root value is required you may safely call this ahead of time to ensure that it has been initialized. If it has already been this is a no - op.
def init_tk_default_root(withdraw=True): """ In case the _default_root value is required, you may safely call this ahead of time to ensure that it has been initialized. If it has already been, this is a no-op. """ if not capable.OF_GRAPHICS: raise RuntimeError("Cannot run this command with...
Read a line from file while running Tk mainloop.
def tkreadline(file=None): """Read a line from file while running Tk mainloop. If the file is not line-buffered then the Tk mainloop will stop running after one character is typed. The function will still work but Tk widgets will stop updating. This should work OK for stdin and other line-buffer...
Given a URL try to pop it up in a browser on most platforms. brow_bin is only used on OS s where there is no open or start cmd.
def launchBrowser(url, brow_bin='mozilla', subj=None): """ Given a URL, try to pop it up in a browser on most platforms. brow_bin is only used on OS's where there is no "open" or "start" cmd. """ if not subj: subj = url # Tries to use webbrowser module on most OSes, unless a system command # i...
Read nbytes characters from file while running Tk mainloop
def read(self, file, nbytes): """Read nbytes characters from file while running Tk mainloop""" if not capable.OF_GRAPHICS: raise RuntimeError("Cannot run this command without graphics") if isinstance(file, int): fd = file else: # Otherwise, assume we h...
Read waiting data and terminate Tk mainloop if done
def _read(self, fd, mask): """Read waiting data and terminate Tk mainloop if done""" try: # if EOF was encountered on a tty, avoid reading again because # it actually requests more data if select.select([fd],[],[],0)[0]: snew = os.read(fd, self.nbytes)...
reads a delimited file and converts into a Signal: param filename: string: param timeColumnIdx: 0 indexed column number: param dataColumnIdx: 0 indexed column number: param delimiter: char: return a Signal instance
def loadSignalFromDelimitedFile(filename, timeColumnIdx=0, dataColumnIdx=1, delimiter=',', skipHeader=0) -> Signal: """ reads a delimited file and converts into a Signal :param filename: string :param timeColumnIdx: 0 indexed column number :param dataColumnIdx: 0 indexed column number :param delimit...
reads a wav file into a Signal and scales the input so that the sample are expressed in real world values ( as defined by the calibration signal ).: param inputSignalFile: a path to the input signal file: param calibrationSignalFile: a path the calibration signal file: param calibrationRealWorldValue: the real world va...
def loadSignalFromWav(inputSignalFile, calibrationRealWorldValue=None, calibrationSignalFile=None, start=None, end=None) -> Signal: """ reads a wav file into a Signal and scales the input so that the sample are expressed in real world values (as defined by the calibration signal). :par...
reads a wav file into a Signal.: param inputSignalFile: a path to the input signal file: param selectedChannel: the channel to read.: param start: the time to start reading from in HH: mm: ss. SSS format.: param end: the time to end reading from in HH: mm: ss. SSS format.: returns: Signal.
def readWav(inputSignalFile, selectedChannel=1, start=None, end=None) -> Signal: """ reads a wav file into a Signal. :param inputSignalFile: a path to the input signal file :param selectedChannel: the channel to read. :param start: the time to start reading from in HH:mm:ss.SSS format. :param end: t...
A factory method for loading a tri axis measurement from a single file.: param filename: the file to load from.: param timeColumnIdx: the column containing time data.: param xIdx: the column containing x axis data.: param yIdx: the column containing y axis data.: param zIdx: the column containing z axis data.: param de...
def loadTriAxisSignalFromFile(filename, timeColumnIdx=0, xIdx=1, yIdx=2, zIdx=3, delimiter=',', skipHeader=0) -> TriAxisSignal: """ A factory method for loading a tri axis measurement from a single file. :param filename: the file to load from. :param timeColumnIdx: the colu...
analyses the source and returns a PSD segment is set to get ~1Hz frequency resolution: param ref: the reference value for dB purposes.: param segmentLengthMultiplier: allow for increased resolution.: param mode: cq or none.: return: f: ndarray Array of sample frequencies. Pxx: ndarray Power spectral density.
def psd(self, ref=None, segmentLengthMultiplier=1, mode=None, **kwargs): """ analyses the source and returns a PSD, segment is set to get ~1Hz frequency resolution :param ref: the reference value for dB purposes. :param segmentLengthMultiplier: allow for increased resolution. :pa...
analyses the source to generate the linear spectrum.: param ref: the reference value for dB purposes.: param segmentLengthMultiplier: allow for increased resolution.: param mode: cq or none.: return: f: ndarray Array of sample frequencies. Pxx: ndarray linear spectrum.
def spectrum(self, ref=None, segmentLengthMultiplier=1, mode=None, **kwargs): """ analyses the source to generate the linear spectrum. :param ref: the reference value for dB purposes. :param segmentLengthMultiplier: allow for increased resolution. :param mode: cq or none. ...
analyses the source to generate the max values per bin per segment: param ref: the reference value for dB purposes.: param segmentLengthMultiplier: allow for increased resolution.: param mode: cq or none.: return: f: ndarray Array of sample frequencies. Pxx: ndarray linear spectrum max values.
def peakSpectrum(self, ref=None, segmentLengthMultiplier=1, mode=None, window='hann'): """ analyses the source to generate the max values per bin per segment :param ref: the reference value for dB purposes. :param segmentLengthMultiplier: allow for increased resolution. :param mo...
analyses the source to generate a spectrogram: param ref: the reference value for dB purposes.: param segmentLengthMultiplier: allow for increased resolution.: return: t: ndarray Array of time slices. f: ndarray Array of sample frequencies. Pxx: ndarray linear spectrum values.
def spectrogram(self, ref=None, segmentLengthMultiplier=1, window='hann'): """ analyses the source to generate a spectrogram :param ref: the reference value for dB purposes. :param segmentLengthMultiplier: allow for increased resolution. :return: t : ndarray ...
Creates a copy of the signal with the low pass applied args specifed are passed through to _butter.: return:
def lowPass(self, *args): """ Creates a copy of the signal with the low pass applied, args specifed are passed through to _butter. :return: """ return Signal(self._butter(self.samples, 'low', *args), fs=self.fs)
Creates a copy of the signal with the high pass applied args specifed are passed through to _butter.: return:
def highPass(self, *args): """ Creates a copy of the signal with the high pass applied, args specifed are passed through to _butter. :return: """ return Signal(self._butter(self.samples, 'high', *args), fs=self.fs)
Applies a digital butterworth filter via filtfilt at the specified f3 and order. Default values are set to correspond to apparently sensible filters that distinguish between vibration and tilt from an accelerometer.: param data: the data to filter.: param btype: high or low.: param f3: the f3 of the filter.: param orde...
def _butter(self, data, btype, f3=2, order=2): """ Applies a digital butterworth filter via filtfilt at the specified f3 and order. Default values are set to correspond to apparently sensible filters that distinguish between vibration and tilt from an accelerometer. :param data: the dat...
gets the named analysis on the given axis and caches the result ( or reads from the cache if data is available already ): param axis: the named axis.: param analysis: the analysis name.: return: the analysis tuple.
def _getAnalysis(self, axis, analysis, ref=None): """ gets the named analysis on the given axis and caches the result (or reads from the cache if data is available already) :param axis: the named axis. :param analysis: the analysis name. :return: the analysis tuple. ...
Checks if a given date is a legal positivist date
def legal_date(year, month, day): '''Checks if a given date is a legal positivist date''' try: assert year >= 1 assert 0 < month <= 14 assert 0 < day <= 28 if month == 14: if isleap(year + YEAR_EPOCH - 1): assert day <= 2 else: ...
Convert a Positivist date to Julian day count.
def to_jd(year, month, day): '''Convert a Positivist date to Julian day count.''' legal_date(year, month, day) gyear = year + YEAR_EPOCH - 1 return ( gregorian.EPOCH - 1 + (365 * (gyear - 1)) + floor((gyear - 1) / 4) + (-floor((gyear - 1) / 100)) + floor((gyear - 1) / 400) + (mo...
Convert a Julian day count to Positivist date.
def from_jd(jd): '''Convert a Julian day count to Positivist date.''' try: assert jd >= EPOCH except AssertionError: raise ValueError('Invalid Julian day') depoch = floor(jd - 0.5) + 0.5 - gregorian.EPOCH quadricent = floor(depoch / gregorian.INTERCALATION_CYCLE_DAYS) dqc = dep...
Give the name of the month and day for a given date.
def dayname(year, month, day): ''' Give the name of the month and day for a given date. Returns: tuple month_name, day_name ''' legal_date(year, month, day) yearday = (month - 1) * 28 + day if isleap(year + YEAR_EPOCH - 1): dname = data.day_names_leap[yearday - 1] else...
: return: true if the lastUpdateTime is more than maxAge seconds ago.
def hasExpired(self): """ :return: true if the lastUpdateTime is more than maxAge seconds ago. """ return (datetime.datetime.utcnow() - self.lastUpdateTime).total_seconds() > self.maxAgeSeconds
Adds the named device to the store.: param deviceId:: param device:: return:
def accept(self, deviceId, device): """ Adds the named device to the store. :param deviceId: :param device: :return: """ storedDevice = self.devices.get(deviceId) if storedDevice is None: logger.info('Initialising device ' + deviceId) ...
The devices in the given state or all devices is the arg is none.: param status: the state to match against.: return: the devices
def getDevices(self, status=None): """ The devices in the given state or all devices is the arg is none. :param status: the state to match against. :return: the devices """ return [d for d in self.devices.values() if status is None or d.payload.get('status') == status]
gets the named device.: param id: the id.: return: the device
def getDevice(self, id): """ gets the named device. :param id: the id. :return: the device """ return next(iter([d for d in self.devices.values() if d.deviceId == id]), None)
A housekeeping function which runs in a worker thread and which evicts devices that haven t sent an update for a while.
def _evictStaleDevices(self): """ A housekeeping function which runs in a worker thread and which evicts devices that haven't sent an update for a while. """ while self.running: expiredDeviceIds = [key for key, value in self.devices.items() if value.hasExpired()] ...
Schedules the requested measurement session with all INITIALISED devices.: param measurementId:: param duration:: param start:: return: a dict of device vs status.
def scheduleMeasurement(self, measurementId, duration, start): """ Schedules the requested measurement session with all INITIALISED devices. :param measurementId: :param duration: :param start: :return: a dict of device vs status. """ # TODO subtract 1s fr...
Allows the UI to update parameters ensuring that all devices are kept in sync. Payload is json in TargetState format.: return:
def patch(self): """ Allows the UI to update parameters ensuring that all devices are kept in sync. Payload is json in TargetState format. :return: """ # TODO block until all devices have updated? json = request.get_json() logger.info("Updating target stat...
Parse a comma - separated list of values or a filename ( starting with
def list_parse(name_list): """Parse a comma-separated list of values, or a filename (starting with @) containing a list value on each line. """ if name_list and name_list[0] == '@': value = name_list[1:] if not os.path.exists(value): log.warning('The file %s does not exist' ...
Create the minimum match dictionary of keys
def _mmInit(self): """Create the minimum match dictionary of keys""" # cache references to speed up loop a bit mmkeys = {} mmkeysGet = mmkeys.setdefault minkeylength = self.minkeylength for key in self.data.keys(): # add abbreviations as short as minkeylength ...
Hook to resolve ambiguities in selected keys
def resolve(self, key, keylist): """Hook to resolve ambiguities in selected keys""" raise AmbiguousKeyError("Ambiguous key "+ repr(key) + ", could be any of " + str(sorted(keylist)))
Add a new key/ item pair to the dictionary. Resets an existing key value only if this is an exact match to a known key.
def add(self, key, item): """Add a new key/item pair to the dictionary. Resets an existing key value only if this is an exact match to a known key.""" mmkeys = self.mmkeys if mmkeys is not None and not (key in self.data): # add abbreviations as short as minkeylength ...
Raises exception if key is ambiguous
def get(self, key, failobj=None, exact=0): """Raises exception if key is ambiguous""" if not exact: key = self.getfullkey(key,new=1) return self.data.get(key,failobj)
Raises an exception if key is ambiguous
def _has(self, key, exact=0): """Raises an exception if key is ambiguous""" if not exact: key = self.getfullkey(key,new=1) return key in self.data
Returns a list of all the matching values for key containing a single entry for unambiguous matches and multiple entries for ambiguous matches.
def getall(self, key, failobj=None): """Returns a list of all the matching values for key, containing a single entry for unambiguous matches and multiple entries for ambiguous matches.""" if self.mmkeys is None: self._mmInit() k = self.mmkeys.get(key) if not k: return fai...
Returns a list of the full key names ( not the items ) for all the matching values for key. The list will contain a single entry for unambiguous matches and multiple entries for ambiguous matches.
def getallkeys(self, key, failobj=None): """Returns a list of the full key names (not the items) for all the matching values for key. The list will contain a single entry for unambiguous matches and multiple entries for ambiguous matches.""" if self.mmkeys is None: self._mmInit(...
Returns failobj if key is not found or is ambiguous
def get(self, key, failobj=None, exact=0): """Returns failobj if key is not found or is ambiguous""" if not exact: try: key = self.getfullkey(key) except KeyError: return failobj return self.data.get(key,failobj)
Returns false if key is not found or is ambiguous
def _has(self, key, exact=0): """Returns false if key is not found or is ambiguous""" if not exact: try: key = self.getfullkey(key) return 1 except KeyError: return 0 else: return key in self.data
parameter factory function
def parFactory(fields, strict=0): """parameter factory function fields is a list of the comma-separated fields (as in the .par file). Each entry is a string or None (indicating that field was omitted.) Set the strict parameter to a non-zero value to do stricter parsing (to find errors in the inpu...
Set cmdline flag
def setCmdline(self,value=1): """Set cmdline flag""" # set through dictionary to avoid extra calls to __setattr__ if value: self.__dict__['flags'] = self.flags | _cmdlineFlag else: self.__dict__['flags'] = self.flags & ~_cmdlineFlag
Set changed flag
def setChanged(self,value=1): """Set changed flag""" # set through dictionary to avoid another call to __setattr__ if value: self.__dict__['flags'] = self.flags | _changedFlag else: self.__dict__['flags'] = self.flags & ~_changedFlag
Return true if this parameter is learned
def isLearned(self, mode=None): """Return true if this parameter is learned Hidden parameters are not learned; automatic parameters inherit behavior from package/cl; other parameters are learned. If mode is set, it determines how automatic parameters behave. If not set, cl.mode ...
Interactively prompt for parameter value
def getWithPrompt(self): """Interactively prompt for parameter value""" if self.prompt: pstring = self.prompt.split("\n")[0].strip() else: pstring = self.name if self.choice: schoice = list(map(self.toString, self.choice)) pstring = pstring...
Return value of this parameter as a string ( or in native format if native is non - zero. )
def get(self, field=None, index=None, lpar=0, prompt=1, native=0, mode="h"): """Return value of this parameter as a string (or in native format if native is non-zero.)""" if field and field != "p_value": # note p_value comes back to this routine, so shortcut that case re...
Set value of this parameter from a string or other value. Field is optional parameter field ( p_prompt p_minimum etc. ) Index is optional array index ( zero - based ). Set check = 0 to assign the value without checking to see if it is within the min - max range or in the choice list.
def set(self, value, field=None, index=None, check=1): """Set value of this parameter from a string or other value. Field is optional parameter field (p_prompt, p_minimum, etc.) Index is optional array index (zero-based). Set check=0 to assign the value without checking to see if it is ...
Check and convert a parameter value.
def checkValue(self,value,strict=0): """Check and convert a parameter value. Raises an exception if the value is not permitted for this parameter. Otherwise returns the value (converted to the right type.) """ v = self._coerceValue(value,strict) return self.chec...
Checks a single value to see if it is in range or choice list
def checkOneValue(self,v,strict=0): """Checks a single value to see if it is in range or choice list Allows indirection strings starting with ")". Assumes v has already been converted to right value by _coerceOneValue. Returns value if OK, or raises ValueError if not OK. ...
Return dpar - style executable assignment for parameter
def dpar(self, cl=1): """Return dpar-style executable assignment for parameter Default is to write CL version of code; if cl parameter is false, writes Python executable code instead. """ sval = self.toString(self.value, quoted=1) if not cl: if sval == "": sv...
Return pretty list description of parameter
def pretty(self,verbose=0): """Return pretty list description of parameter""" # split prompt lines and add blanks in later lines to align them plines = self.prompt.split('\n') for i in range(len(plines)-1): plines[i+1] = 32*' ' + plines[i+1] plines = '\n'.join(plines) nam...
Return. par format string for this parameter
def save(self, dolist=0): """Return .par format string for this parameter If dolist is set, returns fields as a list of strings. Default is to return a single string appropriate for writing to a file. """ quoted = not dolist fields = 7*[""] fields[0] = self.name...
Set choice parameter from string s
def _setChoice(self,s,strict=0): """Set choice parameter from string s""" clist = _getChoice(s,strict) self.choice = list(map(self._coerceValue, clist)) self._setChoiceDict()
Create dictionary for choice list
def _setChoiceDict(self): """Create dictionary for choice list""" # value is name of choice parameter (same as key) self.choiceDict = {} for c in self.choice: self.choiceDict[c] = c
Interactively prompt for parameter if necessary
def _optionalPrompt(self, mode): """Interactively prompt for parameter if necessary Prompt for value if (1) mode is hidden but value is undefined or bad, or (2) mode is query and value was not set on command line Never prompt for "u" mode parameters, which are local variables. ...
Get p_filename field for this parameter
def _getPFilename(self,native,prompt): """Get p_filename field for this parameter Same as get for non-list params """ return self.get(native=native,prompt=prompt)
Get a parameter field value
def _getField(self, field, native=0, prompt=1): """Get a parameter field value""" try: # expand field name using minimum match field = _getFieldDict[field] except KeyError as e: # re-raise the exception with a bit more info raise SyntaxError("Canno...
Set a parameter field value
def _setField(self, value, field, check=1): """Set a parameter field value""" try: # expand field name using minimum match field = _setFieldDict[field] except KeyError as e: raise SyntaxError("Cannot set field " + field + " for parameter " ...
Return. par format string for this parameter
def save(self, dolist=0): """Return .par format string for this parameter If dolist is set, returns fields as a list of strings. Default is to return a single string appropriate for writing to a file. """ quoted = not dolist array_size = 1 for d in self.shape: ...
Return dpar - style executable assignment for parameter
def dpar(self, cl=1): """Return dpar-style executable assignment for parameter Default is to write CL version of code; if cl parameter is false, writes Python executable code instead. Note that dpar doesn't even work for arrays in the CL, so we just use Python syntax here. ...
Return value of this parameter as a string ( or in native format if native is non - zero. )
def get(self, field=None, index=None, lpar=0, prompt=1, native=0, mode="h"): """Return value of this parameter as a string (or in native format if native is non-zero.)""" if field: return self._getField(field,native=native,prompt=prompt) # may prompt for value if prompt flag is set ...
Set value of this parameter from a string or other value. Field is optional parameter field ( p_prompt p_minimum etc. ) Index is optional array index ( zero - based ). Set check = 0 to assign the value without checking to see if it is within the min - max range or in the choice list.
def set(self, value, field=None, index=None, check=1): """Set value of this parameter from a string or other value. Field is optional parameter field (p_prompt, p_minimum, etc.) Index is optional array index (zero-based). Set check=0 to assign the value without checking to see if it is ...
Check and convert a parameter value.
def checkValue(self,value,strict=0): """Check and convert a parameter value. Raises an exception if the value is not permitted for this parameter. Otherwise returns the value (converted to the right type.) """ v = self._coerceValue(value,strict) for i in range(l...
Convert tuple index to 1 - D index into value
def _sumindex(self, index=None): """Convert tuple index to 1-D index into value""" try: ndim = len(index) except TypeError: # turn index into a 1-tuple index = (index,) ndim = 1 if len(self.shape) != ndim: raise ValueError("Inde...
Coerce parameter to appropriate type
def _coerceValue(self,value,strict=0): """Coerce parameter to appropriate type Should accept None or null string. Must be an array. """ try: if isinstance(value,str): # allow single blank-separated string as input value = value.split() ...
Create min - match dictionary for choice list
def _setChoiceDict(self): """Create min-match dictionary for choice list""" # value is full name of choice parameter self.choiceDict = minmatch.MinMatchDict() for c in self.choice: self.choiceDict.add(c, c)
Check initial attributes to make sure they are legal
def _checkAttribs(self, strict): """Check initial attributes to make sure they are legal""" if self.min: warning("Minimum value not allowed for boolean-type parameter " + self.name, strict) self.min = None if self.max: if not self.prompt: ...
Check initial attributes to make sure they are legal
def _checkAttribs(self, strict): """Check initial attributes to make sure they are legal""" if self.choice: warning("Choice values not allowed for real-type parameter " + self.name, strict) self.choice = None
Updates the device with the given data. Supports a json payload like { fs: newFs samplesPerBatch: samplesPerBatch gyroEnabled: true gyroSensitivity: 500 accelerometerEnabled: true accelerometerSensitivity: 2 } A heartbeat is sent on completion of the request to ensure the analyser gets a rapid update.: return: the devi...
def patch(self, deviceId): """ Updates the device with the given data. Supports a json payload like { fs: newFs samplesPerBatch: samplesPerBatch gyroEnabled: true gyroSensitivity: 500 accelerometerEnabled: true accelerometer...
Check if this is a legal date in the Gregorian calendar
def legal_date(year, month, day): '''Check if this is a legal date in the Gregorian calendar''' if month == 2: daysinmonth = 29 if isleap(year) else 28 else: daysinmonth = 30 if month in HAVE_30_DAYS else 31 if not (0 < day <= daysinmonth): raise ValueError("Month {} doesn't hav...
Gregorian to Julian Day Count for years between 1801 - 2099
def to_jd2(year, month, day): '''Gregorian to Julian Day Count for years between 1801-2099''' # http://quasar.as.utexas.edu/BillInfo/JulianDatesG.html legal_date(year, month, day) if month <= 2: year = year - 1 month = month + 12 a = floor(year / 100) b = floor(a / 4) c = ...
Return Gregorian date in a ( Y M D ) tuple
def from_jd(jd): '''Return Gregorian date in a (Y, M, D) tuple''' wjd = floor(jd - 0.5) + 0.5 depoch = wjd - EPOCH quadricent = floor(depoch / INTERCALATION_CYCLE_DAYS) dqc = depoch % INTERCALATION_CYCLE_DAYS cent = floor(dqc / LEAP_SUPPRESSION_DAYS) dcent = dqc % LEAP_SUPPRESSION_DAYS ...
Stores a new item in the cache if it is allowed in.: param name: the name.: param hingePoints: the hinge points.: return: true if it is stored.
def storeFromHinge(self, name, hingePoints): """ Stores a new item in the cache if it is allowed in. :param name: the name. :param hingePoints: the hinge points. :return: true if it is stored. """ if name not in self._cache: if self._valid(hingePoints...
Stores a new item in the cache.: param name: file name.: param start: start time.: param end: end time.: return: true if stored.
def storeFromWav(self, uploadCacheEntry, start, end): """ Stores a new item in the cache. :param name: file name. :param start: start time. :param end: end time. :return: true if stored. """ prefix = uploadCacheEntry['name'] + '_' + start + '_' + end ...
Deletes the named entry in the cache.: param name: the name.: return: true if it is deleted.
def delete(self, name): """ Deletes the named entry in the cache. :param name: the name. :return: true if it is deleted. """ if name in self._cache: del self._cache[name] self.writeCache() # TODO clean files return True ...
reads the specified file.: param name: the name.: return: the analysis as frequency/ Pxx.
def analyse(self, name): """ reads the specified file. :param name: the name. :return: the analysis as frequency/Pxx. """ if name in self._cache: target = self._cache[name] if target['type'] == 'wav': signal = self._uploadController...
Performs a log space 1d interpolation.: param xx: the x values.: param yy: the y values.: param kind: the type of interpolation to apply ( as per scipy interp1d ): return: the interpolation function.
def log_interp1d(self, xx, yy, kind='linear'): """ Performs a log space 1d interpolation. :param xx: the x values. :param yy: the y values. :param kind: the type of interpolation to apply (as per scipy interp1d) :return: the interpolation function. """ log...
Retrieve the Julian date equivalent for this date
def to_jd(year, month, day): "Retrieve the Julian date equivalent for this date" return day + (month - 1) * 30 + (year - 1) * 365 + floor(year / 4) + EPOCH - 1
Create a new date from a Julian date.
def from_jd(jdc): "Create a new date from a Julian date." cdc = floor(jdc) + 0.5 - EPOCH year = floor((cdc - floor((cdc + 366) / 1461)) / 365) + 1 yday = jdc - to_jd(year, 1, 1) month = floor(yday / 30) + 1 day = yday - (month - 1) * 30 + 1 return year, month, day
Computes the roll angle at the target position based on::
def troll(roll, dec, v2, v3): """ Computes the roll angle at the target position based on:: the roll angle at the V1 axis(roll), the dec of the target(dec), and the V2/V3 position of the aperture (v2,v3) in arcseconds. Based on the algorithm provided by Colin Cox that i...