text stringlengths 81 112k |
|---|
Removes the unreferenced ID attributes.
Returns the number of ID attributes removed
def removeUnreferencedIDs(referencedIDs, identifiedElements):
"""
Removes the unreferenced ID attributes.
Returns the number of ID attributes removed
"""
global _num_ids_removed
keepTags = ['font']
num... |
This walks further and further down the tree, removing groups
which do not have any attributes or a title/desc child and
promoting their children up one level
def removeNestedGroups(node):
"""
This walks further and further down the tree, removing groups
which do not have any attributes or a title/... |
This recursively calls this function on all children of the passed in element
and then iterates over all child elements and removes common inheritable attributes
from the children and places them in the parent group. But only if the parent contains
nothing but element children and whitespace. The attribut... |
Creates <g> elements to contain runs of 3 or more
consecutive child elements having at least one common attribute.
Common attributes are not promoted to the <g> by this function.
This is handled by moveCommonAttributesToParentGroup.
If all children have a common attribute, an extra <g> is not created.... |
This recursively calls this function on all children of the element passed in,
then removes any unused attributes on this elem if none of the children inherit it
def removeUnusedAttributesOnParent(elem):
"""
This recursively calls this function on all children of the element passed in,
then removes any... |
u"""Returns the style attribute of a node as a dictionary.
def _getStyle(node):
u"""Returns the style attribute of a node as a dictionary."""
if node.nodeType == Node.ELEMENT_NODE and len(node.getAttribute('style')) > 0:
styleMap = {}
rawStyles = node.getAttribute('style').split(';')
fo... |
u"""Sets the style attribute of a node to the dictionary ``styleMap``.
def _setStyle(node, styleMap):
u"""Sets the style attribute of a node to the dictionary ``styleMap``."""
fixedStyle = ';'.join([prop + ':' + styleMap[prop] for prop in styleMap])
if fixedStyle != '':
node.setAttribute('style', f... |
Returns the value of 'style' that is inherited from the parents of the passed-in node
Warning: This method only considers presentation attributes and inline styles,
any style sheets are ignored!
def styleInheritedFromParent(node, style):
"""
Returns the value of 'style' that is inherited from... |
Returns whether 'style' is inherited by any children of the passed-in node
If False is returned, it is guaranteed that 'style' can safely be removed
from the passed-in node without influencing visual output of it's children
If True is returned, the passed-in node should not have its text-based
attribu... |
Returns True if the passed-in node is probably a text element, or at least
one of its descendants is probably a text element.
If False is returned, it is guaranteed that the passed-in node has no
business having text-based attributes.
If True is returned, the passed-in node should not have its text-ba... |
u"""Adds an attribute to a set of attributes.
Related attributes are also included.
def taint(taintedSet, taintedAttribute):
u"""Adds an attribute to a set of attributes.
Related attributes are also included."""
taintedSet.add(taintedAttribute)
if taintedAttribute == 'marker':
taintedSet ... |
Removes the DefaultAttribute 'attribute' from 'node' if specified conditions are fulfilled
Warning: Does NOT check if the attribute is actually valid for the passed element type for increased preformance!
def removeDefaultAttributeValue(node, attribute):
"""
Removes the DefaultAttribute 'attribute' from '... |
u"""'tainted' keeps a set of attributes defined in parent nodes.
For such attributes, we don't delete attributes with default values.
def removeDefaultAttributeValues(node, options, tainted=set()):
u"""'tainted' keeps a set of attributes defined in parent nodes.
For such attributes, we don't delete attri... |
Converts the input color string and returns a #RRGGBB (or #RGB if possible) string
def convertColor(value):
"""
Converts the input color string and returns a #RRGGBB (or #RGB if possible) string
"""
s = value
if s in colors:
s = colors[s]
rgbpMatch = rgbp.match(s)
if rgbpMatch ... |
Recursively converts all color properties into #RRGGBB format if shorter
def convertColors(element):
"""
Recursively converts all color properties into #RRGGBB format if shorter
"""
numBytes = 0
if element.nodeType != Node.ELEMENT_NODE:
return 0
# set up list of color attributes fo... |
Cleans the path string (d attribute) of the element
def cleanPath(element, options):
"""
Cleans the path string (d attribute) of the element
"""
global _num_bytes_saved_in_path_data
global _num_path_segments_removed
# this gets the parser object from svg_regex.py
oldPathStr = element.ge... |
Parse string into a list of points.
Returns a list containing an even number of coordinate strings
def parseListOfPoints(s):
"""
Parse string into a list of points.
Returns a list containing an even number of coordinate strings
"""
i = 0
# (wsp)? comma-or-wsp-separated coordinat... |
Remove unnecessary closing point of polygon points attribute
def cleanPolygon(elem, options):
"""
Remove unnecessary closing point of polygon points attribute
"""
global _num_points_removed_from_polygon
pts = parseListOfPoints(elem.getAttribute('points'))
N = len(pts) / 2
if N >= 2:
... |
Scour the polyline points attribute
def cleanPolyline(elem, options):
"""
Scour the polyline points attribute
"""
pts = parseListOfPoints(elem.getAttribute('points'))
elem.setAttribute('points', scourCoordinates(pts, options, True)) |
Checks if there are control points in the path data
Returns the indices of all values in the path data which are control points
def controlPoints(cmd, data):
"""
Checks if there are control points in the path data
Returns the indices of all values in the path data which are control points
... |
Checks if there are flags in the path data
Returns the indices of all values in the path data which are flags
def flags(cmd, data):
"""
Checks if there are flags in the path data
Returns the indices of all values in the path data which are flags
"""
if cmd.lower() == 'a': # a: (rx r... |
Reserializes the path data with some cleanups.
def serializePath(pathObj, options):
"""
Reserializes the path data with some cleanups.
"""
# elliptical arc commands must have comma/wsp separating the coordinates
# this fixes an issue outlined in Fix https://bugs.launchpad.net/scour/+bug/412754
... |
Reserializes the transform data with some cleanups.
def serializeTransform(transformObj):
"""
Reserializes the transform data with some cleanups.
"""
return ' '.join([command + '(' + ' '.join([scourUnitlessLength(number) for number in numbers]) + ')'
for command, numbers in tran... |
Serializes coordinate data with some cleanups:
- removes all trailing zeros after the decimal
- integerize coordinates if possible
- removes extraneous whitespace
- adds spaces between values in a subcommand if required (or if force_whitespace is True)
def scourCoordinates(data,... |
Scours a length. Accepts units.
def scourLength(length):
"""
Scours a length. Accepts units.
"""
length = SVGLength(length)
return scourUnitlessLength(length.value) + Unit.str(length.units) |
Scours the numeric part of a length only. Does not accept units.
This is faster than scourLength on elements guaranteed not to
contain units.
def scourUnitlessLength(length, renderer_workaround=False, is_control_point=False): # length is of a numeric type
"""
Scours the numeric part of a length only.... |
Because opacities, letter spacings, stroke widths and all that don't need
to be preserved in SVG files with 9 digits of precision.
Takes all of these attributes, in the given element node and its children,
and reduces their precision to the current Decimal context's precision.
Also checks for the attri... |
Because any rotation can be expressed within 360 degrees
of any given number, and since negative angles sometimes
are one character longer than corresponding positive angle,
we shorten the number to one in the range to [-90, 270[.
def optimizeAngle(angle):
"""
Because any rotation can be expressed ... |
Optimises a series of transformations parsed from a single
transform="" attribute.
The transformation list is modified in-place.
def optimizeTransform(transform):
"""
Optimises a series of transformations parsed from a single
transform="" attribute.
The transformation list is modified in-plac... |
Attempts to optimise transform specifications on the given node and its children.
Returns the number of bytes saved after performing these reductions.
def optimizeTransforms(element, options):
"""
Attempts to optimise transform specifications on the given node and its children.
Returns the number of ... |
Removes comments from the element and its children.
def removeComments(element):
"""
Removes comments from the element and its children.
"""
global _num_bytes_saved_in_comments
num = 0
if isinstance(element, xml.dom.minidom.Comment):
_num_bytes_saved_in_comments += len(element.data)... |
Converts raster references to inline images.
NOTE: there are size limits to base64-encoding handling in browsers
def embedRasters(element, options):
import base64
"""
Converts raster references to inline images.
NOTE: there are size limits to base64-encoding handling in browsers
"""
g... |
Find format schema in $FORMAT_PATH or nerium/schema
def get_format(format_):
""" Find format schema in $FORMAT_PATH or nerium/schema
"""
format_path = os.getenv('FORMAT_PATH', 'format_files')
try:
spec = importlib.util.spec_from_file_location(
"format_mod", f"{format_path}/{format_}... |
Set a new (or updating existing) key value pair.
Args:
key: A string containing the key namespace
value: A str, int, or bool value
Raises:
NotImplementedError: an unsupported value-type was provided
def set_property(self, key, value):
'''Set a new (or updat... |
Save current property list representation to the original file.
def save(self):
'''Save current property list representation to the original file.'''
with open(self.filename, 'w') as plist_file:
plist_file.write(str(self.soup)) |
Return the userid for the specified bed side.
def fetch_userid(self, side):
"""Return the userid for the specified bed side."""
for user in self.users:
obj = self.users[user]
if obj.side == side:
return user |
Start api initialization.
async def start(self):
"""Start api initialization."""
_LOGGER.debug('Initializing pyEight Version: %s', __version__)
await self.fetch_token()
if self._token is not None:
await self.fetch_device_list()
await self.assign_users()
... |
Fetch new session token from api.
async def fetch_token(self):
"""Fetch new session token from api."""
url = '{}/login'.format(API_URL)
payload = 'email={}&password={}'.format(self._email, self._password)
reg = await self.api_post(url, None, payload)
if reg is None:
... |
Fetch list of devices.
async def fetch_device_list(self):
"""Fetch list of devices."""
url = '{}/users/me'.format(API_URL)
dlist = await self.api_get(url)
if dlist is None:
_LOGGER.error('Unable to fetch eight devices.')
else:
self._devices = dlist['user... |
Update device properties.
async def assign_users(self):
"""Update device properties."""
device = self._devices[0]
url = '{}/devices/{}?filter=ownerId,leftUserId,rightUserId' \
.format(API_URL, device)
data = await self.api_get(url)
if data is None:
_LOGG... |
Return room temperature for both sides of bed.
def room_temperature(self):
"""Return room temperature for both sides of bed."""
# Check which side is active, if both are return the average
tmp = None
tmp2 = None
for user in self.users:
obj = self.users[user]
... |
Manage the device json list.
def handle_device_json(self, data):
"""Manage the device json list."""
self._device_json.insert(0, data)
self._device_json.pop() |
Update device data json.
async def update_device_data(self):
"""Update device data json."""
url = '{}/devices/{}?offlineView=true'.format(API_URL, self.deviceid)
# Check for access token expiration (every 15days)
exp_delta = datetime.strptime(self._expdate, '%Y-%m-%dT%H:%M:%S.%fZ') \
... |
Make api fetch request.
async def api_get(self, url, params=None):
"""Make api fetch request."""
request = None
headers = DEFAULT_HEADERS.copy()
headers.update({'Session-Token': self._token})
try:
with async_timeout.timeout(DEFAULT_TIMEOUT, loop=self._event_loop):
... |
Make api post request.
async def api_put(self, url, data=None):
"""Make api post request."""
put = None
headers = DEFAULT_HEADERS.copy()
headers.update({'Session-Token': self._token})
try:
with async_timeout.timeout(DEFAULT_TIMEOUT, loop=self._event_loop):
... |
Checks whether the given requirements are satisfiable within the given
execution context
Parameter
---------
requirements : list(Requirement)
List of requirements to check whether they are satisfiable
def satisfy(self, *requirements):
"""
Checks whether the ... |
Convert a X10 housecode to a zero-based index
def housecode_to_index(housecode):
"""Convert a X10 housecode to a zero-based index"""
match = re.search(r'^([A-P])(\d{1,2})$', housecode.upper())
if match:
house_index = int(match.group(2))
if 1 <= house_index <= 16:
return (ord(mat... |
Convert a zero-based index to a X10 housecode.
def index_to_housecode(index):
"""Convert a zero-based index to a X10 housecode."""
if index < 0 or index > 255:
raise ValueError
quotient, remainder = divmod(index, 16)
return chr(quotient+ord('A')) + '{:02d}'.format(remainder+1) |
Ensure checksum in message is good.
def _check_checksum(msg):
"""Ensure checksum in message is good."""
checksum = int(msg[-2:], 16)
for char in msg[:-2]:
checksum += ord(char)
if (checksum % 256) != 0:
raise ValueError("Elk message checksum invalid") |
Check packet length valid and that checksum is good.
def _check_message_valid(msg):
"""Check packet length valid and that checksum is good."""
try:
if int(msg[:2], 16) != (len(msg) - 2):
raise ValueError("Elk message length incorrect")
_check_checksum(msg)
except IndexError:
... |
cw: Write a custom value.
def cw_encode(index, value, value_format):
"""cw: Write a custom value."""
if value_format == 2:
value = value[0] << 8 + value[1]
return MessageEncode('0Dcw{:02d}{:05d}00'.format(index+1, value), None) |
dm: Display message on keypad.
def dm_encode(keypad_area, clear, beep, timeout, line1, line2):
"""dm: Display message on keypad."""
return MessageEncode(
'2Edm{:1d}{:1d}{:1d}{:05d}{:^<16.16}{:^<16.16}00'
.format(keypad_area+1, clear, beep, timeout, line1, line2), None
) |
pc: Control any PLC device.
def pc_encode(index, function_code, extended_code, time):
"""pc: Control any PLC device."""
return MessageEncode('11pc{hc}{fc:02d}{ec:02d}{time:04d}00'.
format(hc=index_to_housecode(index),
fc=function_code, ec=extended_code,
... |
zb: Zone bypass. Zone < 0 unbypass all; Zone > Max bypass all.
def zb_encode(zone, area, user_code):
"""zb: Zone bypass. Zone < 0 unbypass all; Zone > Max bypass all."""
if zone < 0:
zone = 0
elif zone > Max.ZONES.value:
zone = 999
else:
zone += 1
return MessageEncode('10zb{... |
Manage callbacks for message handlers.
def add_handler(self, message_type, handler):
"""Manage callbacks for message handlers."""
if message_type not in self._handlers:
self._handlers[message_type] = []
if handler not in self._handlers[message_type]:
self._handlers[mess... |
Decode an Elk message by passing to appropriate decoder
def decode(self, msg):
"""Decode an Elk message by passing to appropriate decoder"""
_check_message_valid(msg)
cmd = msg[2:4]
decoder = getattr(self, '_{}_decode'.format(cmd.lower()), None)
if not decoder:
cmd =... |
AS: Arming status report.
def _as_decode(self, msg):
"""AS: Arming status report."""
return {'armed_statuses': [x for x in msg[4:12]],
'arm_up_states': [x for x in msg[12:20]],
'alarm_states': [x for x in msg[20:28]]} |
CR: Custom values
def _cr_decode(self, msg):
"""CR: Custom values"""
if int(msg[4:6]) > 0:
index = int(msg[4:6])-1
return {'values': [self._cr_one_custom_value_decode(index, msg[6:12])]}
else:
part = 6
ret = []
for i in range(Max.SETTI... |
CS: Output status for all outputs.
def _cs_decode(self, msg):
"""CS: Output status for all outputs."""
output_status = [x == '1' for x in msg[4:4+Max.OUTPUTS.value]]
return {'output_status': output_status} |
EE: Entry/exit timer report.
def _ee_decode(self, msg):
"""EE: Entry/exit timer report."""
return {'area': int(msg[4:5])-1, 'is_exit': msg[5:6] == '0',
'timer1': int(msg[6:9]), 'timer2': int(msg[9:12]),
'armed_status': msg[12:13]} |
IC: Send Valid Or Invalid User Code Format.
def _ic_decode(self, msg):
"""IC: Send Valid Or Invalid User Code Format."""
code = msg[4:16]
if re.match(r'(0\d){6}', code):
code = re.sub(r'0(\d)', r'\1', code)
return {'code': code, 'user': int(msg[16:19])-1,
'ke... |
KA: Keypad areas for all keypads.
def _ka_decode(self, msg):
"""KA: Keypad areas for all keypads."""
return {'keypad_areas': [ord(x)-0x31 for x in msg[4:4+Max.KEYPADS.value]]} |
LW: temperatures from all keypads and zones 1-16.
def _lw_decode(self, msg):
"""LW: temperatures from all keypads and zones 1-16."""
keypad_temps = []
zone_temps = []
for i in range(16):
keypad_temps.append(int(msg[4+3*i:7+3*i]) - 40)
zone_temps.append(int(msg[52... |
PC: PLC (lighting) change.
def _pc_decode(self, msg):
"""PC: PLC (lighting) change."""
housecode = msg[4:7]
return {'housecode': housecode, 'index': housecode_to_index(housecode),
'light_level': int(msg[7:9])} |
SD: Description text.
def _sd_decode(self, msg):
"""SD: Description text."""
desc_ch1 = msg[9]
show_on_keypad = ord(desc_ch1) >= 0x80
if show_on_keypad:
desc_ch1 = chr(ord(desc_ch1) & 0x7f)
return {'desc_type': int(msg[4:6]), 'unit': int(msg[6:9])-1,
... |
ST: Temperature update.
def _st_decode(self, msg):
"""ST: Temperature update."""
group = int(msg[4:5])
temperature = int(msg[7:10])
if group == 0:
temperature -= 60
elif group == 1:
temperature -= 40
return {'group': group, 'device': int(msg[5:7])... |
TR: Thermostat data response.
def _tr_decode(self, msg):
"""TR: Thermostat data response."""
return {'thermostat_index': int(msg[4:6])-1, 'mode': int(msg[6]),
'hold': msg[7] == '1', 'fan': int(msg[8]),
'current_temp': int(msg[9:11]), 'heat_setpoint': int(msg[11:13]),
... |
VN: Version information.
def _vn_decode(self, msg):
"""VN: Version information."""
elkm1_version = "{}.{}.{}".format(int(msg[4:6], 16), int(msg[6:8], 16),
int(msg[8:10], 16))
xep_version = "{}.{}.{}".format(int(msg[10:12], 16), int(msg[12:14], 16),
... |
ZC: Zone Change.
def _zc_decode(self, msg):
"""ZC: Zone Change."""
status = _status_decode(int(msg[7:8], 16))
return {'zone_number': int(msg[4:7])-1, 'zone_status': status} |
ZD: Zone definitions.
def _zd_decode(self, msg):
"""ZD: Zone definitions."""
zone_definitions = [ord(x)-0x30 for x in msg[4:4+Max.ZONES.value]]
return {'zone_definitions': zone_definitions} |
ZP: Zone partitions.
def _zp_decode(self, msg):
"""ZP: Zone partitions."""
zone_partitions = [ord(x)-0x31 for x in msg[4:4+Max.ZONES.value]]
return {'zone_partitions': zone_partitions} |
ZS: Zone statuses.
def _zs_decode(self, msg):
"""ZS: Zone statuses."""
status = [_status_decode(int(x, 16)) for x in msg[4:4+Max.ZONES.value]]
return {'zone_statuses': status} |
Parameters
----------
prev_login : xnat.XNATSession
An XNAT login that has been opened in the code that calls
the method that calls login. It is wrapped in a
NoExitWrapper so the returned connection can be used
in a "with" statement in the method.
def con... |
Caches a single fileset (if the 'path' attribute is accessed
and it has not been previously cached for example
Parameters
----------
fileset : Fileset
The fileset to cache
prev_login : xnat.XNATSession
An XNATSession object to use for the connection. A ne... |
Downloads the MD5 digests associated with the files in the file-set.
These are saved with the downloaded files in the cache and used to
check if the files have been updated on the server
Parameters
----------
resource : xnat.ResourceCatalog
The xnat resource
... |
Find all filesets, fields and provenance records within an XNAT project
Parameters
----------
subject_ids : list(str)
List of subject IDs with which to filter the tree with. If
None all are returned
visit_ids : list(str)
List of visit IDs with which t... |
Convert subject ids to strings if they are integers
def convert_subject_ids(self, subject_ids):
"""
Convert subject ids to strings if they are integers
"""
# TODO: need to make this generalisable via a
# splitting+mapping function passed to the repository
if subjec... |
Returns the XNAT session and cache dir corresponding to the
item.
def get_xsession(self, item):
"""
Returns the XNAT session and cache dir corresponding to the
item.
"""
subj_label, sess_label = self._get_item_labels(item)
with self:
xproject = self._... |
Returns the labels for the XNAT subject and sessions given
the frequency and provided IDs.
def _get_item_labels(self, item, no_from_study=False):
"""
Returns the labels for the XNAT subject and sessions given
the frequency and provided IDs.
"""
subject_id = self.inv_map_... |
Returns the labels for the XNAT subject and sessions given
the frequency and provided IDs.
def _get_labels(self, frequency, subject_id=None, visit_id=None):
"""
Returns the labels for the XNAT subject and sessions given
the frequency and provided IDs.
"""
if frequency ==... |
(Helper) Turn on an output
def turn_on(self, time):
"""(Helper) Turn on an output"""
self._elk.send(cn_encode(self._index, time)) |
Retrieve areas from ElkM1
def sync(self):
"""Retrieve areas from ElkM1"""
self.elk.send(cs_encode())
self.get_descriptions(TextDescriptions.OUTPUT.value) |
Try to detect version of package from command help text. Bit of a long
shot as they are typically included
def detect_version_str(self):
"""
Try to detect version of package from command help text. Bit of a long
shot as they are typically included
"""
help_text = run_mat... |
Return target heating level.
def target_heating_level(self):
"""Return target heating level."""
try:
if self.side == 'left':
level = self.device.device_data['leftTargetHeatingLevel']
elif self.side == 'right':
level = self.device.device_data['righ... |
Return heating level.
def heating_level(self):
"""Return heating level."""
try:
if self.side == 'left':
level = self.device.device_data['leftHeatingLevel']
elif self.side == 'right':
level = self.device.device_data['rightHeatingLevel']
... |
Return a heating level from the past.
def past_heating_level(self, num):
"""Return a heating level from the past."""
if num > 9:
return 0
try:
if self.side == 'left':
level = self.device.device_data_history[
num]['leftHeatingLevel']
... |
Return current heating state.
def now_heating(self):
"""Return current heating state."""
try:
if self.side == 'left':
heat = self.device.device_data['leftNowHeating']
elif self.side == 'right':
heat = self.device.device_data['rightNowHeating']
... |
Return seconds of heat time remaining.
def heating_remaining(self):
"""Return seconds of heat time remaining."""
try:
if self.side == 'left':
timerem = self.device.device_data['leftHeatingDuration']
elif self.side == 'right':
timerem = self.device... |
Return mattress last seen time.
def last_seen(self):
"""Return mattress last seen time."""
"""
These values seem to be rarely updated correctly in the API.
Don't expect accurate results from this property.
"""
try:
if self.side == 'left':
last... |
Return a dict of all the current heating values.
def heating_values(self):
"""Return a dict of all the current heating values."""
heating_dict = {
'level': self.heating_level,
'target': self.target_heating_level,
'active': self.now_heating,
'remaining': s... |
Return sleep stage for in-progress session.
def current_sleep_stage(self):
"""Return sleep stage for in-progress session."""
try:
stages = self.intervals[0]['stages']
num_stages = len(stages)
if num_stages == 0:
return None
# API now alw... |
Return durations of sleep stages for in-progress session.
def current_sleep_breakdown(self):
"""Return durations of sleep stages for in-progress session."""
try:
stages = self.intervals[0]['stages']
breakdown = {'awake': 0, 'light': 0, 'deep': 0, 'rem': 0}
for stage ... |
Return current bed temperature for in-progress session.
def current_bed_temp(self):
"""Return current bed temperature for in-progress session."""
try:
bedtemps = self.intervals[0]['timeseries']['tempBedC']
num_temps = len(bedtemps)
if num_temps == 0:
... |
Return current room temperature for in-progress session.
def current_room_temp(self):
"""Return current room temperature for in-progress session."""
try:
rmtemps = self.intervals[0]['timeseries']['tempRoomC']
num_temps = len(rmtemps)
if num_temps == 0:
... |
Return current respiratory rate for in-progress session.
def current_resp_rate(self):
"""Return current respiratory rate for in-progress session."""
try:
rates = self.intervals[0]['timeseries']['respiratoryRate']
num_rates = len(rates)
if num_rates == 0:
... |
Return current heart rate for in-progress session.
def current_heart_rate(self):
"""Return current heart rate for in-progress session."""
try:
rates = self.intervals[0]['timeseries']['heartRate']
num_rates = len(rates)
if num_rates == 0:
return None
... |
Return a dict of all the 'current' parameters.
def current_values(self):
"""Return a dict of all the 'current' parameters."""
current_dict = {
'date': self.current_session_date,
'score': self.current_sleep_score,
'stage': self.current_sleep_stage,
'breakd... |
Return date/time for start of last session data.
def last_session_date(self):
"""Return date/time for start of last session data."""
try:
date = self.intervals[1]['ts']
except KeyError:
return None
date_f = datetime.strptime(date, '%Y-%m-%dT%H:%M:%S.%fZ')
... |
Return durations of sleep stages for last complete session.
def last_sleep_breakdown(self):
"""Return durations of sleep stages for last complete session."""
try:
stages = self.intervals[1]['stages']
except KeyError:
return None
breakdown = {'awake': 0, 'light':... |
Return avg bed temperature for last session.
def last_bed_temp(self):
"""Return avg bed temperature for last session."""
try:
bedtemps = self.intervals[1]['timeseries']['tempBedC']
except KeyError:
return None
tmp = 0
num_temps = len(bedtemps)
if... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.