output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def get_application(self, id=None, name=None):
""" Get application object by name or id.
"""
log.info("Picking application: %s (%s)" % (name, id))
return self.applications[id or name] | Create a Python 3 function for
getting application object by name or id. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Get or create an application by id or name. If not found create with given or generated parameters. | Here you have a function in Python 3, explain what it does
def get_or_create_application(self, id=None, manifest=None, name=None):
if id:
return self.get_application(id=id)
elif name:
try:
app = self.get_application(name=name)
except exceptions.NotFoun... | As a Python code analyst, you investigate and solve complex coding mysteries |
def application(self, id=None, manifest=None, name=None):
""" Smart method. Creates, picks or modifies application.
If application found by name or id and manifest not changed: return app.
If app found by id, but other parameters differs: change them.
If no application found, create.
... | Can you write a function in Python 3 where it
smarts method. Creates picks or modifies application. | You are a Python code generator, capable of creating scripts from specifications. |
Launches an instance in application and returns Instance object. | How would you explain what the following Python 3 function does
def create_instance(self, application, revision=None, environment=None, name=None, parameters=None, submodules=None,
destroyInterval=None, manifestVersion=None):
""" Launches instance in application and returns Instance obje... | As a python code expert, you are capable of creating scripts from specifications. |
def get_instance(self, id=None, name=None):
""" Get instance object by name or id.
If application set, search within the application.
"""
log.info("Picking instance: %s (%s)" % (name, id))
if id: # submodule instances are invisible for lists
return Instance(id=id, or... | Implement a function in Python 3 to
get instance by name or id. | As a python code expert, you are capable of creating scripts from specifications. |
def list_instances_json(self, application=None, show_only_destroyed=False):
""" Get list of instances in json format converted to list"""
# todo: application should not be parameter here. Application should do its own list, just in sake of code reuse
q_filter = {'sortBy': 'byCreation', 'descendi... | Create a Python 3 function for
getting list of instances in json format converted to list | You are a Python code architect, reviewing and designing scalable and efficient code |
Get or create a new instance. | How would you explain what the following Python 3 function does
def get_or_create_instance(self, id=None, application=None, revision=None, environment=None, name=None, parameters=None, submodules=None,
destroyInterval=None):
""" Get instance by id or name.
If not found: cr... | You are a Python code analyst, evaluating scripts for potential improvements. |
This method returns an instance with given parameters within the application. | How would you explain what the following Python 3 function does
def instance(self, id=None, application=None, name=None, revision=None, environment=None, parameters=None, submodules=None, destroyInterval=None):
instance = self.get_or_create_instance(id, application, revision, environment, name, parameters, subm... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def create_environment(self, name, default=False, zone=None):
""" Creates environment and returns Environment object.
"""
from qubell.api.private.environment import Environment
return Environment.new(organization=self, name=name, zone_id=zone, default=default, router=self._router) | Write a Python 3 script to
create a new environment object. | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_environment(self, id=None, name=None):
""" Get environment object by name or id.
"""
log.info("Picking environment: %s (%s)" % (name, id))
return self.environments[id or name] | How would you implement a function in Python 3 that
gets environment object by name or id. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Get or create a new environment. | Make a summary of the following Python 3 code
def get_or_create_environment(self, id=None, name=None, zone=None, default=False):
if id:
return self.get_environment(id=id)
elif name:
try:
env = self.get_environment(name=name)
self._assert_env_and_zo... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def environment(self, id=None, name=None, zone=None, default=False):
""" Smart method. Creates, picks or modifies environment.
If environment found by name or id parameters not changed: return env.
If env found by id, but other parameters differs: change them.
If no environment found, cr... | Write a Python 3 script to
smart method. Creates picks or modifies environment. | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_zone(self, id=None, name=None):
""" Get zone object by name or id.
"""
log.info("Picking zone: %s (%s)" % (name, id))
return self.zones[id or name] | Create a Python 3 function for
getting a zone object by name or id. | You are a Python code architect, reviewing and designing scalable and efficient code |
Creates a new role with the given name and permissions. | Given the following Python 3 function, write the documentation
def create_role(self, name=None, permissions=""):
name = name or "autocreated-role"
from qubell.api.private.role import Role
return Role.new(self._router, organization=self, name=name, permissions=permissions) | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_role(self, id=None, name=None):
""" Get role object by name or id.
"""
log.info("Picking role: %s (%s)" % (name, id))
return self.roles[id or name] | Can you write a function in Python 3 where it
gets role object by name or id. | As a Python code composer, you craft elegant and concise scripts. |
def get_user(self, id=None, name=None, email=None):
""" Get user object by email or id.
"""
log.info("Picking user: %s (%s) (%s)" % (name, email, id))
from qubell.api.private.user import User
if email:
user = User.get(self._router, organization=self, email=email)
... | Create a Python 3 function for
getting user object by name or email or id. | As a python code expert, you are capable of creating scripts from specifications. |
def invite(self, email, roles=None):
"""
Send invitation to email with a list of roles
:param email:
:param roles: None or "ALL" or list of role_names
:return:
"""
if roles is None:
role_ids = [self.roles['Guest'].roleId]
elif roles == "ALL":
... | Write a Python 3 script to
send an invitation to the user with a list of roles | You are a Python code architect, reviewing and designing scalable and efficient code |
def init(self, access_key=None, secret_key=None):
"""
Mimics wizard's environment preparation
"""
if not access_key and not secret_key:
self._router.post_init(org_id=self.organizationId, data='{"initCloudAccount": true}')
else:
self._router.post_init(org_i... | Write a Python 3 function that can
mimic wizard s environment preparation | As a Python code analyst, you investigate and solve complex coding mysteries |
def set_applications_from_meta(self, metadata, exclude=None):
"""
Parses meta and update or create each application
:param str metadata: path or url to meta.yml
:param list[str] exclude: List of application names, to exclude from meta.
This might be need... | Create a Python 3 function for
parsing meta and updates or creates each application | As a Python code translator, you convert algorithms and pseudocode into Python. |
Mimics get starter -kit and wizard functionality to create components | Here you have a function in Python 3, explain what it does
def upload_applications(self, metadata, category=None):
upload_json = self._router.get_upload(params=dict(metadataUrl=metadata)).json()
manifests = [dict(name=app['name'], manifest=app['url']) for app in upload_json['applications']]
if n... | You are a Python code analyst, evaluating scripts for potential improvements. |
Commits and leaves transaction management. | Can you tell what is the following Python 3 function doing
def process_response(self, request, response):
if tldap.transaction.is_managed():
tldap.transaction.commit()
tldap.transaction.leave_transaction_management()
return response | As a Python code composer, you craft elegant and concise scripts. |
def line_protocol(name, tags: dict = None, fields: dict = None, timestamp: float = None) -> str:
"""
Format a report as per InfluxDB line protocol
:param name: name of the report
:param tags: tags identifying the specific report
:param fields: measurements of the report
:param timestamp: when t... | Write a Python 3 function that can
format a report as per InfluxDB line protocol | As a python code expert, you are capable of creating scripts from specifications. |
def get_default_blocks(self, top=False):
"""
Return a list of column default block tuples (URL, verbose name).
Used for quick add block buttons.
"""
default_blocks = []
for block_model, block_name in self.glitter_page.default_blocks:
block = apps.get_model(b... | Write a Python 3 script to
return a list of column default blocks tuples. Used for quick add block buttons. | As a Python code composer, you craft elegant and concise scripts. |
def add_block_widget(self, top=False):
"""
Return a select widget for blocks which can be added to this column.
"""
widget = AddBlockSelect(attrs={
'class': 'glitter-add-block-select',
}, choices=self.add_block_options(top=top))
return widget.render(name='', ... | How would you implement a function in Python 3 that
returns a select widget for blocks which can be added to this column. | As a Python code analyst, you investigate and solve complex coding mysteries |
Return a list of URLs and titles for blocks which can be added to this column. | Here you have a function in Python 3, explain what it does
def add_block_options(self, top):
from .blockadmin import blocks
block_choices = []
# Group all block by category
for category in sorted(blocks.site.block_list):
category_blocks = blocks.site.block_list[category]
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def default_blocks(self):
"""
Return a list of default block tuples (appname.ModelName, verbose name).
Next to the dropdown list of block types, a small number of common blocks which are
frequently used can be added immediately to a column with one click. This method defines
the... | Write a Python 3 function for
returning a list of default blocks for this application. | You are a Python code generator, capable of creating scripts from specifications. |
Returns a boolean if the current user has permission to add another object of the same
type which is being viewed or edited. | Make a summary of the following Python 3 code
def has_add_permission(self):
has_permission = False
if self.user is not None:
# We don't check for the object level permission - as the add permission doesn't make
# sense on a per object level here.
has_permission = sel... | You are a Python code generator, capable of creating scripts from specifications. |
Returns a boolean if the current user has permission to change the current object being
viewed or edited. | Explain what the following Python 3 code does
def has_change_permission(self):
has_permission = False
if self.user is not None:
# We check for the object level permission here, even though by default the Django
# admin doesn't. If the Django ModelAdmin is extended to allow objec... | You are a Python code architect, reviewing and designing scalable and efficient code |
Get correct embed url for Youtube or Vimeo. | Given the following Python 3 function, write the documentation
def get_embed_url(self):
embed_url = None
youtube_embed_url = 'https://www.youtube.com/embed/{}'
vimeo_embed_url = 'https://player.vimeo.com/video/{}'
# Get video ID from url.
if re.match(YOUTUBE_URL_RE, self.url):
... | You are a Python code generator, capable of creating scripts from specifications. |
Set html field with correct iframe. | Make a summary of the following Python 3 code
def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
if self.url:
iframe_html = '<iframe src="{}" frameborder="0" title="{}" allowfullscreen></iframe>'
self.html = iframe_html.format(
self.ge... | As a python code expert, you are capable of creating scripts from specifications. |
def _get_ip():
"""Get IP address for the docker host
"""
cmd_netstat = ['netstat', '-nr']
p1 = subprocess.Popen(cmd_netstat, stdout=subprocess.PIPE)
cmd_grep = ['grep', '^0\.0\.0\.0']
p2 = subprocess.Popen(cmd_grep, stdin=p1.stdout, stdout=subprocess.PIPE)
cmd_awk = ['awk', '{ print $2 }']
... | Write a Python 3 function for
getting the IP address for the docker host | You are a Python code architect, reviewing and designing scalable and efficient code |
Try to connect to the Galaxy API using the given configuration dict. | Make a summary of the following Python 3 code
def get_galaxy_connection(history_id=None, obj=True):
history_id = history_id or os.environ['HISTORY_ID']
key = os.environ['API_KEY']
### Customised/Raw galaxy_url ###
galaxy_ip = _get_ip()
# Substitute $DOCKER_HOST with real IP
url = Template(os.en... | As a Python code analyst, you investigate and solve complex coding mysteries |
Upload a list of files to the GX instance | Can you generate the documentation for the following Python 3 function
def put(filenames, file_type='auto', history_id=None):
history_id = history_id or os.environ['HISTORY_ID']
gi = get_galaxy_connection(history_id=history_id)
for filename in filenames:
log.debug('Uploading gx=%s history=%s localpa... | You are a Python code generator, capable of creating scripts from specifications. |
This function will download the file from the history and store them under the / import directory. | Can you generate a brief explanation for the following Python 3 code
def get(datasets_identifiers, identifier_type='hid', history_id=None):
history_id = history_id or os.environ['HISTORY_ID']
# The object version of bioblend is to slow in retrieving all datasets from a history
# fallback to the non-object p... | As a python code expert, you are capable of creating scripts from specifications. |
def get_user_history (history_id=None):
"""
Get all visible dataset infos of user history.
Return a list of dict of each dataset.
"""
history_id = history_id or os.environ['HISTORY_ID']
gi = get_galaxy_connection(history_id=history_id, obj=False)
hc = HistoryClient(gi)
history = h... | Write a Python 3 script for
getting all visible datasets of the user history. | You are a Python code analyst, evaluating scripts for potential improvements. |
Build an act block from a node and a test function node. | Make a summary of the following Python 3 code
def build_act(cls: Type[_Block], node: ast.stmt, test_func_node: ast.FunctionDef) -> _Block:
add_node_parents(test_func_node)
# Walk up the parent nodes of the parent node to find test's definition.
act_block_node = node
while act_block_node.... | As a python code expert, you are capable of creating scripts from specifications. |
def build_arrange(cls: Type[_Block], nodes: List[ast.stmt], max_line_number: int) -> _Block:
"""
Arrange block is all non-pass and non-docstring nodes before the Act
block start.
"""
return cls(filter_arrange_nodes(nodes, max_line_number), LineType.arrange) | Write a Python 3 function that can
build an array entry point block from a list of AST nodes. | As a python code expert, you are capable of creating scripts from specifications. |
Build an assert block from a list of nodes. | Can you generate the documentation for the following Python 3 function
def build_assert(cls: Type[_Block], nodes: List[ast.stmt], min_line_number: int) -> _Block:
return cls(filter_assert_nodes(nodes, min_line_number), LineType._assert) | As a python code expert, you are capable of creating scripts from specifications. |
Returns the span of the first line and last line of the current block. | Given the following Python 3 function, write the documentation
def get_span(self, first_line_no: int) -> Tuple[int, int]:
if not self.nodes:
raise EmptyBlock('span requested from {} block with no nodes'.format(self.line_type))
return (
get_first_token(self.nodes[0]).start[0] - fi... | As a Python code translator, you convert algorithms and pseudocode into Python. |
r A list of all the CLI class aliases. | Explain what the following Python 3 code does
def cli_aliases(self):
scripting_groups = []
aliases = {}
for cli_class in self.cli_classes:
instance = cli_class()
if getattr(instance, "alias", None):
scripting_group = getattr(instance, "scripting_group", No... | As a python code expert, you are capable of creating scripts from specifications. |
def get_flat_stats(self):
"""
:return: statistics as flat table {port/strea,/tpld name {group_stat name: value}}
"""
flat_stats = OrderedDict()
for obj, port_stats in self.statistics.items():
flat_obj_stats = OrderedDict()
for group_name, group_values in p... | Create a Python 3 function for
returning statistics as flat table | As a python code expert, you are capable of creating scripts from specifications. |
def read_stats(self):
""" Read current ports statistics from chassis.
:return: dictionary {port name {group name, {stat name: stat value}}}
"""
self.statistics = TgnObjectsDict()
for port in self.session.ports.values():
self.statistics[port] = port.read_port_stats()... | How would you code a function in Python 3 to
read current ports statistics from chassis. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def read_stats(self):
""" Read current statistics from chassis.
:return: dictionary {stream: {tx: {stat name: stat value}} rx: {tpld: {stat group {stat name: value}}}}
"""
self.tx_statistics = TgnObjectsDict()
for port in self.session.ports.values():
for stream in p... | Write a Python 3 function that can
read current statistics from chassis. | As a Python code analyst, you investigate and solve complex coding mysteries |
Read current statistics from chassis. | Explain what the following Python 3 code does
def read_stats(self):
self.statistics = TgnObjectsDict()
for port in self.session.ports.values():
for tpld in port.tplds.values():
self.statistics[tpld] = tpld.read_stats()
return self.statistics | As a Python code composer, you craft elegant and concise scripts. |
Find all user sets. | Can you generate a brief explanation for the following Python 3 code
def get_user_sets(client_id, user_id):
data = api_call('get', 'users/{}/sets'.format(user_id), client_id=client_id)
return [WordSet.from_dict(wordset) for wordset in data] | As a Python code analyst, you investigate and solve complex coding mysteries |
def print_user_sets(wordsets, print_terms):
"""Print all user sets by title. If 'print_terms', also prints all terms of all user sets.
:param wordsets: List of WordSet.
:param print_terms: If True, also prints all terms of all user sets.
"""
if not wordsets:
print('No sets found')
else:
... | How would you code a function in Python 3 to
print all user sets by title. If print_terms is True also prints all terms of all user sets. | You are a Python code generator, capable of creating scripts from specifications. |
Get all term duplicates across all user word sets as a list of
tuples. | Can you generate the documentation for the following Python 3 function
def get_common_terms(*api_envs):
common_terms = []
# pylint: disable=no-value-for-parameter
wordsets = get_user_sets(*api_envs)
# pylint: enable=no-value-for-parameter
for wordset1, wordset2 in combinations(wordsets, 2):
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Print common terms for each pair of word sets. | Given the following Python 3 function, write the documentation
def print_common_terms(common_terms):
if not common_terms:
print('No duplicates')
else:
for set_pair in common_terms:
set1, set2, terms = set_pair
print('{} and {} have in common:'.format(set1, set2))
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Delete the given term. | Can you generate the documentation for the following Python 3 function
def delete_term(set_id, term_id, access_token):
api_call('delete', 'sets/{}/terms/{}'.format(set_id, term_id), access_token=access_token) | As a python code expert, you are capable of creating scripts from specifications. |
def add_term(set_id, term, access_token):
"""Add the given term to the given set.
:param term: Instance of Term.
"""
api_call('post', 'sets/{}/terms'.format(set_id), term.to_dict(), access_token=access_token) | Write a Python 3 function for
adding the given term to the given set. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Reset the stats of a term by deleting and re - creating it. | Given the following Python 3 function, write the documentation
def reset_term_stats(set_id, term_id, client_id, user_id, access_token):
found_sets = [user_set for user_set in get_user_sets(client_id, user_id)
if user_set.set_id == set_id]
if len(found_sets) != 1:
raise ValueError('{} s... | You are a Python code generator, capable of creating scripts from specifications. |
def createController(self, key, attributes, ipmi, printer=False):
""" Function createController
Create a controller node
@param key: The host name or ID
@param attributes:The payload of the host creation
@param printer: - False for no creation progression message
... | Can you implement a function in Python 3 that
functions createController Create a controller node with the given attributes and IPMI. | As a Python code analyst, you investigate and solve complex coding mysteries |
def waitPuppetCatalogToBeApplied(self, key, sleepTime=5):
""" Function waitPuppetCatalogToBeApplied
Wait for puppet catalog to be applied
@param key: The host name or ID
@return RETURN: None
"""
# Wait for puppet catalog to be applied
loop_stop = False
wh... | How would you code a function in Python 3 to
function waitPuppetCatalogToBeApplied Wait for puppet catalog to be applied to the given key | You are a Python code analyst, evaluating scripts for potential improvements. |
def createVM(self, key, attributes, printer=False):
""" Function createVM
Create a Virtual Machine
The creation of a VM with libVirt is a bit complexe.
We first create the element in foreman, the ask to start before
the result of the creation.
To do so, we make async cal... | Implement a Python 3 function for
functioning createVM Create a Virtual Machine with the given attributes | You are a Python code analyst, evaluating scripts for potential improvements. |
def get(router, organization, email):
"""
:rtype: User
"""
log.info("Getting user: %s" % email)
resp = router.get_users(org_id=organization.id).json()
ids = [x['id'] for x in resp if x['email'] == email]
if len(ids):
user = User(organization, ids[0]).i... | Implement a Python 3 function for
getting a user from the router. | As a python code expert, you are capable of creating scripts from specifications. |
def construct(self, mapping: dict, **kwargs):
"""
Construct an object from a mapping
:param mapping: the constructor definition, with ``__type__`` name and keyword arguments
:param kwargs: additional keyword arguments to pass to the constructor
"""
assert '__type__' not ... | How would you code a function in Python 3 to
construct an object from a mapping | You are a Python code generator, capable of creating scripts from specifications. |
def load_name(absolute_name: str):
"""Load an object based on an absolute, dotted name"""
path = absolute_name.split('.')
try:
__import__(absolute_name)
except ImportError:
try:
obj = sys.modules[path[0]]
except KeyError:
... | Can you create a Python 3 function that
loads an object based on an absolute dotted name | As a Python code composer, you craft elegant and concise scripts. |
Set specified value to yaml path. | Can you tell what is the following Python 3 function doing
def patch(self, path, value=None):
# noinspection PyShadowingNames
def pathGet(dictionary, path):
for item in path.split("/"):
dictionary = dictionary[item]
return dictionary
# noinspection PyShad... | As a Python code composer, you craft elegant and concise scripts. |
A thread that waits for all the nurseries to finish and cancels all payloads. | Can you tell what is the following Python 3 function doing
async def _await_all(self):
delay = 0.0
# we run a top-level nursery that automatically reaps/cancels for us
async with trio.open_nursery() as nursery:
while self.running.is_set():
await self._start_payloads(n... | You are a Python code analyst, evaluating scripts for potential improvements. |
async def _start_payloads(self, nursery):
"""Start all queued payloads"""
with self._lock:
for coroutine in self._payloads:
nursery.start_soon(coroutine)
self._payloads.clear()
await trio.sleep(0) | How would you code a function in Python 3 to
start all queued payloads | As a Python code composer, you craft elegant and concise scripts. |
Check if longer list starts with shorter list | Explain what the following Python 3 code does
def contains_list(longer, shorter):
if len(longer) <= len(shorter):
return False
for a, b in zip(shorter, longer):
if a != b:
return False
return True | As a Python code analyst, you investigate and solve complex coding mysteries |
def load(f, dict_=dict):
"""Load and parse toml from a file object
An additional argument `dict_` is used to specify the output type
"""
if not f.read:
raise ValueError('The first parameter needs to be a file object, ',
'%r is passed' % type(f))
return loads(f.read()... | Write a Python 3 function for
loading and parse toml from a file object | You are a Python code architect, reviewing and designing scalable and efficient code |
Parse a toml string
| Make a summary of the following Python 3 code
def loads(content, dict_=dict):
if not isinstance(content, basestring):
raise ValueError('The first parameter needs to be a string object, ',
'%r is passed' % type(content))
decoder = Decoder(content, dict_)
decoder.parse()
r... | As a python code expert, you are capable of creating scripts from specifications. |
def convert(self, line=None, is_end=True):
"""Read the line content and return the converted value
:param line: the line to feed to converter
:param is_end: if set to True, will raise an error if
the line has something remaining.
"""
if line is not None:
self... | Can you implement a function in Python 3 that
reads the line content and return the converted value. | You are a Python code analyst, evaluating scripts for potential improvements. |
Parse the lines from the index i
ova. | Can you generate the documentation for the following Python 3 function
def parse(self, data=None, table_name=None):
temp = self.dict_()
sub_table = None
is_array = False
line = ''
while True:
line = self._readline()
if not line:
self._store... | As a Python code analyst, you investigate and solve complex coding mysteries |
def split_string(self, string, splitter='.', allow_empty=True):
"""Split the string with respect of quotes"""
i = 0
rv = []
need_split = False
while i < len(string):
m = re.compile(_KEY_NAME).match(string, i)
if not need_split and m:
i = m.... | Can you implement a function in Python 3 that
splits the string with respect of quotes | You are a Python code analyst, evaluating scripts for potential improvements. |
Transform a source string into a list of tokens. | Can you generate the documentation for the following Python 3 function
def transform_source(text):
'''removes a "where" clause which is identified by the use of "where"
as an identifier and ends at the first DEDENT (i.e. decrease in indentation)'''
toks = tokenize.generate_tokens(StringIO(text).readline)
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def is_visible(self):
"""
Return a boolean if the page is visible in navigation.
Pages must have show in navigation set. Regular pages must be published (published and
have a current version - checked with `is_published`), pages with a glitter app associated
don't need any page ... | Create a Python 3 function for
returning a boolean if the page is visible in navigation. | You are a Python code generator, capable of creating scripts from specifications. |
def build_node_tree(self, source_paths):
"""
Build a node tree.
"""
import uqbar.apis
root = PackageNode()
# Build node tree, top-down
for source_path in sorted(
source_paths, key=lambda x: uqbar.apis.source_path_to_package_path(x)
):
... | Write a Python 3 function that can
build a node tree from a list of source paths. | As a python code expert, you are capable of creating scripts from specifications. |
Validate that the fields are unique. | Can you tell what is the following Python 3 function doing
def validate_unique(self):
unique_checks, date_checks = self.instance._get_unique_checks(exclude=[])
errors = self.instance._perform_unique_checks(unique_checks)
if errors:
self.add_error(None, errors) | As a Python code translator, you convert algorithms and pseudocode into Python. |
def prepare_monitor(tenant=tenant, user=user, password=password, organization=organization, zone_name=zone_name):
"""
:param tenant: tenant url
:param user: user's email
:param password: user's password
:param zone_name: (optional) zone_name
:return:
"""
router = PrivatePath(tenant, veri... | Write a Python 3 function for
preparing the Monkey Management Service for the tenant. | You are a Python code analyst, evaluating scripts for potential improvements. |
def launch(self, timeout=2):
"""
Hierapp instance, with environment dependencies:
- can be launched within short timeout
- auto-destroys shortly
"""
self.start_time = time.time()
self.end_time = time.time()
instance = self.app.launch(environment=self.env)
... | Can you write a function in Python 3 where it
launches the Hierapp instance and update the status attribute | You are a Python code architect, reviewing and designing scalable and efficient code |
def clone(self):
"""
Do not initialize again since everything is ready to launch app.
:return: Initialized monitor instance
"""
return Monitor(org=self.org, app=self.app, env=self.env) | Implement a function in Python 3 to
clone the current instance of the Monitor. | As a python code expert, you are capable of creating scripts from specifications. |
Create Image from raw dictionary data. | Here you have a function in Python 3, explain what it does
def from_dict(raw_data):
url = None
width = None
height = None
try:
url = raw_data['url']
width = raw_data['width']
height = raw_data['height']
except KeyError:
raise ValueE... | As a Python code analyst, you investigate and solve complex coding mysteries |
def to_dict(self):
"""Convert Image into raw dictionary data."""
if not self.url:
return None
return {
'url': self.url,
'width': self.width,
'height': self.height
} | Can you implement a function in Python 3 that
converts Image into raw dictionary data. | As a Python code analyst, you investigate and solve complex coding mysteries |
Create Term from raw dictionary data. | How would you explain what the following Python 3 function does
def from_dict(raw_data):
try:
definition = raw_data['definition']
term_id = raw_data['id']
image = Image.from_dict(raw_data['image'])
rank = raw_data['rank']
term = raw_data['term']
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Convert Term into raw dictionary data. | Can you generate the documentation for the following Python 3 function
def to_dict(self):
return {
'definition': self.definition,
'id': self.term_id,
'image': self.image.to_dict(),
'rank': self.rank,
'term': self.term
} | You are a Python code analyst, evaluating scripts for potential improvements. |
Return set of common words between two word sets. | Make a summary of the following Python 3 code
def has_common(self, other):
if not isinstance(other, WordSet):
raise ValueError('Can compare only WordSets')
return self.term_set & other.term_set | As a Python code analyst, you investigate and solve complex coding mysteries |
Create WordSet from raw dictionary data. | How would you explain what the following Python 3 function does
def from_dict(raw_data):
try:
set_id = raw_data['id']
title = raw_data['title']
terms = [Term.from_dict(term) for term in raw_data['terms']]
return WordSet(set_id, title, terms)
except KeyErro... | You are a Python code analyst, evaluating scripts for potential improvements. |
Convert WordSet into raw dictionary data. | Can you generate the documentation for the following Python 3 function
def to_dict(self):
return {
'id': self.set_id,
'title': self.title,
'terms': [term.to_dict() for term in self.terms]
} | You are a Python code architect, reviewing and designing scalable and efficient code |
Create a new release in github | Given the following Python 3 function, write the documentation
def release(ctx, yes, latest):
m = RepoManager(ctx.obj['agile'])
api = m.github_repo()
if latest:
latest = api.releases.latest()
if latest:
click.echo(latest['tag_name'])
elif m.can_release('sandbox'):
bra... | As a python code expert, you are capable of creating scripts from specifications. |
Hooks into Sphinx s builder - inited event. | Can you generate the documentation for the following Python 3 function
def on_builder_inited(app):
app.cache_db_path = ":memory:"
if app.config["uqbar_book_use_cache"]:
logger.info(bold("[uqbar-book]"), nonl=True)
logger.info(" initializing cache db")
app.connection = uqbar.book.sphinx.c... | As a python code expert, you are capable of creating scripts from specifications. |
def on_config_inited(app, config):
"""
Hooks into Sphinx's ``config-inited`` event.
"""
extension_paths = config["uqbar_book_extensions"] or [
"uqbar.book.extensions.GraphExtension"
]
app.uqbar_book_extensions = []
for extension_path in extension_paths:
module_name, _, class_... | How would you implement a function in Python 3 that
hooks into Sphinx s config - inited event. | You are a Python code analyst, evaluating scripts for potential improvements. |
def on_doctree_read(app, document):
"""
Hooks into Sphinx's ``doctree-read`` event.
"""
literal_blocks = uqbar.book.sphinx.collect_literal_blocks(document)
cache_mapping = uqbar.book.sphinx.group_literal_blocks_by_cache_path(literal_blocks)
node_mapping = {}
use_cache = bool(app.config["uqba... | Write a Python 3 function that can
hook into Sphinx s doctree - read event. | As a Python code composer, you craft elegant and concise scripts. |
Hooks into Sphinx s build - finished event. | Can you generate the documentation for the following Python 3 function
def on_build_finished(app, exception):
if not app.config["uqbar_book_use_cache"]:
return
logger.info("")
for row in app.connection.execute("SELECT path, hits FROM cache ORDER BY path"):
path, hits = row
if not hit... | You are a Python code analyst, evaluating scripts for potential improvements. |
def handle_class(signature_node, module, object_name, cache):
"""
Styles ``autoclass`` entries.
Adds ``abstract`` prefix to abstract classes.
"""
class_ = getattr(module, object_name, None)
if class_ is None:
return
if class_ not in cache:
cache[class_] = {}
attribut... | How would you code a function in Python 3 to
style ``autoclass`` entries. Adds ``abstract`` prefix to abstract classes. | As a Python code analyst, you investigate and solve complex coding mysteries |
Handles the method signature node. | Can you tell what is the following Python 3 function doing
def handle_method(signature_node, module, object_name, cache):
*class_names, attr_name = object_name.split(".") # Handle nested classes
class_ = module
for class_name in class_names:
class_ = getattr(class_, class_name, None)
if cla... | As a Python code composer, you craft elegant and concise scripts. |
def on_doctree_read(app, document):
"""
Hooks into Sphinx's ``doctree-read`` event.
"""
cache: Dict[type, Dict[str, object]] = {}
for desc_node in document.traverse(addnodes.desc):
if desc_node.get("domain") != "py":
continue
signature_node = desc_node.traverse(addnodes.d... | Write a Python 3 function for
hooking into Sphinx s doctree - read event. | As a Python code composer, you craft elegant and concise scripts. |
def on_builder_inited(app):
"""
Hooks into Sphinx's ``builder-inited`` event.
Used for copying over CSS files to theme directory.
"""
local_css_path = pathlib.Path(__file__).parent / "uqbar.css"
theme_css_path = (
pathlib.Path(app.srcdir) / app.config.html_static_path[0] / "uqbar.css"
... | Can you create a Python 3 function that
hooks into Sphinx s builder - inited event. | As a Python code composer, you craft elegant and concise scripts. |
Sets up Sphinx extension. | Explain what the following Python 3 code does
def setup(app) -> Dict[str, Any]:
app.connect("doctree-read", on_doctree_read)
app.connect("builder-inited", on_builder_inited)
app.add_css_file("uqbar.css")
app.add_node(
nodes.classifier, override=True, html=(visit_classifier, depart_classifier)
... | As a Python code composer, you craft elegant and concise scripts. |
Create XenaManager object.
:param api: cli/rest
:param logger: python logger
:param owner: owner of the scripting session
:param ip: rest server IP
:param port: rest server TCP port
:return: Xena object
:rtype: XenaApp | Explain what the following Python 3 code does
def init_xena(api, logger, owner, ip=None, port=57911):
if api == ApiType.socket:
api_wrapper = XenaCliWrapper(logger)
elif api == ApiType.rest:
api_wrapper = XenaRestWrapper(logger, ip, port)
return XenaApp(logger, owner, api_wrapper) | As a python code expert, you are capable of creating scripts from specifications. |
Add chassis to the list of chassis. | Make a summary of the following Python 3 code
def add_chassis(self, chassis, port=22611, password='xena'):
if chassis not in self.chassis_list:
try:
XenaChassis(self, chassis, port, password)
except Exception as error:
self.objects.pop('{}/{}'.format(self... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Get inventory for all chassis. | Explain what the following Python 3 code does
def inventory(self):
for chassis in self.chassis_list.values():
chassis.inventory(modules_inventory=True) | As a Python code translator, you convert algorithms and pseudocode into Python. |
Reserve ports and reset factory defaults. | Given the following Python 3 function, write the documentation
def reserve_ports(self, locations, force=False, reset=True):
for location in locations:
ip, module, port = location.split('/')
self.chassis_list[ip].reserve_ports(['{}/{}'.format(module, port)], force, reset)
return... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Start traffic on list of ports. | Can you generate the documentation for the following Python 3 function
def start_traffic(self, blocking=False, *ports):
for chassis, chassis_ports in self._per_chassis_ports(*self._get_operation_ports(*ports)).items():
chassis.start_traffic(False, *chassis_ports)
if blocking:
fo... | You are a Python code analyst, evaluating scripts for potential improvements. |
Stop traffic on list of ports. | Here you have a function in Python 3, explain what it does
def stop_traffic(self, *ports):
for chassis, chassis_ports in self._per_chassis_ports(*self._get_operation_ports(*ports)).items():
chassis.stop_traffic(*chassis_ports) | As a Python code translator, you convert algorithms and pseudocode into Python. |
def ports(self):
"""
:return: dictionary {name: object} of all ports.
"""
ports = {}
for chassis in self.chassis_list.values():
ports.update({str(p): p for p in chassis.get_objects_by_type('port')})
return ports | Implement a function in Python 3 to
return a dictionary of all ports. | You are a Python code generator, capable of creating scripts from specifications. |
def inventory(self, modules_inventory=False):
""" Get chassis inventory.
:param modules_inventory: True - read modules inventory, false - don't read.
"""
self.c_info = self.get_attributes()
for m_index, m_portcounts in enumerate(self.c_info['c_portcounts'].split()):
... | Write a Python 3 script for
getting chassis inventory. :param modules_inventory: True - read modules inventory, false - don't read. | You are a Python code analyst, evaluating scripts for potential improvements. |
Reserve ports and reset ports factory defaults. | Can you generate the documentation for the following Python 3 function
def reserve_ports(self, locations, force=False, reset=True):
for location in locations:
port = XenaPort(parent=self, index=location)
port.reserve(force)
if reset:
port.reset()
ret... | You are a Python code analyst, evaluating scripts for potential improvements. |
def start_traffic(self, blocking=False, *ports):
""" Start traffic on list of ports.
:param blocking: True - start traffic and wait until traffic ends, False - start traffic and return.
:param ports: list of ports to start traffic on. Default - all session ports.
"""
self._traf... | Write a Python 3 function for
starting traffic on list of ports. | 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.