code
stringlengths
1
18.2k
def check_cache(self, type, data, obj=None): '''Returns the updated cached version of the given dict''' try: id = data['id'] except: # Not an identifiable item #print 'don\'t know this item %r:%r' % (type, data) return data # If obj was passed in, its type takes precedence try: type = obj._get_type() except: pass # Fin...
try: hit = self.item_cache[type][id] except KeyError: pass else: hit._update_data(data) #print 'cache hit for %s at %s' % (type, id) return hit # Not there? Let's make us a new item # If we weren't given the object ref, find the name in the global scope if not obj: # Default to Redmine_Item if it's not found obj = self...
type=type) # Store it self.item_cache.setdefault(type, {})[id] = new_item #print 'set new %s at %s' % (type, id) return new_item
def substract(self, pt): """Return a Point instance as the displacement of two points.""" if isinstance(pt, Point): return Point(pt.x - self.x, pt.y - self.y, pt.z - self.z) else: raise TypeError
def from_list(cls, l): """Return a Point instance from a given list""" if len(l) == 3: x, y, z = map(float, l) return cls(x, y, z) elif len(l) == 2: x, y = map(float, l) return cls(x, y) else: raise AttributeError
def multiply(self, number): """Return a Vector as the product of the vector and a real number.""" return self.from_list([x * number for x in self.to_list()])
def magnitude(self): """Return magnitude of the vector.""" return math.sqrt( reduce(lambda x, y: x + y, [x ** 2 for x in self.to_list()]) )
def sum(self, vector): """Return a Vector instance as the vector sum of two vectors.""" return self.from_list( [x + vector.vector[i] for i, x in self.to_list()] )
def dot(self, vector, theta=None): """Return the dot product of two vectors. If theta is given then the dot product is computed as v1*v1 = |v1||v2|cos(theta). Argument theta is measured in degrees. """ if theta is not None: return (self.magnitude() * vector.magnitude() * math.degrees(math.cos(theta))) return (reduce(la...
def cross(self, vector): """Return a Vector instance as the cross product of two vectors""" return Vector((self.y * vector.z - self.z * vector.y), (self.z * vector.x - self.x * vector.z), (self.x * vector.y - self.y * vector.x))
def unit(self): """Return a Vector instance of the unit vector""" return Vector( (self.x / self.magnitude()), (self.y / self.magnitude()), (self.z / self.magnitude()) )
def angle(self, vector): """Return the angle between two vectors in degrees.""" return math.degrees( math.acos( self.dot(vector) / (self.magnitude() * vector.magnitude()) ) )
def non_parallel(self, vector): """Return True if vectors are non-parallel. Non-parallel vectors are vectors which are neither parallel nor perpendicular to each other. """ if (self.is_parallel(vector) is not True and self.is_perpendicular(vector) is not True): return True return False
def rotate(self, angle, axis=(0, 0, 1)): """Returns the rotated vector. Assumes angle is in radians""" if not all(isinstance(a, int) for a in axis): raise ValueError x, y, z = self.x, self.y, self.z # Z axis rotation if(axis[2]): x = (self.x * math.cos(angle) - self.y * math.sin(angle)) y = (self.x * math.sin(angle) + ...
math.cos(angle) + self.z * math.sin(angle) z = -self.x * math.sin(angle) + self.z * math.cos(angle) # X axis rotation if(axis[0]): y = self.y * math.cos(angle) - self.z * math.sin(angle) z = self.y * math.sin(angle) + self.z * math.cos(angle) return Vector(x, y, z)
def from_points(cls, point1, point2): """Return a Vector instance from two given points.""" if isinstance(point1, Point) and isinstance(point2, Point): displacement = point1.substract(point2) return cls(displacement.x, displacement.y, displacement.z) raise TypeError
def spherical(cls, mag, theta, phi=0): '''Returns a Vector instance from spherical coordinates''' return cls( mag * math.sin(phi) * math.cos(theta), # X mag * math.sin(phi) * math.sin(theta), # Y mag * math.cos(phi) # Z )
def cylindrical(cls, mag, theta, z=0): '''Returns a Vector instance from cylindircal coordinates''' return cls( mag * math.cos(theta), # X mag * math.sin(theta), # Y z # Z )
def amod(a, b): '''Modulus function which returns numerator if modulus is zero''' modded = int(a % b) return b if modded is 0 else modded
def search_weekday(weekday, jd, direction, offset): '''Determine the Julian date for the next or previous weekday''' return weekday_before(weekday, jd + (direction * offset))
def nth_day_of_month(n, weekday, month, year): """ Return (year, month, day) tuple that represents nth weekday of month in year. If n==0, returns last weekday of month. Weekdays: Monday=0 """ if not (0 <= n <= 5): raise IndexError("Nth day of month must be 0-5. Received: {}".format(n)) if not (0 <= weekday <= 6): raise...
Get first WEEKDAY of month first_weekday_of_kind = 1 + (weekday - firstday) % 7 if n == 0: # find last weekday of kind, which is 5 if these conditions are met, else 4 if first_weekday_of_kind in [1, 2, 3] and first_weekday_of_kind + 28 < daysinmonth: n = 5 else: n = 4 day = first_weekday_of_kind + ((n - 1) * 7) if day
> daysinmonth: raise IndexError("No {}th day of month {}".format(n, month)) return (year, month, day)
def irafglob(inlist, atfile=None): """ Returns a list of filenames based on the type of IRAF input. Handles lists, wild-card characters, and at-files. For special at-files, use the atfile keyword to process them. This function is recursive, so IRAF lists can also contain at-files and wild-card characters, e.g. `a.fits`...
# Determine which form of input was provided: if isinstance(inlist, list): # python list flist = [] for f in inlist: flist += irafglob(f) elif ',' in inlist: # comma-separated string list flist = [] for f in inlist.split(','): f = f.strip() flist += irafglob(f) elif inlist[0] == '@': # file list flist = [] for f in ope...
hook for application specific atfiles. if atfile: f = atfile(f) flist += irafglob(f) else: # shell globbing if osfn: inlist = osfn(inlist) flist = glob.glob(inlist) return flist
def pack(self): """Return binary format of packet. The returned string is the binary format of the packet with stuffing and framing applied. It is ready to be sent to the GPS. """ # Possible structs for packet ID. # try: structs_ = get_structs_for_fields([self.fields[0]]) except (TypeError): # TypeError, if self.fields...
subcode # if structs_ == []: try: structs_ = get_structs_for_fields([self.fields[0], self.fields[1]]) except (IndexError, TypeError): # IndexError, if no self.fields[1] # TypeError, if self.fields[1] is a wrong argument to `chr()`. raise PackError(self) # Try to pack the packet with any of the possible structs. # for s...
loop # above wasn't reached, i.e. none of the `structs_` matched. # raise PackError(self)
def unpack(cls, rawpacket): """Instantiate `Packet` from binary string. :param rawpacket: TSIP pkt in binary format. :type rawpacket: String. `rawpacket` must already have framing (DLE...DLE/ETX) removed and byte stuffing reversed. """ structs_ = get_structs_for_rawpacket(rawpacket) for struct_ in structs_: try: return...
format. # return cls(0xff, rawpacket)
def ch_handler(offset=0, length=-1, **kw): """ Handle standard PRIMARY clipboard access. Note that offset and length are passed as strings. This differs from CLIPBOARD. """ global _lastSel offset = int(offset) length = int(length) if length < 0: length = len(_lastSel) return _lastSel[offset:offset+length]
def put(text, cbname): """ Put the given string into the given clipboard. """ global _lastSel _checkTkInit() if cbname == 'CLIPBOARD': _theRoot.clipboard_clear() if text: # for clipboard_append, kwds can be -displayof, -format, or -type _theRoot.clipboard_append(text) return if cbname == 'PRIMARY': _lastSel = text _the...
to be called when we lose ownership return raise RuntimeError("Unexpected clipboard name: "+str(cbname))
def get(cbname): """ Get the contents of the given clipboard. """ _checkTkInit() if cbname == 'PRIMARY': try: return _theRoot.selection_get(selection='PRIMARY') except: return None if cbname == 'CLIPBOARD': try: return _theRoot.selection_get(selection='CLIPBOARD') except: return None raise RuntimeError("Unexpected clip...
def createDevice(self, deviceCfg): """ Creates a measurement deviceCfg from the input configuration. :param: deviceCfg: the deviceCfg cfg. :param: handlers: the loaded handlers. :return: the constructed deviceCfg. """ ioCfg = deviceCfg['io'] type = deviceCfg['type'] if type == 'mpu6050': fs = deviceCfg.get('fs') name =...
raise ValueError(provider + " is not a supported mock io data provider") self.logger.warning("Loading mock data provider for mpu6050") io = mock_io(dataProvider=dataProvider.provide) elif ioCfg['type'] == 'smbus': busId = ioCfg['busId'] self.logger.warning("Loading smbus %d", busId) io = smbus_io(busId) else: raise Val...
else mpu6050(io, fs=fs) else: raise ValueError(type + " is not a supported device")
def _loadRecordingDevices(self): """ Loads the recordingDevices specified in the configuration. :param: handlers the loaded handlers. :return: the constructed recordingDevices in a dict keyed by name. """ return {device.name: device for device in [self.createDevice(deviceCfg) for deviceCfg in self.config['accelerometer...
def createHandler(self, handler): """ Creates a data handler from the input configuration. :param handler: the handler cfg. :return: the constructed handler. """ target = handler['target'] if handler['type'] == 'log': self.logger.warning("Initialising csvlogger to log data to " + target) return CSVLogger('recorder', ha...
def _loadHandlers(self): """ creates a dictionary of named handler instances :return: the dictionary """ return {handler.name: handler for handler in map(self.createHandler, self.config['handlers'])}
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 or 400 if nothing was written. """ logger.info(...
' for ' + filename) import flask bytesWritten = self._uploadController.writeChunk(flask.request.stream, filename, int(chunkIdx)) return str(bytesWritten), 200 if bytesWritten > 0 else 400
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 None else 404 except Exception as e: return str(e), 500
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._targetController.storeFromWav(entry, start, end) else 500 else: return None, 404
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 ' + resolution + 'x resolution using ' + window + ' window') signal = self._uploadCon...
else None, end=end if end != 'end' else None) if signal is not None: window = tuple(filter(None, window.split(' '))) if len(window) == 2: window = (window[0], float(window[1])) import time data = { 'spectrum': self._jsonify( signal.spectrum(ref=SPECLAB_REFERENCE, segmentLengthMultiplier=int(resolution), window=window) ...
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 + ' - ' + status) self._uploadController.finalise(filename, int(totalChun...
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_json() if data is not None: logger.debug('Received payload f...
edit payload ' + measurementId) return None, 404 else: logger.error('Invalid data payload received ' + measurementId) return None, 400
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 :return: """ json = request.get_json() try: sta...
if 'duration' in json else 10 if start is None: # should never happen but just in case return 'no start time', 400 else: scheduled, message = self._measurementController.schedule(measurementId, duration, start, description=json.get('description')) return message, 200 if scheduled else 400
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 :return: the absolute start time...
delay = json['delay'] if 'delay' in json else None if start is None and delay is None: return self._getAbsoluteTime(datetime.datetime.utcnow(), 2) elif start is not None: target = datetime.datetime.strptime(start, DATETIME_FORMAT) if target <= datetime.datetime.utcnow(): time = self._getAbsoluteTime(datetime.datetime.u...
self._getAbsoluteTime(datetime.datetime.utcnow(), delay) else: return None
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)
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: return message, 404 elif deleted is None: return message,...
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._measurementController.startMeasurement(measurementId, deviceId): logger.info('Star...
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.debug('Received payload ' + measurementId + '/' + deviceId + ': ' + str(len(parsedData))...
'/' + deviceId) return None, 404 else: logger.error('Invalid data payload received ' + measurementId + '/' + deviceId) return None, 400
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('failureReason') if payload is not None else None logger.warning('Fail...
+ ' for ' + deviceId) return None, 200 else: logger.error('Unable to fail measurement ' + measurementId + ' for ' + deviceId) return None, 404
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) return None, 200
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 single string (so you ...
assert in_strings and len(in_strings)>0, 'Unexpected: '+repr(in_strings) # get max width in input maxWidth = len(max(in_strings, key=len)) + (2*min_pad) # width with pad numCols = term_width//maxWidth # integer div # set numCols so we take advantage of the whole line width numCols = min(numCols, len(in_strings)) # easy...
big but print one item per line anyway lines = [x.center(term_width) for x in in_strings] return '\n'.join(lines) # normal case - 2 or more columns colWidth = term_width//numCols # integer div # colWidth is guaranteed to be larger than all items in input retval = '' for i in range(len(in_strings)): retval+=in_strings[i...
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, r = divmod(i,nlines) nwid = c*wid...
+ strlist[i] for s in line: print(s)
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] == "'": value = value[1:] if value[-1:] == "'": value = value[:-...
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 two bugs (descri...
these bugs are fixed, this function should be forsaken in favor of direct use of the csv module (or similar). The basic use case is to split a function signature string, so for: afunc(arg1='str1', arg2='str, with, embedded, commas', arg3=7) we want a 3 element sequence: ["arg1='str1'", "arg2='str, with, embedded, comma...
>>> rdr = csv.reader( (y,), dialect='excel', quotechar="'", skipinitialspace=True) >>> l = rdr.next(); print(len(l), str(l)) # doctest: +SKIP 6 ["arg1='str1'", "arg2='str", 'with', 'embedded', "commas'", "arg3=7"] which we can see is not correct - we wanted 3 tokens. This occurs in Python 2.5.2 and 2.6. It seems to be ...
the whole token. If we were to remove the names of the args and the equal signs, it works: >>> x = "'str1', 'str, with, embedded, commas', 7" >>> rdr = csv.reader( (x,), dialect='excel', quotechar="'", skipinitialspace=True) >>> l = rdr.next(); print(len(l), str(l)) # doctest: +SKIP 3 ['str1', 'str, with, embedded, com...
it fails: >>> x = "'str1', 'str, with, embedded, commas', 7" >>> rdr = csv.reader( (x,), dialect='excel', quotechar="'") >>> l = rdr.next(); print(len(l), str(l)) # doctest: +SKIP 6 ['str1', " 'str", ' with', ' embedded', " commas'", ' 7'] So, for now, we'll roll our own. """ # Algorithm: read chars left to right, go f...
a single/double/triple quote is hit, scan forward # (ignoring all else) until its matching end-quote is found. # For now, we will not specially handle escaped quotes. tokens = [] ldl = len(delim) keepOnRollin = line is not None and len(line) > 0 while keepOnRollin: tok = _getCharsUntil(line, delim, True, allowEol=allow...
delimiter # except on last token if len(tok) > 0: # append it, but without the delimiter if tok[-ldl:] == delim: tokens.append(tok[:-ldl]) else: tokens.append(tok) # tok goes to EOL - has no delimiter keepOnRollin = False line = line[len(tok):] else: # This is the case of the empty end token tokens.append('') keepOnRol...
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) retlist.extend(os.path.join(base, f) for f in ...
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: if makeWritable: os.c...
just try, don't whine else: raise
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 Should we remove \\ too? ""...
i = value.find(r"\'") while i>=0: value = value[:i] + value[i+1:] i = value.find(r"\'",i+1) # delete backslash-newlines i = value.find("\\\n") while i>=0: j = i+2 if quoted: # ignore blanks and tabs following \-newline in quoted strings for c in value[i+2:]: if c not in ' \t': break j = j+1 value = value[:i] + value[j:...
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' """ s = s.replace('$', 'DOL...
in string.digits or \ keyword.iskeyword(sparts[i]): sparts[i] = 'PY' + sparts[i] if dot: return 'DOT'.join(sparts) else: return '.'.join(sparts)
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 without graphics") if not TKNTR._d...
TKNTR._default_root if withdraw and retval: retval.withdraw() return retval
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-buffered filehandles. If file ...
If it does not have a fileno method (which can happen e.g. for the status line input on the graphics window) then the readline method is simply called directly. """ if file is None: file = sys.stdin if not hasattr(file, "readline"): raise TypeError("file must be a filehandle with a readline method") # Call tkread now.....
not GUI-related (e.g. terminal- # focused code in a sometimes-GUI app) then skip tkread and simply call # readline on the input eg. stdin. Otherwise we'd fail in _TkRead().read() try: fd = file.fileno() except: fd = None if (fd and capable.OF_GRAPHICS): tkread(fd, 0) # if EOF was encountered on a tty, avoid reading aga...
return '' return file.readline()
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 # is needed. (E.g. win, linux...
in ('os2warp, iphone'): # try webbrowser w/ everything? import webbrowser if not webbrowser.open(url): print("Error opening URL: "+url) else: print('Help on "'+subj+'" is now being displayed in a web browser') return # Go ahead and fork a subprocess to call the correct binary pid = os.fork() if pid == 0: # child if sys...
to keep '#.*' print("Error opening URL: "+url) os._exit(0) # The following retries if "-remote" doesnt work, opening a new browser # cmd = brow_bin+" -remote 'openURL("+url+")' '"+url+"' 1> /dev/null 2>&1" # if 0 != os.system(cmd) # print "Running "+brow_bin+" for HTML help..." # os.execvp(brow_bin,[brow_bin,url]) # os...
browser')
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 have Python file object try: fd = file.fileno() except: raise TypeErr...
# no Tk widgets yet, so no need for mainloop # (shouldnt happen now with init_tk_default_root) s = [] while nbytes>0: snew = os.read(fd, nbytes) # returns bytes in PY3K if snew: if PY3K: snew = snew.decode('ascii','replace') s.append(snew) nbytes -= len(snew) else: # EOF -- just return what we have so far break return ...
| TKNTR.EXCEPTION, self._read) try: self.widget.mainloop() finally: self.widget.tk.deletefilehandler(fd) return "".join(self.value)
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) # returns bytes in PY3K if PY3K: snew = snew.decode('ascii','replac...
and self.widget: # stop the mainloop self.widget.quit() except OSError: raise IOError("Error reading from %s" % (fd,))
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 delimiter: char :return a S...
columnCount + ' columns, time values can\'t be at column ' + timeColumnIdx) if columnCount < dataColumnIdx + 1: raise ValueError( filename + ' has only ' + columnCount + ' columns, data values can\'t be at column ' + dataColumnIdx) t = data[:, [timeColumnIdx]] samples = data[:, [dataColumnIdx]] # calculate fs as the in...