code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
''' Remove all handlers with a given name
Args:
name:
The name of the handler(s) to remove.
'''
empty_capturers_indeces = []
for k, sc in self._stream_capturers.iteritems():
stream_capturer = sc[0]
stream_capturer.remove_handle... | def stop_capture_handler(self, name) | Remove all handlers with a given name
Args:
name:
The name of the handler(s) to remove. | 3.963663 | 3.496201 | 1.133706 |
''' Stop a capturer that the manager controls.
Args:
address:
An address array of the form ['host', 'port'] or similar
depending on the connection type of the stream capturer being
terminated. The capturer for the address will be terminated
... | def stop_stream_capturer(self, address) | Stop a capturer that the manager controls.
Args:
address:
An address array of the form ['host', 'port'] or similar
depending on the connection type of the stream capturer being
terminated. The capturer for the address will be terminated
... | 5.562011 | 1.868473 | 2.976768 |
''' Force a rotation of a handler's log file
Args:
name:
The name of the handler who's log file should be rotated.
'''
for sc_key, sc in self._stream_capturers.iteritems():
for h in sc[0].capture_handlers:
if h['name'] == name:
... | def rotate_capture_handler_log(self, name) | Force a rotation of a handler's log file
Args:
name:
The name of the handler who's log file should be rotated. | 5.9233 | 4.469445 | 1.325288 |
''' Return data on managed loggers.
Returns a dictionary of managed logger configuration data. The format
is primarily controlled by the
:func:`SocketStreamCapturer.dump_handler_config_data` function::
{
<capture address>: <list of handler config for data ca... | def get_logger_data(self) | Return data on managed loggers.
Returns a dictionary of managed logger configuration data. The format
is primarily controlled by the
:func:`SocketStreamCapturer.dump_handler_config_data` function::
{
<capture address>: <list of handler config for data capturers>
... | 9.880458 | 2.072507 | 4.767394 |
''' Return handler read statistics
Returns a dictionary of managed handler data read statistics. The
format is primarily controlled by the
:func:`SocketStreamCapturer.dump_all_handler_stats` function::
{
<capture address>: <list of handler capture statistics... | def get_handler_stats(self) | Return handler read statistics
Returns a dictionary of managed handler data read statistics. The
format is primarily controlled by the
:func:`SocketStreamCapturer.dump_all_handler_stats` function::
{
<capture address>: <list of handler capture statistics>
... | 10.277199 | 2.24555 | 4.576695 |
''' Return data for handlers of a given name.
Args:
name:
Name of the capture handler(s) to return config data for.
Returns:
Dictionary dump from the named capture handler as given by
the :func:`SocketStreamCapturer.dump_handler_config_data` ... | def get_capture_handler_config_by_name(self, name) | Return data for handlers of a given name.
Args:
name:
Name of the capture handler(s) to return config data for.
Returns:
Dictionary dump from the named capture handler as given by
the :func:`SocketStreamCapturer.dump_handler_config_data` method. | 4.925624 | 2.125697 | 2.317181 |
''' Start monitoring managed loggers. '''
try:
while True:
self._pool.join()
# If we have no loggers we'll sleep briefly to ensure that we
# allow other processes (I.e., the webserver) to do their work.
if len(self._logger_data... | def run_socket_event_loop(self) | Start monitoring managed loggers. | 6.77422 | 5.457337 | 1.241305 |
''' Starts the server. '''
self._app.run(host=self._host, port=self._port) | def start(self) | Starts the server. | 5.878656 | 6.979453 | 0.84228 |
''' Handles server route instantiation. '''
self._app.route('/',
method='GET',
callback=self._get_logger_list)
self._app.route('/stats',
method='GET',
callback=self._fetch_handler_stats)
self.... | def _route(self) | Handles server route instantiation. | 2.946297 | 2.642336 | 1.115035 |
''' Handles POST requests for adding a new logger.
Expects logger configuration to be passed in the request's query string.
The logger name is included in the URL and the address components and
connection type should be included as well. The loc attribute is
defaulted to "localh... | def _add_logger_by_name(self, name) | Handles POST requests for adding a new logger.
Expects logger configuration to be passed in the request's query string.
The logger name is included in the URL and the address components and
connection type should be included as well. The loc attribute is
defaulted to "localhost" when ma... | 5.638881 | 1.983328 | 2.843142 |
'''Recursive handling of includes for any input list of defns.
The assumption here is that when an include is handled by the
pyyaml reader, it adds them as a list, which is stands apart from the rest
of the expected YAML definitions.
'''
newdefns = []
for d in defns:
if isinstance(d,... | def handle_includes(defns) | Recursive handling of includes for any input list of defns.
The assumption here is that when an include is handled by the
pyyaml reader, it adds them as a list, which is stands apart from the rest
of the expected YAML definitions. | 7.338865 | 1.775563 | 4.13326 |
result = None
terms = None
if self._when is None or self._when.eval(packet):
result = self._equation.eval(packet)
return result | def eval(self, packet) | Returns the result of evaluating this DNToEUConversion in the
context of the given Packet. | 8.23986 | 7.608702 | 1.082952 |
valid = True
primitive = value
def log(msg):
if messages is not None:
messages.append(msg)
if self.enum:
if value not in self.enum.values():
valid = False
flds = (self.name, str(value))
... | def validate(self, value, messages=None) | Returns True if the given field value is valid, False otherwise.
Validation error messages are appended to an optional messages
array. | 3.609128 | 3.516393 | 1.026372 |
if index is not None and isinstance(self.type, dtype.ArrayType):
value = self.type.decode( bytes[self.slice()], index, raw )
else:
value = self.type.decode( bytes[self.slice()], raw )
# Apply bit mask if needed
if self.mask is not None:
valu... | def decode(self, bytes, raw=False, index=None) | Decodes the given bytes according to this Field Definition.
If raw is True, no enumeration substitutions will be applied
to the data returned.
If index is an integer or slice (and the type of this
FieldDefinition is an ArrayType), then only the element(s) at
the specified posit... | 3.428567 | 3.386664 | 1.012373 |
if type(value) == str and self.enum and value in self.enum:
value = self.enum[value]
if type(value) == int:
if self.shift > 0:
value <<= self.shift
if self.mask is not None:
value &= self.mask
return self.type.encode(... | def encode(self, value) | Encodes the given value according to this FieldDefinition. | 3.253222 | 3.131879 | 1.038744 |
if self.bytes is None:
start = 0
stop = start + self.nbytes
elif type(self.bytes) is int:
start = self.bytes
stop = start + self.nbytes
else:
start = self.bytes[0]
stop = self.bytes[1] + 1
return slice(s... | def slice(self, offset=0) | Returns a Python slice object (e.g. for array indexing) indicating
the start and stop byte position of this Telemetry field. The
start and stop positions may be translated by the optional
byte offset. | 2.616618 | 2.398088 | 1.091127 |
if not self._hasattr(fieldname):
values = self._defn.name, fieldname
raise AttributeError("Packet '%s' has no field '%s'" % values) | def _assertField(self, fieldname) | Raise AttributeError when Packet has no field with the given
name. | 9.471129 | 7.094608 | 1.334976 |
self._assertField(fieldname)
value = None
if fieldname == 'raw':
value = createRawPacket(self)
elif fieldname == 'history':
value = self._defn.history
else:
if fieldname in self._defn.derivationmap:
defn = self._defn.d... | def _getattr (self, fieldname, raw=False, index=None) | Returns the value of the given packet field name.
If raw is True, the field value is only decoded. That is no
enumeration substituions or DN to EU conversions are applied. | 3.831149 | 3.443616 | 1.112537 |
special = 'history', 'raw'
return (fieldname in special or
fieldname in self._defn.fieldmap or
fieldname in self._defn.derivationmap) | def _hasattr(self, fieldname) | Returns True if this packet contains fieldname, False otherwise. | 10.978631 | 10.990745 | 0.998898 |
pos = slice(start, start)
for fd in defns:
if fd.bytes == '@prev' or fd.bytes is None:
if fd.bytes == '@prev':
fd.bytes = None
pos = fd.slice(pos.start)
elif fd.bytes is None:
pos ... | def _update_bytes(self, defns, start=0) | Updates the 'bytes' field in all FieldDefinition.
Any FieldDefinition.bytes which is undefined (None) or '@prev'
will have its bytes field computed based on its data type size
and where the previous FieldDefinition ended (or the start
parameter in the case of very first FieldDefinition)... | 4.123716 | 2.926744 | 1.408977 |
max_byte = -1
for defn in self.fields:
byte = defn.bytes if type(defn.bytes) is int else max(defn.bytes)
max_byte = max(max_byte, byte)
return max_byte + 1 | def nbytes(self) | The number of bytes for this telemetry packet | 4.638355 | 4.645029 | 0.998563 |
valid = True
for f in self.fields:
try:
value = getattr(pkt, f.name)
except AttributeError:
valid = False
if messages is not None:
msg = "Telemetry field mismatch for packet '%s'. "
... | def validate(self, pkt, messages=None) | Returns True if the given Packet is valid, False otherwise.
Validation error messages are appended to an optional messages
array. | 3.927176 | 3.695968 | 1.062557 |
try:
context = createPacketContext(packet)
result = eval(self._code, packet._defn.globals, context)
except ZeroDivisionError:
result = None
return result | def eval(self, packet) | Returns the result of evaluating this PacketExpression in the
context of the given Packet. | 9.755955 | 7.333912 | 1.330252 |
if name not in self._names:
msg = 'PacketHistory "%s" has no field "%s"'
values = self._defn.name, name
raise AttributeError(msg % values) | def _assertField(self, name) | Raise AttributeError when PacketHistory has no field with the given
name. | 10.393554 | 5.835914 | 1.780964 |
for name in self._names:
value = getattr(packet, name)
if value is not None:
self._dict[name] = value | def add(self, packet) | Add the given Packet to this PacketHistory. | 3.738458 | 3.696561 | 1.011334 |
if defn.name not in self:
self[defn.name] = defn
else:
msg = "Duplicate packet name '%s'" % defn.name
log.error(msg)
raise util.YAMLError(msg) | def add(self, defn) | Adds the given Packet Definition to this Telemetry Dictionary. | 3.596722 | 2.983208 | 1.205656 |
return createPacket(self[name], data) if name in self else None | def create(self, name, data=None) | Creates a new packet with the given definition and raw data. | 18.227409 | 10.019285 | 1.819233 |
if self.filename is None:
if os.path.isfile(content):
self.filename = content
stream = open(self.filename, 'rb')
else:
stream = content
pkts = yaml.load(stream)
pkts = handle_includes(pkts)
... | def load(self, content) | Loads Packet Definitions from the given YAML content into this
Telemetry Dictionary. Content may be either a filename
containing YAML content or a YAML string.
Load has no effect if this Command Dictionary was already
instantiated with a filename or YAML content. | 4.422722 | 3.736683 | 1.183596 |
'''writeToCSV - write the telemetry dictionary to csv
'''
header = ['Name', 'First Byte', 'Last Byte', 'Bit Mask', 'Endian',
'Type', 'Description', 'Values']
if output_path is None:
output_path = ait.config._directory
for pkt_name in self.tlmdict:
... | def writeToCSV(self, output_path=None) | writeToCSV - write the telemetry dictionary to csv | 3.71802 | 3.565224 | 1.042857 |
value = self.type.decode(bytes)
if self._enum is not None:
for name, val in self._enum.items():
if value == val:
value = name
break
return value | def decode(self, bytes) | Decodes the given bytes according to this AIT Argument
Definition. | 3.424159 | 3.388998 | 1.010375 |
if type(value) == str and self.enum and value in self.enum:
value = self.enum[value]
return self.type.encode(value) if self.type else bytearray() | def encode(self, value) | Encodes the given value according to this AIT Argument
Definition. | 3.981877 | 3.780439 | 1.053284 |
valid = True
primitive = value
def log(msg):
if messages is not None:
messages.append(msg)
if self.enum:
if value not in self.enum.keys():
valid = False
args = (self.name, str(value))
... | def validate(self, value, messages=None) | Returns True if the given Argument value is valid, False otherwise.
Validation error messages are appended to an optional messages
array. | 2.55426 | 2.519847 | 1.013657 |
opcode = struct.pack('>H', self.defn.opcode)
offset = len(opcode)
size = max(offset + self.defn.argsize, pad)
encoded = bytearray(size)
encoded[0:offset] = opcode
encoded[offset] = self.defn.argsize
offset += 1
index ... | def encode(self, pad=106) | Encodes this AIT command to binary.
If pad is specified, it indicates the maximum size of the encoded
command in bytes. If the encoded command is less than pad, the
remaining bytes are set to zero.
Commands sent to ISS payloads over 1553 are limited to 64 words
(128 bytes) wit... | 3.931283 | 4.124259 | 0.95321 |
return len(self.opcode) + 1 + sum(arg.nbytes for arg in self.argdefns) | def nbytes(self) | The number of bytes required to encode this command.
Encoded commands are comprised of a two byte opcode, followed by a
one byte size, and then the command argument bytes. The size
indicates the number of bytes required to represent command
arguments. | 9.555829 | 9.36245 | 1.020655 |
argsize = sum(arg.nbytes for arg in self.argdefns)
return argsize if len(self.argdefns) > 0 else 0 | def argsize(self) | The total size in bytes of all the command arguments. | 4.931217 | 4.369567 | 1.128537 |
valid = True
args = [ arg for arg in cmd.args if arg is not None ]
if self.nargs != len(args):
valid = False
if messages is not None:
msg = 'Expected %d arguments, but received %d.'
messages.append(msg % (self.nargs, len(args)))... | def validate(self, cmd, messages=None) | Returns True if the given Command is valid, False otherwise.
Validation error messages are appended to an optional messages
array. | 2.475056 | 2.440877 | 1.014003 |
self[defn.name] = defn
self.opcodes[defn._opcode] = defn | def add(self, defn) | Adds the given Command Definition to this Command Dictionary. | 9.778907 | 7.192972 | 1.359509 |
tokens = name.split()
if len(tokens) > 1 and (len(args) > 0 or len(kwargs) > 0):
msg = 'A Cmd may be created with either positional arguments '
msg += '(passed as a string or a Python list) or keyword '
msg += 'arguments, but not both.'
raise Ty... | def create(self, name, *args, **kwargs) | Creates a new AIT command with the given arguments. | 3.861761 | 3.849887 | 1.003084 |
opcode = struct.unpack(">H", bytes[0:2])[0]
nbytes = struct.unpack("B", bytes[2:3])[0]
name = None
args = []
if opcode in self.opcodes:
defn = self.opcodes[opcode]
name = defn.name
stop = 3
for arg in defn.argdefns... | def decode(self, bytes) | Decodes the given bytes according to this AIT Command
Definition. | 4.10324 | 4.028528 | 1.018546 |
if self.filename is None:
if os.path.isfile(content):
self.filename = content
stream = open(self.filename, 'rb')
else:
stream = content
for cmd in yaml.load(stream):
self.add(cmd)
... | def load(self, content) | Loads Command Definitions from the given YAML content into
into this Command Dictionary. Content may be either a
filename containing YAML content or a YAML string.
Load has no effect if this Command Dictionary was already
instantiated with a filename or YAML content. | 4.15639 | 3.433545 | 1.210524 |
if x >= 0:
return math.pow(x , 1.0 / 3.0)
else:
return - math.pow(abs(x), 1.0 / 3.0) | def cbrt (x) | Returns the cube root of x. | 3.32118 | 3.013725 | 1.102018 |
if gmst is None:
gmst = dmc.toGMST()
X = (x * math.cos(gmst)) + (y * math.sin(gmst))
Y = (x * (-math.sin(gmst))) + (y * math.cos(gmst))
Z = z
return X, Y, Z | def eci2ecef (x, y, z, gmst=None) | Converts the given ECI coordinates to ECEF at the given Greenwich
Mean Sidereal Time (GMST) (defaults to now).
This code was adapted from
`shashwatak/satellite-js <https://github.com/shashwatak/satellite-js/blob/master/src/coordinate-transforms.js>`_
and http://ccar.colorado.edu/ASEN5070/handouts/coordsys.do... | 2.866741 | 3.410532 | 0.840555 |
if gmst is None:
gmst = dmc.toGMST()
if ellipsoid is None:
ellipsoid = WGS84
a = WGS84.a
b = WGS84.b
f = WGS84.f
r = math.sqrt((x * x) + (y * y))
e2 = (2 * f) - (f * f)
lon = math.atan2(y, x) - gmst
k = 0
kmax = 20
lat = math.atan2(z, r)
while (k < kmax):
sla... | def eci2geodetic (x, y, z, gmst=None, ellipsoid=None) | Converts the given ECI coordinates to Geodetic coordinates at the
given Greenwich Mean Sidereal Time (GMST) (defaults to now) and with
the given ellipsoid (defaults to WGS84).
This code was adapted from
`shashwatak/satellite-js <https://github.com/shashwatak/satellite-js/blob/master/src/coordinate-transforms.j... | 2.613995 | 2.651419 | 0.985885 |
for handler in self.handlers:
output = handler.handle(input_data)
input_data = output
self.publish(input_data) | def process(self, input_data, topic=None) | Invokes each handler in sequence.
Publishes final output data.
Params:
input_data: message received by stream
topic: name of plugin or stream message received from,
if applicable | 4.937885 | 4.51169 | 1.094465 |
for ix, handler in enumerate(self.handlers[:-1]):
next_input_type = self.handlers[ix + 1].input_type
if (handler.output_type is not None and
next_input_type is not None):
if handler.output_type != next_input_type:
return F... | def valid_workflow(self) | Return true if each handler's output type is the same as
the next handler's input type. Return False if not.
Returns: boolean - True if workflow is valid, False if not | 3.383827 | 2.674933 | 1.265014 |
input_size = 0
output_size = 0
if output_filename is None:
output_filename = input_fillename + '.ait-zlib'
try:
stream = open(input_filename , 'rb')
output = open(output_filename, 'wb')
bytes = stream.read()
input_size = len(bytes)
if verbose:
log.info("Compress... | def compress (input_filename, output_filename=None, verbose=False) | compress(input_filename, output_filename=None, verbose=False) -> integer
Uses zlib to compress input_filename and store the result in
output_filename. The size of output_filename is returned on
success; zero is returned on failure.
The input file is compressed in one fell swoop. The output_filename
defaul... | 2.831133 | 2.619379 | 1.080841 |
if preamble is None:
preamble = ""
bytes = bytearray(bytes)
size = len(bytes)
for n in xrange(0, size, stepsize):
if addr is not None:
dump = preamble + "0x%04X: " % (addr + n)
else:
dump = preamble
end = min(size, n + stepsize)
dump += hexdumpLine(bytes[n:end], stepsize)... | def hexdump (bytes, addr=None, preamble=None, printfunc=None, stepsize=16) | hexdump(bytes[, addr[, preamble[, printfunc[, stepsize=16]]]])
Outputs bytes in hexdump format lines similar to the following (here
preamble='Bank1', stepsize=8, and len(bytes) == 15)::
Bank1: 0xFD020000: 7f45 4c46 0102 0100 *.ELF....*
Bank1: 0xFD020008: 0000 0000 0000 00 *....... *
Where ste... | 2.465999 | 2.788664 | 0.884294 |
line = ""
if length is None:
length = len(bytes)
for n in xrange(0, length, 2):
if n < len(bytes) - 1:
line += "%02x%02x " % (bytes[n], bytes[n + 1])
elif n < len(bytes):
line += "%02x " % bytes[n]
else:
line += " "
line += "*"
for n in xrange(length):
i... | def hexdumpLine (bytes, length=None) | hexdumpLine(bytes[, length])
Returns a single hexdump formatted line for bytes. If length is
greater than len(bytes), the line will be padded with ASCII space
characters to indicate no byte data is present.
Used by hexdump(). | 2.169836 | 2.198493 | 0.986965 |
options = dict(defaults)
numeric = \
[ k for k, v in options.items() if type(v) is float or type(v) is int ]
try:
longopts = [ "%s=" % key for key in options.keys() ]
opts, args = getopt.getopt(argv, "", longopts)
for key, value in opts:
if key.startswith("--"):
key = key[2:]
... | def parseArgs (argv, defaults) | parseArgs(argv, defaults) -> (dict, list)
Parses command-line arguments according to the given defaults. For
every key in defaults, an argument of the form --key=value will be
parsed. Numeric arguments are converted from strings with errors
reported via ait.core.log.error() and default values used instead.
... | 2.808779 | 2.985914 | 0.940677 |
stream = open(sys.argv[0])
for line in stream.readlines():
if line.startswith("##"): print line.replace("##", ""),
stream.close()
if exit:
sys.exit(2) | def usage (exit=False) | usage([exit])
Prints the usage statement at the top of a Python program. A usage
statement is any comment at the start of a line that begins with a
double hash marks (##). The double hash marks are removed before
the usage statement is printed. If exit is True, the program is
terminated with a return code... | 4.916328 | 4.191387 | 1.17296 |
return [(s.connect(('8.8.8.8', 80)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1] | def getip() | getip()
Returns the IP address of the computer. Helpful for those hosts that might
sit behind gateways and report a hostname that is a little strange (I'm
looking at you oco3-sim1). | 1.604005 | 1.742487 | 0.920526 |
if not description:
description = ""
ap = argparse.ArgumentParser(
description = description,
formatter_class = argparse.ArgumentDefaultsHelpFormatter
)
for name, params in arguments.items():
ap.add_argument(name, **params)
args = ap.parse_args()
return args | def arg_parse(arguments, description=None) | arg_parse()
Parses the arguments using argparse. Returns a Namespace object. The
arguments dictionary should match the argparse expected data structure:
.. code-block::python
arguments = {
'--port': {
'type' : int,
'default' : 3075,
'help' : 'Port on which to send data'
... | 2.818007 | 2.917182 | 0.966003 |
if not os.path.exists(file):
# Argparse uses the ArgumentTypeError to give a rejection message like:
# error: argument input: file does not exist
raise argparse.ArgumentTypeError("{0} does not exist".format(file))
return file | def extant_file(file) | 'Type' for argparse - checks that file exists but does not open. | 2.418487 | 2.319855 | 1.042516 |
if self.z:
return (self.x * other.x) + (self.y * other.y) + (self.z * other.z)
else:
return (self.x * other.x) + (self.y * other.y) | def dot (self, other) | dot (self, other) -> number
Returns the dot product of this Point with another. | 2.037051 | 1.959341 | 1.039661 |
return (self.p.y - self.q.y) / (self.p.x - self.q.x) | def slope (self) | slope () -> float | 3.562118 | 3.226743 | 1.103936 |
(x1, y1) = (self.p.x, self.p.y)
(x2, y2) = (self.q.x, self.q.y)
(x3, y3) = (line.p.x, line.p.y)
(x4, y4) = (line.q.x, line.q.y)
denom = ((y4 - y3) * (x2 - x1)) - ((x4 - x3) * (y2 - y1))
num1 = ((x4 - x3) * (y1 - y3)) - ((y4 - y3) * (x1 - x3))
num2 = ((x2 - x1) * (y1 - ... | def intersect (self, line) | intersect (line) -> Point | None
Returns the intersection point of this line segment with another.
If this line segment and the other line segment are conincident,
the first point on this line segment is returned. If the line
segments do not intersect, None is returned.
See http://local.wasp.uwa.... | 1.550601 | 1.646674 | 0.941656 |
eps = 1e-8
d = (line.q - line.p)
dn = d.dot(self.n)
point = None
if abs(dn) >= eps:
mu = self.n.dot(self.p - line.p) / dn
if mu >= 0 and mu <= 1:
point = line.p + mu * d
return point | def intersect (self, line) | intersect(line) -> Point | None
Returns the point at which the line segment and Plane intersect
or None if they do not intersect. | 4.221328 | 3.675291 | 1.14857 |
area = 0.0
for segment in self.segments():
area += ((segment.p.x * segment.q.y) - (segment.q.x * segment.p.y))/2
return area | def area (self) | area() -> number
Returns the area of this Polygon. | 4.458991 | 4.28194 | 1.041348 |
if self._dirty:
min = self.vertices[0].copy()
max = self.vertices[0].copy()
for point in self.vertices[1:]:
if point.x < min.x: min.x = point.x
if point.y < min.y: min.y = point.y
if point.x > max.x: max.x = point.x
if point.y > max.y: max.y = point.y
se... | def bounds (self) | bounds() -> Rect
Returns the bounding Rectangle for this Polygon. | 2.105245 | 1.89576 | 1.110502 |
Cx = 0.0
Cy = 0.0
denom = 6.0 * self.area()
for segment in self.segments():
x = (segment.p.x + segment.q.x)
y = (segment.p.y + segment.q.y)
xy = (segment.p.x * segment.q.y) - (segment.q.x * segment.p.y)
Cx += (x * xy)
Cy += (y * xy)
Cx /= denom
Cy ... | def center (self) | center() -> (x, y)
Returns the center (of mass) point of this Polygon.
See http://en.wikipedia.org/wiki/Polygon
Examples:
>>> p = Polygon()
>>> p.vertices = [ Point(3, 8), Point(6, 4), Point(0, 3) ]
>>> p.center()
Point(2.89285714286, 4.82142857143) | 2.812625 | 2.956109 | 0.951462 |
inside = False
if p in self.bounds():
for s in self.segments():
if ((s.p.y > p.y) != (s.q.y > p.y) and
(p.x < (s.q.x - s.p.x) * (p.y - s.p.y) / (s.q.y - s.p.y) + s.p.x)):
inside = not inside
return inside | def contains (self, p) | Returns True if point is contained inside this Polygon, False
otherwise.
This method uses the Ray Casting algorithm.
Examples:
>>> p = Polygon()
>>> p.vertices = [Point(1, 1), Point(1, -1), Point(-1, -1), Point(-1, 1)]
>>> p.contains( Point(0, 0) )
True
>>> p.contains( Point(2, ... | 2.272342 | 2.764185 | 0.822066 |
for n in xrange(len(self.vertices) - 1):
yield Line(self.vertices[n], self.vertices[n + 1])
yield Line(self.vertices[-1], self.vertices[0]) | def segments (self) | Return the Line segments that comprise this Polygon. | 3.163147 | 2.382454 | 1.327685 |
return (point.x >= self.ul.x and point.x <= self.lr.x) and \
(point.y >= self.ul.y and point.y <= self.lr.y) | def contains (self, point) | contains(point) -> True | False
Returns True if point is contained inside this Rectangle, False otherwise.
Examples:
>>> r = Rect( Point(-1, -1), Point(1, 1) )
>>> r.contains( Point(0, 0) )
True
>>> r.contains( Point(2, 3) )
False | 2.334843 | 2.631761 | 0.887179 |
ul = self.ul
lr = self.lr
ur = Point(lr.x, ul.y)
ll = Point(ul.x, lr.y)
return [ Line(ul, ur), Line(ur, lr), Line(lr, ll), Line(ll, ul) ] | def segments (self) | segments () -> [ Line, Line, Line, Line ]
Return a list of Line segments that comprise this Rectangle. | 2.973243 | 2.121087 | 1.401754 |
if line.startswith('#') and line.find(':') > 0:
tokens = [ t.strip().lower() for t in line[1:].split(":", 1) ]
name = tokens[0]
pos = SeqPos(line, lineno)
if name in self.header:
msg = 'Ignoring duplicate header parameter: %s'
log.warning(msg % name, pos)
els... | def _parseHeader (self, line, lineno, log) | Parses a sequence header line containing 'name: value' pairs. | 3.750508 | 3.49639 | 1.07268 |
self.lines.append( SeqCmd(cmd, delay, attrs) ) | def append (self, cmd, delay=0.000, attrs=None) | Adds a new command with a relative time delay to this sequence. | 15.830559 | 9.794311 | 1.616301 |
if stream is None:
stream = sys.stdout
stream.write('# seqid : %u\n' % self.seqid )
stream.write('# version : %u\n' % self.version )
stream.write('# crc32 : 0x%04x\n' % self.crc32 )
stream.write('# ncmds : %u\n' % len(self.commands) )
stream.wr... | def printText (self, stream=None) | Prints a text representation of this sequence to the given stream or
standard output. | 3.014536 | 2.842017 | 1.060703 |
if filename is None:
filename = self.pathname
stream = open(filename, 'rb')
magic = struct.unpack('>H', stream.read(2))[0]
stream.close()
if magic == Seq.Magic:
self.readBinary(filename)
else:
self.readText(filename) | def read (self, filename=None) | Reads a command sequence from the given filename (defaults to
self.pathname). | 4.243399 | 3.502577 | 1.211508 |
if filename is None:
filename = self.pathname
stream = open(filename, 'rb')
magic = struct.unpack('>H', stream.read(2))[0]
self.crc32 = struct.unpack('>I', stream.read(4))[0]
self.seqid = struct.unpack('>H', stream.read(2))[0]
self.version = struct.unpack('>H', strea... | def readBinary (self, filename=None) | Reads a binary command sequence from the given filename (defaults to
self.pathname). | 3.012278 | 2.691295 | 1.119267 |
if filename is None:
filename = self.pathname
self.header = { }
inBody = False
with open(filename, 'rt') as stream:
for (lineno, line) in enumerate(stream.readlines()):
stripped = line.strip()
if stripped == '':
continue
elif stripped.startswith(... | def readText (self, filename=None) | Reads a text command sequence from the given filename (defaults to
self.pathname). | 3.434096 | 3.237118 | 1.06085 |
if not os.path.isfile(self.pathname):
self.message.append('Filename "%s" does not exist.')
else:
try:
with open(self.pathname, 'r') as stream:
pass
except IOError:
self.messages.append('Could not open "%s" for reading.' % self.pathname)
for line in self.comm... | def validate (self) | Returns True if this Sequence is valid, False otherwise.
Validation error messages are stored in self.messages. | 3.842089 | 3.581527 | 1.072751 |
if filename is None:
filename = self.binpath
with open(filename, 'wb') as output:
# Magic Number
output.write( struct.pack('>H', Seq.Magic ) )
# Upload Type
output.write( struct.pack('B', 9 ) )
# Version
output.write( struct.pack('B', ... | def writeBinary (self, filename=None) | Writes a binary representation of this sequence to the given filename
(defaults to self.binpath). | 3.145332 | 2.932129 | 1.072713 |
if filename is None:
filename = self.txtpath
with open(filename, 'wt') as output:
self.printText(output) | def writeText (self, filename=None) | Writes a text representation of this sequence to the given filename
(defaults to self.txtpath). | 6.080232 | 3.37433 | 1.801908 |
attrs = SeqCmdAttrs.decode(bytes[0:1])
delay = SeqDelay .decode(bytes[1:4])
cmd = cmddict .decode(bytes[4:] )
return cls(cmd, delay, attrs) | def decode (cls, bytes, cmddict) | Decodes a sequence command from an array of bytes, according to the
given command dictionary, and returns a new SeqCmd. | 8.797216 | 7.136853 | 1.232646 |
return self.attrs.encode() + self.delay.encode() + self.cmd.encode() | def encode (self) | Encodes this SeqCmd to binary and returns a bytearray. | 12.767555 | 8.826419 | 1.446516 |
delay = SeqDelay .parse(line, lineno, log, cmddict)
attrs = SeqCmdAttrs.parse(line, lineno, log, cmddict)
comment = SeqComment .parse(line, lineno, log, cmddict)
stop = len(line)
if comment:
stop = comment.pos.col.start - 1
if attrs and attrs.pos.col.stop != -1:
stop ... | def parse (cls, line, lineno, log, cmddict) | Parses the sequence command from a line of text, according to the
given command dictionary, and returns a new SeqCmd. | 3.608387 | 3.474877 | 1.038422 |
byte = 0
for bit, name, value0, value1, default in SeqCmdAttrs.Table:
if default == value1:
byte = setBit(byte, bit, 1)
return byte | def default (self) | The default sequence command attributes (as an integer). | 14.430994 | 8.890873 | 1.623125 |
byte = struct.unpack('B', bytes)[0]
self = cls()
defval = self.default
for bit, name, value0, value1, default in SeqCmdAttrs.Table:
mask = 1 << bit
bitset = mask & byte
defset = mask & defval
if bitset != defset:
if bitset:
self.attrs[name] = value1
... | def decode (cls, bytes, cmddict=None) | Decodes sequence command attributes from an array of bytes and
returns a new SeqCmdAttrs. | 6.086556 | 4.763053 | 1.277869 |
byte = self.default
for bit, name, value0, value1, default in SeqCmdAttrs.Table:
if name in self.attrs:
value = self.attrs[name]
byte = setBit(byte, bit, value == value1)
return struct.pack('B', byte) | def encode (self) | Encodes this SeqCmdAttrs to binary and returns a bytearray. | 9.504386 | 6.629936 | 1.433556 |
start = line.find('{')
stop = line.find('}')
pos = SeqPos(line, lineno, start + 1, stop)
result = cls(None, pos)
if start >= 0 and stop >= start:
attrs = { }
pairs = line[start + 1:stop].split(',')
for item in pairs:
ncolons = item.count(':')
if ncolons... | def parse (cls, line, lineno, log, cmddict=None) | Parses a SeqCmdAttrs from a line of text and returns it or None.
Warning and error messages are logged via the SeqMsgLog log. | 3.015181 | 2.786012 | 1.082257 |
delay_s = struct.unpack('>H', bytes[0:2])[0]
delay_ms = struct.unpack('B' , bytes[2:3])[0]
return cls(delay_s + (delay_ms / 255.0)) | def decode (cls, bytes, cmddict=None) | Decodes a sequence delay from an array of bytes, according to the
given command dictionary, and returns a new SeqDelay. | 3.95854 | 3.682419 | 1.074984 |
delay_s = int( math.floor(self.delay) )
delay_ms = int( (self.delay - delay_s) * 255.0 )
return struct.pack('>H', delay_s) + struct.pack('B', delay_ms) | def encode (self) | Encodes this SeqDelay to a binary bytearray. | 3.877808 | 3.29853 | 1.175617 |
delay = -1
token = line.split()[0]
start = line.find(token)
pos = SeqPos(line, lineno, start + 1, start + len(token))
try:
delay = float(token)
except ValueError:
msg = 'String "%s" could not be interpreted as a numeric time delay.'
log.error(msg % token, pos)
retu... | def parse (cls, line, lineno, log, cmddict=None) | Parses the SeqDelay from a line of text. Warning and error
messages are logged via the SeqMsgLog log. | 5.287561 | 4.443156 | 1.190046 |
start = line.find('%')
pos = SeqPos(line, lineno, start + 1, len(line))
result = None
if start >= 0:
result = cls(line[start:], pos)
return result | def parse (cls, line, lineno, log, cmddict=None) | Parses the SeqMetaCmd from a line of text. Warning and error
messages are logged via the SeqMsgLog log. | 6.919907 | 6.363537 | 1.087431 |
self.log(msg, 'error: ' + self.location(pos)) | def error (self, msg, pos=None) | Logs an error message pertaining to the given SeqPos. | 15.07527 | 9.6953 | 1.554905 |
result = ''
if self.filename:
result += self.filename + ':'
if pos:
result += str(pos)
return result | def location (self, pos) | Formats the location of the given SeqPos as:
filename:line:col: | 4.8441 | 4.423349 | 1.09512 |
if prefix:
if not prefix.strip().endswith(':'):
prefix += ': '
msg = prefix + msg
self.messages.append(msg) | def log (self, msg, prefix=None) | Logs a message with an optional prefix. | 5.144796 | 4.286435 | 1.20025 |
self.log(msg, 'warning: ' + self.location(pos)) | def warning (self, msg, pos=None) | Logs a warning message pertaining to the given SeqAtom. | 14.01886 | 9.30865 | 1.506004 |
if len(keys) == 0:
keys = PATH_KEYS
for name, value in config.items():
if name in keys and type(name) is str:
expanded = util.expandPath(value, prefix)
cleaned = replaceVariables(expanded, datetime=datetime, pathvars=pathvars)
for p in cleaned:
... | def expandConfigPaths (config, prefix=None, datetime=None, pathvars=None, parameter_key='', *keys) | Updates all relative configuration paths in dictionary config,
which contain a key in keys, by prepending prefix.
If keys is omitted, it defaults to 'directory', 'file',
'filename', 'path', 'pathname'.
See util.expandPath(). | 2.925204 | 2.911649 | 1.004655 |
if datetime is None:
datetime = time.gmtime()
# if path variables are not given, set as empty list
if pathvars is None:
pathvars = [ ]
# create an init path list to loop through
if isinstance(path, list):
path_list = path
else:
path_list = [ path ]
# ... | def replaceVariables(path, datetime=None, pathvars=None) | Return absolute path with path variables replaced as applicable | 4.472483 | 4.429675 | 1.009664 |
flat = { }
for k in keys:
flat = merge(flat, d.pop(k, { }))
return flat | def flatten (d, *keys) | Flattens the dictionary d by merging keys in order such that later
keys take precedence over earlier keys. | 5.02522 | 5.355612 | 0.938309 |
config = None
try:
if filename:
data = open(filename, 'rt')
config = yaml.load(data)
if type(data) is file:
data.close()
except IOError, e:
msg = 'Could not read AIT configuration file "%s": %s'
log.error(msg, filename, str(e))
ret... | def loadYAML (filename=None, data=None) | Loads either the given YAML configuration file or YAML data.
Returns None if there was an error reading from the configuration
file and logs an error message via ait.core.log.error(). | 3.781573 | 3.389208 | 1.115769 |
for k in o.keys():
if type(o[k]) is dict and k in d:
merge(d[k], o[k])
else:
d[k] = o[k]
return d | def merge (d, o) | Recursively merges keys from o into d and returns d. | 1.848569 | 1.796223 | 1.029143 |
value = self._config.get(name)
if type(value) is dict:
value = AitConfig(self._filename, config=value)
return value | def _getattr_ (self, name) | Internal method. Used by __getattr__() and __getitem__(). | 7.430062 | 6.413184 | 1.15856 |
if self._filename is None:
return os.path.join(self._ROOT_DIR, 'config')
else:
return os.path.dirname(self._filename) | def _directory (self) | The directory for this AitConfig. | 4.239273 | 3.073891 | 1.379123 |
paths = { }
try:
data = self._config['data']
for k in data:
paths[k] = data[k]['path']
except KeyError as e:
raise AitConfigMissing(e.message)
except Exception as e:
raise AitConfigError('Error reading data paths: %... | def _datapaths(self) | Returns a simple key-value map for easy access to data paths | 4.054561 | 3.724383 | 1.088653 |
if data is None and filename is None:
filename = self._filename
self._config = loadYAML(filename, data)
self._filename = filename
if self._config is not None:
keys = 'default', self._platform, self._hostname
self._config = flatten(... | def reload (self, filename=None, data=None) | Reloads the a AIT configuration.
The AIT configuration is automatically loaded when the AIT
package is first imported. To replace the configuration, call
reload() (defaults to the current config.filename) or
reload(new_filename). | 6.585044 | 6.683895 | 0.985211 |
if name in self:
return self[name]
config = self
parts = name.split('.')
heads = parts[:-1]
tail = parts[-1]
for part in heads:
if part in config and type(config[part]) is AitConfig:
config = config[part]
... | def get (self, name, default=None) | Returns the attribute value *AitConfig.name* or *default*
if name does not exist.
The name may be a series of attributes separated periods. For
example, "foo.bar.baz". In that case, lookups are attempted
in the following order until one succeeeds:
1. AitConfig['foo.bar.b... | 3.095789 | 3.027054 | 1.022707 |
if type(pathvars) is dict:
self._pathvars = merge(self._pathvars, pathvars) | def addPathVariables(self, pathvars) | Adds path variables to the pathvars map property | 4.014282 | 3.832326 | 1.047479 |
if typename not in PrimitiveTypeMap and typename.startswith("S"):
PrimitiveTypeMap[typename] = PrimitiveType(typename)
return PrimitiveTypeMap.get(typename, None) | def getPDT(typename) | get(typename) -> PrimitiveType
Returns the PrimitiveType for typename or None. | 6.531158 | 4.432829 | 1.473361 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.