output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def populate_extra_files():
"""
Creates a list of non-python data files to include in package distribution
"""
out = ['cauldron/settings.json']
for entry in glob.iglob('cauldron/resources/examples/**/*', recursive=True):
out.append(entry)
for entry in glob.iglob('cauldron/resources/te... | Write a Python 3 script to
populate the list of extra files that are not python data files. | As a Python code analyst, you investigate and solve complex coding mysteries |
Creates a STEP_RENAME entry for the given project step. | Here you have a function in Python 3, explain what it does
def create_rename_entry(
step: 'projects.ProjectStep',
insertion_index: int = None,
stash_path: str = None
) -> typing.Union[None, STEP_RENAME]:
"""
Creates a STEP_RENAME for the given ProjectStep instance
:param step:
... | As a python code expert, you are capable of creating scripts from specifications. |
Synchronizes the names of the steps in the project. | Explain what the following Python 3 code does
def synchronize_step_names(
project: 'projects.Project',
insert_index: int = None
) -> Response:
"""
:param project:
:param insert_index:
"""
response = Response()
response.returned = dict()
if not project.naming_scheme:
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Assembles a fully - resolved remote connection URL from the given endpoint and remote_connection structure. | Given the following Python 3 function, write the documentation
def assemble_url(
endpoint: str,
remote_connection: 'environ.RemoteConnection' = None
) -> str:
"""
Assembles a fully-resolved remote connection URL from the given endpoint
and remote_connection structure. If the remote_connectio... | As a python code expert, you are capable of creating scripts from specifications. |
def parse_http_response(http_response: HttpResponse) -> 'environ.Response':
"""
Returns a Cauldron response object parsed from the serialized JSON data
specified in the http_response argument. If the response doesn't contain
valid Cauldron response data, an error Cauldron response object is
returned... | Can you write a function in Python 3 where it
parses the given HTTP response into a Cauldron response object. | You are a Python code generator, capable of creating scripts from specifications. |
def send_request(
endpoint: str,
data: dict = None,
remote_connection: 'environ.RemoteConnection' = None,
method: str = None,
timeout: int = 10,
max_retries: int = 10,
**kwargs
) -> 'environ.Response':
"""
Sends a request to the remote kernel specified by ... | Write a Python 3 function for
sending a request to the remote kernel and processes the response. | You are a Python code analyst, evaluating scripts for potential improvements. |
def view(route: str):
"""
Retrieves the contents of the file specified by the view route if it
exists.
"""
project = cauldron.project.get_internal_project()
results_path = project.results_path if project else None
if not project or not results_path:
return '', 204
path = os.path... | How would you code a function in Python 3 to
retrieve the contents of the file specified by the route if it exists. | As a python code expert, you are capable of creating scripts from specifications. |
def save(
project: 'projects.Project',
write_list: typing.List[tuple] = None
) -> typing.List[tuple]:
"""
Computes the file write list for the current state of the project if no
write_list was specified in the arguments, and then writes each entry in
that list to disk.
:param projec... | Implement a Python 3 function for
saving the current state of the project to disk. | You are a Python code generator, capable of creating scripts from specifications. |
def list_asset_writes(
project: 'projects.Project'
) -> typing.List[file_io.FILE_COPY_ENTRY]:
"""
Returns a list containing the file/directory writes that should be executed
to deploy the project assets to the results folder. If the project has no
assets an empty list is returned.
:param pr... | Implement a Python 3 function for
returning a list of file writes that should be executed for the project assets to the results folder. | As a Python code composer, you craft elegant and concise scripts. |
def add_library_path(path: str) -> bool:
"""
Adds the path to the Python system path if not already added and the path
exists.
:param path:
The path to add to the system paths
:return:
Whether or not the path was added. Only returns False if the path was
not added because it... | Implement a function in Python 3 to
add the path to the Python system path if not already added. | As a Python code composer, you craft elegant and concise scripts. |
def remove_library_path(path: str) -> bool:
"""
Removes the path from the Python system path if it is found in the system
paths.
:param path:
The path to remove from the system paths
:return:
Whether or not the path was removed.
"""
if path in sys.path:
sys.path.rem... | Write a Python 3 script for
removing the path from the system path if it is found in the system paths. | As a Python code composer, you craft elegant and concise scripts. |
Close the current project and remove all libraries and source directories. | Given the following Python 3 function, write the documentation
def close():
os.chdir(os.path.expanduser('~'))
project = cauldron.project.internal_project
if not project:
return False
[remove_library_path(path) for path in project.library_directories]
remove_library_path(project.source_direc... | You are a Python code generator, capable of creating scripts from specifications. |
Reloads the libraries stored in the project s local and shared library directories. | Make a summary of the following Python 3 code
def reload_libraries(library_directories: list = None):
directories = library_directories or []
project = cauldron.project.get_internal_project()
if project:
directories += project.library_directories
if not directories:
return
def relo... | You are a Python code analyst, evaluating scripts for potential improvements. |
def complete(
response: Response,
project: typing.Union[Project, None],
starting: ProjectStep = None,
force: bool = False,
limit: int = -1
) -> list:
"""
Runs the entire project, writes the results files, and returns the URL to
the report file
:param response:
... | Implement a Python 3 function for
running the entire project writes the results files and returns the URL to the report file | As a Python code analyst, you investigate and solve complex coding mysteries |
def elapsed_time(self) -> float:
"""
The number of seconds that has elapsed since the step started running
if the step is still running. Or, if the step has already finished
running, the amount of time that elapsed during the last execution of
the step.
"""
curren... | How would you implement a function in Python 3 that
returns the number of seconds that has elapsed since the step started running or the amount of time that has elapsed during the last execution of the step. | As a Python code composer, you craft elegant and concise scripts. |
Returns a human - readable version of the elapsed time for the last execution of the project step. | Can you generate a brief explanation for the following Python 3 code
def get_elapsed_timestamp(self) -> str:
t = self.elapsed_time
minutes = int(t / 60)
seconds = int(t - (60 * minutes))
millis = int(100 * (t - int(t)))
return '{:>02d}:{:>02d}.{:<02d}'.format(minutes, seconds, mi... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_dom(self) -> str:
""" Retrieves the current value of the DOM for the step """
if self.is_running:
return self.dumps()
if self.dom is not None:
return self.dom
dom = self.dumps()
self.dom = dom
return dom | Write a Python 3 function for
returning the current value of the DOM for the step. | As a Python code composer, you craft elegant and concise scripts. |
def dumps(self) -> str:
"""Writes the step information to an HTML-formatted string"""
code_file_path = os.path.join(
self.project.source_directory,
self.filename
)
code = dict(
filename=self.filename,
path=code_file_path,
code=r... | How would you code a function in Python 3 to
write the step information to an HTML - formatted string. | As a Python code translator, you convert algorithms and pseudocode into Python. |
A decorator that retries the given function if any of the given exceptions are caught by the given job. | Can you generate a brief explanation for the following Python 3 code
def retry(*excepts):
'''A decorator to specify a bunch of exceptions that should be caught
and the job retried. It turns out this comes up with relative frequency'''
@decorator.decorator
def new_func(func, job):
'''No docstring... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Return an array of job objects that are being tracked | Can you generate a brief explanation for the following Python 3 code
def tracked(self):
'''Return an array of job objects that are being tracked'''
results = json.loads(self.client('track'))
results['jobs'] = [Job(self, **job) for job in results['jobs']]
return results | As a Python code composer, you craft elegant and concise scripts. |
def tagged(self, tag, offset=0, count=25):
'''Return the paginated jids of jobs tagged with a tag'''
return json.loads(self.client('tag', 'get', tag, offset, count)) | Can you implement a function in Python 3 that
returns the paginated jids of jobs tagged with a tag | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns a JSON blob of the counts of
the various types of failures known. | Can you tell what is the following Python 3 function doing
def failed(self, group=None, start=0, limit=25):
'''If no group is provided, this returns a JSON blob of the counts of
the various types of failures known. If a type is provided, returns
paginated job objects affected by that kind of fai... | You are a Python code architect, reviewing and designing scalable and efficient code |
Return jobs objects for all the jids | Can you tell what is the following Python 3 function doing
def get(self, *jids):
'''Return jobs objects for all the jids'''
if jids:
return [
Job(self.client, **j) for j in
json.loads(self.client('multiget', *jids))]
return [] | You are a Python code analyst, evaluating scripts for potential improvements. |
Set the title of the process | Can you generate the documentation for the following Python 3 function
def title(cls, message=None):
'''Set the title of the process'''
if message == None:
return getproctitle()
else:
setproctitle('qless-py-worker %s' % message)
logger.info(message) | As a Python code translator, you convert algorithms and pseudocode into Python. |
Divide up the provided jobs into count evenly - sized groups. | Can you tell what is the following Python 3 function doing
def divide(cls, jobs, count):
'''Divide up the provided jobs into count evenly-sized groups'''
jobs = list(zip(*zip_longest(*[iter(jobs)] * count)))
# If we had no jobs to resume, then we get an empty list
jobs = jobs or [()] * c... | You are a Python code generator, capable of creating scripts from specifications. |
def clean(cls, path):
'''Clean up all the files in a provided path'''
for pth in os.listdir(path):
pth = os.path.abspath(os.path.join(path, pth))
if os.path.isdir(pth):
logger.debug('Removing directory %s' % pth)
shutil.rmtree(pth)
else... | Can you create a Python 3 function that
cleans up all the files in a provided path | As a python code expert, you are capable of creating scripts from specifications. |
def sandbox(cls, path):
'''Ensures path exists before yielding, cleans up after'''
# Ensure the path exists and is clean
try:
os.makedirs(path)
logger.debug('Making %s' % path)
except OSError:
if not os.path.isdir(path):
raise
f... | Can you write a function in Python 3 where it
ensures path exists before yielding cleans up after | You are a Python code analyst, evaluating scripts for potential improvements. |
Find all the jobs that we re currently working on | Make a summary of the following Python 3 code
def resumable(self):
'''Find all the jobs that we'd previously been working on'''
# First, find the jids of all the jobs registered to this client.
# Then, get the corresponding job objects
jids = self.client.workers[self.client.worker_name][... | You are a Python code generator, capable of creating scripts from specifications. |
Listen for pubsub messages relevant to this worker in a thread | Can you generate the documentation for the following Python 3 function
def listener(self):
'''Listen for pubsub messages relevant to this worker in a thread'''
channels = ['ql:w:' + self.client.worker_name]
listener = Listener(self.client.redis, channels)
thread = threading.Thread(target... | You are a Python code analyst, evaluating scripts for potential improvements. |
Listen for events that affect our ownership of a job | How would you explain what the following Python 3 function does
def listen(self, listener):
'''Listen for events that affect our ownership of a job'''
for message in listener.listen():
try:
data = json.loads(message['data'])
if data['event'] in ('canceled', 'l... | As a Python code composer, you craft elegant and concise scripts. |
def signals(self, signals=('QUIT', 'USR1', 'USR2')):
'''Register our signal handler'''
for sig in signals:
signal.signal(getattr(signal, 'SIG' + sig), self.handler) | Write a Python 3 script for
registering our signal handler | You are a Python code architect, reviewing and designing scalable and efficient code |
Signal handler for this process | Explain what the following Python 3 code does
def handler(self, signum, frame): # pragma: no cover
'''Signal handler for this process'''
if signum == signal.SIGQUIT:
# QUIT - Finish processing, but don't do any more work after that
self.stop()
elif signum == signal.SIGUS... | You are a Python code analyst, evaluating scripts for potential improvements. |
def kill(self, jid):
'''Stop the greenlet processing the provided jid'''
greenlet = self.greenlets.get(jid)
if greenlet is not None:
logger.warn('Lost ownership of %s' % jid)
greenlet.kill() | How would you code a function in Python 3 to
stop the greenlet processing the provided jid | As a Python code analyst, you investigate and solve complex coding mysteries |
Initialize a postgresql connection by each connection string | Make a summary of the following Python 3 code
def init_db_conn(connection_name, connection_string, scopefunc=None):
engine = create_engine(connection_string)
session = scoped_session(sessionmaker(), scopefunc=scopefunc)
session.configure(bind=engine)
pool.connections[connection_name] = Connection(engine... | As a Python code analyst, you investigate and solve complex coding mysteries |
Initializes the database connection pool and session pool for the given application. | Make a summary of the following Python 3 code
def initialize(g, app):
if 'DATABASES' in app.config and 'POSTGRESQL' in app.config['DATABASES']:
# Database connection established for console commands
for k, v in app.config['DATABASES']['POSTGRESQL'].items():
init_db_conn(k, v)
if... | As a Python code analyst, you investigate and solve complex coding mysteries |
def load_extensions_from_config(**config):
"""
Loads extensions
"""
extensions = []
if 'EXTENSIONS' in config:
for ext in config['EXTENSIONS']:
try:
extensions.append(locate(ext))
except Exception as e:
print(e)
return extensions | Write a Python 3 function that can
load the list of extensions from the config file. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Sets the request object to the globals dict | Make a summary of the following Python 3 code
def set_request(self, r):
for k in self.environments.keys():
self.environments[k].globals['REQUEST'] = r | You are a Python code architect, reviewing and designing scalable and efficient code |
Initialize a redis connection by each connection string | Here you have a function in Python 3, explain what it does
def init_db_conn(connection_name, HOSTS=None):
el = elasticsearch.Elasticsearch(hosts=HOSTS)
el_pool.connections[connection_name] = ElasticSearchClient(el) | As a Python code analyst, you investigate and solve complex coding mysteries |
def parse_tags(targs):
"""
Tags can be in the forma key:value or simply value
"""
tags = {}
for t in targs:
split_tag = t.split(':')
if len(split_tag) > 1:
tags['tag:' + split_tag[0]] = split_tag[1]
else:
tags['tag:' + split_tag[0]] = ''
return tag... | Write a Python 3 script to
parse tags from a list of strings | You are a Python code analyst, evaluating scripts for potential improvements. |
def json_response(self, status=200, data={}, headers={}):
'''
To set flask to inject specific headers on response request,
such as CORS_ORIGIN headers
'''
mimetype = 'application/json'
header_dict = {}
for k, v in headers.items():
header_dict[k] =... | How would you implement a function in Python 3 that
returns a JSON response. | You are a Python code architect, reviewing and designing scalable and efficient code |
Constructs a response with the template_name and headers | Make a summary of the following Python 3 code
def template_response(self, template_name, headers={}, **values):
response = make_response(
self.render_template(template_name, **values))
for field, value in headers.items():
response.headers.set(field, value)
return respon... | As a Python code composer, you craft elegant and concise scripts. |
Returns all key pairs for all regions in the current region | Can you generate the documentation for the following Python 3 function
def describe_key_pairs():
region_keys = {}
for r in boto3.client('ec2', 'us-west-2').describe_regions()['Regions']:
region = r['RegionName']
client = boto3.client('ec2', region_name=region)
try:
pairs = cl... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Initializes an application with the given module and BASE_DIR. | How would you explain what the following Python 3 function does
def init_app(module, BASE_DIR, **kwargs):
global app
def init_config():
"""
Load settings module and attach values to the application
config dictionary
"""
if 'FLASK_PHILO_SETTINGS_MODULE' not in os.environ:... | As a Python code analyst, you investigate and solve complex coding mysteries |
execute a console command | How would you explain what the following Python 3 function does
def execute_command(cmd, **kwargs):
cmd_dict = {
c: 'flask_philo.commands_flask_philo.' + c for c
in dir(commands_flask_philo) if not c.startswith('_') and c != 'os' # noqa
}
# loading specific app commands
try:
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Create tables if they don t exist | Can you generate a brief explanation for the following Python 3 code
def syncdb():
from flask_philo.db.postgresql.schema import Base
from flask_philo.db.postgresql.orm import BaseModel # noqa
from flask_philo.db.postgresql.connection import get_pool
for conn_name, conn in get_pool().connections.items(... | As a Python code composer, you craft elegant and concise scripts. |
Creates a PasswordHash from the given password and rounds. | Can you tell what is the following Python 3 function doing
def new(cls, password, rounds):
if isinstance(password, str):
password = password.encode('utf8')
value = bcrypt.hashpw(password, bcrypt.gensalt(rounds))
return cls(value) | You are a Python code architect, reviewing and designing scalable and efficient code |
Converts the given string to a PasswordHash instance. | Can you tell what is the following Python 3 function doing
def _convert(self, value):
if isinstance(value, PasswordHash):
return value
elif isinstance(value, str):
value = value.encode('utf-8')
return PasswordHash.new(value, self.rounds)
elif value is not None... | As a Python code analyst, you investigate and solve complex coding mysteries |
Initialize a redis connection by each connection string
| Here you have a function in Python 3, explain what it does
def init_db_conn(
connection_name, HOST=None, PORT=None, DB=None, PASSWORD=None):
"""
Initialize a redis connection by each connection string
defined in the configuration file
"""
rpool = redis.ConnectionPool(
host=HOST, port... | You are a Python code analyst, evaluating scripts for potential improvements. |
def initialize(g, app):
"""
If redis connection parameters are defined in configuration params a
session will be created
"""
if 'DATABASES' in app.config and 'REDIS' in app.config['DATABASES']:
# Initialize connections for console commands
for k, v in app.config['DATABASES']['REDIS... | Can you implement a function in Python 3 that
initializes the database connection parameters and redis connection pool for the global application. | You are a Python code architect, reviewing and designing scalable and efficient code |
Loads the serializer from a dictionary. | Can you tell what is the following Python 3 function doing
def _initialize_from_dict(self, data):
self._json = data
self._validate()
for name, value in self._json.items():
if name in self._properties:
if '$ref' in self._properties[name]:
if 'decim... | As a Python code analyst, you investigate and solve complex coding mysteries |
def _initialize_from_model(self, model):
"""
Loads a model from
"""
for name, value in model.__dict__.items():
if name in self._properties:
setattr(self, name, value) | Create a Python 3 function for
initializing the object from a model. | You are a Python code generator, capable of creating scripts from specifications. |
def update(self):
"""
Finds record and update it based in serializer values
"""
obj = self.__model__.objects.get_for_update(id=self.id)
for name, value in self.__dict__.items():
if name in self._properties:
setattr(obj, name, value)
obj.update(... | Implement a Python 3 function for
updating the record based on serializer values | As a Python code analyst, you investigate and solve complex coding mysteries |
def to_json(self):
"""
Returns a json representation
"""
data = {}
for k, v in self.__dict__.items():
if not k.startswith('_'):
# values not serializable, should be converted to strings
if isinstance(v, datetime):
v ... | Write a Python 3 script to
return a json representation of the object. | You are a Python code architect, reviewing and designing scalable and efficient code |
General information about the operating system. | How would you explain what the following Python 3 function does
def OPERATING_SYSTEM(stats, info):
info.append(('architecture', platform.machine().lower()))
info.append(('distribution',
"%s;%s" % (platform.linux_distribution()[0:2])))
info.append(('system',
"%s;%s" % (platf... | As a Python code composer, you craft elegant and concise scripts. |
Total time elapsed from the construction of the Stats object to
| Can you generate the documentation for the following Python 3 function
def SESSION_TIME(stats, info):
duration = time.time() - stats.started_time
secs = int(duration)
msecs = int((duration - secs) * 1000)
info.append(('session_time', '%d.%d' % (secs, msecs))) | As a Python code translator, you convert algorithms and pseudocode into Python. |
def read_config(self):
"""Reads the configuration.
This method can be overloaded to integrate with your application's own
configuration mechanism. By default, a single 'status' file is read
from the reports' directory.
This should set `self.status` to one of the state constants... | Can you implement a function in Python 3 that
reads the configuration file and sets the status attribute of the usage statistics object. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Writes the configuration.
This method can be overloaded to integrate with your application's own
configuration mechanism. By default, a single 'status' file is written
in the reports' directory, containing either ``ENABLED`` or
``DISABLED``; if the file doesn't exist, `UNSET` is assumed... | Here you have a function in Python 3, explain what it does
def write_config(self, enabled):
status_file = os.path.join(self.location, 'status')
with open(status_file, 'w') as fp:
if enabled is Stats.ENABLED:
fp.write('ENABLED')
elif enabled is Stats.DISABLED:
... | As a Python code composer, you craft elegant and concise scripts. |
Set the status of the current report to Stats. ENABLED. | Here you have a function in Python 3, explain what it does
def enable_reporting(self):
if self.status == Stats.ENABLED:
return
if not self.enableable:
logger.critical("Can't enable reporting")
return
self.status = Stats.ENABLED
self.write_config(self.s... | You are a Python code architect, reviewing and designing scalable and efficient code |
def disable_reporting(self):
"""Call this method to explicitly disable reporting.
The current report will be discarded, along with the previously
recorded ones that haven't been uploaded. The configuration is updated
so that future runs do not record or upload reports.
"""
... | Create a Python 3 function to
call this method to explicitly disable reporting. The current report will be discarded, along with the previously recorded ones that haven't been uploaded. The configuration is updated so that future runs do not record or upload reports. | As a python code expert, you are capable of creating scripts from specifications. |
def note(self, info):
"""Record some info to the report.
:param info: Dictionary of info to record. Note that previous info
recorded under the same keys will not be overwritten.
"""
if self.recording:
if self.notes is None:
raise ValueError("This repo... | Can you create a Python 3 function that
records some info to the report. | You are a Python code generator, capable of creating scripts from specifications. |
def submit(self, info, *flags):
"""Finish recording and upload or save the report.
This closes the `Stats` object, no further methods should be called.
The report is either saved, uploaded or discarded, depending on
configuration. If uploading is enabled, previous reports might be
... | Create a Python 3 function for
submitting a new report. | You are a Python code architect, reviewing and designing scalable and efficient code |
def store(report, address):
"""Stores the report on disk.
"""
now = time.time()
secs = int(now)
msecs = int((now - secs) * 1000)
submitted_date = filename = None # avoids warnings
while True:
submitted_date = '%d.%03d' % (secs, msecs)
filename = 'report_%s.txt' % submitted_d... | How would you implement a function in Python 3 that
stores the report on disk. | As a python code expert, you are capable of creating scripts from specifications. |
Read the pin state of an input pin. | Can you generate a brief explanation for the following Python 3 code
def read(self, pin):
port, pin = self.pin_to_port(pin)
self.i2c_write([0x12 + port])
raw = self.i2c_read(1)
value = struct.unpack('>B', raw)[0]
return (value & (1 << pin)) > 0 | As a python code expert, you are capable of creating scripts from specifications. |
def read_port(self, port):
""" Read the pin state of a whole port (8 pins)
:Example:
>>> expander = MCP23017I2C(gw)
>>> # Read pin A0-A7 as a int (A0 and A1 are high)
>>> expander.read_port('A')
3
>>> # Read pin B0-B7 as a int (B2 is high)
>>> expander.r... | Implement a Python 3 function for
reading the state of a whole port. | As a Python code composer, you craft elegant and concise scripts. |
Set the pin state to the specified value. | Make a summary of the following Python 3 code
def write(self, pin, value):
port, pin = self.pin_to_port(pin)
portname = 'A'
if port == 1:
portname = 'B'
self._update_register('GPIO' + portname, pin, value)
self.sync() | As a python code expert, you are capable of creating scripts from specifications. |
def write_port(self, port, value):
""" Use a whole port as a bus and write a byte to it.
:param port: Name of the port ('A' or 'B')
:param value: Value to write (0-255)
"""
if port == 'A':
self.GPIOA = value
elif port == 'B':
self.GPIOB = value
... | Write a Python 3 script to
write a byte to a port in the current system. | As a Python code composer, you craft elegant and concise scripts. |
def sync(self):
""" Upload the changed registers to the chip
This will check which register have been changed since the last sync and send them to the chip.
You need to call this method if you modify one of the register attributes (mcp23017.IODIRA for example) or
if you use one of the h... | Can you implement a function in Python 3 that
uploads the changed registers to the chip This will check which register have been changed since the last sync and send them to the chip. You need to call this method if you modify one of the register attributes (mcp23017.IODIRA for example) or if you use one of the helper ... | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_pins(self):
""" Get a list containing references to all 16 pins of the chip.
:Example:
>>> expander = MCP23017I2C(gw)
>>> pins = expander.get_pins()
>>> pprint.pprint(pins)
[<GPIOPin A0 on MCP23017I2C>,
<GPIOPin A1 on MCP23017I2C>,
<GPIOPin A2 ... | Create a Python 3 function for
getting a list containing all 16 pins of the chip. | You are a Python code architect, reviewing and designing scalable and efficient code |
Get the logic input level for the pin
| Can you tell what is the following Python 3 function doing
def read(self):
m = getattr(self.chip, self.method)
return m(**self.arguments) | You are a Python code generator, capable of creating scripts from specifications. |
def write(self, value):
""" Set the logic output level for the pin.
:type value: bool
:param value: True for a logic high
"""
if self.inverted:
value = not value
m = getattr(self.chip, self.method)
m(value=value, **self.arguments) | Write a Python 3 function that can
set the logic output level for the pin. | As a python code expert, you are capable of creating scripts from specifications. |
def init_app(self, app, **kwargs):
"""Initialize application object.
:param app: An instance of :class:`~flask.Flask`.
"""
self.init_config(app)
# Initialize extensions
self.menu_ext.init_app(app)
self.menu = app.extensions['menu']
self.breadcrumbs.init_... | Can you implement a function in Python 3 that
initializes application object. :param app: An instance of :class:`~flask.Flask`. | You are a Python code generator, capable of creating scripts from specifications. |
def init_config(self, app):
"""Initialize configuration.
:param app: An instance of :class:`~flask.Flask`.
"""
_vars = ['BASE_TEMPLATE', 'COVER_TEMPLATE', 'SETTINGS_TEMPLATE']
# Sets RequireJS config and SASS binary as well if not already set.
for k in dir(config):
... | How would you implement a function in Python 3 that
initializes configuration. :param app: An instance of :class:`~flask.Flask`. | As a python code expert, you are capable of creating scripts from specifications. |
def set_range(self, accel=1, gyro=1):
"""Set the measurement range for the accel and gyro MEMS. Higher range means less resolution.
:param accel: a RANGE_ACCEL_* constant
:param gyro: a RANGE_GYRO_* constant
:Example:
.. code-block:: python
sensor = MPU6050I2C(gat... | Implement a Python 3 function for
setting the measurement range for the accel and gyro MEMS. Higher range means less resolution. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def set_slave_bus_bypass(self, enable):
"""Put the aux i2c bus on the MPU-6050 in bypass mode, thus connecting it to the main i2c bus directly
Dont forget to use wakeup() or else the slave bus is unavailable
:param enable:
:return:
"""
current = self.i2c_read_register(0x... | Implement a function in Python 3 to
set the aux i2c bus in bypass mode thus connecting it to the main i2c bus. | As a Python code composer, you craft elegant and concise scripts. |
def temperature(self):
"""Read the value for the internal temperature sensor.
:returns: Temperature in degree celcius as float
:Example:
>>> sensor = MPU6050I2C(gw)
>>> sensor.wakeup()
>>> sensor.temperature()
49.38
"""
if not self.awake:
... | Write a Python 3 script for
reading the value for the internal temperature sensor. | You are a Python code analyst, evaluating scripts for potential improvements. |
def acceleration(self):
"""Return the acceleration in G's
:returns: Acceleration for every axis as a tuple
:Example:
>>> sensor = MPU6050I2C(gw)
>>> sensor.wakeup()
>>> sensor.acceleration()
(0.6279296875, 0.87890625, 1.1298828125)
"""
if not se... | How would you code a function in Python 3 to
return the acceleration in G s as a tuple | As a Python code translator, you convert algorithms and pseudocode into Python. |
Return the angular rate for every axis in degree / second. | Can you generate a brief explanation for the following Python 3 code
def angular_rate(self):
if not self.awake:
raise Exception("MPU6050 is in sleep mode, use wakeup()")
raw = self.i2c_read_register(0x43, 6)
x, y, z = struct.unpack('>HHH', raw)
scales = {
self.RA... | As a Python code analyst, you investigate and solve complex coding mysteries |
Create strings from lazy strings. | Can you tell what is the following Python 3 function doing
def _get_contents(self):
return [
str(value) if is_lazy_string(value) else value
for value in super(LazyNpmBundle, self)._get_contents()
] | You are a Python code generator, capable of creating scripts from specifications. |
def load_calibration(self):
"""Load factory calibration data from device."""
registers = self.i2c_read_register(0xAA, 22)
(
self.cal['AC1'],
self.cal['AC2'],
self.cal['AC3'],
self.cal['AC4'],
self.cal['AC5'],
self.cal['AC6']... | Can you write a function in Python 3 where it
loads factory calibration data from device. | As a python code expert, you are capable of creating scripts from specifications. |
Get the temperature from the sensor. | Here you have a function in Python 3, explain what it does
def temperature(self):
ut = self.get_raw_temp()
x1 = ((ut - self.cal['AC6']) * self.cal['AC5']) >> 15
x2 = (self.cal['MC'] << 11) // (x1 + self.cal['MD'])
b5 = x1 + x2
return ((b5 + 8) >> 4) / 10 | You are a Python code generator, capable of creating scripts from specifications. |
Get barometric pressure in milibar as a int | Given the following Python 3 function, write the documentation
def pressure(self):
ut = self.get_raw_temp()
up = self.get_raw_pressure()
x1 = ((ut - self.cal['AC6']) * self.cal['AC5']) >> 15
x2 = (self.cal['MC'] << 11) // (x1 + self.cal['MD'])
b5 = x1 + x2
b6 = b5 - 4000
... | As a Python code composer, you craft elegant and concise scripts. |
Explicitly switch the Bus Pirate mode. | Explain what the following Python 3 code does
def switch_mode(self, new_mode):
packet = bytearray()
packet.append(new_mode)
self.device.write(packet)
possible_responses = {
self.MODE_I2C: b'I2C1',
self.MODE_RAW: b'BBIO1',
self.MODE_SPI: b'API1',
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Set the state of the internal peripheral state at runtime. | Given the following Python 3 function, write the documentation
def set_peripheral(self, power=None, pullup=None, aux=None, chip_select=None):
if power is not None:
self.power = power
if pullup is not None:
self.pullup = pullup
if aux is not None:
self.aux = au... | You are a Python code generator, capable of creating scripts from specifications. |
Set the I2C speed of the ISO. | Here you have a function in Python 3, explain what it does
def _set_i2c_speed(self, i2c_speed):
lower_bits_mapping = {
'400kHz': 3,
'100kHz': 2,
'50kHz': 1,
'5kHz': 0,
}
if i2c_speed not in lower_bits_mapping:
raise ValueError('Invalid ... | As a Python code analyst, you investigate and solve complex coding mysteries |
Sets the resolution of the current log entry. | Can you tell what is the following Python 3 function doing
def set_resolution(self, resolution=1090):
options = {
1370: 0,
1090: 1,
820: 2,
660: 3,
440: 4,
390: 5,
330: 6,
230: 7
}
if resolution not ... | As a python code expert, you are capable of creating scripts from specifications. |
def gauss(self):
"""
Get the magnetometer values as gauss for each axis as a tuple (x,y,z)
:example:
>>> sensor = HMC5883L(gw)
>>> sensor.gauss()
(16.56, 21.2888, 26.017599999999998)
"""
raw = self.raw()
factors = {
1370: 0.73,
... | Write a Python 3 script for
getting the magnetometer values as gauss for each axis as a tuple x y z | As a python code expert, you are capable of creating scripts from specifications. |
def temperature(self):
""" Get the temperature in degree celcius
"""
result = self.i2c_read(2)
value = struct.unpack('>H', result)[0]
if value < 32768:
return value / 256.0
else:
return (value - 65536) / 256.0 | Can you implement a function in Python 3 that
gets the temperature in degree celcius | You are a Python code architect, reviewing and designing scalable and efficient code |
def write(self, char):
""" Display a single character on the display
:type char: str or int
:param char: Character to display
"""
char = str(char).lower()
self.segments.write(self.font[char]) | Can you implement a function in Python 3 that
displays a single character on the display | As a python code expert, you are capable of creating scripts from specifications. |
Get the absolute path of the directory containing the theme files. | Here you have a function in Python 3, explain what it does
def get_html_theme_path():
return os.path.abspath(os.path.dirname(os.path.dirname(__file__))) | As a Python code analyst, you investigate and solve complex coding mysteries |
def feedback_form_url(project, page):
"""
Create a URL for feedback on a particular page in a project.
"""
return FEEDBACK_FORM_FMT.format(pageid=quote("{}: {}".format(project, page))) | Implement a function in Python 3 to
create a URL for feedback on a particular page in a project. | As a Python code composer, you craft elegant and concise scripts. |
def update_context(app, pagename, templatename, context, doctree): # pylint: disable=unused-argument
"""
Update the page rendering context to include ``feedback_form_url``.
"""
context['feedback_form_url'] = feedback_form_url(app.config.project, pagename) | Can you create a Python 3 function that
updates the page rendering context to include feedback_form_url. | You are a Python code analyst, evaluating scripts for potential improvements. |
Load some objects from a PEM file. | Can you tell what is the following Python 3 function doing
def objectsFromPEM(pemdata):
certificates = []
keys = []
blobs = [b""]
for line in pemdata.split(b"\n"):
if line.startswith(b'-----BEGIN'):
if b'CERTIFICATE' in line:
blobs = certificates
else:
... | As a python code expert, you are capable of creating scripts from specifications. |
Returns the key immediately following the input key - based on the Java implementation found in
org. apache. accumulo. core. data. Key function followingKey | Here you have a function in Python 3, explain what it does
def following_key(key):
if key.timestamp is not None:
key.timestamp -= 1
elif key.colVisibility is not None:
key.colVisibility = following_array(key.colVisibility)
elif key.colQualifier is not None:
key.colQualifier = followi... | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns a String that sorts just after all Strings beginning with a prefix | Can you tell what is the following Python 3 function doing
def followingPrefix(prefix):
prefixBytes = array('B', prefix)
changeIndex = len(prefixBytes) - 1
while (changeIndex >= 0 and prefixBytes[changeIndex] == 0xff ):
changeIndex = changeIndex - 1;
if(changeIndex < 0):
... | You are a Python code generator, capable of creating scripts from specifications. |
def prefix(rowPrefix):
"""Returns a Range that covers all rows beginning with a prefix"""
fp = Range.followingPrefix(rowPrefix)
return Range(srow=rowPrefix, sinclude=True, erow=fp, einclude=False) | How would you code a function in Python 3 to
return a Range that covers all rows beginning with a prefix | As a Python code composer, you craft elegant and concise scripts. |
def add_mutations_and_flush(self, table, muts):
"""
Add mutations to a table without the need to create and manage a batch writer.
"""
if not isinstance(muts, list) and not isinstance(muts, tuple):
muts = [muts]
cells = {}
for mut in muts:
cells.se... | Write a Python 3 script for
adding mutations to a table and flush the batch writer. | You are a Python code generator, capable of creating scripts from specifications. |
def remove_constraint(self, table, constraint):
"""
:param table: table name
:param constraint: the constraint number as returned by list_constraints
"""
self.client.removeConstraint(self.login, table, constraint) | Write a Python 3 script for
removing a constraint from the specified table | As a Python code translator, you convert algorithms and pseudocode into Python. |
def login(self, principal, loginProperties):
"""
Parameters:
- principal
- loginProperties
"""
self.send_login(principal, loginProperties)
return self.recv_login() | Write a Python 3 script for
sending login to the server and receive the response. | You are a Python code architect, reviewing and designing scalable and efficient code |
Adds a constraint to the table with the specified login. | Explain what the following Python 3 code does
def addConstraint(self, login, tableName, constraintClassName):
self.send_addConstraint(login, tableName, constraintClassName)
return self.recv_addConstraint() | As a python code expert, you are capable of creating scripts from specifications. |
Adds a list of splits to the table with login login. | How would you explain what the following Python 3 function does
def addSplits(self, login, tableName, splits):
self.send_addSplits(login, tableName, splits)
self.recv_addSplits() | You are a Python code analyst, evaluating scripts for potential improvements. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.