code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
dt = getPDT(typename) or getCDT(typename) if dt is None: pdt, nelems = ArrayType.parse(typename) if pdt and nelems: dt = ArrayType(pdt, nelems) return dt
def get(typename)
get(typename) -> PrimitiveType or ComplexType Returns the PrimitiveType or ComplexType for typename or None.
6.827569
5.669622
1.204237
return struct.unpack(self.format, buffer(bytes))[0]
def decode(self, bytes, raw=False)
decode(bytearray, raw=False) -> value Decodes the given bytearray according to this PrimitiveType definition. NOTE: The parameter ``raw`` is present to adhere to the ``decode()`` inteface, but has no effect for PrimitiveType definitions.
8.186811
13.332646
0.614042
valid = False def log(msg): if messages is not None: if prefix is not None: tok = msg.split() msg = prefix + ' ' + tok[0].lower() + " " + " ".join(tok[1:]) messages.append(msg) if self.string: ...
def validate(self, value, messages=None, prefix=None)
validate(value[, messages[, prefix]]) -> True | False Validates the given value according to this PrimitiveType definition. Validation error messages are appended to an optional messages array, each with the optional message prefix.
2.860643
2.868405
0.997294
if type(index) is not int: raise TypeError('list indices must be integers') if index < 0 or index >= self.nelems: raise IndexError('list index out of range')
def _assertIndex(self, index)
Raise TypeError or IndexError if index is not an integer or out of range for the number of elements in this array, respectively.
3.253313
2.832127
1.148717
if index is None: index = slice(0, self.nelems) if type(index) is slice: step = 1 if index.step is None else index.step indices = xrange(index.start, index.stop, step) result = [ self.decodeElem(bytes, n, raw) for n in indices ] else:...
def decode(self, bytes, index=None, raw=False)
decode(bytes[[, index], raw=False]) -> value1, ..., valueN Decodes the given sequence of bytes according to this Array's element type. If the optional `index` parameter is an integer or slice, then only the element(s) at the specified position(s) will be decoded and returned.
2.75171
2.999613
0.917355
self._assertIndex(index) start = index * self.type.nbytes stop = start + self.type.nbytes if stop > len(bytes): msg = 'Decoding %s[%d] requires %d bytes, ' msg += 'but the ArrayType.decode() method received only %d bytes.' raise IndexError(...
def decodeElem(self, bytes, index, raw=False)
Decodes a single element at array[index] from a sequence bytes that contain data for the entire array.
4.130916
3.861912
1.069655
if len(args) != self.nelems: msg = 'ArrayType %s encode() requires %d values, but received %d.' raise ValueError(msg % (self.name, self.nelems, len(args))) return bytearray().join(self.type.encode(arg) for arg in args)
def encode(self, *args)
encode(value1[, ...]) -> bytes Encodes the given values to a sequence of bytes according to this Array's underlying element type
4.569973
4.459031
1.02488
parts = [None, None] start = name.find('[') if start != -1: stop = name.find(']', start) if stop != -1: try: parts[0] = name[:start] parts[1] = int(name[start + 1:stop]) if parts[1] <= 0...
def parse (name)
parse(name) -> [typename | None, nelems | None] Parses an ArrayType name to return the element type name and number of elements, e.g.: >>> ArrayType.parse('MSB_U16[32]') ['MSB_U16', 32] If typename cannot be determined, None is returned. Similarly, if nelems is...
3.342028
3.143878
1.063027
if self._cmddict is None: self._cmddict = cmd.getDefaultDict() return self._cmddict
def cmddict(self)
PrimitiveType base for the ComplexType
5.444119
5.22682
1.041574
opcode = self.cmddict[value].opcode return super(CmdType, self).encode(opcode)
def encode(self, value)
encode(value) -> bytearray Encodes the given value to a bytearray according to this PrimitiveType definition.
16.03841
22.87352
0.701178
opcode = super(CmdType, self).decode(bytes) result = None if raw: result = opcode elif opcode in self.cmddict.opcodes: result = self.cmddict.opcodes[opcode] else: raise ValueError('Unrecognized command opcode: %d' % opcode) r...
def decode(self, bytes, raw=False)
decode(bytearray, raw=False) -> value Decodes the given bytearray and returns the corresponding Command Definition (:class:`CmdDefn`) for the underlying 'MSB_U16' command opcode. If the optional parameter ``raw`` is ``True``, the command opcode itself will be returned instead o...
4.466064
3.968217
1.125459
if self._evrs is None: import ait.core.evr as evr self._evrs = evr.getDefaultDict() return self._evrs
def evrs(self)
Getter EVRs dictionary
5.794557
4.660639
1.243297
e = self.evrs.get(value, None) if not e: log.error(str(value) + " not found as EVR. Cannot encode.") return None else: return super(EVRType, self).encode(e.code)
def encode(self, value)
encode(value) -> bytearray Encodes the given value to a bytearray according to this Complex Type definition.
6.12685
6.49632
0.943126
code = super(EVRType, self).decode(bytes) result = None if raw: result = code elif code in self.evrs.codes: result = self.evrs.codes[code] else: result = code log.warn('Unrecognized EVR code: %d' % code) return ...
def decode(self, bytes, raw=False)
decode(bytearray, raw=False) -> value Decodes the given bytearray according the corresponding EVR Definition (:class:`EVRDefn`) for the underlying 'MSB_U16' EVR code. If the optional parameter ``raw`` is ``True``, the EVR code itself will be returned instead of the EVR Definiti...
5.026142
4.799949
1.047124
result = super(Time8Type, self).decode(bytes) if not raw: result /= 256.0 return result
def decode(self, bytes, raw=False)
decode(bytearray, raw=False) -> value Decodes the given bytearray and returns the number of (fractional) seconds. If the optional parameter ``raw`` is ``True``, the byte (U8) itself will be returned.
6.289289
7.175275
0.876522
if type(value) is not datetime.datetime: raise TypeError('encode() argument must be a Python datetime') return super(Time32Type, self).encode( dmc.toGPSSeconds(value) )
def encode(self, value)
encode(value) -> bytearray Encodes the given value to a bytearray according to this ComplexType definition.
10.132483
9.994587
1.013797
sec = super(Time32Type, self).decode(bytes) return sec if raw else dmc.toLocalTime(sec)
def decode(self, bytes, raw=False)
decode(bytearray, raw=False) -> value Decodes the given bytearray containing the elapsed time in seconds since the GPS epoch and returns the corresponding Python :class:`datetime`. If the optional parameter ``raw`` is ``True``, the integral number of seconds will be returned in...
12.901095
18.503704
0.697217
if type(value) is not datetime.datetime: raise TypeError('encode() argument must be a Python datetime') coarse = Time32Type().encode(value) fine = Time8Type() .encode(value.microsecond / 1e6) return coarse + fine
def encode(self, value)
encode(value) -> bytearray Encodes the given value to a bytearray according to this ComplexType definition.
6.53329
6.104924
1.070167
coarse = Time32Type().decode(bytes[:4], raw) fine = Time8Type() .decode(bytes[4:]) if not raw: fine = datetime.timedelta(microseconds=fine * 1e6) return coarse + fine
def decode(self, bytes, raw=False)
decode(bytearray, raw=False) -> value Decodes the given bytearray containing the elapsed time in seconds plus 1/256 subseconds since the GPS epoch returns the corresponding Python :class:`datetime`. If the optional parameter ``raw`` is ``True``, the number of seconds and subsec...
6.364854
7.165987
0.888204
if ymlfile is not None: self.ymlfile = ymlfile try: # If yaml should be 'cleaned' of document references if self._clean: self.data = self.process(self.ymlfile) else: with open(self.ymlfile, 'rb') as stream: ...
def load(self, ymlfile=None)
Load and process the YAML file
4.932606
4.764663
1.035248
output = "" try: # Need a list of line numbers where the documents resides # Used for finding/displaying errors self.doclines = [] linenum = None with open(ymlfile, 'r') as txt: for linenum, line in enumerate(txt): ...
def process(self, ymlfile)
Cleans out all document tags from the YAML file to make it JSON-friendly to work with the JSON Schema.
4.250108
4.020458
1.05712
if schemafile is not None: self._schemafile = schemafile try: self.data = json.load(open(self._schemafile)) except (IOError, ValueError), e: msg = "Could not load schema file '" + self._schemafile + "': '" + str(e) + "'" raise jsonschema....
def load(self, schemafile=None)
Load and process the schema file
2.776447
2.737161
1.014353
"Perform validation with processed YAML and Schema" self._ymlproc = YAMLProcessor(self._ymlfile) self._schemaproc = SchemaProcessor(self._schemafile) valid = True log.debug("BEGIN: Schema-based validation for YAML '%s' with schema '%s'", self._ymlfile, self._schemafile) ...
def schema_val(self, messages=None)
Perform validation with processed YAML and Schema
5.114458
4.859084
1.052556
self._ymlproc = YAMLProcessor(self._ymlfile, False) # Turn off the YAML Processor log.debug("BEGIN: Content-based validation of Command dictionary") if ymldata is not None: cmddict = ymldata elif ymldata is None and self._ymlproc.loaded: cmddict...
def content_val(self, ymldata=None, messages=None)
Validates the Command Dictionary to ensure the contents for each of the fields meets specific criteria regarding the expected types, byte ranges, etc.
4.226453
4.11561
1.026932
schema_val = self.schema_val(messages) if len(messages) == 0: content_val = self.content_val(ymldata, messages) return schema_val and content_val
def validate(self, ymldata=None, messages=None)
Validates the Telemetry Dictionary definitions
4.744752
4.683014
1.013183
# Turn off the YAML Processor log.debug("BEGIN: Content-based validation of Telemetry dictionary") if ymldata is not None: tlmdict = ymldata else: tlmdict = tlm.TlmDict(self._ymlfile) try: # instantiate the document number. this will...
def content_val(self, ymldata=None, messages=None)
Validates the Telemetry Dictionary to ensure the contents for each of the fields meets specific criteria regarding the expected types, byte ranges, etc.
4.68083
4.614239
1.014432
val = getattr(defn, self.attr) if val is not None and val in self.val_list: self.messages.append(self.msg % str(val)) # TODO self.messages.append("TBD location message") self.valid = False elif val is not None: self.val_list.append(val) ...
def check(self, defn)
Performs the uniqueness check against the value list maintained in this rule objects
5.284422
4.6
1.148787
allowedTypes = dtype.PrimitiveType, dtype.ArrayType if not isinstance(defn.type, allowedTypes): self.messages.append(self.msg % str(defn.name)) # self.messages.append("TBD location message") self.valid = False
def check(self, defn)
Performs isinstance check for the definitions data type. Assumes the defn has 'type' and 'name' attributes
10.644963
10.132915
1.050533
if isinstance(defn.type, dtype.PrimitiveType): # Check the nbytes designated in the YAML match the PDT nbytes = defn.type.nbytes defnbytes = defn.slice().stop - defn.slice().start if nbytes != defnbytes: self.messages.append(self.msg % def...
def check(self, defn, msg=None)
Uses the byte range in the object definition to determine the number of bytes and compares to the size defined in the type. Assumes the defn has 'type' and 'name' attributes, and a slice() method
6.674325
5.672505
1.17661
# Check enum does not contain boolean keys if (defn.slice().start != self.prevstop): self.messages.append(self.msg % str(defn.name)) # TODO self.messages.append("TBD location message") self.valid = False self.prevstop = defn.slice().stop
def check(self, defn, msg=None)
Uses the definitions slice() method to determine its start/stop range.
14.295538
11.312938
1.263645
status = False delay = 0.25 elapsed = 0 if msg is None and type(cond) is str: msg = cond if type(cond) is bool: if cond: log.warn('Boolean passed as argument to wait. Make sure argument to wait is surrounded by a lambda or " "') else: raise F...
def wait (cond, msg=None, _timeout=10, _raiseException=True)
Waits either a specified number of seconds, e.g.: .. code-block:: python wait(1.2) or for a given condition to be True. Conditions may be take several forms: Python string expression, lambda, or function, e.g.: .. code-block:: python wait('instrument_mode == "SAFE"') wa...
3.337055
3.216128
1.0376
status = False cmdobj = self._cmddict.create(command, *args, **kwargs) messages = [] if not cmdobj.validate(messages): for msg in messages: log.error(msg) else: encoded = cmdobj.encode() if self._verbose: ...
def send (self, command, *args, **kwargs)
Creates, validates, and sends the given command as a UDP packet to the destination (host, port) specified when this CmdAPI was created. Returns True if the command was created, valid, and sent, False otherwise.
4.205731
4.129237
1.018525
item = None timer = None deque = self._deque empty = IndexError('pop from an empty deque') if block is False: if len(self._deque) > 0: item = deque.popleft() if left else deque.pop() else: raise empty else...
def _pop(self, block=True, timeout=None, left=False)
Removes and returns the an item from this GeventDeque. This is an internal method, called by the public methods pop() and popleft().
2.650676
2.580178
1.027323
self._deque.append(item) self.notEmpty.set()
def append(self, item)
Add item to the right side of the GeventDeque. This method does not block. Either the GeventDeque grows to consume available memory, or if this GeventDeque has and is at maxlen, the leftmost item is removed.
11.274908
9.81491
1.148753
self._deque.appendleft(item) self.notEmpty.set()
def appendleft(self, item)
Add item to the left side of the GeventDeque. This method does not block. Either the GeventDeque grows to consume available memory, or if this GeventDeque has and is at maxlen, the rightmost item is removed.
9.138411
9.0523
1.009513
self._deque.extend(iterable) if len(self._deque) > 0: self.notEmpty.set()
def extend(self, iterable)
Extend the right side of this GeventDeque by appending elements from the iterable argument.
5.840332
4.705706
1.241117
self._deque.extendleft(iterable) if len(self._deque) > 0: self.notEmpty.set()
def extendleft(self, iterable)
Extend the left side of this GeventDeque by appending elements from the iterable argument. Note, the series of left appends results in reversing the order of elements in the iterable argument.
5.632998
4.795674
1.1746
return self._pop(block, timeout, left=True)
def popleft(self, block=True, timeout=None)
Remove and return an item from the right side of the GeventDeque. If no elements are present, raises an IndexError. If optional args *block* is True and *timeout* is ``None`` (the default), block if necessary until an item is available. If *timeout* is a positive number, it blocks at ...
8.408929
16.079229
0.522968
values = self._defn.name, self.server_host, self.server_port log.info('Listening for %s telemetry on %s:%d (UDP)' % values) super(UdpTelemetryServer, self).start()
def start (self)
Starts this UdpTelemetryServer.
10.169885
6.876733
1.478883
''' Send a confirm prompt to the GUI Arguments: msg (string): The message to display to the user. _timeout (int): The optional amount of time for which the prompt should be displayed to the user before a timeout occurs. ...
def confirm(self, msg, _timeout=-1)
Send a confirm prompt to the GUI Arguments: msg (string): The message to display to the user. _timeout (int): The optional amount of time for which the prompt should be displayed to the user before a timeout occurs. ...
6.054382
2.117229
2.859578
''' Send a user prompt request to the GUI Arguments: promptType (string): The prompt type to send to the GUI. Currently the only type supported is 'confirm'. _timeout (int): The optional amount of time for which the prompt ...
def msgBox(self, promptType, _timeout=-1, **options)
Send a user prompt request to the GUI Arguments: promptType (string): The prompt type to send to the GUI. Currently the only type supported is 'confirm'. _timeout (int): The optional amount of time for which the prompt sho...
5.018294
1.315087
3.815941
for stream in (self.inbound_streams + self.outbound_streams): for input_ in stream.inputs: if not type(input_) is int and input_ is not None: self._subscribe(stream, input_) for plugin in self.plugins: for input_ in plugin.inputs: ...
def _subscribe_all(self)
Subscribes all streams to their input. Subscribes all plugins to all their inputs. Subscribes all plugin outputs to the plugin.
3.695508
3.391624
1.089598
termlog = logging.StreamHandler() termlog.setFormatter( LogFormatter() ) logger.addHandler( termlog ) logger.addHandler( SysLogHandler() ) logger.addHandler( SysLogHandler(('localhost', 2514)) )
def addLocalHandlers (logger)
Adds logging handlers to logger to log to the following local resources: 1. The terminal 2. localhost:514 (i.e. syslogd) 3. localhost:2514 (i.e. the AIT GUI syslog-like handler)
4.334956
3.340172
1.297824
try: hostname = ait.config.logging.hostname # Do not "remote" log to this host, as that's already covered # by addLocalHandlers(). if socket.getfqdn() != hostname: socket.getaddrinfo(hostname, None) logger.addHandler( SysLogHandler( (hostname, 514) ) ) ...
def addRemoteHandlers (logger)
Adds logging handlers to logger to remotely log to: ait.config.logging.hostname:514 (i.e. syslogd) If not set or hostname cannot be resolved, this method has no effect.
6.880688
4.79914
1.433733
tokens = msg.split(' ', 6) result = { } if len(tokens) > 0: pri = tokens[0] start = pri.find('<') stop = pri.find('>') if start != -1 and stop != -1: result['pri'] = pri[start + 1:stop] else: result['pri'] = '' if stop != -1 ...
def parseSyslog(msg)
Parses Syslog messages (RFC 5424) The `Syslog Message Format (RFC 5424) <https://tools.ietf.org/html/rfc5424#section-6>`_ can be parsed with simple whitespace tokenization:: SYSLOG-MSG = HEADER SP STRUCTURED-DATA [SP MSG] HEADER = PRI VERSION SP TIMESTAMP SP HOSTNAME ...
2.493725
2.078462
1.199793
if datefmt is None: datefmt = '%Y-%m-%d %H:%M:%S' ct = self.converter(record.created) t = time.strftime(datefmt, ct) s = '%s.%03d' % (t, record.msecs) return s
def formatTime (self, record, datefmt=None)
Return the creation time of the specified LogRecord as formatted text.
2.428647
2.281541
1.064476
record.hostname = self.hostname return logging.Formatter.format(self, record)
def format (self, record)
Returns the given LogRecord as formatted text.
5.758348
5.177504
1.112186
if self.bsd: lt_ts = datetime.datetime.fromtimestamp(record.created) ts = lt_ts.strftime(self.BSD_DATEFMT) if ts[4] == '0': ts = ts[0:4] + ' ' + ts[5:] else: utc_ts = datetime.datetime.utcfromtimestamp(record.created) t...
def formatTime (self, record, datefmt=None)
Returns the creation time of the given LogRecord as formatted text. NOTE: The datefmt parameter and self.converter (the time conversion method) are ignored. BSD Syslog Protocol messages always use local time, and by our convention, Syslog Protocol messages use UTC.
3.353666
3.406679
0.984438
mode = mode.replace('b', '') + 'b' if options.get('rollover', False): stream = PCapRolloverStream(filename, options.get('nbytes' , None), options.get('npackets', None), options.get('nsecond...
def open (filename, mode='r', **options)
Returns an instance of a :class:`PCapStream` class which contains the ``read()``, ``write()``, and ``close()`` methods. Binary mode is assumed for this module, so the "b" is not required when calling ``open()``. If the optiontal ``rollover`` parameter is True, a :class:`PCapRolloverStream` is crea...
5.306501
2.877521
1.844122
'''Given a time range and input file, query creates a new file with only that subset of data. If no outfile name is given, the new file name is the old file name with the time range appended. Args: starttime: The datetime of the beginning time range to be extracted from the files. ...
def query(starttime, endtime, output=None, *filenames)
Given a time range and input file, query creates a new file with only that subset of data. If no outfile name is given, the new file name is the old file name with the time range appended. Args: starttime: The datetime of the beginning time range to be extracted from the files. ...
4.078417
1.880119
2.169234
output = open(format, rollover=True, **options) if isinstance(filenames, str): filenames = [ filenames ] for filename in filenames: with open(filename, 'r') as stream: for header, packet in stream: output.write(packet, header) output.close()
def segment(filenames, format, **options)
Segment the given pcap file(s) by one or more thresholds (``nbytes``, ``npackets``, ``nseconds``). New segment filenames are determined based on the ``strftime(3)`` ``format`` string and the timestamp of the first packet in the file. :param filenames: Single filename (string) or list of filenames ...
4.47205
4.726487
0.946168
times = { } delta = datetime.timedelta(seconds=tolerance) if isinstance(filenames, str): filenames = [ filenames ] for filename in filenames: with open(filename, 'r') as stream: times[filename] = list() header, packet = stream.read() start , st...
def times(filenames, tolerance=2)
For the given file(s), return the time ranges available. Tolerance sets the number of seconds between time ranges. Any gaps larger than tolerance seconds will result in a new time range. :param filenames: Single filename (string) or list of filenames :param tolerance: Maximum seconds between contiguo...
3.56988
3.653683
0.977063
self._data = stream.read(self._size) if len(self._data) >= self._size: values = struct.unpack(self._format, self._data) else: values = None, None, None, None, None, None, None if values[0] == 0xA1B2C3D4 or values[0] == 0xA1B23C4D: self._sw...
def read (self, stream)
Reads PCapGlobalHeader data from the given stream.
2.586442
2.21194
1.169309
self._data = stream.read(self._size) if len(self._data) >= self._size: values = struct.unpack(self._swap + self._format, self._data) else: values = None, None, None, None self.ts_sec = values[0] self.ts_usec = values[1] self.incl_len = values[2] ...
def read (self, stream)
Reads PCapPacketHeader data from the given stream.
3.674815
3.006707
1.222206
rollover = False if not rollover and self._threshold.nbytes is not None: rollover = self._total.nbytes >= self._threshold.nbytes if not rollover and self._threshold.npackets is not None: rollover = self._total.npackets >= self._threshold.npackets if no...
def rollover (self)
Indicates whether or not its time to rollover to a new file.
2.753589
2.594187
1.061446
if header is None: header = PCapPacketHeader(orig_len=len(bytes)) if self._stream is None: if self._threshold.nseconds is not None: # Round down to the nearest multiple of nseconds nseconds = self._threshold.nseconds rema...
def write (self, bytes, header=None)
Writes packet ``bytes`` and the optional pcap packet ``header``. If the pcap packet ``header`` is not specified, one will be generated based on the number of packet ``bytes`` and current time.
4.720692
4.556462
1.036043
if self._stream: values = ( self._total.nbytes, self._total.npackets, int( math.ceil(self._total.nseconds) ), self._filename ) if self._dryrun: msg = 'Would write %d bytes, %d packets, %d secon...
def close (self)
Closes this :class:``PCapStream`` by closing the underlying Python stream.
4.233208
4.060061
1.042646
header, packet = self.read() if packet is None: raise StopIteration return header, packet
def next (self)
Returns the next header and packet from this PCapStream. See read().
8.027063
4.137064
1.94028
header = PCapPacketHeader(self._stream, self.header._swap) packet = None if not header.incomplete(): packet = self._stream.read(header.incl_len) return (header, packet)
def read (self)
Reads a single packet from the this pcap stream, returning a tuple (PCapPacketHeader, packet)
11.197029
6.600235
1.696459
if type(bytes) is str: bytes = bytearray(bytes) if not isinstance(header, PCapPacketHeader): header = PCapPacketHeader(orig_len=len(bytes)) packet = bytes[0:header.incl_len] self._stream.write( str(header) ) self._stream.write( packet ) ...
def write (self, bytes, header=None)
write() is meant to work like the normal file write(). It takes two arguments, a byte array to write to the file as a single PCAP packet, and an optional header if one already exists. The length of the byte array should be less than 65535 bytes. write() returns the number of bytes actua...
4.571615
4.021273
1.136858
# make a hash object h = hashlib.sha1() # open file for reading in binary mode with open(filename,'rb') as file: # loop till the end of the file chunk = 0 while chunk != b'': # read only 1024 bytes at a time chunk = file.read(1024) h.update(chunk)...
def hash_file(filename)
This function returns the SHA-1 hash of the file passed into it
1.773657
1.629444
1.088504
self[defn.name] = defn self.colnames[defn.name] = defn
def add (self, defn)
Adds the given Command Definition to this Command Dictionary.
8.59008
6.47941
1.32575
tab = None defn = self.get(name, None) if defn: tab = FSWTab(defn, *args) return tab
def create (self, name, *args)
Creates a new command with the given arguments.
10.983873
10.775931
1.019297
if self.filename is None: self.filename = filename stream = open(self.filename, "rb") for doc in yaml.load_all(stream): for table in doc: self.add(table) stream.close()
def load (self, filename)
Loads Command Definitions from the given YAML file into this Command Dictionary.
3.936615
3.451099
1.140684
self.pub.send("{} {}".format(self.name, msg)) log.debug('Published message from {}'.format(self))
def publish(self, msg)
Publishes input message with client name as topic.
9.691219
7.210894
1.343969
if tlmdict is None: tlmdict = tlm.getDefaultDict() dbconn = connect(database) for name, defn in tlmdict.items(): createTable(dbconn, defn) return dbconn
def create(database, tlmdict=None)
Creates a new database for the given Telemetry Dictionary and returns a connection to it.
4.670132
4.479842
1.042477
cols = ('%s %s' % (defn.name, getTypename(defn)) for defn in pd.fields) sql = 'CREATE TABLE IF NOT EXISTS %s (%s)' % (pd.name, ', '.join(cols)) dbconn.execute(sql) dbconn.commit()
def createTable(dbconn, pd)
Creates a database table for the given PacketDefinition.
3.205281
2.932524
1.093011
values = [ ] pd = packet._defn for defn in pd.fields: if defn.enum: val = getattr(packet.raw, defn.name) else: val = getattr(packet, defn.name) if val is None and defn.name in pd.history: val = getattr(packet.history, defn.name) ...
def insert(dbconn, packet)
Inserts the given packet into the connected database.
3.377751
3.358184
1.005827
global Backend try: Backend = importlib.import_module(backend) except ImportError: msg = 'Could not import (load) database.backend: %s' % backend raise cfg.AitConfigError(msg)
def use(backend)
Use the given database backend, e.g. 'MySQLdb', 'psycopg2', 'MySQLdb', etc.
7.430923
7.208044
1.030921
''' Connect to an InfluxDB instance Connects to an InfluxDB instance and switches to a given database. If the database doesn't exist it is created first via :func:`create`. **Configuration Parameters** host The host for the connection. Passed as either the config key...
def connect(self, **kwargs)
Connect to an InfluxDB instance Connects to an InfluxDB instance and switches to a given database. If the database doesn't exist it is created first via :func:`create`. **Configuration Parameters** host The host for the connection. Passed as either the config key *...
2.264205
1.348927
1.678523
''' Create a database in a connected InfluxDB instance **Configuration Parameters** database name The database name to create. Passed as either the config key **database.dbname** or the kwargs argument **database**. Defaults to **ait**. Raises: ...
def create(self, **kwargs)
Create a database in a connected InfluxDB instance **Configuration Parameters** database name The database name to create. Passed as either the config key **database.dbname** or the kwargs argument **database**. Defaults to **ait**. Raises: At...
7.667597
2.070779
3.702759
''' Insert a packet into the database Arguments packet The :class:`ait.core.tlm.Packet` instance to insert into the database time Optional parameter specifying the time value to use when inserting the record into t...
def insert(self, packet, time=None, **kwargs)
Insert a packet into the database Arguments packet The :class:`ait.core.tlm.Packet` instance to insert into the database time Optional parameter specifying the time value to use when inserting the record into the database....
3.974655
2.057782
1.931524
''' Generate AIT Packets from a InfluxDB query ResultSet Extract Influx DB query results into one packet per result entry. This assumes that telemetry data was inserted in the format generated by :func:`InfluxDBBackend.insert`. Complex types such as CMD16 and EVR16 are evaluated...
def create_packets_from_results(self, packet_name, result_set)
Generate AIT Packets from a InfluxDB query ResultSet Extract Influx DB query results into one packet per result entry. This assumes that telemetry data was inserted in the format generated by :func:`InfluxDBBackend.insert`. Complex types such as CMD16 and EVR16 are evaluated if they can...
3.720641
2.009091
1.851903
''' Connect to a SQLite instance **Configuration Parameters** database The database name or file to "connect" to. Defaults to **ait**. ''' if 'database' not in kwargs: kwargs['database'] = 'ait' self._conn = self._backend.connect(kwargs[...
def connect(self, **kwargs)
Connect to a SQLite instance **Configuration Parameters** database The database name or file to "connect" to. Defaults to **ait**.
11.627441
3.308293
3.514635
''' Create a database for the current telemetry dictionary Connects to a SQLite instance via :func:`connect` and creates a skeleton database for future data inserts. **Configuration Parameters** tlmdict The :class:`ait.core.tlm.TlmDict` instance to use. Defaults t...
def create(self, **kwargs)
Create a database for the current telemetry dictionary Connects to a SQLite instance via :func:`connect` and creates a skeleton database for future data inserts. **Configuration Parameters** tlmdict The :class:`ait.core.tlm.TlmDict` instance to use. Defaults to ...
9.989347
2.568187
3.889649
''' Creates a database table for the given PacketDefinition Arguments packet_defn The :class:`ait.core.tlm.PacketDefinition` instance for which a table entry should be made. ''' cols = ('%s %s' % (defn.name, self._getTypename(defn)) for defn i...
def _create_table(self, packet_defn)
Creates a database table for the given PacketDefinition Arguments packet_defn The :class:`ait.core.tlm.PacketDefinition` instance for which a table entry should be made.
4.302616
2.422023
1.776456
''' Insert a packet into the database Arguments packet The :class:`ait.core.tlm.Packet` instance to insert into the database ''' values = [ ] pd = packet._defn for defn in pd.fields: val = getattr(packet.raw, ...
def insert(self, packet, **kwargs)
Insert a packet into the database Arguments packet The :class:`ait.core.tlm.Packet` instance to insert into the database
4.618991
3.555202
1.299221
return 'REAL' if defn.type.float or 'TIME' in defn.type.name or defn.dntoeu else 'INTEGER'
def _getTypename(self, defn)
Returns the SQL typename required to store the given FieldDefinition
23.339472
18.46221
1.264175
def genCubeVector(x, y, z, x_mult=1, y_mult=1, z_mult=1): cX = (x - 1) / 2.0 cY = (y - 1) / 2.0 cZ = (z - 1) / 2.0 def vect(_x, _y, _z): return int(math.sqrt(math.pow(_x - cX, 2 * x_mult) + math.pow(_y - cY, 2 * y_mult) + m...
Generates a map of vector lengths from the center point to each coordinate x - width of matrix to generate y - height of matrix to generate z - depth of matrix to generate x_mult - value to scale x-axis by y_mult - value to scale y-axis by z_mult - value to scale z-axis by
null
null
null
if to_tz is None: to_tz = settings.TIME_ZONE if value.tzinfo is None: if not hasattr(from_tz, "localize"): from_tz = pytz.timezone(smart_str(from_tz)) value = from_tz.localize(value) return value.astimezone(pytz.timezone(smart_str(to_tz)))
def adjust_datetime_to_timezone(value, from_tz, to_tz=None)
Given a ``datetime`` object adjust it according to the from_tz timezone string into the to_tz timezone string.
2.03
2.04222
0.994016
## convert to settings.TIME_ZONE if value is not None: if value.tzinfo is None: value = default_tz.localize(value) else: value = value.astimezone(default_tz) return super(LocalizedDateTimeField, self).get_db_prep_save(value, connec...
def get_db_prep_save(self, value, connection=None)
Returns field's value prepared for saving into a database.
2.881519
2.876183
1.001855
## convert to settings.TIME_ZONE if value.tzinfo is None: value = default_tz.localize(value) else: value = value.astimezone(default_tz) return super(LocalizedDateTimeField, self).get_db_prep_lookup(lookup_type, value, connection=connection, prepared=prepa...
def get_db_prep_lookup(self, lookup_type, value, connection=None, prepared=None)
Returns field's value prepared for database lookup.
2.93905
2.942904
0.99869
def liveNeighbours(self, z, y, x): count = 0 for oz, oy, ox in self.offsets: cz, cy, cx = z + oz, y + oy, x + ox if cz >= self.depth: cz = 0 if cy >= self.height: cy = 0 if cx >= self.width: ...
Returns the number of live neighbours.
null
null
null
def turn(self): r = (4, 5, 5, 5) nt = copy.deepcopy(self.table) for z in range(self.depth): for y in range(self.height): for x in range(self.width): neighbours = self.liveNeighbours(z, y, x) if self.table[z][y][...
Turn
null
null
null
"Make a set of 'shaped' random #'s for particle brightness deltas (bd)" self.bd = concatenate(( # These values will dim the particles random.normal( self.bd_mean - self.bd_mu, self.bd_sigma, 16).astype(int), # These values will brighten the particles ...
def make_bd(self)
Make a set of 'shaped' random #'s for particle brightness deltas (bd)
6.751412
3.415238
1.976849
"Make a set of velocities to be randomly chosen for emitted particles" self.vel = random.normal(self.vel_mu, self.vel_sigma, 16) # Make sure nothing's slower than 1/8 pixel / step for i, vel in enumerate(self.vel): if abs(vel) < 0.125 / self._size: if vel < 0:...
def make_vel(self)
Make a set of velocities to be randomly chosen for emitted particles
4.440895
3.384382
1.312173
moved_particles = [] for vel, pos, stl, color, bright in self.particles: stl -= 1 # steps to live if stl > 0: pos = pos + vel if vel > 0: if pos >= (self._end + 1): if self.wrap: ...
def move_particles(self)
Move each particle by it's velocity, adjusting brightness as we go. Particles that have moved beyond their range (steps to live), and those that move off the ends and are not wrapped get sacked. Particles can stay between _end and up to but not including _end+1 No particles can exitst be...
5.01232
3.762958
1.332016
moved_emitters = [] for e_pos, e_dir, e_vel, e_range, e_color, e_pal in self.emitters: e_pos = e_pos + e_vel if e_vel > 0: if e_pos >= (self._end + 1): if self.wrap: e_pos = e_pos - (self._end + 1) + self._star...
def move_emitters(self)
Move each emitter by it's velocity. Emmitters that move off the ends and are not wrapped get sacked.
2.762671
2.349646
1.175782
for e_pos, e_dir, e_vel, e_range, e_color, e_pal in self.emitters: for roll in range(self.starts_at_once): if random.random() < self.starts_prob: # Start one? p_vel = self.vel[random.choice(len(self.vel))] if e_dir < 0 or e_dir == 0 a...
def start_new_particles(self)
Start some new particles from the emitters. We roll the dice starts_at_once times, seeing if we can start each particle based on starts_prob. If we start, the particle gets a color form the palette and a velocity from the vel list.
4.991419
3.514457
1.420253
dist = abs(particle_pos - strip_pos) if dist > self.half_size: dist = self._size - dist if dist < self.aperture: return (self.aperture - dist) / self.aperture else: return 0
def visibility(self, strip_pos, particle_pos)
Compute particle visibility based on distance between current strip position being rendered and particle position. A value of 0.0 is returned if they are >= one aperture away, values between 0.0 and 1.0 are returned if they are less than one aperature apart.
3.566006
3.037092
1.174151
for strip_pos in range(self._start, self._end + 1): blended = COLORS.black # Render visible emitters if self.has_e_colors: for (e_pos, e_dir, e_vel, e_range, e_color, e_pal) in self.emitters: if e_color is no...
def render_particles(self)
Render visible particles at each strip position, by modifying the strip's color list.
4.259354
3.836074
1.110342
"Make a frame of the animation" self.move_particles() if self.has_moving_emitters: self.move_emitters() self.start_new_particles() self.render_particles() if self.emitters == [] and self.particles == []: self.completed = True
def step(self, amt=1)
Make a frame of the animation
6.460964
5.172364
1.249132
if None not in [v for v in self.squares]: return True if self.winner() is not None: return True return False
def complete(self)
is the game over?
6.880841
4.857178
1.416634
if player: return [k for k, v in enumerate(self.squares) if v == player] else: return self.squares
def get_squares(self, player=None)
squares that belong to a player
3.415835
3.044434
1.121994
count = 0 if y > 0: if self.table[y - 1][x]: count = count + 1 if x > 0: if self.table[y - 1][x - 1]: count = count + 1 if self.width > (x + 1): if self.table[y - 1][x + 1]: ...
def liveNeighbours(self, y, x)
Returns the number of live neighbours.
1.338667
1.322391
1.012308
'''Creates a Glycine residue''' ##Create Residue Data Structure res= Residue((' ', segID, ' '), "GLY", ' ') res.add(N) res.add(CA) res.add(C) res.add(O) ##print(res) return res
def makeGly(segID, N, CA, C, O, geo)
Creates a Glycine residue
6.152136
6.48659
0.948439
'''Creates an Alanine residue''' ##R-Group CA_CB_length=geo.CA_CB_length C_CA_CB_angle=geo.C_CA_CB_angle N_C_CA_CB_diangle=geo.N_C_CA_CB_diangle carbon_b= calculateCoordinates(N, C, CA, CA_CB_length, C_CA_CB_angle, N_C_CA_CB_diangle) CB= Atom("CB", carbon_b, 0.0 , 1.0, " "," CB", 0,"C") ...
def makeAla(segID, N, CA, C, O, geo)
Creates an Alanine residue
3.881247
4.005626
0.968949
'''Creates a Serine residue''' ##R-Group CA_CB_length=geo.CA_CB_length C_CA_CB_angle=geo.C_CA_CB_angle N_C_CA_CB_diangle=geo.N_C_CA_CB_diangle CB_OG_length=geo.CB_OG_length CA_CB_OG_angle=geo.CA_CB_OG_angle N_CA_CB_OG_diangle=geo.N_CA_CB_OG_diangle carbon_b= calculateCoordinate...
def makeSer(segID, N, CA, C, O, geo)
Creates a Serine residue
2.682234
2.692826
0.996067
'''Creates a Cysteine residue''' ##R-Group CA_CB_length=geo.CA_CB_length C_CA_CB_angle=geo.C_CA_CB_angle N_C_CA_CB_diangle=geo.N_C_CA_CB_diangle CB_SG_length= geo.CB_SG_length CA_CB_SG_angle= geo.CA_CB_SG_angle N_CA_CB_SG_diangle= geo.N_CA_CB_SG_diangle carbon_b= calculateCoord...
def makeCys(segID, N, CA, C, O, geo)
Creates a Cysteine residue
2.663297
2.681302
0.993285
'''Creates a Valine residue''' ##R-Group CA_CB_length=geo.CA_CB_length C_CA_CB_angle=geo.C_CA_CB_angle N_C_CA_CB_diangle=geo.N_C_CA_CB_diangle CB_CG1_length=geo.CB_CG1_length CA_CB_CG1_angle=geo.CA_CB_CG1_angle N_CA_CB_CG1_diangle=geo.N_CA_CB_CG1_diangle CB_CG2_length=geo.C...
def makeVal(segID, N, CA, C, O, geo)
Creates a Valine residue
1.9151
1.903865
1.005901