output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
Send extended status request for group and button. | Can you generate the documentation for the following Python 3 function
def extended_status_request(self):
self._status_received = False
user_data = Userdata({'d1': self.group,
'd2': 0x00})
cmd = ExtendedSend(self._address,
COMMAND_EXTENDED... | You are a Python code generator, capable of creating scripts from specifications. |
def _status_message_received(self, msg):
"""Receive confirmation that the status message is coming.
The real status message is the extended direct message.
"""
if not self._status_received:
asyncio.ensure_future(self._confirm_status_received(),
... | Write a Python 3 function that can
receive a status message from the server. | As a python code expert, you are capable of creating scripts from specifications. |
Receeive an extended status message. | Can you generate the documentation for the following Python 3 function
def _status_extended_message_received(self, msg):
self._status_received = True
self._status_retries = 0
_LOGGER.debug("Extended status message received")
if self._status_response_lock.locked():
self._statu... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _property_set(self, msg):
"""Set command received and acknowledged."""
prop = self._sent_property.get('prop')
if prop and hasattr(self, prop):
setattr(self, prop, self._sent_property.get('val'))
self._sent_property = {} | Write a Python 3 function that can
set property of the object. | You are a Python code analyst, evaluating scripts for potential improvements. |
Set status properties from userdata response. | Here you have a function in Python 3, explain what it does
def _set_status_data(self, userdata):
self._on_mask = userdata['d3']
self._off_mask = userdata['d4']
self._x10_house_code = userdata['d5']
self._x10_unit = userdata['d6']
self._ramp_rate = userdata['d7']
self._on_... | As a python code expert, you are capable of creating scripts from specifications. |
def _create_set_property_msg(self, prop, cmd, val):
"""Create an extended message to set a property.
Create an extended message with:
cmd1: 0x2e
cmd2: 0x00
flags: Direct Extended
d1: group
d2: cmd
d3: val
d4 - d14: 0x00... | Write a Python 3 script for
creating an extended message to set a property. | You are a Python code architect, reviewing and designing scalable and efficient code |
def on(self, group):
"""Turn the LED on for a group."""
asyncio.ensure_future(self._send_led_on_off_request(group, 1),
loop=self._loop) | Can you write a function in Python 3 where it
turns the LED on for a group. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Turn the LED off for a group. | Make a summary of the following Python 3 code
def off(self, group):
asyncio.ensure_future(self._send_led_on_off_request(group, 0),
loop=self._loop) | As a Python code translator, you convert algorithms and pseudocode into Python. |
Register a callback when a specific button LED changes. | Can you generate the documentation for the following Python 3 function
def register_led_updates(self, callback, button):
button_callbacks = self._button_observer_callbacks.get(button)
if not button_callbacks:
self._button_observer_callbacks[button] = []
_LOGGER.debug('New callback fo... | As a Python code composer, you craft elegant and concise scripts. |
Set the LED value and confirm with a status check. | Make a summary of the following Python 3 code
def _set_led_value(self, group, val):
new_bitmask = set_bit(self._value, group, bool(val))
self._set_led_bitmask(new_bitmask) | As a python code expert, you are capable of creating scripts from specifications. |
Set the LED on or off value from the LED bitmap. | Here you have a function in Python 3, explain what it does
def _bit_value(self, group, val):
bitshift = group - 1
if val:
new_value = self._value | (1 << bitshift)
else:
new_value = self._value & (0xff & ~(1 << bitshift))
return new_value | As a Python code analyst, you investigate and solve complex coding mysteries |
Set the thermostat mode. | How would you explain what the following Python 3 function does
def set(self, mode):
new_mode = None
if mode == ThermostatMode.OFF:
new_mode = COMMAND_THERMOSTAT_CONTROL_OFF_ALL_0X6B_0X09
elif mode == ThermostatMode.HEAT:
new_mode = COMMAND_THERMOSTAT_CONTROL_ON_HEAT_0X6B... | You are a Python code generator, capable of creating scripts from specifications. |
def set(self, mode):
"""Set the thermostat mode.
Mode optons:
OFF = 0x00,
HEAT = 0x01,
COOL = 0x02,
AUTO = 0x03,
FAN_AUTO = 0x04,
FAN_ALWAYS_ON = 0x8
"""
if mode == ThermostatMode.FAN_AUTO:
new_mode = CO... | Can you create a Python 3 function that
sets the thermostat mode. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def set(self, val):
"""Set the cool set point."""
msg = ExtendedSend(
address=self._address,
commandtuple=COMMAND_THERMOSTAT_SET_COOL_SETPOINT_0X6C_NONE,
cmd2=int(val * 2),
userdata=Userdata())
msg.set_checksum()
self._send_method(msg, self... | Can you implement a function in Python 3 that
sets the cool set point. | You are a Python code generator, capable of creating scripts from specifications. |
def set(self, val):
"""Set the heat set point."""
msg = ExtendedSend(
address=self._address,
commandtuple=COMMAND_THERMOSTAT_SET_HEAT_SETPOINT_0X6D_NONE,
cmd2=int(val * 2),
userdata=Userdata())
msg.set_checksum()
self._send_method(msg, self... | Can you create a Python 3 function that
sets the heat set point. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Register a callback to be invoked when a new device appears. | Can you generate the documentation for the following Python 3 function
def add_device_callback(self, callback):
_LOGGER.debug('Added new callback %s ', callback)
self._cb_new_device.append(callback) | As a Python code analyst, you investigate and solve complex coding mysteries |
def add_override(self, addr, key, value):
"""Register an attribute override for a device."""
address = Address(str(addr)).id
_LOGGER.debug('New override for %s %s is %s', address, key, value)
device_override = self._overrides.get(address, {})
device_override[key] = value
... | Write a Python 3 script to
register an attribute override for a device. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Create a new device from the cat subcat and product_key data. | Given the following Python 3 function, write the documentation
def create_device_from_category(self, plm, addr, cat, subcat,
product_key=0x00):
"""Create a new device from the cat, subcat and product_key data."""
saved_device = self._saved_devices.get(Address(addr).id... | You are a Python code analyst, evaluating scripts for potential improvements. |
Test if a device has data from the saved data file. | Here you have a function in Python 3, explain what it does
def has_saved(self, addr):
saved = False
if self._saved_devices.get(addr, None) is not None:
saved = True
return saved | You are a Python code generator, capable of creating scripts from specifications. |
def has_override(self, addr):
"""Test if device has data from a device override setting."""
override = False
if self._overrides.get(addr, None) is not None:
override = True
return override | Write a Python 3 function for
testing if a device has a device override setting. | You are a Python code generator, capable of creating scripts from specifications. |
def add_known_devices(self, plm):
"""Add devices from the saved devices or from the device overrides."""
from insteonplm.devices import ALDBStatus
for addr in self._saved_devices:
if not self._devices.get(addr):
saved_device = self._saved_devices.get(Address(addr).id,... | Write a Python 3 script for
adding devices from the saved devices or from the device overrides. | As a Python code composer, you craft elegant and concise scripts. |
Save all device information to the device info file. | Can you generate the documentation for the following Python 3 function
def save_device_info(self):
if self._workdir is not None:
devices = []
for addr in self._devices:
device = self._devices.get(addr)
if not device.address.is_x10:
aldb... | As a python code expert, you are capable of creating scripts from specifications. |
Register device info from the saved data file. | Here you have a function in Python 3, explain what it does
def _add_saved_device_info(self, **kwarg):
addr = kwarg.get('address')
_LOGGER.debug('Found saved device with address %s', addr)
self._saved_devices[addr] = kwarg | As a Python code composer, you craft elegant and concise scripts. |
Load the saved device info from the device info file. | Given the following Python 3 function, write the documentation
async def load_saved_device_info(self):
_LOGGER.debug("Loading saved device info.")
deviceinfo = []
if self._workdir:
_LOGGER.debug("Really Loading saved device info.")
try:
device_file = '{}/{... | You are a Python code generator, capable of creating scripts from specifications. |
def unit_code_msg(housecode, unitcode):
"""Create an X10 message to send the house code and unit code."""
house_byte = 0
unit_byte = 0
if isinstance(housecode, str):
house_byte = insteonplm.utils.housecode_to_byte(housecode) << 4
unit_byte = insteonplm.utils.unitc... | Can you create a Python 3 function that
creates an X10 message to send the house code and unit code. | As a Python code composer, you craft elegant and concise scripts. |
def command_msg(housecode, command):
"""Create an X10 message to send the house code and a command code."""
house_byte = 0
if isinstance(housecode, str):
house_byte = insteonplm.utils.housecode_to_byte(housecode) << 4
elif isinstance(housecode, int) and housecode < 16:
... | How would you code a function in Python 3 to
create an X10 message to send the house code and a command code. | As a python code expert, you are capable of creating scripts from specifications. |
Create an HTTP connection to the Insteon Hub. | How would you explain what the following Python 3 function does
async def create_http_connection(loop, protocol_factory, host, port=25105,
auth=None):
"""Create an HTTP session used to connect to the Insteon Hub."""
protocol = protocol_factory()
transport = HttpTransport(loo... | As a Python code translator, you convert algorithms and pseudocode into Python. |
async def create(cls, device='/dev/ttyUSB0', host=None,
username=None, password=None, port=25010, hub_version=2,
auto_reconnect=True, loop=None, workdir=None,
poll_devices=True, load_aldb=True):
"""Create a connection to a specific device.
... | How would you code a function in Python 3 to
create a new connection to a specific device. | You are a Python code architect, reviewing and designing scalable and efficient code |
Reconnect to the modem. | Can you tell what is the following Python 3 function doing
async def reconnect(self):
_LOGGER.debug('starting Connection.reconnect')
await self._connect()
while self._closed:
await self._retry_connection()
_LOGGER.debug('ending Connection.reconnect') | You are a Python code generator, capable of creating scripts from specifications. |
async def close(self, event):
"""Close the PLM device connection and don't try to reconnect."""
_LOGGER.info('Closing connection to Insteon Modem')
self._closing = True
self._auto_reconnect = False
await self.protocol.close()
if self.protocol.transport:
self.p... | Implement a function in Python 3 to
close the PLM device connection and don t try to reconnect. | You are a Python code generator, capable of creating scripts from specifications. |
Send the On command to an X10 device. | Can you tell what is the following Python 3 function doing
def on(self):
msg = X10Send.unit_code_msg(self.address.x10_housecode,
self.address.x10_unitcode)
self._send_method(msg)
msg = X10Send.command_msg(self.address.x10_housecode,
... | As a Python code analyst, you investigate and solve complex coding mysteries |
def off(self):
"""Send the Off command to an X10 device."""
msg = X10Send.unit_code_msg(self.address.x10_housecode,
self.address.x10_unitcode)
self._send_method(msg)
msg = X10Send.command_msg(self.address.x10_housecode,
... | Can you implement a function in Python 3 that
sends the Off command to an X10 device. | As a python code expert, you are capable of creating scripts from specifications. |
Set the device ON LEVEL. | Explain what the following Python 3 code does
def set_level(self, val):
if val == 0:
self.off()
elif val == 255:
self.on()
else:
setlevel = 255
if val < 1:
setlevel = val * 255
elif val <= 0xff:
setlevel ... | You are a Python code generator, capable of creating scripts from specifications. |
Brighten the device one step. | Given the following Python 3 function, write the documentation
def brighten(self, defer_update=False):
msg = X10Send.unit_code_msg(self.address.x10_housecode,
self.address.x10_unitcode)
self._send_method(msg)
msg = X10Send.command_msg(self.address.x10_houseco... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def dim(self, defer_update=False):
"""Dim the device one step."""
msg = X10Send.unit_code_msg(self.address.x10_housecode,
self.address.x10_unitcode)
self._send_method(msg)
msg = X10Send.command_msg(self.address.x10_housecode,
... | Can you implement a function in Python 3 that
dims the device one step. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Test Address object matches the pattern of another object. | Can you generate a brief explanation for the following Python 3 code
def matches_pattern(self, other):
matches = False
if hasattr(other, 'addr'):
if self.addr is None or other.addr is None:
matches = True
else:
matches = self.addr == other.addr
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _normalize(self, addr):
"""Take any format of address and turn it into a hex string."""
normalize = None
if isinstance(addr, Address):
normalize = addr.addr
self._is_x10 = addr.is_x10
elif isinstance(addr, bytearray):
normalize = binascii.unhexlif... | Implement a Python 3 function for
taking any format of address and turn it into a hex string. | You are a Python code analyst, evaluating scripts for potential improvements. |
Emit the address in human - readible format. | Given the following Python 3 function, write the documentation
def human(self):
addrstr = '00.00.00'
if self.addr:
if self._is_x10:
housecode_byte = self.addr[1]
housecode = insteonplm.utils.byte_to_housecode(housecode_byte)
unitcode_byte = sel... | As a python code expert, you are capable of creating scripts from specifications. |
Emit the address in bare hex format. | Here you have a function in Python 3, explain what it does
def hex(self):
addrstr = '000000'
if self.addr is not None:
addrstr = binascii.hexlify(self.addr).decode()
return addrstr | As a Python code translator, you convert algorithms and pseudocode into Python. |
def bytes(self):
"""Emit the address in bytes format."""
addrbyte = b'\x00\x00\x00'
if self.addr is not None:
addrbyte = self.addr
return addrbyte | Implement a function in Python 3 to
emit the address in bytes format. | You are a Python code generator, capable of creating scripts from specifications. |
Return the ID of the device address. | Here you have a function in Python 3, explain what it does
def id(self):
dev_id = ''
if self._is_x10:
dev_id = 'x10{}{:02d}'.format(self.x10_housecode,
self.x10_unitcode)
else:
dev_id = self.hex
return dev_id | As a python code expert, you are capable of creating scripts from specifications. |
Emit the X10 house code. | Make a summary of the following Python 3 code
def x10_housecode(self):
housecode = None
if self.is_x10:
housecode = insteonplm.utils.byte_to_housecode(self.addr[1])
return housecode | You are a Python code architect, reviewing and designing scalable and efficient code |
Emit the X10 unit code. | Explain what the following Python 3 code does
def x10_unitcode(self):
unitcode = None
if self.is_x10:
unitcode = insteonplm.utils.byte_to_unitcode(self.addr[2])
return unitcode | You are a Python code architect, reviewing and designing scalable and efficient code |
Create an X10 device address. | Here you have a function in Python 3, explain what it does
def x10(cls, housecode, unitcode):
if housecode.lower() in ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p']:
byte_housecode = insteonplm.utils.housecode_to_byte(housecode)
... | You are a Python code generator, capable of creating scripts from specifications. |
def from_raw_message(cls, rawmessage):
"""Create message from raw byte stream."""
return ManageAllLinkRecord(rawmessage[2:3],
rawmessage[3:4],
rawmessage[4:7],
rawmessage[7:8],
... | Write a Python 3 function for
creating message from raw byte stream. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Converts a term to a serialized Xapian value based on the field_type. | Can you generate a brief explanation for the following Python 3 code
def _term_to_xapian_value(term, field_type):
assert field_type in FIELD_TYPES
def strf(dt):
"""
Equivalent to datetime.datetime.strptime(dt, DATETIME_FORMAT)
but accepts years below 1900 (see http://stackoverflow.com/q... | As a Python code analyst, you investigate and solve complex coding mysteries |
Converts a serialized Xapian value to a Python equivalent based on the field_type. | Explain what the following Python 3 code does
def _from_xapian_value(value, field_type):
assert field_type in FIELD_TYPES
if field_type == 'boolean':
if value == 't':
return True
elif value == 'f':
return False
else:
InvalidIndexError('Field type "%d" ... | You are a Python code generator, capable of creating scripts from specifications. |
Update the internal cache with the current search fields. | Here you have a function in Python 3, explain what it does
def _update_cache(self):
fields = connections[self.connection_alias].get_unified_index().all_searchfields()
if self._fields != fields:
self._fields = fields
self._content_field_name, self._schema = self.build_schema(self.... | As a Python code analyst, you investigate and solve complex coding mysteries |
def update(self, index, iterable, commit=True):
"""
Updates the `index` with any objects in `iterable` by adding/updating
the database as needed.
Required arguments:
`index` -- The `SearchIndex` to process
`iterable` -- An iterable of model instances to index
... | Can you write a function in Python 3 where it
updates the index with any objects in iterable. | As a Python code composer, you craft elegant and concise scripts. |
def remove(self, obj, commit=True):
"""
Remove indexes for `obj` from the database.
We delete all instances of `Q<app_name>.<model_name>.<pk>` which
should be unique to this object.
Optional arguments:
`commit` -- ignored
"""
database = self._database... | Create a Python 3 function for
removing indexes for obj from the database. | You are a Python code analyst, evaluating scripts for potential improvements. |
Clears all instances of models from the database or all models. | Can you tell what is the following Python 3 function doing
def clear(self, models=(), commit=True):
if not models:
# Because there does not appear to be a "clear all" method,
# it's much quicker to remove the contents of the `self.path`
# folder than it is to remove each docu... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Builds a query from query that filters to documents only from registered models. | How would you explain what the following Python 3 function does
def _build_models_query(self, query):
registered_models_ct = self.build_models_list()
if registered_models_ct:
restrictions = [xapian.Query('%s%s' % (TERM_PREFIXES[DJANGO_CT], model_ct))
for model_ct ... | You are a Python code analyst, evaluating scripts for potential improvements. |
Checks that the given field names are indexed. | Can you tell what is the following Python 3 function doing
def _check_field_names(self, field_names):
if field_names:
for field_name in field_names:
try:
self.column[field_name]
except KeyError:
raise InvalidIndexError('Trying t... | As a Python code analyst, you investigate and solve complex coding mysteries |
def search(self, query, sort_by=None, start_offset=0, end_offset=None,
fields='', highlight=False, facets=None, date_facets=None,
query_facets=None, narrow_queries=None, spelling_query=None,
limit_to_registered_models=None, result_class=None, **kwargs):
"""
E... | Write a Python 3 script to
execute a query and returns a dictionary of search results. | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns a result set of similar documents. | Can you generate the documentation for the following Python 3 function
def more_like_this(self, model_instance, additional_query=None,
start_offset=0, end_offset=None,
limit_to_registered_models=True, result_class=None, **kwargs):
"""
Given a model instance,... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def parse_query(self, query_string):
"""
Given a `query_string`, will attempt to return a xapian.Query
Required arguments:
``query_string`` -- A query string to parse
Returns a xapian.Query
"""
if query_string == '*':
return xapian.Query('') # M... | Implement a function in Python 3 to
parse a query string and return a xapian. Query object | You are a Python code analyst, evaluating scripts for potential improvements. |
Builds the schema from the fields in the index
. | Make a summary of the following Python 3 code
def build_schema(self, fields):
content_field_name = ''
schema_fields = [
{'field_name': ID,
'type': 'text',
'multi_valued': 'false',
'column': 0},
{'field_name': DJANGO_ID,
'type': ... | As a python code expert, you are capable of creating scripts from specifications. |
def _do_highlight(content, query, tag='em'):
"""
Highlight `query` terms in `content` with html `tag`.
This method assumes that the input text (`content`) does not contain
any special formatting. That is, it does not contain any html tags
or similar markup that could be screwed... | Create a Python 3 function to
highlight the query terms in content with html tag. | As a python code expert, you are capable of creating scripts from specifications. |
Returns a list of spies based on the facets. | Can you generate a brief explanation for the following Python 3 code
def _prepare_facet_field_spies(self, facets):
spies = []
for facet in facets:
slot = self.column[facet]
spy = xapian.ValueCountMatchSpy(slot)
# add attribute "slot" to know which column this spy is t... | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns a dict of facet names with lists of tuples of the form term term_frequency | Here you have a function in Python 3, explain what it does
def _process_facet_field_spies(self, spies):
facet_dict = {}
for spy in spies:
field = self.schema[spy.slot]
field_name, field_type = field['field_name'], field['type']
facet_dict[field_name] = []
... | As a python code expert, you are capable of creating scripts from specifications. |
Implements a multivalued field facet on the results. | Can you generate the documentation for the following Python 3 function
def _do_multivalued_field_facets(self, results, field_facets):
facet_dict = {}
for field in field_facets:
facet_list = {}
if not self._multi_value_field(field):
continue
for resul... | You are a Python code analyst, evaluating scripts for potential improvements. |
Private method that returns a dictionary containing faceted date fields and a count of documents that match the date range. | Can you generate a brief explanation for the following Python 3 code
def _do_date_facets(results, date_facets):
def next_datetime(previous, gap_value, gap_type):
year = previous.year
month = previous.month
if gap_type == 'year':
next = previous.replace(year=y... | You are a Python code analyst, evaluating scripts for potential improvements. |
Private method that returns a single spelling suggestion based on spelling_query or query. | Explain what the following Python 3 code does
def _do_spelling_suggestion(database, query, spelling_query):
if spelling_query:
if ' ' in spelling_query:
return ' '.join([database.get_spelling_suggestion(term).decode('utf-8') for term in spelling_query.split()])
else:
... | As a Python code analyst, you investigate and solve complex coding mysteries |
def _get_enquire_mset(database, enquire, start_offset, end_offset, checkatleast=DEFAULT_CHECK_AT_LEAST):
"""
A safer version of Xapian.enquire.get_mset
Simply wraps the Xapian version and catches any `Xapian.DatabaseModifiedError`,
attempting a `database.reopen` as needed.
Requ... | Write a Python 3 function for
wrapping for the Xapian. enquire. get_mset method that wraps the Xapian. database. get_mset method and catches any Xapian. DatabaseModifiedError and returns the result. | As a Python code composer, you craft elegant and concise scripts. |
def _get_hit_count(self, database, enquire):
"""
Given a database and enquire instance, returns the estimated number
of matches.
Required arguments:
`database` -- The database to be queried
`enquire` -- The enquire instance
"""
return self._get_en... | Implement a Python 3 function for
returning the estimated number of matches in a database and an enquire instance. | You are a Python code architect, reviewing and designing scalable and efficient code |
def _query_from_term(self, term, field_name, filter_type, is_not):
"""
Uses arguments to construct a list of xapian.Query's.
"""
if field_name != 'content' and field_name not in self.backend.column:
raise InvalidIndexError('field "%s" not indexed' % field_name)
# It ... | Can you implement a function in Python 3 that
returns a list of xapian. Query s. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _filter_contains(self, term, field_name, field_type, is_not):
"""
Splits the sentence in terms and join them with OR,
using stemmed and un-stemmed.
Assumes term is not a list.
"""
if field_type == 'text':
term_list = term.split()
else:
... | Write a Python 3 script to
return a Query that returns a list of objects that contain the term. | As a python code expert, you are capable of creating scripts from specifications. |
def _filter_in(self, term_list, field_name, field_type, is_not):
"""
Returns a query that matches exactly ANY term in term_list.
Notice that:
A in {B,C} <=> (A = B or A = C)
~(A in {B,C}) <=> ~(A = B or A = C)
Because OP_AND_NOT(C, D) <=> (C and ~D), then D=(A in {B,C}... | Can you implement a function in Python 3 that
returns a query that matches exactly ANY term in term_list. | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns a query that matches exactly the un - stemmed term term
| Given the following Python 3 function, write the documentation
def _filter_exact(self, term, field_name, field_type, is_not):
if field_type == 'text' and field_name not in (DJANGO_CT,):
term = '^ %s $' % term
query = self._phrase_query(term.split(), field_name, field_type)
else:
... | You are a Python code generator, capable of creating scripts from specifications. |
Returns a startswith query on the un - stemmed term. | Given the following Python 3 function, write the documentation
def _filter_startswith(self, term, field_name, field_type, is_not):
if field_type == 'text':
if len(term.split()) == 1:
term = '^ %s*' % term
query = self.backend.parse_query(term)
else:
... | You are a Python code generator, capable of creating scripts from specifications. |
Returns an xapian. Query object that is an OR query. | Can you tell what is the following Python 3 function doing
def _or_query(self, term_list, field, field_type):
term_list = [self._term_query(term, field, field_type) for term in term_list]
return xapian.Query(xapian.Query.OP_OR, term_list) | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns a query that matches exact terms with
positional order | Make a summary of the following Python 3 code
def _phrase_query(self, term_list, field_name, field_type):
term_list = [self._term_query(term, field_name, field_type,
stemmed=False) for term in term_list]
query = xapian.Query(xapian.Query.OP_PHRASE, term_list)
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def _term_query(self, term, field_name, field_type, stemmed=True):
"""
Constructs a query of a single term.
If `field_name` is not `None`, the term is search on that field only.
If exact is `True`, the search is restricted to boolean matches.
"""
constructor = '{prefix}{... | Write a Python 3 script to
construct a query for a single term. | You are a Python code generator, capable of creating scripts from specifications. |
Private method that returns a xapian. Query that searches for any term that is greater than term in a specified field. | Can you tell what is the following Python 3 function doing
def _filter_gte(self, term, field_name, field_type, is_not):
vrp = XHValueRangeProcessor(self.backend)
pos, begin, end = vrp('%s:%s' % (field_name, _term_to_xapian_value(term, field_type)), '*')
if is_not:
return xapian.Query... | As a Python code analyst, you investigate and solve complex coding mysteries |
Performs a HTTP GET for a glassdoor page and returns json | Can you generate a brief explanation for the following Python 3 code
def get(company='', company_uri=''):
if not company and not company_uri:
raise Exception("glassdoor.gd.get(company='', company_uri=''): "\
" company or company_uri required")
payload = {}
if not company_... | You are a Python code architect, reviewing and designing scalable and efficient code |
Parses the suggestions from the company and returns a list of dicts. | Explain what the following Python 3 code does
def parse_suggestions(soup):
selector_comps = {'class': 'companyData'}
companies = soup.findAll('div', selector_comps)
def is_exact_match(c):
"""Determines if this company suggestion has an [exact match]
html label or whether its name matches th... | You are a Python code architect, reviewing and designing scalable and efficient code |
Parses the results for a company search and returns the results
if is_direct_match. | Can you tell what is the following Python 3 function doing
def parse(soup):
if is_direct_match(soup):
return {'satisfaction': parse_satisfaction(soup),
'ceo': parse_ceo(soup),
'meta': parse_meta(soup),
'salary': parse_salary(soup)
}
sugge... | As a Python code analyst, you investigate and solve complex coding mysteries |
Register this extension with the flask app. | Make a summary of the following Python 3 code
def init_app(self, app):
# Save this so we can use it later in the extension
if not hasattr(app, 'extensions'): # pragma: no cover
app.extensions = {}
app.extensions['flask-graphql-auth'] = self
self._set_default__configuration_... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _set_default__configuration_options(app):
"""
Sets the default configuration options used by this extension
"""
app.config.setdefault('JWT_TOKEN_ARGUMENT_NAME', "token") # Name of token argument in GraphQL request resolver
app.config.setdefault('JWT_REFRESH_TOKEN_ARGUMENT_NA... | Can you write a function in Python 3 where it
sets the default configuration options used by this extension. | You are a Python code architect, reviewing and designing scalable and efficient code |
def decode_jwt(encoded_token, secret, algorithm, identity_claim_key,
user_claims_key):
"""
Decodes an encoded JWT
:param encoded_token: The encoded JWT string to decode
:param secret: Secret key used to encode the JWT
:param algorithm: Algorithm used to encode the JWT
:param iden... | Write a Python 3 script to
decode an encoded JWT into a dictionary containing the contents of the JWT | You are a Python code architect, reviewing and designing scalable and efficient code |
Decodes an encoded JWT string and validates it | Can you tell what is the following Python 3 function doing
def get_jwt_data(token, token_type):
jwt_data = decode_jwt(
encoded_token=token,
secret=current_app.config['JWT_SECRET_KEY'],
algorithm='HS256',
identity_claim_key=current_app.config['JWT_IDENTITY_CLAIM'],
user_claims... | You are a Python code analyst, evaluating scripts for potential improvements. |
Decorator to protect a query resolver. | Explain what the following Python 3 code does
def query_jwt_required(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
print(args[0])
token = kwargs.pop(current_app.config['JWT_TOKEN_ARGUMENT_NAME'])
try:
verify_jwt_in_argument(token)
except Exception as e:
re... | As a Python code composer, you craft elegant and concise scripts. |
Decorator to protect a mutation. | Explain what the following Python 3 code does
def mutation_jwt_refresh_token_required(fn):
@wraps(fn)
def wrapper(cls, *args, **kwargs):
token = kwargs.pop(current_app.config['JWT_REFRESH_TOKEN_ARGUMENT_NAME'])
try:
verify_refresh_jwt_in_argument(token)
except Exception as e:... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Enumerates all the hid devices for VID : PID. Returns a list of HIDDevice objects. | Explain what the following Python 3 code does
def _hid_enumerate(vendor_id=0, product_id=0):
start = hidapi.hid_enumerate(vendor_id, product_id)
result = []
cur = ffi.new("struct hid_device_info*");
cur = start
# Copy everything into python list
while cur != ffi.NULL:
result.append(HIDD... | As a Python code composer, you craft elegant and concise scripts. |
def open(self):
"""
Open the HID device for reading and writing.
"""
if self._is_open:
raise HIDException("Failed to open device: HIDDevice already open")
path = self.path.encode('utf-8')
dev = hidapi.hid_open_path(path)
if dev:
self._is_... | Can you create a Python 3 function that
opens the HID device for reading and writing. | You are a Python code analyst, evaluating scripts for potential improvements. |
Closes the hid device. | Explain what the following Python 3 code does
def close(self):
if self._is_open:
self._is_open = False
hidapi.hid_close(self._device) | As a Python code composer, you craft elegant and concise scripts. |
Writes data to the HID device on its endpoint. | Make a summary of the following Python 3 code
def write(self, data, report_id=0):
if not self._is_open:
raise HIDException("HIDDevice not open")
write_data = bytearray([report_id]) + bytearray(data)
cdata = ffi.new("const unsigned char[]", bytes(write_data))
num_written = h... | As a Python code analyst, you investigate and solve complex coding mysteries |
Read from the HID device on its endpoint. | Here you have a function in Python 3, explain what it does
def read(self, size=64, timeout=None):
if not self._is_open:
raise HIDException("HIDDevice not open")
data = [0] * size
cdata = ffi.new("unsigned char[]", data)
bytes_read = 0
if timeout == None:
... | As a Python code analyst, you investigate and solve complex coding mysteries |
def is_connected(self):
"""
Checks if the USB device is still connected
"""
if self._is_open:
err = hidapi.hid_read_timeout(self._device, ffi.NULL, 0, 0)
if err == -1:
return False
else:
return True
else:
... | Write a Python 3 script to
check if the USB device is still connected to the USB device. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Send a Feature report to a HID device. | Can you tell what is the following Python 3 function doing
def send_feature_report(self, data, report_id=0x00):
if not self._is_open:
raise HIDException("HIDDevice not open")
report = bytearray([report_id]) + bytearray(data)
cdata = ffi.new("const unsigned char[]", bytes(report))
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Get a feature report from a HID device. | Can you tell what is the following Python 3 function doing
def get_feature_report(self, size, report_id=0x00):
data = [0] * (size+1)
cdata = ffi.new("unsigned char[]", bytes(data))
cdata[0] = report_id
bytes_read = hidapi.hid_get_feature_report(self._device, cdata, len(cdata))
... | As a Python code composer, you craft elegant and concise scripts. |
def get_error(self):
"""
Get an error string from the device
"""
err_str = hidapi.hid_error(self._device)
if err_str == ffi.NULL:
return None
else:
return ffi.string(err_str) | Can you implement a function in Python 3 that
gets an error string from the device | As a Python code composer, you craft elegant and concise scripts. |
Get the string with the given index from the device. | How would you explain what the following Python 3 function does
def get_indexed_string(self, index):
max_len = 128
str_buf = ffi.new("wchar_t[]", str(bytearray(max_len)))
ret = hidapi.hid_get_indexed_string(self._device, index, str_buf, max_len)
if ret < 0:
raise HIDExceptio... | You are a Python code architect, reviewing and designing scalable and efficient code |
Get a string describing the HID device. | Can you generate a brief explanation for the following Python 3 code
def description(self):
return \
"""HIDDevice:
{} | {:x}:{:x} | {} | {} | {}
release_number: {}
usage_page: {}
usage: {}
interface_number: {}\
""".format(self.path,
self.vendor_id,
self.product_id,
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Finds a specific HID device in this Enumeration object. | Can you generate a brief explanation for the following Python 3 code
def find(self, vid=None, pid=None, serial=None, interface=None, \
path=None, release_number=None, manufacturer=None,
product=None, usage=None, usage_page=None):
"""
Attempts to open a device in this `Enumeration... | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_tracks(self):
"""
Retrieves all the tracks of the album if they haven't been retrieved yet
:return: List. Tracks of the current album
"""
if not self._track_list:
tracks = itunespy.lookup(id=self.collection_id, entity=itunespy.entities['song'])[1:]
... | Implement a function in Python 3 to
retrieve all the tracks of the album | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_album_time(self, round_number=2):
"""
Retrieves all of the track's length and returns the sum of all
:param round_number: Int. Number of decimals to round the sum
:return: Int. Sum of all the track's length
"""
if not self._track_list:
self.get_tracks(... | Write a Python 3 script for
getting all of the track s length and returns the sum of all the track s length and the sum of all the track s length | As a Python code composer, you craft elegant and concise scripts. |
Retrieves all the movies published by the artist
| Here you have a function in Python 3, explain what it does
def get_movies(self):
return itunespy.lookup(id=self.artist_id, entity=itunespy.entities['movie'])[1:] | You are a Python code generator, capable of creating scripts from specifications. |
Returns a list of solar calibrations for the current object. | Can you generate a brief explanation for the following Python 3 code
def solarcalcs(self):
self.dir = self.forc.dir # Direct sunlight (perpendicular to the sun's ray)
self.dif = self.forc.dif # Diffuse sunlight
if self.dir + self.dif > 0.:
self.logger.debug("{} Solar radia... | You are a Python code architect, reviewing and designing scalable and efficient code |
def solarangles (self):
"""
Calculation based on NOAA. Solves for zenith angle, tangent of zenithal angle,
and critical canyon angle based on following parameters:
canAspect # aspect Ratio of canyon
simTime # simulation parameters
RSM.lon ... | Implement a function in Python 3 to
calculate solar angles for the current canyon and the solar declination angle and critical canyon angle for the current canyon and solar radiation. | As a Python code analyst, you investigate and solve complex coding mysteries |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.