text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _load_sensors(self, path=None):
"""Load sensors from file.""" |
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
_LOGGER.de... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def safe_load_sensors(self):
"""Load sensors safely from file.""" |
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:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _perform_file_action(self, filename, action):
"""Perform action on specific file types. Dynamic dispatch function for performing actions on specific file typ... |
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def default(self, obj):
"""Serialize obj into JSON.""" |
# 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,
's... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dict_to_object(self, obj):
# pylint: disable=no-self-use """Return object from dict.""" |
if not isinstance(obj, dict):
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']):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_const(protocol_version):
"""Return the const module for the protocol_version.""" |
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)
LO... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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... |
return struct.unpack('<{}H'.format(words), binascii.unhexlify(hex_str)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fw_int_to_hex(*args):
"""Pack integers into hex string. Use little-endian and unsigned int format. """ |
return binascii.hexlify(
struct.pack('<{}H'.format(len(args)), *args)).decode('utf-8') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compute_crc(data):
"""Compute CRC16 of data and return an int.""" |
crc16 = crcmod.predefined.Crc('modbus')
crc16.update(data)
return int(crc16.hexdigest(), 16) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_fw(path):
"""Open firmware file and return a binary string.""" |
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') a... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prepare_fw(bin_string):
"""Check that firmware is valid and return dict with binary data.""" |
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,
}
return... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_fw(self, msg, updates, req_fw_type=None, req_fw_ver=None):
"""Get firmware type, version and a dict holding binary data.""" |
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_id] = f... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def respond_fw(self, msg):
"""Respond to a firmware request.""" |
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(
msg... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def respond_fw_config(self, msg):
"""Respond to a firmware config request.""" |
(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',
req_fw_t... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_update(self, nids, fw_type, fw_ver, fw_bin=None):
"""Start firmware update process for one or more node_id.""" |
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 = prepare... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_smartsleep(msg):
"""Process a message before going back to smartsleep.""" |
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, ChildSensor(ch... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_presentation(msg):
"""Process a presentation message.""" |
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_vers... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_set(msg):
"""Process a set message.""" |
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_id, ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_req(msg):
"""Process a req message. This will return the value if it exists. If no value exists, nothing is returned. """ |
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 None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_internal(msg):
"""Process an internal message.""" |
internal = msg.gateway.const.Internal(msg.sub_type)
handler = internal.get_handler(msg.gateway.handlers)
if handler is None:
return None
return handler(msg) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_stream(msg):
"""Process a stream type message.""" |
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_id_request(msg):
"""Process an internal id request message.""" |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_time(msg):
"""Process an internal time request message.""" |
return msg.copy(ack=0, payload=calendar.timegm(time.localtime())) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_battery_level(msg):
"""Process an internal battery level message.""" |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_sketch_name(msg):
"""Process an internal sketch name message.""" |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_sketch_version(msg):
"""Process an internal sketch version message.""" |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_log_message(msg):
# pylint: disable=useless-return """Process an internal log message.""" |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def publish(self, topic, payload, qos, retain):
"""Publish an MQTT message.""" |
self._mqttc.publish(topic, payload, qos, retain) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def subscribe(self, topic, callback, qos):
"""Subscribe to an MQTT topic.""" |
if topic in self.topics:
return
def _message_callback(mqttc, userdata, msg):
"""Callback added to callback list for received message."""
callback(msg.topic, msg.payload.decode('utf-8'), msg.qos)
self._mqttc.subscribe(topic, qos)
self._mqttc.message_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _connect(self):
"""Connect to the serial port. This should be run in a new thread.""" |
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 to %s', s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _connect(self):
"""Connect to the serial port.""" |
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
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_version(value):
"""Validate that value is a valid version string.""" |
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)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_battery_level(value):
"""Validate that value is a valid battery level integer.""" |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_heartbeat(value):
"""Validate that value is a valid heartbeat integer.""" |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mksalt(method=None, rounds=None):
"""Generate a salt for the specified method. If not specified, the strongest available method will be used. """ |
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def double_prompt_for_plaintext_password():
"""Get the desired password from the user through a double prompt.""" |
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')
return p... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 strin... |
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 = message_type... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def alert(self, msg):
"""Tell anyone who wants to know that a sensor was updated.""" |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_next_id(self):
"""Return the next available sensor id.""" |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_sensor(self, sensorid=None):
"""Add a sensor to the gateway.""" |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_sensor(self, sensorid, child_id=None):
"""Return True if a sensor and its child exist.""" |
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)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 vi... |
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 with call %... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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... |
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_job(parti... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _poll_queue(self):
"""Poll the queue for work.""" |
while not self._stop_event.is_set():
reply = self.run_job()
self.send(reply)
if self.queue:
continue
time.sleep(0.02) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stop(self):
"""Stop the background thread.""" |
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() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_fw(self, nids, fw_type, fw_ver, fw_path=None):
"""Update firwmare of all node_ids in nids.""" |
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _disconnect(self):
"""Disconnect from the transport.""" |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send(self, message):
"""Write a message to the gateway.""" |
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(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stop(self):
"""Stop the gateway.""" |
_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:
s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 pass... |
job = func, args
reply = self.run_job(job)
self.send(reply) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connection_made(self, transport):
"""Handle created connection.""" |
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_line(self, line):
"""Handle incoming string data one line at a time.""" |
if not self.gateway.can_log:
_LOGGER.debug('Receiving %s', line)
self.gateway.add_job(self.gateway.logic, line) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_child_sensor(self, child_id, child_type, description=''):
"""Create and add a child sensor.""" |
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, description)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_child_value(self, child_id, value_type, value, **kwargs):
"""Set a child sensor's value.""" |
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=child_id, ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_schema(self, protocol_version):
"""Return the child schema for the correct const version.""" |
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 const.VALID... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate(self, protocol_version, values=None):
"""Validate child value types and values against protocol_version.""" |
if values is None:
values = self.values
return self.get_schema(protocol_version)(values) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_shipped_from(row):
"""Get where package was shipped from.""" |
try:
spans = row.find('div', {'id': 'coltextR2'}).find_all('span')
if len(spans) < 2:
return None
return spans[1].string
except AttributeError:
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_status_timestamp(row):
"""Get latest package timestamp.""" |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_driver(driver_type):
"""Get webdriver.""" |
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_WEBDRI... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_profile(session):
"""Get profile data.""" |
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('tr')... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_packages(session):
"""Get package data.""" |
_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),
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_mail(session, date=None):
"""Get mail data.""" |
_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_mailpiece_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_session(username, password, cookie_path=COOKIE_PATH, cache=True, cache_expiry=300, cache_path=CACHE_PATH, driver='phantomjs'):
"""Get session, existing o... |
class USPSAuth(AuthBase): # pylint: disable=too-few-public-methods
"""USPS authorization storage."""
def __init__(self, username, password, cookie_path, driver):
"""Init."""
self.username = username
self.password = password
self.cookie_path = cookie... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rc4(data, key):
"""RC4 encryption and decryption method.""" |
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] + S[... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def verify_email_for_object(self, email, content_object, email_field_name='email'):
""" Create an email confirmation for `content_object` and send a confirmation... |
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 = confi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clean(self):
""" delete all confirmations for the same content_object and the same field """ |
EmailConfirmation.objects.filter(content_type=self.content_type, object_id=self.object_id, email_field_name=self.email_field_name).delete() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def render_paginate(request, template, objects, per_page, extra_context={}):
""" Paginated list of objects. """ |
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_numbe... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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.... |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 who... |
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_str_value... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load(self, source, as_defaults=False):
""" Load configuration values from the specified source. Args: source: as_defaults (bool):
if ``True``, contents of `... |
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 source:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def loads(self, config_str, as_defaults=False):
""" Load configuration values from the specified source string. Args: config_str: as_defaults (bool):
if ``True`... |
self._rw.load_config_from_string(self._config, config_str, as_defaults=as_defaults) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dump(self, destination, with_defaults=False):
""" Write configuration values to the specified destination. Args: destination: with_defaults (bool):
if ``Tru... |
if isinstance(destination, six.string_types):
with open(destination, 'w', encoding='utf-8') as f:
self._rw.dump_config_to_file(self._config, f, with_defaults=with_defaults)
else:
self._rw.dump_config_to_file(self._config, destination, with_defaults=with_defaults) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dumps(self, with_defaults=False):
""" Generate a string representing all the configuration values. Args: with_defaults (bool):
if ``True``, values of items ... |
return self._rw.dump_config_to_string(self._config, with_defaults=with_defaults) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _default_key_setter(self, name, subject):
""" This method is used only when there is a custom key_setter set. Do not override this method. """ |
if is_config_item(subject):
self.add_item(name, subject)
elif is_config_section(subject):
self.add_section(name, subject)
else:
raise TypeError(
'Section items can only be replaced with items, '
'got {type}. To set item value u... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_section(self, *key):
""" The recommended way of retrieving a section by key when extending configmanager's behaviour. """ |
section = self._get_item_or_section(key)
if not section.is_section:
raise RuntimeError('{} is an item, not a section'.format(key))
return section |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_item(self, alias, item):
""" Add a config item to this section. """ |
if not isinstance(alias, six.string_types):
raise TypeError('Item name must be a string, got a {!r}'.format(type(alias)))
item = copy.deepcopy(item)
if item.name is not_set:
item.name = alias
if self.settings.str_path_separator in item.name:
raise Va... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_section(self, alias, section):
""" Add a sub-section to this section. """ |
if not isinstance(alias, six.string_types):
raise TypeError('Section name must be a string, got a {!r}'.format(type(alias)))
self._tree[alias] = section
if self.settings.str_path_separator in alias:
raise ValueError(
'Section alias must not contain str_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_recursive_iterator(self, recursive=False):
""" Basic recursive iterator whose only purpose is to yield all items and sections in order, with their full ... |
names_yielded = set()
for obj_alias, obj in self._tree.items():
if obj.is_section:
if obj.alias in names_yielded:
continue
names_yielded.add(obj.alias)
yield (obj.alias,), obj
if not recursive:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reset(self):
""" Recursively resets values of all items contained in this section and its subsections to their default values. """ |
for _, item in self.iter_items(recursive=True):
item.reset() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_default(self):
""" ``True`` if values of all config items in this section and its subsections have their values equal to defaults or have no value set. ""... |
for _, item in self.iter_items(recursive=True):
if not item.is_default:
return False
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dump_values(self, with_defaults=True, dict_cls=dict, flat=False):
""" Export values of all items contained in this section to a dictionary. Items with no val... |
values = dict_cls()
if flat:
for str_path, item in self.iter_items(recursive=True, key='str_path'):
if item.has_value:
if with_defaults or not item.is_default:
values[str_path] = item.value
else:
for item_name,... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_values(self, dictionary, as_defaults=False, flat=False):
""" Import config values from a dictionary. When ``as_defaults`` is set to ``True``, the values... |
if flat:
# Deflatten the dictionary and then pass on to the normal case.
separator = self.settings.str_path_separator
flat_dictionary = dictionary
dictionary = collections.OrderedDict()
for k, v in flat_dictionary.items():
k_parts = k.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_section(self, *args, **kwargs):
""" Internal factory method used to create an instance of configuration section. Should only be used when extending or... |
kwargs.setdefault('section', self)
return self.settings.section_factory(*args, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def item_attribute(self, f=None, name=None):
""" A decorator to register a dynamic item attribute provider. By default, uses function name for attribute name. Ov... |
def decorator(func):
attr_name = name or func.__name__
if attr_name.startswith('_'):
raise RuntimeError('Invalid dynamic item attribute name -- should not start with an underscore')
self.__item_attributes[attr_name] = func
return func
if ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_item_attribute(self, item, name):
""" Method called by item when an attribute is not found. """ |
if name in self.__item_attributes:
return self.__item_attributes[name](item)
elif self.section:
return self.section.get_item_attribute(item, name)
else:
raise AttributeError(name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dispatch_event(self, event_, **kwargs):
""" Dispatch section event. Notes: You MUST NOT call event.trigger() directly because it will circumvent the section ... |
if self.settings.hooks_enabled:
result = self.hooks.dispatch_event(event_, **kwargs)
if result is not None:
return result
# Must also dispatch the event in parent section
if self.section:
return self.section.dispatch_event(event_,... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load(self):
""" Load user configuration based on settings. """ |
# Must reverse because we want the sources assigned to higher-up Config instances
# to overrides sources assigned to lower Config instances.
for section in reversed(list(self.iter_sections(recursive=True, key=None))):
if section.is_config:
section.load()
fo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def option(self, *args, **kwargs):
""" Registers a click.option which falls back to a configmanager Item if user hasn't provided a value in the command line. Ite... |
args, kwargs = _config_parameter(args, kwargs)
return self._click.option(*args, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def argument(self, *args, **kwargs):
""" Registers a click.argument which falls back to a configmanager Item if user hasn't provided a value in the command line.... |
if kwargs.get('required', True):
raise TypeError(
'In click framework, arguments are mandatory, unless marked required=False. '
'Attempt to use configmanager as a fallback provider suggests that this is an optional option, '
'not a mandatory argument... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_kwarg(self, name, kwargs):
""" Helper to get value of a named attribute irrespective of whether it is passed with or without "@" prefix. """ |
at_name = '@{}'.format(name)
if name in kwargs:
if at_name in kwargs:
raise ValueError('Both {!r} and {!r} specified in kwargs'.format(name, at_name))
return kwargs[name]
if at_name in kwargs:
return kwargs[at_name]
return not_set |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_envvar_value(self):
""" Internal helper to get item value from an environment variable if item is controlled by one, and if the variable is set. Returns... |
envvar_name = None
if self.envvar is True:
envvar_name = self.envvar_name
if envvar_name is None:
envvar_name = '_'.join(self.get_path()).upper()
elif self.envvar:
envvar_name = self.envvar
if envvar_name and envvar_name in os.enviro... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get(self, fallback=not_set):
""" Returns config value. See Also: :meth:`.set` and :attr:`.value` """ |
envvar_value = self._get_envvar_value()
if envvar_value is not not_set:
return envvar_value
if self.has_value:
if self._value is not not_set:
return self._value
else:
return copy.deepcopy(self.default)
elif fallback i... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set(self, value):
""" Sets config value. """ |
old_value = self._value
old_raw_str_value = self.raw_str_value
self.type.set_item_value(self, value)
new_value = self._value
if old_value is not_set and new_value is not_set:
# Nothing to report
return
if self.section:
self.section... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reset(self):
""" Resets the value of config item to its default value. """ |
old_value = self._value
old_raw_str_value = self.raw_str_value
self._value = not_set
self.raw_str_value = not_set
new_value = self._value
if old_value is not_set:
# Nothing to report
return
if self.section:
self.section.dis... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_default(self):
""" ``True`` if the item's value is its default value or if no value and no default value are set. If the item is backed by an environment ... |
envvar_value = self._get_envvar_value()
if envvar_value is not not_set:
return envvar_value == self.default
else:
return self._value is not_set or self._value == self.default |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def has_value(self):
""" ``True`` if item has a default value or custom value set. """ |
if self._get_envvar_value() is not not_set:
return True
else:
return self.default is not not_set or self._value is not not_set |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate(self):
""" Validate item. """ |
if self.required and not self.has_value:
raise RequiredValueMissing(name=self.name, item=self) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def filebrowser(request, file_type):
""" Trigger view for filebrowser """ |
template = 'filebrowser.html'
upload_form = FileUploadForm()
uploaded_file = None
upload_tab_active = False
is_images_dialog = (file_type == 'img')
is_documents_dialog = (file_type == 'doc')
files = FileBrowserFile.objects.filter(file_type=file_type)
if request.POST:
u... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def available_domains(self):
""" Return list of available domains for use in email address. """ |
if not hasattr(self, '_available_domains'):
url = 'http://{0}/request/domains/format/json/'.format(
self.api_domain)
req = requests.get(url)
domains = req.json()
setattr(self, '_available_domains', domains)
return self._available_domains |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_login(self, min_length=6, max_length=10, digits=True):
""" Generate string for email address login with defined length and alphabet. :param min_leng... |
chars = string.ascii_lowercase
if digits:
chars += string.digits
length = random.randint(min_length, max_length)
return ''.join(random.choice(chars) for x in range(length)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.