code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
value = self.to_python(value)
value = self.value_to_string(value)
return super(RegexField, self).run_validators(value) | def run_validators(self, value) | Make sure value is a string so it can run through django validators | 3.28837 | 2.606806 | 1.261455 |
try:
binascii.unhexlify(value)
except Exception:
raise vol.Invalid(
'{} is not of hex format'.format(value))
return value | def validate_hex(value) | Validate that value has hex format. | 4.166521 | 3.960234 | 1.05209 |
if len(value) != 6:
raise vol.Invalid(
'{} is not six characters long'.format(value))
return validate_hex(value) | def validate_v_rgb(value) | Validate a V_RGB value. | 5.490833 | 5.545219 | 0.990192 |
if len(value) != 8:
raise vol.Invalid(
'{} is not eight characters long'.format(value))
return validate_hex(value) | def validate_v_rgbw(value) | Validate a V_RGBW value. | 5.889002 | 5.750215 | 1.024136 |
msg = Message(self.encode(), self.gateway)
for key, val in kwargs.items():
setattr(msg, key, val)
return msg | def copy(self, **kwargs) | Copy a message, optionally replace attributes with kwargs. | 5.612423 | 3.876717 | 1.447726 |
for key, val in kwargs.items():
setattr(self, key, val)
return self | def modify(self, **kwargs) | Modify and return message, replace attributes with kwargs. | 3.207006 | 2.814354 | 1.139518 |
try:
list_data = data.rstrip().split(delimiter)
self.payload = list_data.pop()
(self.node_id,
self.child_id,
self.type,
self.ack,
self.sub_type) = [int(f) for f in list_data]
except ValueError:
_... | def decode(self, data, delimiter=';') | Decode a message from command string. | 4.621663 | 4.341684 | 1.064486 |
try:
return delimiter.join([str(f) for f in [
self.node_id,
self.child_id,
int(self.type),
self.ack,
int(self.sub_type),
self.payload,
]]) + '\n'
except ValueError:
... | def encode(self, delimiter=';') | Encode a command string from message. | 5.418351 | 4.978642 | 1.088319 |
const = get_const(protocol_version)
valid_node_ids = vol.All(vol.Coerce(int), vol.Range(
min=0, max=BROADCAST_ID, msg='Not valid node_id: {}'.format(
self.node_id)))
valid_child_ids = vol.All(vol.Coerce(int), vol.Range(
min=0, max=SYSTEM_CHILD_ID,... | def validate(self, protocol_version) | Validate message. | 2.261945 | 2.255316 | 1.002939 |
with open(filename, 'wb') as file_handle:
pickle.dump(self._sensors, file_handle, pickle.HIGHEST_PROTOCOL)
file_handle.flush()
os.fsync(file_handle.fileno()) | def _save_pickle(self, filename) | Save sensors to pickle file. | 2.286906 | 1.998439 | 1.144346 |
with open(filename, 'rb') as file_handle:
self._sensors.update(pickle.load(file_handle)) | def _load_pickle(self, filename) | Load sensors from pickle file. | 4.107431 | 2.98312 | 1.376891 |
with open(filename, 'w') as file_handle:
json.dump(self._sensors, file_handle, cls=MySensorsJSONEncoder,
indent=4)
file_handle.flush()
os.fsync(file_handle.fileno()) | def _save_json(self, filename) | Save sensors to json file. | 3.372216 | 2.834942 | 1.189518 |
with open(filename, 'r') as file_handle:
self._sensors.update(json.load(
file_handle, cls=MySensorsJSONDecoder)) | def _load_json(self, filename) | Load sensors from json file. | 5.76908 | 4.209371 | 1.370532 |
if not self.need_save:
return
fname = os.path.realpath(self.persistence_file)
exists = os.path.isfile(fname)
dirname = os.path.dirname(fname)
if (not os.access(dirname, os.W_OK) or exists and
not os.access(fname, os.W_OK)):
_LOGGER... | def save_sensors(self) | Save sensors to file. | 2.751001 | 2.67555 | 1.0282 |
if path is None:
path = self.persistence_file
exists = os.path.isfile(path)
if exists and os.access(path, os.R_OK):
if path == self.persistence_bak:
os.rename(path, self.persistence_file)
path = self.persistence_file
_L... | def _load_sensors(self, path=None) | Load sensors from file. | 3.179213 | 2.991057 | 1.062906 |
try:
loaded = self._load_sensors()
except (EOFError, ValueError):
_LOGGER.error('Bad file contents: %s', self.persistence_file)
loaded = False
if not loaded:
_LOGGER.warning('Trying backup file: %s', self.persistence_bak)
try:
... | def safe_load_sensors(self) | Load sensors safely from file. | 2.586471 | 2.468547 | 1.047771 |
ext = os.path.splitext(filename)[1]
try:
func = getattr(self, '_{}_{}'.format(action, ext[1:]))
except AttributeError:
raise Exception('Unsupported file type {}'.format(ext[1:]))
func(filename) | def _perform_file_action(self, filename, action) | Perform action on specific file types.
Dynamic dispatch function for performing actions on
specific file types. | 2.616224 | 2.844476 | 0.919756 |
# pylint: disable=method-hidden, protected-access, arguments-differ
if isinstance(obj, Sensor):
return {
'sensor_id': obj.sensor_id,
'children': obj.children,
'type': obj.type,
'sketch_name': obj.sketch_name,
... | def default(self, obj) | Serialize obj into JSON. | 2.526567 | 2.418815 | 1.044547 |
return obj
if 'sensor_id' in obj:
sensor = Sensor(obj['sensor_id'])
for key, val in obj.items():
setattr(sensor, key, val)
return sensor
if all(k in obj for k in ['id', 'type', 'values']):
child = ChildSensor(
ob... | def dict_to_object(self, obj): # pylint: disable=no-self-use
if not isinstance(obj, dict) | Return object from dict. | 2.800291 | 2.723575 | 1.028167 |
path = next((
CONST_VERSIONS[const_version]
for const_version in sorted(CONST_VERSIONS, reverse=True)
if parse_ver(protocol_version) >= parse_ver(const_version)
), 'mysensors.const_14')
if path in LOADED_CONST:
return LOADED_CONST[path]
const = import_module(path)
... | def get_const(protocol_version) | Return the const module for the protocol_version. | 4.459902 | 4.170854 | 1.069302 |
return struct.unpack('<{}H'.format(words), binascii.unhexlify(hex_str)) | def fw_hex_to_int(hex_str, words) | Unpack hex string into integers.
Use little-endian and unsigned int format. Specify number of words to
unpack with argument words. | 3.175922 | 3.948941 | 0.804247 |
return binascii.hexlify(
struct.pack('<{}H'.format(len(args)), *args)).decode('utf-8') | def fw_int_to_hex(*args) | Pack integers into hex string.
Use little-endian and unsigned int format. | 4.249838 | 4.324261 | 0.982789 |
crc16 = crcmod.predefined.Crc('modbus')
crc16.update(data)
return int(crc16.hexdigest(), 16) | def compute_crc(data) | Compute CRC16 of data and return an int. | 2.576372 | 2.350665 | 1.096018 |
fname = os.path.realpath(path)
exists = os.path.isfile(fname)
if not exists or not os.access(fname, os.R_OK):
_LOGGER.error(
'Firmware path %s does not exist or is not readable',
path)
return None
try:
intel_hex = IntelHex()
with open(path, 'r... | def load_fw(path) | Open firmware file and return a binary string. | 2.740188 | 2.566167 | 1.067813 |
pads = len(bin_string) % 128 # 128 bytes per page for atmega328
for _ in range(128 - pads): # pad up to even 128 bytes
bin_string += b'\xff'
fware = {
'blocks': int(len(bin_string) / FIRMWARE_BLOCK_SIZE),
'crc': compute_crc(bin_string),
'data': bin_string,
}
re... | def prepare_fw(bin_string) | Check that firmware is valid and return dict with binary data. | 4.070443 | 3.814152 | 1.067195 |
fw_type = None
fw_ver = None
if not isinstance(updates, tuple):
updates = (updates, )
for store in updates:
fw_id = store.pop(msg.node_id, None)
if fw_id is not None:
fw_type, fw_ver = fw_id
updates[-1][msg.node... | def _get_fw(self, msg, updates, req_fw_type=None, req_fw_ver=None) | Get firmware type, version and a dict holding binary data. | 2.153056 | 2.12283 | 1.014238 |
req_fw_type, req_fw_ver, req_blk = fw_hex_to_int(msg.payload, 3)
_LOGGER.debug(
'Received firmware request with firmware type %s, '
'firmware version %s, block index %s',
req_fw_type, req_fw_ver, req_blk)
fw_type, fw_ver, fware = self._get_fw(
... | def respond_fw(self, msg) | Respond to a firmware request. | 3.90814 | 3.782335 | 1.033261 |
(req_fw_type,
req_fw_ver,
req_blocks,
req_crc,
bloader_ver) = fw_hex_to_int(msg.payload, 5)
_LOGGER.debug(
'Received firmware config request with firmware type %s, '
'firmware version %s, %s blocks, CRC %s, bootloader %s',
... | def respond_fw_config(self, msg) | Respond to a firmware config request. | 3.595847 | 3.440284 | 1.045218 |
try:
fw_type, fw_ver = int(fw_type), int(fw_ver)
except ValueError:
_LOGGER.error(
'Firmware type %s or version %s not valid, '
'please enter integers', fw_type, fw_ver)
return
if fw_bin is not None:
fware =... | def make_update(self, nids, fw_type, fw_ver, fw_bin=None) | Start firmware update process for one or more node_id. | 2.922198 | 2.888122 | 1.011799 |
while msg.gateway.sensors[msg.node_id].queue:
msg.gateway.add_job(
str, msg.gateway.sensors[msg.node_id].queue.popleft())
for child in msg.gateway.sensors[msg.node_id].children.values():
new_child = msg.gateway.sensors[msg.node_id].new_state.get(
child.id, ChildSenso... | def handle_smartsleep(msg) | Process a message before going back to smartsleep. | 2.759665 | 2.731571 | 1.010285 |
if msg.child_id == SYSTEM_CHILD_ID:
# this is a presentation of the sensor platform
sensorid = msg.gateway.add_sensor(msg.node_id)
if sensorid is None:
return None
msg.gateway.sensors[msg.node_id].type = msg.sub_type
msg.gateway.sensors[msg.node_id].protocol_... | def handle_presentation(msg) | Process a presentation message. | 3.514904 | 3.45944 | 1.016033 |
if not msg.gateway.is_sensor(msg.node_id, msg.child_id):
return None
msg.gateway.sensors[msg.node_id].set_child_value(
msg.child_id, msg.sub_type, msg.payload)
if msg.gateway.sensors[msg.node_id].new_state:
msg.gateway.sensors[msg.node_id].set_child_value(
msg.child_... | def handle_set(msg) | Process a set message. | 3.850315 | 3.778476 | 1.019013 |
if not msg.gateway.is_sensor(msg.node_id, msg.child_id):
return None
value = msg.gateway.sensors[msg.node_id].children[
msg.child_id].values.get(msg.sub_type)
if value is not None:
return msg.copy(
type=msg.gateway.const.MessageType.set, payload=value)
return Non... | def handle_req(msg) | Process a req message.
This will return the value if it exists. If no value exists,
nothing is returned. | 5.752278 | 5.596078 | 1.027912 |
internal = msg.gateway.const.Internal(msg.sub_type)
handler = internal.get_handler(msg.gateway.handlers)
if handler is None:
return None
return handler(msg) | def handle_internal(msg) | Process an internal message. | 8.066113 | 7.621073 | 1.058396 |
if not msg.gateway.is_sensor(msg.node_id):
return None
stream = msg.gateway.const.Stream(msg.sub_type)
handler = stream.get_handler(msg.gateway.handlers)
if handler is None:
return None
return handler(msg) | def handle_stream(msg) | Process a stream type message. | 6.440251 | 6.274536 | 1.026411 |
node_id = msg.gateway.add_sensor()
return msg.copy(
ack=0, sub_type=msg.gateway.const.Internal['I_ID_RESPONSE'],
payload=node_id) if node_id is not None else None | def handle_id_request(msg) | Process an internal id request message. | 13.563942 | 12.573683 | 1.078756 |
return msg.copy(ack=0, payload=calendar.timegm(time.localtime())) | def handle_time(msg) | Process an internal time request message. | 13.824626 | 11.917721 | 1.160006 |
if not msg.gateway.is_sensor(msg.node_id):
return None
msg.gateway.sensors[msg.node_id].battery_level = msg.payload
msg.gateway.alert(msg)
return None | def handle_battery_level(msg) | Process an internal battery level message. | 5.601689 | 5.196223 | 1.078031 |
if not msg.gateway.is_sensor(msg.node_id):
return None
msg.gateway.sensors[msg.node_id].sketch_name = msg.payload
msg.gateway.alert(msg)
return None | def handle_sketch_name(msg) | Process an internal sketch name message. | 6.130328 | 5.879727 | 1.042621 |
if not msg.gateway.is_sensor(msg.node_id):
return None
msg.gateway.sensors[msg.node_id].sketch_version = msg.payload
msg.gateway.alert(msg)
return None | def handle_sketch_version(msg) | Process an internal sketch version message. | 6.1052 | 5.923452 | 1.030683 |
def handle_log_message(msg): # pylint: disable=useless-return
msg.gateway.can_log = True
_LOGGER.debug(
'n:%s c:%s t:%s s:%s p:%s', msg.node_id, msg.child_id, msg.type,
msg.sub_type, msg.payload)
return None | Process an internal log message. | null | null | null | |
def handle_gateway_ready(msg): # pylint: disable=useless-return
_LOGGER.info(
'n:%s c:%s t:%s s:%s p:%s', msg.node_id, msg.child_id, msg.type,
msg.sub_type, msg.payload)
msg.gateway.alert(msg)
return None | Process an internal gateway ready message. | null | null | null | |
_LOGGER.info(
'n:%s c:%s t:%s s:%s p:%s', msg.node_id, msg.child_id, msg.type,
msg.sub_type, msg.payload)
msg.gateway.alert(msg)
return msg.copy(
node_id=255, ack=0,
sub_type=msg.gateway.const.Internal.I_DISCOVER, payload='') | def handle_gateway_ready_20(msg) | Process an internal gateway ready message. | 6.949456 | 6.462918 | 1.075282 |
if not msg.gateway.is_sensor(msg.node_id):
return None
handle_smartsleep(msg)
msg.gateway.sensors[msg.node_id].heartbeat = msg.payload
msg.gateway.alert(msg)
return None | def handle_heartbeat_response(msg) | Process an internal heartbeat response message. | 7.824319 | 7.611621 | 1.027944 |
if not msg.gateway.is_sensor(msg.node_id):
return None
msg.gateway.sensors[msg.node_id].heartbeat = msg.payload
msg.gateway.alert(msg)
return None | def handle_heartbeat_response_22(msg) | Process an internal heartbeat response message. | 6.059299 | 5.696124 | 1.063758 |
self._mqttc.publish(topic, payload, qos, retain) | def publish(self, topic, payload, qos, retain) | Publish an MQTT message. | 2.791553 | 2.816017 | 0.991313 |
if topic in self.topics:
return
def _message_callback(mqttc, userdata, msg):
callback(msg.topic, msg.payload.decode('utf-8'), msg.qos)
self._mqttc.subscribe(topic, qos)
self._mqttc.message_callback_add(topic, _message_callback)
self... | def subscribe(self, topic, callback, qos) | Subscribe to an MQTT topic. | 2.547053 | 2.475134 | 1.029057 |
info = next(serial.tools.list_ports.grep(self.port), None)
return info.serial_number if info is not None else None | def get_gateway_id(self) | Return a unique id for the gateway. | 6.054256 | 5.05873 | 1.196794 |
while self.protocol:
_LOGGER.info('Trying to connect to %s', self.port)
try:
ser = serial.serial_for_url(
self.port, self.baud, timeout=self.timeout)
except serial.SerialException:
_LOGGER.error('Unable to connect t... | def _connect(self) | Connect to the serial port. This should be run in a new thread. | 2.943425 | 2.737629 | 1.075173 |
try:
while True:
_LOGGER.info('Trying to connect to %s', self.port)
try:
yield from serial_asyncio.create_serial_connection(
self.loop, lambda: self.protocol, self.port, self.baud)
return
... | def _connect(self) | Connect to the serial port. | 2.437498 | 2.311275 | 1.054612 |
try:
value = str(value)
if not parse_ver('1.4') <= parse_ver(value):
raise ValueError()
return value
except (AttributeError, TypeError, ValueError):
raise vol.Invalid(
'{} is not a valid version specifier'.format(value)) | def is_version(value) | Validate that value is a valid version string. | 5.184916 | 4.694525 | 1.10446 |
try:
value = percent_int(value)
return value
except vol.Invalid:
_LOGGER.warning(
'%s is not a valid battery level, falling back to battery level 0',
value)
return 0 | def is_battery_level(value) | Validate that value is a valid battery level integer. | 5.274189 | 5.066548 | 1.040983 |
try:
value = vol.Coerce(int)(value)
return value
except vol.Invalid:
_LOGGER.warning(
'%s is not a valid heartbeat value, falling back to heartbeat 0',
value)
return 0 | def is_heartbeat(value) | Validate that value is a valid heartbeat integer. | 4.895659 | 4.110985 | 1.190873 |
if method is None:
method = methods[0]
salt = ['${0}$'.format(method.ident) if method.ident else '']
if rounds:
salt.append('rounds={0:d}$'.format(rounds))
salt.append(''.join(_sr.choice(_BASE64_CHARACTERS) for char in range(method.salt_chars)))
return ''.join(salt) | def mksalt(method=None, rounds=None) | Generate a salt for the specified method.
If not specified, the strongest available method will be used. | 5.100555 | 5.163507 | 0.987808 |
if salt is None or isinstance(salt, _Method):
salt = mksalt(salt, rounds)
algo, rounds, salt = extract_components_from_salt(salt)
if algo == 5:
hashfunc = hashlib.sha256
elif algo == 6:
hashfunc = hashlib.sha512
else:
raise ValueError('Unsupported algorithm, mus... | def crypt(word, salt=None, rounds=_ROUNDS_DEFAULT) | Return a string representing the one-way hash of a password, with a salt
prepended.
If ``salt`` is not specified or is ``None``, the strongest
available method will be selected and a salt generated. Otherwise,
``salt`` may be one of the ``crypt.METHOD_*`` values, or a string as
returned by ``crypt.... | 3.637918 | 3.634824 | 1.000851 |
password = 1
password_repeat = 2
while password != password_repeat:
password = getpass.getpass('Enter password: ')
password_repeat = getpass.getpass('Repeat password: ')
if password != password_repeat:
sys.stderr.write('Passwords do not match, try again.\n')
retu... | def double_prompt_for_plaintext_password() | Get the desired password from the user through a double prompt. | 2.201029 | 2.152392 | 1.022597 |
try:
msg = Message(data, self)
msg.validate(self.protocol_version)
except (ValueError, vol.Invalid) as exc:
_LOGGER.warning('Not a valid message: %s', exc)
return None
message_type = self.const.MessageType(msg.type)
handler = mess... | def logic(self, data) | Parse the data and respond to it appropriately.
Response is returned to the caller and has to be sent
data as a mysensors command string. | 4.708269 | 4.899314 | 0.961006 |
if self.event_callback is not None:
try:
self.event_callback(msg)
except Exception as exception: # pylint: disable=broad-except
_LOGGER.exception(exception)
if self.persistence:
self.persistence.need_save = True | def alert(self, msg) | Tell anyone who wants to know that a sensor was updated. | 3.894458 | 3.65326 | 1.066023 |
if self.sensors:
next_id = max(self.sensors.keys()) + 1
else:
next_id = 1
if next_id <= self.const.MAX_NODE_ID:
return next_id
return None | def _get_next_id(self) | Return the next available sensor id. | 3.715383 | 2.944777 | 1.261686 |
if sensorid is None:
sensorid = self._get_next_id()
if sensorid is not None and sensorid not in self.sensors:
self.sensors[sensorid] = Sensor(sensorid)
return sensorid if sensorid in self.sensors else None | def add_sensor(self, sensorid=None) | Add a sensor to the gateway. | 2.270171 | 2.2187 | 1.023199 |
ret = sensorid in self.sensors
if not ret:
_LOGGER.warning('Node %s is unknown', sensorid)
if ret and child_id is not None:
ret = child_id in self.sensors[sensorid].children
if not ret:
_LOGGER.warning('Child %s is unknown', child_id)
... | def is_sensor(self, sensorid, child_id=None) | Return True if a sensor and its child exist. | 4.561353 | 4.619905 | 0.987326 |
if job is None:
if not self.queue:
return None
job = self.queue.popleft()
start = timer()
func, args = job
reply = func(*args)
end = timer()
if end - start > 0.1:
_LOGGER.debug(
'Handle queue wit... | def run_job(self, job=None) | Run a job, either passed in or from the queue.
A job is a tuple of function and optional args. Keyword arguments
can be passed via use of functools.partial. The job should return a
string that should be sent by the gateway protocol. The function will
be called with the arguments and the... | 3.850776 | 3.731814 | 1.031878 |
if not self.is_sensor(sensor_id, child_id):
return
if self.sensors[sensor_id].new_state:
self.sensors[sensor_id].set_child_value(
child_id, value_type, value,
children=self.sensors[sensor_id].new_state)
else:
self.add_j... | def set_child_value(
self, sensor_id, child_id, value_type, value, **kwargs) | Add a command to set a sensor value, to the queue.
A queued command will be sent to the sensor when the gateway
thread has sent all previously queued commands.
If the sensor attribute new_state returns True, the command will be
buffered in a queue on the sensor, and only the internal s... | 2.663028 | 2.612465 | 1.019355 |
connect_thread = threading.Thread(target=self._connect)
connect_thread.start() | def start(self) | Start the connection to a transport. | 4.853332 | 4.399852 | 1.103067 |
while not self._stop_event.is_set():
reply = self.run_job()
self.send(reply)
if self.queue:
continue
time.sleep(0.02) | def _poll_queue(self) | Poll the queue for work. | 5.956335 | 5.397914 | 1.103451 |
def schedule_save():
save_sensors()
scheduler = threading.Timer(10.0, schedule_save)
scheduler.start()
self._cancel_save = scheduler.cancel
return schedule_save | def _create_scheduler(self, save_sensors) | Return function to schedule saving sensors. | 6.45815 | 5.30684 | 1.216948 |
if not self.persistence:
return
self.persistence.safe_load_sensors()
self.persistence.schedule_save_sensors() | def start_persistence(self) | Load persistence file and schedule saving of persistence file. | 8.762542 | 5.74846 | 1.524328 |
self._stop_event.set()
if not self.persistence:
return
if self._cancel_save is not None:
self._cancel_save()
self._cancel_save = None
self.persistence.save_sensors() | def stop(self) | Stop the background thread. | 5.004729 | 4.532364 | 1.10422 |
fw_bin = None
if fw_path:
fw_bin = load_fw(fw_path)
if not fw_bin:
return
self.ota.make_update(nids, fw_type, fw_ver, fw_bin) | def update_fw(self, nids, fw_type, fw_ver, fw_path=None) | Update firwmare of all node_ids in nids. | 3.655002 | 3.542664 | 1.03171 |
if not self.protocol or not self.protocol.transport:
self.protocol = None # Make sure protocol is None
return
_LOGGER.info('Disconnecting from gateway')
self.protocol.transport.close()
self.protocol = None | def _disconnect(self) | Disconnect from the transport. | 4.842179 | 4.507359 | 1.074283 |
if not message or not self.protocol or not self.protocol.transport:
return
if not self.can_log:
_LOGGER.debug('Sending %s', message.strip())
try:
self.protocol.transport.write(message.encode())
except OSError as exc:
_LOGGER.error(... | def send(self, message) | Write a message to the gateway. | 3.370362 | 3.332819 | 1.011265 |
_LOGGER.info('Stopping gateway')
self._disconnect()
if self.connect_task and not self.connect_task.cancelled():
self.connect_task.cancel()
self.connect_task = None
if not self.persistence:
return
if self._cancel_save is not None:
... | def stop(self) | Stop the gateway. | 3.80346 | 3.411568 | 1.114871 |
job = func, args
reply = self.run_job(job)
self.send(reply) | def add_job(self, func, *args) | Add a job that should return a reply to be sent.
A job is a tuple of function and optional args. Keyword arguments
can be passed via use of functools.partial. The job should return a
string that should be sent by the gateway protocol.
The async version of this method will send the repl... | 9.764071 | 5.898211 | 1.655429 |
@asyncio.coroutine
def schedule_save():
yield from self.loop.run_in_executor(None, save_sensors)
callback = partial(self.loop.create_task, schedule_save())
task = self.loop.call_later(10.0, callback)
self._cancel_save = task.cancel
... | def _create_scheduler(self, save_sensors) | Return function to schedule saving sensors. | 4.07688 | 3.816107 | 1.068335 |
if not self.persistence:
return
yield from self.loop.run_in_executor(
None, self.persistence.safe_load_sensors)
yield from self.persistence.schedule_save_sensors() | def start_persistence(self) | Load persistence file and schedule saving of persistence file. | 6.093342 | 4.727116 | 1.289019 |
super().connection_made(transport)
if hasattr(self.transport, 'serial'):
_LOGGER.info('Connected to %s', self.transport.serial)
else:
_LOGGER.info('Connected to %s', self.transport) | def connection_made(self, transport) | Handle created connection. | 2.870607 | 2.54608 | 1.127462 |
if not self.gateway.can_log:
_LOGGER.debug('Receiving %s', line)
self.gateway.add_job(self.gateway.logic, line) | def handle_line(self, line) | Handle incoming string data one line at a time. | 10.039723 | 9.162031 | 1.095797 |
_LOGGER.debug('Connection lost with %s', self.transport.serial)
if exc:
_LOGGER.error(exc)
self.transport.serial.close()
self.conn_lost_callback()
self.transport = None | def connection_lost(self, exc) | Handle lost connection. | 4.564343 | 4.070378 | 1.121356 |
if child_id in self.children:
_LOGGER.warning(
'child_id %s already exists in children of node %s, '
'cannot add child', child_id, self.sensor_id)
return None
self.children[child_id] = ChildSensor(
child_id, child_type, descrip... | def add_child_sensor(self, child_id, child_type, description='') | Create and add a child sensor. | 2.806509 | 2.750137 | 1.020498 |
children = kwargs.get('children', self.children)
if not isinstance(children, dict) or child_id not in children:
return None
msg_type = kwargs.get('msg_type', 1)
ack = kwargs.get('ack', 0)
msg = Message().modify(
node_id=self.sensor_id, child_id=ch... | def set_child_value(self, child_id, value_type, value, **kwargs) | Set a child sensor's value. | 2.721144 | 2.638591 | 1.031287 |
const = get_const(protocol_version)
custom_schema = vol.Schema({
typ.value: const.VALID_SETREQ[typ]
for typ in const.VALID_TYPES[const.Presentation.S_CUSTOM]})
return custom_schema.extend({
typ.value: const.VALID_SETREQ[typ]
for typ in con... | def get_schema(self, protocol_version) | Return the child schema for the correct const version. | 7.437883 | 7.241704 | 1.02709 |
if values is None:
values = self.values
return self.get_schema(protocol_version)(values) | def validate(self, protocol_version, values=None) | Validate child value types and values against protocol_version. | 5.432718 | 4.754991 | 1.14253 |
try:
spans = row.find('div', {'id': 'coltextR2'}).find_all('span')
if len(spans) < 2:
return None
return spans[1].string
except AttributeError:
return None | def _get_shipped_from(row) | Get where package was shipped from. | 4.967676 | 4.526751 | 1.097404 |
try:
divs = row.find('div', {'id': 'coltextR3'}).find_all('div')
if len(divs) < 2:
return None
timestamp_string = divs[1].string
except AttributeError:
return None
try:
return parse(timestamp_string)
except ValueError:
return None | def _get_status_timestamp(row) | Get latest package timestamp. | 3.843041 | 3.615631 | 1.062896 |
try:
month = row.find('div', {'class': 'date-small'}).string
day = row.find('div', {'class': 'date-num-large'}).string
except AttributeError:
return None
try:
return parse('{} {}'.format(month, day)).date()
except ValueError:
return None | def _get_delivery_date(row) | Get delivery date (estimated or actual). | 3.676342 | 3.550407 | 1.03547 |
if driver_type == 'phantomjs':
return webdriver.PhantomJS(service_log_path=os.path.devnull)
if driver_type == 'firefox':
return webdriver.Firefox(firefox_options=FIREFOXOPTIONS)
elif driver_type == 'chrome':
chrome_options = webdriver.ChromeOptions()
for arg in CHROME_WE... | def _get_driver(driver_type) | Get webdriver. | 2.218338 | 2.178931 | 1.018085 |
_LOGGER.debug("attempting login")
session.cookies.clear()
try:
session.remove_expired_responses()
except AttributeError:
pass
try:
driver = _get_driver(session.auth.driver)
except WebDriverException as exception:
raise USPSError(str(exception))
driver.get... | def _login(session) | Login.
Use Selenium webdriver to login. USPS authenticates users
in part by a key generated by complex, obfuscated client-side
Javascript, which can't (easily) be replicated in Python.
Invokes the webdriver once to perform login, then uses the
resulting session cookies with a standard Python `reque... | 2.432998 | 2.40674 | 1.01091 |
def wrapped(*args):
try:
return function(*args)
except USPSError:
_LOGGER.info("attempted to access page before login")
_login(args[0])
return function(*args)
return wrapped | def authenticated(function) | Re-authenticate if session expired. | 6.719069 | 7.282542 | 0.922627 |
response = session.get(PROFILE_URL, allow_redirects=False)
if response.status_code == 302:
raise USPSError('expired session')
parsed = BeautifulSoup(response.text, HTML_PARSER)
profile = parsed.find('div', {'class': 'atg_store_myProfileInfo'})
data = {}
for row in profile.find_all('... | def get_profile(session) | Get profile data. | 2.712638 | 2.640564 | 1.027295 |
_LOGGER.info("attempting to get package data")
response = _get_dashboard(session)
parsed = BeautifulSoup(response.text, HTML_PARSER)
packages = []
for row in parsed.find_all('div', {'class': 'pack_row'}):
packages.append({
'tracking_number': _get_tracking_number(row),
... | def get_packages(session) | Get package data. | 2.85015 | 2.690022 | 1.059527 |
_LOGGER.info("attempting to get mail data")
if not date:
date = datetime.datetime.now().date()
response = _get_dashboard(session, date)
parsed = BeautifulSoup(response.text, HTML_PARSER)
mail = []
for row in parsed.find_all('div', {'class': 'mailpiece'}):
image = _get_mailpi... | def get_mail(session, date=None) | Get mail data. | 3.368561 | 3.211448 | 1.048923 |
class USPSAuth(AuthBase): # pylint: disable=too-few-public-methods
def __init__(self, username, password, cookie_path, driver):
self.username = username
self.password = password
self.cookie_path = cookie_path
self.driver = driver
... | def get_session(username, password, cookie_path=COOKIE_PATH, cache=True,
cache_expiry=300, cache_path=CACHE_PATH, driver='phantomjs') | Get session, existing or new. | 2.293315 | 2.308138 | 0.993578 |
S, j, out = list(range(256)), 0, []
for i in range(256):
j = (j + S[i] + ord(key[i % len(key)])) % 256
S[i], S[j] = S[j], S[i]
i = j = 0
for ch in data:
i = (i + 1) % 256
j = (j + S[i]) % 256
S[i], S[j] = S[j], S[i]
out.append(chr(ord(ch) ^ S[(S[i] ... | def rc4(data, key) | RC4 encryption and decryption method. | 1.411321 | 1.451798 | 0.972119 |
confirmation_key = generate_random_token()
try:
confirmation = EmailConfirmation()
confirmation.content_object = content_object
confirmation.email_field_name = email_field_name
confirmation.email = email
confirmation.confirmation_key... | def verify_email_for_object(self, email, content_object, email_field_name='email') | Create an email confirmation for `content_object` and send a confirmation mail.
The email will be directly saved to `content_object.email_field_name` when `is_primary` and `skip_verify` both are true. | 2.046434 | 2.037865 | 1.004205 |
EmailConfirmation.objects.filter(content_type=self.content_type, object_id=self.object_id, email_field_name=self.email_field_name).delete() | def clean(self) | delete all confirmations for the same content_object and the same field | 4.333255 | 2.839908 | 1.525844 |
paginator = Paginator(objects, per_page)
page = request.GET.get('page', 1)
get_params = '&'.join(['%s=%s' % (k, request.GET[k])
for k in request.GET if k != 'page'])
try:
page_number = int(page)
except ValueError:
if page == 'last':
page_n... | def render_paginate(request, template, objects, per_page, extra_context={}) | Paginated list of objects. | 1.535978 | 1.539093 | 0.997977 |
report = {}
for k, k_changes in self._changes.items():
if len(k_changes) == 1:
report[k] = k_changes[0].new_value
elif k_changes[0].old_value != k_changes[-1].new_value:
report[k] = k_changes[-1].new_value
return report | def values(self) | Returns a mapping of items to their new values. The mapping includes only items whose value or raw string value
has changed in the context. | 2.701727 | 2.481361 | 1.088809 |
report = {}
for k, k_changes in self._changes.items():
if len(k_changes) == 1:
report[k] = k_changes[0]
else:
first = k_changes[0]
last = k_changes[-1]
if first.old_value != last.new_value or first.old_raw_s... | def changes(self) | Returns a mapping of items to their effective change objects which include the old values
and the new. The mapping includes only items whose value or raw string value has changed in the context. | 2.346865 | 2.018896 | 1.16245 |
if isinstance(source, six.string_types):
source = os.path.expanduser(source)
with open(source, encoding='utf-8') as f:
self._rw.load_config_from_file(self._config, f, as_defaults=as_defaults)
elif isinstance(source, (list, tuple)):
for s in s... | def load(self, source, as_defaults=False) | Load configuration values from the specified source.
Args:
source:
as_defaults (bool): if ``True``, contents of ``source`` will be treated as schema of configuration items. | 1.863318 | 1.951059 | 0.955029 |
self._rw.load_config_from_string(self._config, config_str, as_defaults=as_defaults) | def loads(self, config_str, as_defaults=False) | Load configuration values from the specified source string.
Args:
config_str:
as_defaults (bool): if ``True``, contents of ``source`` will be treated as schema of configuration items. | 5.350387 | 5.947732 | 0.899568 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.