output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
Generate changes object for ldap object. | Given the following Python 3 function, write the documentation
def changeset(python_data: LdapObject, d: dict) -> Changeset:
table: LdapObjectClass = type(python_data)
fields = table.get_fields()
changes = Changeset(fields, src=python_data, d=d)
return changes | As a python code expert, you are capable of creating scripts from specifications. |
Convert a DbDate object to a LdapObject. | How would you explain what the following Python 3 function does
def _db_to_python(db_data: dict, table: LdapObjectClass, dn: str) -> LdapObject:
fields = table.get_fields()
python_data = table({
name: field.to_python(db_data[name])
for name, field in fields.items()
if field.db_field
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Convert a LdapChanges object to a modlist for add operation. | Here you have a function in Python 3, explain what it does
def _python_to_mod_new(changes: Changeset) -> Dict[str, List[List[bytes]]]:
table: LdapObjectClass = type(changes.src)
fields = table.get_fields()
result: Dict[str, List[List[bytes]]] = {}
for name, field in fields.items():
if field.db... | As a python code expert, you are capable of creating scripts from specifications. |
def _python_to_mod_modify(changes: Changeset) -> Dict[str, List[Tuple[Operation, List[bytes]]]]:
""" Convert a LdapChanges object to a modlist for a modify operation. """
table: LdapObjectClass = type(changes.src)
changes = changes.changes
result: Dict[str, List[Tuple[Operation, List[bytes]]]] = {}
... | How would you code a function in Python 3 to
convert a LdapChanges object to a modlist for a modify operation. | You are a Python code architect, reviewing and designing scalable and efficient code |
Search for an object of given type in the database. | Given the following Python 3 function, write the documentation
def search(table: LdapObjectClass, query: Optional[Q] = None,
database: Optional[Database] = None, base_dn: Optional[str] = None) -> Iterator[LdapObject]:
""" Search for a object of given type in the database. """
fields = table.get_field... | As a Python code analyst, you investigate and solve complex coding mysteries |
Get exactly one result from the database or fail. | Can you generate the documentation for the following Python 3 function
def get_one(table: LdapObjectClass, query: Optional[Q] = None,
database: Optional[Database] = None, base_dn: Optional[str] = None) -> LdapObject:
""" Get exactly one result from the database or fail. """
results = search(table, q... | As a python code expert, you are capable of creating scripts from specifications. |
Preload all NotLoaded fields in LdapObject. | Here you have a function in Python 3, explain what it does
def preload(python_data: LdapObject, database: Optional[Database] = None) -> LdapObject:
changes = {}
# Load objects within lists.
def preload_item(value: Any) -> Any:
if isinstance(value, NotLoaded):
return value.load(database... | You are a Python code architect, reviewing and designing scalable and efficient code |
Insert a new python_data object in the database. | Make a summary of the following Python 3 code
def insert(python_data: LdapObject, database: Optional[Database] = None) -> LdapObject:
assert isinstance(python_data, LdapObject)
table: LdapObjectClass = type(python_data)
# ADD NEW ENTRY
empty_data = table()
changes = changeset(empty_data, python_da... | As a python code expert, you are capable of creating scripts from specifications. |
def save(changes: Changeset, database: Optional[Database] = None) -> LdapObject:
""" Save all changes in a LdapChanges. """
assert isinstance(changes, Changeset)
if not changes.is_valid:
raise RuntimeError(f"Changeset has errors {changes.errors}.")
database = get_database(database)
connect... | Create a Python 3 function to
save all changes in a single object. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Delete a LdapObject from the database. | Can you generate the documentation for the following Python 3 function
def delete(python_data: LdapObject, database: Optional[Database] = None) -> None:
dn = python_data.get_as_single('dn')
assert dn is not None
database = get_database(database)
connection = database.connection
connection.delete(d... | You are a Python code generator, capable of creating scripts from specifications. |
Lookup a field by its name. | Explain what the following Python 3 code does
def _get_field_by_name(table: LdapObjectClass, name: str) -> tldap.fields.Field:
fields = table.get_fields()
return fields[name] | You are a Python code analyst, evaluating scripts for potential improvements. |
Move or rename a LdapObject in the database. | Can you generate the documentation for the following Python 3 function
def rename(python_data: LdapObject, new_base_dn: str = None,
database: Optional[Database] = None, **kwargs) -> LdapObject:
""" Move/rename a LdapObject in the database. """
table = type(python_data)
dn = python_data.get_as_sin... | As a Python code analyst, you investigate and solve complex coding mysteries |
def route(route_str): # decorator param
"""
Provides play2 likes routes, with python formatter
All string fileds should be named parameters
:param route_str: a route "GET /parent/{parentID}/child/{childId}{ctype}"
:return: the response of requests.request
"""
def ilog(elapsed):
# s... | Write a Python 3 script to
provide play2 likes routes, with python formatter All string fileds should be named parameters :param route_str: a route "GET /parent/{parentID}/child/{childId}{ctype}" :return: the response of requests.request | As a Python code composer, you craft elegant and concise scripts. |
Decorator for route
Vehicle. Injects cookies into requests call over route
Vehicle | Can you generate a brief explanation for the following Python 3 code
def play_auth(f):
def wrapper(*args, **kwargs):
self = args[0]
if 'cookies' in kwargs:
raise AttributeError("don't set cookies explicitly")
if 'auth' in kwargs:
raise AttributeError("don't set auth ... | As a Python code composer, you craft elegant and concise scripts. |
Decorator for basic auth | Can you tell what is the following Python 3 function doing
def basic_auth(f):
def wrapper(*args, **kwargs):
self = args[0]
if 'auth' in kwargs:
raise AttributeError("don't set auth token explicitly")
assert self.is_connected, "not connected, call router.connect(email, password) ... | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns a dictionary with all items of l being the keys of the dictionary
| Here you have a function in Python 3, explain what it does
def _list_dict(l: Iterator[str], case_insensitive: bool = False):
if case_insensitive:
raise NotImplementedError()
d = tldap.dict.CaseInsensitiveDict()
else:
d = {}
for i in l:
d[i] = None
return d | As a Python code analyst, you investigate and solve complex coding mysteries |
def addModlist(entry: dict, ignore_attr_types: Optional[List[str]] = None) -> Dict[str, List[bytes]]:
"""Build modify list for call of method LDAPObject.add()"""
ignore_attr_types = _list_dict(map(str.lower, (ignore_attr_types or [])))
modlist: Dict[str, List[bytes]] = {}
for attrtype in entry.keys():
... | Write a Python 3 function that can
build modify list for call of method LDAPObject. add | As a python code expert, you are capable of creating scripts from specifications. |
def modifyModlist(
old_entry: dict, new_entry: dict, ignore_attr_types: Optional[List[str]] = None,
ignore_oldexistent: bool = False) -> Dict[str, Tuple[str, List[bytes]]]:
"""
Build differential modify list for calling LDAPObject.modify()/modify_s()
:param old_entry:
Dictionary hol... | Can you write a function in Python 3 where it
builds differential modify list for calling LDAPObject.modify()/modify_s() :param old_entry: Dictionary holding the old entry :param new_entry: Dictionary holding what the new entry should be :param ignore_attr_types: List of attribute type names to be ignored completely :p... | You are a Python code generator, capable of creating scripts from specifications. |
Authenticates user and returns new platform instance. | Can you generate a brief explanation for the following Python 3 code
def connect(tenant=None, user=None, password=None, token=None, is_public=False):
if not is_public:
router = PrivatePath(tenant)
else:
router = PublicPath(tenant)
router.public_api_in_use = is_public
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Connect to another user | Given the following Python 3 function, write the documentation
def connect_to_another_user(self, user, password, token=None, is_public=False):
return QubellPlatform.connect(self._router.base_url, user, password, token, is_public) | You are a Python code generator, capable of creating scripts from specifications. |
def create_organization(self, name):
"""
Creates new organization
:rtype: Organization
"""
org = Organization.new(name, self._router)
assert org.ready(), "Organization {} hasn't got ready after creation".format(name)
return org | Create a Python 3 function for
creating a new organization with the given name. | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_organization(self, id=None, name=None):
"""
Gets existing and accessible organization
:rtype: Organization
"""
log.info("Picking organization: %s (%s)" % (name, id))
return self.organizations[id or name] | Write a Python 3 script for
getting existing and accessible organization. | As a Python code composer, you craft elegant and concise scripts. |
Gets existing or creates new organization. | Can you generate the documentation for the following Python 3 function
def get_or_create_organization(self, id=None, name=None):
if id:
return self.get_organization(id)
else:
assert name
try:
return self.get_organization(name=name)
except e... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Get backends versions
:return: dict containing name of backend and version. | Can you generate the documentation for the following Python 3 function
def get_backends_versions(self):
# We are not always have permission, so find open.
for i in range(0, len(self.organizations)):
try:
backends = self.organizations[i].environments['default'].backends
... | As a Python code composer, you craft elegant and concise scripts. |
Returns a stop driver. | Given the following Python 3 function, write the documentation
def make_driver(loop=None):
''' Returns a stop driver.
The optional loop argument can be provided to use the driver in another
loop than the default one.
Parameters
-----------
loop: BaseEventLoop
The event loop to us... | You are a Python code architect, reviewing and designing scalable and efficient code |
def rdn_to_dn(changes: Changeset, name: str, base_dn: str) -> Changeset:
""" Convert the rdn to a fully qualified DN for the specified LDAP
connection.
:param changes: The changes object to lookup.
:param name: rdn to convert.
:param base_dn: The base_dn to lookup.
:return: fully qualified DN.
... | Write a Python 3 function that can
convert the rdn to a fully qualified DN for the specified LDAP connection. | As a python code expert, you are capable of creating scripts from specifications. |
def _stdin_(p):
"""Takes input from user. Works for Python 2 and 3."""
_v = sys.version[0]
return input(p) if _v is '3' else raw_input(p) | How would you code a function in Python 3 to
take input from user. Works for Python 2 and 3. | You are a Python code generator, capable of creating scripts from specifications. |
def survey_loader(sur_dir=SUR_DIR, sur_file=SUR_FILE):
"""Loads up the given survey in the given dir."""
survey_path = os.path.join(sur_dir, sur_file)
survey = None
with open(survey_path) as survey_file:
survey = Survey(survey_file.read())
return survey | Write a Python 3 function for
loading up the given survey in the given dir. | As a Python code analyst, you investigate and solve complex coding mysteries |
Return the choices in string form. | Here you have a function in Python 3, explain what it does
def format_choices(self):
ce = enumerate(self.choices)
f = lambda i, c: '%s (%d)' % (c, i+1)
# apply formatter and append help token
toks = [f(i,c) for i, c in ce] + ['Help (?)']
return ' '.join(toks) | You are a Python code analyst, evaluating scripts for potential improvements. |
Validate user s answer against available choices. | Can you generate the documentation for the following Python 3 function
def is_answer_valid(self, ans):
return ans in [str(i+1) for i in range(len(self.choices))] | You are a Python code architect, reviewing and designing scalable and efficient code |
Run the given question. | Here you have a function in Python 3, explain what it does
def run_question(self, question, input_func=_stdin_):
qi = '[%d/%d] ' % (self.qcount, self.qtotal)
print('%s %s:' % (qi, question['label']))
while True:
# ask for user input until we get a valid one
ans = input_fu... | You are a Python code generator, capable of creating scripts from specifications. |
Run the given section. | Make a summary of the following Python 3 code
def run_section(self, name, input_func=_stdin_):
print('\nStuff %s by the license:\n' % name)
section = self.survey[name]
for question in section:
self.run_question(question, input_func) | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_vector(self):
"""Return the vector for this survey."""
vec = {}
for dim in ['forbidden', 'required', 'permitted']:
if self.survey[dim] is None:
continue
dim_vec = map(lambda x: (x['tag'], x['answer']),
self.survey[dim])
... | Write a Python 3 function that can
return the vector for this survey. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def update(self, span: typing.Tuple[int, int], line_type: LineType) -> None:
"""
Updates line types for a block's span.
Args:
span: First and last relative line number of a Block.
line_type: The type of line to update to.
Raises:
ValidationError: A s... | Create a Python 3 function for
updating the line types for a specific span. | As a python code expert, you are capable of creating scripts from specifications. |
def check_arrange_act_spacing(self) -> typing.Generator[AAAError, None, None]:
"""
* When no spaces found, point error at line above act block
* When too many spaces found, point error at 2nd blank line
"""
yield from self.check_block_spacing(
LineType.arrange,
... | Write a Python 3 script to
check if the action block is at least 1 blank line before the range. | You are a Python code architect, reviewing and designing scalable and efficient code |
Check that the action assert spacing is correct. | Can you generate a brief explanation for the following Python 3 code
def check_act_assert_spacing(self) -> typing.Generator[AAAError, None, None]:
yield from self.check_block_spacing(
LineType.act,
LineType._assert,
'AAA04 expected 1 blank line before Assert block, found {}',... | As a Python code analyst, you investigate and solve complex coding mysteries |
Checks that the spacing of the second block is not empty. | Can you tell what is the following Python 3 function doing
def check_block_spacing(
self,
first_block_type: LineType,
second_block_type: LineType,
error_message: str,
) -> typing.Generator[AAAError, None, None]:
"""
Checks there is a clear single line between ``first_... | You are a Python code analyst, evaluating scripts for potential improvements. |
def vector_distance(v1, v2):
"""Given 2 vectors of multiple dimensions, calculate the euclidean
distance measure between them."""
dist = 0
for dim in v1:
for x in v1[dim]:
dd = int(v1[dim][x]) - int(v2[dim][x])
dist = dist + dd**2
return dist | Create a Python 3 function to
give 2 vectors of multiple dimensions calculate the euclidean distance measure between them. | You are a Python code analyst, evaluating scripts for potential improvements. |
Send command with no output. | Explain what the following Python 3 code does
def send_command(self, command, *arguments):
self.api.send_command(self, command, *arguments) | You are a Python code analyst, evaluating scripts for potential improvements. |
Send command and wait for single line output. | Can you tell what is the following Python 3 function doing
def send_command_return(self, command, *arguments):
return self.api.send_command_return(self, command, *arguments) | As a Python code composer, you craft elegant and concise scripts. |
Send command and wait for multiple lines output. | Make a summary of the following Python 3 code
def send_command_return_multilines(self, command, *arguments):
return self.api.send_command_return_multilines(self, command, *arguments) | As a Python code composer, you craft elegant and concise scripts. |
def load(self, limit=9999):
""" Function list
Get the list of all interfaces
@param key: The targeted object
@param limit: The limit of items to return
@return RETURN: A ForemanItem list
"""
subItemList = self.api.list('{}/{}/{}'.format(self.parentObjName,
... | Write a Python 3 function that can
function list Get the list of all interfaces and return a dict of all the items that are in the current object. | As a Python code composer, you craft elegant and concise scripts. |
Function iadd__
Adds a new entry to the list | Make a summary of the following Python 3 code
def append(self, payload):
if self.objType.setInParentPayload:
print('Error, {} is not elibible to addition, but only set'
.format(self.objName))
return False
ret = self.api.create("{}/{}/{}".format(self.parentObjNam... | As a python code expert, you are capable of creating scripts from specifications. |
Function getPayloadStruct
- Returns the dict containing the payload structure | Can you tell what is the following Python 3 function doing
def getPayloadStruct(self, payload):
newSubItem = self.objType(self.api, 0, self.parentObjName,
self.parentPayloadObj, self.parentKey, {})
return newSubItem.getPayloadStruct(payload, self.parentPayloadObj) | As a Python code composer, you craft elegant and concise scripts. |
def get_repr(expr, multiline=False):
"""
Build a repr string for ``expr`` from its vars and signature.
::
>>> class MyObject:
... def __init__(self, arg1, arg2, *var_args, foo=None, bar=None, **kwargs):
... self.arg1 = arg1
... self.arg2 = arg2
.... | Create a Python 3 function to
return a string representation of the given expression. | You are a Python code analyst, evaluating scripts for potential improvements. |
Get the args var args and kwargs for an object expr. | How would you explain what the following Python 3 function does
def get_vars(expr):
# print('TYPE?', type(expr))
signature = _get_object_signature(expr)
if signature is None:
return ({}, [], {})
# print('SIG?', signature)
args = collections.OrderedDict()
var_args = []
kwargs = {}
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def new(expr, *args, **kwargs):
"""
Template an object.
::
>>> class MyObject:
... def __init__(self, arg1, arg2, *var_args, foo=None, bar=None, **kwargs):
... self.arg1 = arg1
... self.arg2 = arg2
... self.var_args = var_args
...... | Can you implement a function in Python 3 that
creates a new object. | You are a Python code architect, reviewing and designing scalable and efficient code |
Hooked into Sphinx s builder - inited event. | Can you generate a brief explanation for the following Python 3 code
def on_builder_inited(app):
config = app.builder.config
target_directory = (
pathlib.Path(app.builder.env.srcdir) / config.uqbar_api_directory_name
)
initial_source_paths: List[str] = []
source_paths = config.uqbar_api_so... | As a Python code analyst, you investigate and solve complex coding mysteries |
Sets up Sphinx extension. | Make a summary of the following Python 3 code
def setup(app) -> Dict[str, Any]:
app.add_config_value("uqbar_api_directory_name", "api", "env")
app.add_config_value("uqbar_api_document_empty_modules", False, "env")
app.add_config_value("uqbar_api_document_private_members", False, "env")
app.add_config_va... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Retrieve the Glitter App config for a specific Glitter App. | Can you generate the documentation for the following Python 3 function
def get_glitter_app(self, glitter_app_name):
if not self.discovered:
self.discover_glitter_apps()
try:
glitter_app = self.glitter_apps[glitter_app_name]
return glitter_app
except KeyError:... | As a Python code composer, you craft elegant and concise scripts. |
def discover_glitter_apps(self):
"""
Find all the Glitter App configurations in the current project.
"""
for app_name in settings.INSTALLED_APPS:
module_name = '{app_name}.glitter_apps'.format(app_name=app_name)
try:
glitter_apps_module = import_mo... | Implement a Python 3 function for
finding all Glitter App configurations in the current project. | As a Python code analyst, you investigate and solve complex coding mysteries |
Function enhance
Enhance the object with new item or enhanced items
| Given the following Python 3 function, write the documentation
def enhance(self):
self.update({'parameters':
SubDict(self.api, self.objName,
self.payloadObj, self.key,
SubItemParameter)})
self.update({'interfaces':
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Update the kong configuration | How would you explain what the following Python 3 function does
def kong(ctx, namespace, yes):
m = KongManager(ctx.obj['agile'], namespace=namespace)
click.echo(utils.niceJson(m.create_kong(yes))) | You are a Python code architect, reviewing and designing scalable and efficient code |
def schedule_task(self):
"""
Schedules this publish action as a Celery task.
"""
from .tasks import publish_task
publish_task.apply_async(kwargs={'pk': self.pk}, eta=self.scheduled_time) | Can you write a function in Python 3 where it
schedules this publish action as a Celery task. | As a Python code composer, you craft elegant and concise scripts. |
Get the version object for the related object. | How would you explain what the following Python 3 function does
def get_version(self):
return Version.objects.get(
content_type=self.content_type,
object_id=self.object_id,
version_number=self.publish_version,
) | You are a Python code generator, capable of creating scripts from specifications. |
def _publish(self):
"""
Process a publish action on the related object, returns a boolean if a change is made.
Only objects where a version change is needed will be updated.
"""
obj = self.content_object
version = self.get_version()
actioned = False
# On... | Implement a function in Python 3 to
process a publish action on the related object returns a boolean if a change is made. | You are a Python code analyst, evaluating scripts for potential improvements. |
def _unpublish(self):
"""
Process an unpublish action on the related object, returns a boolean if a change is made.
Only objects with a current active version will be updated.
"""
obj = self.content_object
actioned = False
# Only update if needed
if obj.... | Write a Python 3 function that can
process an unpublish action on the related object returns a boolean if a change is made. | As a python code expert, you are capable of creating scripts from specifications. |
Adds a log entry for this action to the object history. | Given the following Python 3 function, write the documentation
def _log_action(self):
if self.publish_version == self.UNPUBLISH_CHOICE:
message = 'Unpublished page (scheduled)'
else:
message = 'Published version {} (scheduled)'.format(self.publish_version)
LogEntry.objec... | As a python code expert, you are capable of creating scripts from specifications. |
Process the action and update the related object returns a boolean if a change is made. | Make a summary of the following Python 3 code
def process_action(self):
if self.publish_version == self.UNPUBLISH_CHOICE:
actioned = self._unpublish()
else:
actioned = self._publish()
# Only log if an action was actually taken
if actioned:
self._log_a... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def checkAndCreate(self, key, payload,
hostgroupConf,
hostgroupParent,
puppetClassesId):
""" Function checkAndCreate
check And Create procedure for an hostgroup
- check the hostgroup is not existing
- create the hostgro... | Can you implement a function in Python 3 that
functions checkAndCreate check if the item is not existing and create the ItemHostsGroup object | You are a Python code generator, capable of creating scripts from specifications. |
Create a handler for logging to target | How would you explain what the following Python 3 function does
def create_handler(target: str):
if target == 'stderr':
return logging.StreamHandler(sys.stderr)
elif target == 'stdout':
return logging.StreamHandler(sys.stdout)
else:
return logging.handlers.WatchedFileHandler(filename... | As a python code expert, you are capable of creating scripts from specifications. |
Initialise basic logging facilities | How would you explain what the following Python 3 function does
def initialise_logging(level: str, target: str, short_format: bool):
try:
log_level = getattr(logging, level)
except AttributeError:
raise SystemExit(
"invalid log level %r, expected any of 'DEBUG', 'INFO', 'WARNING', 'E... | You are a Python code analyst, evaluating scripts for potential improvements. |
def escape_dn_chars(s):
"""
Escape all DN special characters found in s
with a back-slash (see RFC 4514, section 2.4)
"""
if s:
assert isinstance(s, six.string_types)
s = s.replace('\\', '\\\\')
s = s.replace(',', '\\,')
s = s.replace('+', '\\+')
s = s.replace... | Create a Python 3 function for
escaping all DN special characters found in s with a back - slash | As a python code expert, you are capable of creating scripts from specifications. |
This function takes a string as parameter and returns a decomposed DN. | Here you have a function in Python 3, explain what it does
def str2dn(dn, flags=0):
# if python2, we need unicode string
if not isinstance(dn, six.text_type):
dn = dn.decode("utf_8")
assert flags == 0
result, i = _distinguishedName(dn, 0)
if result is None:
raise tldap.exceptions.I... | As a Python code translator, you convert algorithms and pseudocode into Python. |
This function takes a DN and returns a list of all the components in the DN. | Given the following Python 3 function, write the documentation
def explode_dn(dn, notypes=0, flags=0):
if not dn:
return []
dn_decomp = str2dn(dn, flags)
rdn_list = []
for rdn in dn_decomp:
if notypes:
rdn_list.append('+'.join([
escape_dn_chars(avalue or '')
... | You are a Python code generator, capable of creating scripts from specifications. |
def labels(ctx):
"""Crate or update labels in github
"""
config = ctx.obj['agile']
repos = config.get('repositories')
labels = config.get('labels')
if not isinstance(repos, list):
raise CommandError(
'You need to specify the "repos" list in the config'
)
if not is... | Write a Python 3 script for
crating or update labels in github | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_access_token(self, code):
"""Get new access token."""
try:
self._token = super().fetch_token(
MINUT_TOKEN_URL,
client_id=self._client_id,
client_secret=self._client_secret,
code=code,
)
# except Excep... | Implement a Python 3 function for
getting new access token. | As a python code expert, you are capable of creating scripts from specifications. |
Send a request to the Minut Point API. | Explain what the following Python 3 code does
def _request(self, url, request_type='GET', **params):
try:
_LOGGER.debug('Request %s %s', url, params)
response = self.request(
request_type, url, timeout=TIMEOUT.seconds, **params)
response.raise_for_status()
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Request list of devices. | How would you explain what the following Python 3 function does
def _request_devices(self, url, _type):
res = self._request(url)
return res.get(_type) if res else {} | As a python code expert, you are capable of creating scripts from specifications. |
def read_sensor(self, device_id, sensor_uri):
"""Return sensor value based on sensor_uri."""
url = MINUT_DEVICES_URL + "/{device_id}/{sensor_uri}".format(
device_id=device_id, sensor_uri=sensor_uri)
res = self._request(url, request_type='GET', data={'limit': 1})
if not res.ge... | Can you write a function in Python 3 where it
returns sensor value based on sensor_uri. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Remove webhook from the database. | Can you generate the documentation for the following Python 3 function
def remove_webhook(self):
if self._webhook.get('hook_id'):
self._request(
"{}/{}".format(MINUT_WEBHOOKS_URL, self._webhook['hook_id']),
request_type='DELETE',
) | You are a Python code generator, capable of creating scripts from specifications. |
Register webhook (if it doesn't exit). | Explain what the following Python 3 code does
def update_webhook(self, webhook_url, webhook_id, events=None):
hooks = self._request(MINUT_WEBHOOKS_URL, request_type='GET')['hooks']
try:
self._webhook = next(
hook for hook in hooks if hook['url'] == webhook_url)
_L... | As a Python code analyst, you investigate and solve complex coding mysteries |
def update(self):
"""Update all devices from server."""
with self._lock:
devices = self._request_devices(MINUT_DEVICES_URL, 'devices')
if devices:
self._state = {
device['device_id']: device
for device in devices
... | Write a Python 3 script to
update all devices from server. | You are a Python code generator, capable of creating scripts from specifications. |
Update and return sensor value. | Can you generate a brief explanation for the following Python 3 code
def sensor(self, sensor_type):
_LOGGER.debug("Reading %s sensor.", sensor_type)
return self._session.read_sensor(self.device_id, sensor_type) | As a python code expert, you are capable of creating scripts from specifications. |
def device_info(self):
"""Info about device."""
return {
'connections': {('mac', self.device['device_mac'])},
'identifieres': self.device['device_id'],
'manufacturer': 'Minut',
'model': 'Point v{}'.format(self.device['hardware_version']),
'name... | How would you implement a function in Python 3 that
returns info about device. | As a Python code analyst, you investigate and solve complex coding mysteries |
Render the glitter head. | Make a summary of the following Python 3 code
def glitter_head(context):
user = context.get('user')
rendered = ''
template_path = 'glitter/include/head.html'
if user is not None and user.is_staff:
template = context.template.engine.get_template(template_path)
rendered = template.render(... | You are a Python code architect, reviewing and designing scalable and efficient code |
def glitter_startbody(context):
"""
Template tag which renders the glitter overlay and sidebar. This is only
shown to users with permission to edit the page.
"""
user = context.get('user')
path_body = 'glitter/include/startbody.html'
path_plus = 'glitter/include/startbody_%s_%s.html'
ren... | How would you implement a function in Python 3 that
renders the glitter startbody. | You are a Python code analyst, evaluating scripts for potential improvements. |
def escape_filter_chars(assertion_value, escape_mode=0):
"""
Replace all special characters found in assertion_value
by quoted notation.
escape_mode
If 0 only special chars mentioned in RFC 4515 are escaped.
If 1 all NON-ASCII chars are escaped.
If 2 all chars are escaped.
"... | Write a Python 3 function that can
escape all special characters found in assertion_value by quoted notation. | As a Python code composer, you craft elegant and concise scripts. |
def filter_format(filter_template, assertion_values):
"""
filter_template
String containing %s as placeholder for assertion values.
assertion_values
List or tuple of assertion values. Length must match
count of %s in filter_template.
"""
assert isinstance(filter_templat... | Implement a function in Python 3 to
format a filter template. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Converts a naculiuli object to Flake8 object. | Here you have a function in Python 3, explain what it does
def to_flake8(self, checker_cls: type) -> Flake8Error:
return Flake8Error(
line_number=self.line_number,
offset=self.offset,
text=self.text,
checker_cls=checker_cls,
) | As a python code expert, you are capable of creating scripts from specifications. |
Add a chassis object to the set of available chassis. | Can you generate the documentation for the following Python 3 function
def add_chassis(self, chassis):
res = self._request(RestMethod.post, self.user_url, params={'ip': chassis.ip, 'port': chassis.port})
assert(res.status_code == 201) | You are a Python code architect, reviewing and designing scalable and efficient code |
Send command with no output. | Here you have a function in Python 3, explain what it does
def send_command(self, obj, command, *arguments):
self._perform_command('{}/{}'.format(self.session_url, obj.ref), command, OperReturnType.no_output, *arguments) | As a Python code analyst, you investigate and solve complex coding mysteries |
Send command with single line output. | Here you have a function in Python 3, explain what it does
def send_command_return(self, obj, command, *arguments):
return self._perform_command('{}/{}'.format(self.session_url, obj.ref), command, OperReturnType.line_output,
*arguments).json() | As a python code expert, you are capable of creating scripts from specifications. |
Send a command with no output. | Can you generate a brief explanation for the following Python 3 code
def send_command_return_multilines(self, obj, command, *arguments):
return self._perform_command('{}/{}'.format(self.session_url, obj.ref), command,
OperReturnType.multiline_output, *arguments).json() | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_attributes(self, obj):
""" Get all object's attributes.
Sends multi-parameter info/config queries and returns the result as dictionary.
:param obj: requested object.
:returns: dictionary of <name, value> of all attributes returned by the query.
:rtype: dict of (str, str... | Can you create a Python 3 function that
gets all object s attributes. Sends multi - parameter info or config queries and returns the result as dictionary. | You are a Python code generator, capable of creating scripts from specifications. |
Set attributes of the object. | Here you have a function in Python 3, explain what it does
def set_attributes(self, obj, **attributes):
attributes_url = '{}/{}/attributes'.format(self.session_url, obj.ref)
attributes_list = [{u'name': str(name), u'value': str(value)} for name, value in attributes.items()]
self._request(RestMe... | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_stats(self, obj, stat_name):
""" Send CLI command that returns list of integer counters.
:param obj: requested object.
:param stat_name: statistics command name.
:return: list of counters.
:rtype: list(int)
"""
return [int(v) for v in self.send_command_re... | How would you implement a function in Python 3 that
sends command that returns list of integer counters. | You are a Python code analyst, evaluating scripts for potential improvements. |
def init_common_services(self, with_cloud_account=True, zone_name=None):
"""
Initialize common service,
When 'zone_name' is defined " at $zone_name" is added to service names
:param bool with_cloud_account:
:param str zone_name:
:return: OR tuple(Workflow, Vault), OR tupl... | Implement a Python 3 function for
initializing common service, When 'zone_name' is defined " at $zone_name" is added to service names :param bool with_cloud_account: :param str zone_name: :return: OR tuple(Workflow, Vault), OR tuple(Workflow, Vault, CloudAccount) with services | You are a Python code architect, reviewing and designing scalable and efficient code |
def clone(self, name=None):
"""
:param name: new env name
:rtype: Environment
"""
resp = self._router.post_env_clone(env_id=self.environmentId, json=dict(name=name) if name else {}).json()
return Environment(self.organization, id=resp['id']).init_router(self._router) | Can you write a function in Python 3 where it
returns a clone of this environment. | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns environment marked as default. | Make a summary of the following Python 3 code
def default(self):
if ZONE_NAME:
log.info("Getting or creating default environment for zone with name '{0}'".format(DEFAULT_ENV_NAME()))
zone_id = self.organization.zones[ZONE_NAME].id
return self.organization.get_or_create_enviro... | As a python code expert, you are capable of creating scripts from specifications. |
def build_urls(self: NodeVisitor, node: inheritance_diagram) -> Mapping[str, str]:
"""
Builds a mapping of class paths to URLs.
"""
current_filename = self.builder.current_docname + self.builder.out_suffix
urls = {}
for child in node:
# Another document
if child.get("refuri") is ... | Can you write a function in Python 3 where it
builds a mapping of class paths to URLs. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def html_visit_inheritance_diagram(
self: NodeVisitor, node: inheritance_diagram
) -> None:
"""
Builds HTML output from an :py:class:`~uqbar.sphinx.inheritance.inheritance_diagram` node.
"""
inheritance_graph = node["graph"]
urls = build_urls(self, node)
graphviz_graph = inheritance_graph.bu... | Write a Python 3 function for
building HTML output from an inheritance diagram node. | You are a Python code generator, capable of creating scripts from specifications. |
Builds LaTeX output from an inheritance diagram node. | Can you tell what is the following Python 3 function doing
def latex_visit_inheritance_diagram(
self: NodeVisitor, node: inheritance_diagram
) -> None:
"""
Builds LaTeX output from an :py:class:`~uqbar.sphinx.inheritance.inheritance_diagram` node.
"""
inheritance_graph = node["graph"]
graphviz_g... | As a Python code composer, you craft elegant and concise scripts. |
def setup(app) -> Dict[str, Any]:
"""
Sets up Sphinx extension.
"""
app.setup_extension("sphinx.ext.graphviz")
app.add_node(
inheritance_diagram,
html=(html_visit_inheritance_diagram, None),
latex=(latex_visit_inheritance_diagram, None),
man=(skip, None),
texi... | Implement a Python 3 function for
setting up Sphinx extension. | You are a Python code generator, capable of creating scripts from specifications. |
Run the daemon and all its services | Here you have a function in Python 3, explain what it does
def run(configuration: str, level: str, target: str, short_format: bool):
initialise_logging(level=level, target=target, short_format=short_format)
logger = logging.getLogger(__package__)
logger.info('COBalD %s', cobald.__about__.__version__)
lo... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def cli_run():
"""Run the daemon from a command line interface"""
options = CLI.parse_args()
run(options.CONFIGURATION, options.log_level, options.log_target, options.log_journal) | How would you code a function in Python 3 to
run the daemon from a command line interface | As a Python code analyst, you investigate and solve complex coding mysteries |
def build_body(cls: Type[AN], body: List[ast.stmt]) -> List:
"""
Note:
Return type is probably ``-> List[AN]``, but can't get it to pass.
"""
act_nodes = [] # type: List[ActNode]
for child_node in body:
act_nodes += ActNode.build(child_node)
retur... | Create a Python 3 function to
build the list of ActNodes from a list of AST nodes. | As a Python code analyst, you investigate and solve complex coding mysteries |
Builds a list of all ActNode instances. | Here you have a function in Python 3, explain what it does
def build(cls: Type[AN], node: ast.stmt) -> List[AN]:
if node_is_result_assignment(node):
return [cls(node, ActNodeType.result_assignment)]
if node_is_pytest_raises(node):
return [cls(node, ActNodeType.pytest_raises)]
... | As a Python code composer, you craft elegant and concise scripts. |
Checks if organization properly created. | Explain what the following Python 3 code does
def ready(self):
@retry(tries=3, retry_exception=exceptions.NotFoundError) # org init, takes some times
def check_init():
env = self.environments['default']
return env.services['Default workflow service'].running(timeout=1) and \
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def create_application(self, name=None, manifest=None):
""" Creates application and returns Application object.
"""
if not manifest:
raise exceptions.NotEnoughParams('Manifest not set')
if not name:
name = 'auto-generated-name'
from qubell.api.private.appl... | Write a Python 3 function for
creating application and returns Application object. | You are a Python code generator, capable of creating scripts from specifications. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.