text_prompt stringlengths 100 17.7k ⌀ | code_prompt stringlengths 7 9.86k ⌀ |
|---|---|
<SYSTEM_TASK:>
Execute all current and future payloads
<END_TASK>
<USER_TASK:>
Description:
def run(self):
"""
Execute all current and future payloads
Blocks and executes payloads until :py:meth:`stop` is called.
It is an error for any orphaned payload to return or raise.
""" |
self._logger.info('runner started: %s', self)
try:
with self._lock:
assert not self.running.is_set() and self._stopped.is_set(), 'cannot re-run: %s' % self
self.running.set()
self._stopped.clear()
self._run()
except Excepti... |
<SYSTEM_TASK:>
Stop execution of all current and future payloads
<END_TASK>
<USER_TASK:>
Description:
def stop(self):
"""Stop execution of all current and future payloads""" |
if not self.running.wait(0.2):
return
self._logger.debug('runner disabled: %s', self)
with self._lock:
self.running.clear()
self._stopped.wait() |
<SYSTEM_TASK:>
Delimit a string at word boundaries.
<END_TASK>
<USER_TASK:>
Description:
def delimit_words(string: str) -> Generator[str, None, None]:
"""
Delimit a string at word boundaries.
::
>>> import uqbar.strings
>>> list(uqbar.strings.delimit_words("i want to believe"))
['i... |
# TODO: Reimplement this
wordlike_characters = ("<", ">", "!")
current_word = ""
for i, character in enumerate(string):
if (
not character.isalpha()
and not character.isdigit()
and character not in wordlike_characters
):
if current_word:
... |
<SYSTEM_TASK:>
Normalizes whitespace.
<END_TASK>
<USER_TASK:>
Description:
def normalize(string: str) -> str:
"""
Normalizes whitespace.
Strips leading and trailing blank lines, dedents, and removes trailing
whitespace from the result.
""" |
string = string.replace("\t", " ")
lines = string.split("\n")
while lines and (not lines[0] or lines[0].isspace()):
lines.pop(0)
while lines and (not lines[-1] or lines[-1].isspace()):
lines.pop()
for i, line in enumerate(lines):
lines[i] = line.rstrip()
string = "\n"... |
<SYSTEM_TASK:>
Converts the input value into the expected Python data type, raising
<END_TASK>
<USER_TASK:>
Description:
def to_python(self, value):
"""
Converts the input value into the expected Python data type, raising
django.core.exceptions.ValidationError if the data can't be converted.
... |
assert isinstance(value, list)
# convert every value in list
value = list(value)
for i, v in enumerate(value):
value[i] = self.value_to_python(v)
# return result
return value |
<SYSTEM_TASK:>
Get data for this component
<END_TASK>
<USER_TASK:>
Description:
def get(self, id):
"""Get data for this component
""" |
id = self.as_id(id)
url = '%s/%s' % (self, id)
response = self.http.get(url, auth=self.auth)
response.raise_for_status()
return response.json() |
<SYSTEM_TASK:>
Delete a component by id
<END_TASK>
<USER_TASK:>
Description:
def delete(self, id):
"""Delete a component by id
""" |
id = self.as_id(id)
response = self.http.delete(
'%s/%s' % (self.api_url, id),
auth=self.auth)
response.raise_for_status() |
<SYSTEM_TASK:>
Returns a boolean if the user in the request has edit permission for the object.
<END_TASK>
<USER_TASK:>
Description:
def has_edit_permission(self, request, obj=None, version=None):
"""
Returns a boolean if the user in the request has edit permission for the object.
Can also be p... |
# Has the edit permission for this object type
permission_name = '{}.edit_{}'.format(self.opts.app_label, self.opts.model_name)
has_permission = request.user.has_perm(permission_name)
if obj is not None and has_permission is False:
has_permission = request.user.has_perm(per... |
<SYSTEM_TASK:>
Returns a boolean if the user in the request has publish permission for the object.
<END_TASK>
<USER_TASK:>
Description:
def has_publish_permission(self, request, obj=None):
"""
Returns a boolean if the user in the request has publish permission for the object.
""" |
permission_name = '{}.publish_{}'.format(self.opts.app_label, self.opts.model_name)
has_permission = request.user.has_perm(permission_name)
if obj is not None and has_permission is False:
has_permission = request.user.has_perm(permission_name, obj=obj)
return has_permissio... |
<SYSTEM_TASK:>
Function getParam
<END_TASK>
<USER_TASK:>
Description:
def getParam(self, name=None):
""" Function getParam
Return a dict of parameters or a parameter value
@param key: The parameter name
@return RETURN: dict of parameters or a parameter value
""" |
if 'parameters' in self.keys():
l = {x['name']: x['value'] for x in self['parameters'].values()}
if name:
if name in l.keys():
return l[name]
else:
return False
else:
return l |
<SYSTEM_TASK:>
Return a list of form choices for versions of this object which can be published.
<END_TASK>
<USER_TASK:>
Description:
def object_version_choices(obj):
"""
Return a list of form choices for versions of this object which can be published.
""" |
choices = BLANK_CHOICE_DASH + [(PublishAction.UNPUBLISH_CHOICE, 'Unpublish current version')]
# When creating a new object in the Django admin - obj will be None
if obj is not None:
saved_versions = Version.objects.filter(
content_type=ContentType.objects.get_for_model(obj),
... |
<SYSTEM_TASK:>
Set packet header.
<END_TASK>
<USER_TASK:>
Description:
def set_packet_headers(self, headers):
""" Set packet header.
The method will try to set ps_headerprotocol to inform the Xena GUI and tester how to interpret the packet
header byte sequence specified with PS_PACKETHEADER.
... |
bin_headers = '0x' + binascii.hexlify(headers.bin()).decode('utf-8')
self.set_attributes(ps_packetheader=bin_headers)
body_handler = headers
ps_headerprotocol = []
while body_handler:
segment = pypacker_2_xena.get(str(body_handler).split('(')[0].lower(), None)
... |
<SYSTEM_TASK:>
Get a column for given column name from META api.
<END_TASK>
<USER_TASK:>
Description:
def get_column_name(self, column_name):
""" Get a column for given column name from META api. """ |
name = pretty_name(column_name)
if column_name in self._meta.columns:
column_cls = self._meta.columns[column_name]
if column_cls.verbose_name:
name = column_cls.verbose_name
return name |
<SYSTEM_TASK:>
Software version of the current repository
<END_TASK>
<USER_TASK:>
Description:
def version(self):
"""Software version of the current repository
""" |
branches = self.branches()
if self.info['branch'] == branches.sandbox:
try:
return self.software_version()
except Exception as exc:
raise utils.CommandError(
'Could not obtain repo version, do you have a makefile '
... |
<SYSTEM_TASK:>
Validate version by checking if it is a valid semantic version
<END_TASK>
<USER_TASK:>
Description:
def validate_version(self, prefix='v'):
"""Validate version by checking if it is a valid semantic version
and its value is higher than latest github tag
""" |
version = self.software_version()
repo = self.github_repo()
repo.releases.validate_tag(version, prefix)
return version |
<SYSTEM_TASK:>
Check if build should be skipped
<END_TASK>
<USER_TASK:>
Description:
def skip_build(self):
"""Check if build should be skipped
""" |
skip_msg = self.config.get('skip', '[ci skip]')
return (
os.environ.get('CODEBUILD_BUILD_SUCCEEDING') == '0' or
self.info['current_tag'] or
skip_msg in self.info['head']['message']
) |
<SYSTEM_TASK:>
Send a message to third party applications
<END_TASK>
<USER_TASK:>
Description:
def message(self, msg):
"""Send a message to third party applications
""" |
for broker in self.message_brokers:
try:
broker(msg)
except Exception as exc:
utils.error(exc) |
<SYSTEM_TASK:>
Returns single object attribute.
<END_TASK>
<USER_TASK:>
Description:
def get_attribute(self, obj, attribute):
""" Returns single object attribute.
:param obj: requested object.
:param attribute: requested attribute to query.
:returns: returned value.
:rtype: str
... |
raw_return = self.send_command_return(obj, attribute, '?')
if len(raw_return) > 2 and raw_return[0] == '"' and raw_return[-1] == '"':
return raw_return[1:-1]
return raw_return |
<SYSTEM_TASK:>
Iterate depth-first.
<END_TASK>
<USER_TASK:>
Description:
def depth_first(self, top_down=True):
"""
Iterate depth-first.
::
>>> from uqbar.containers import UniqueTreeContainer, UniqueTreeNode
>>> root_container = UniqueTreeContainer(name="root")
... |
for child in tuple(self):
if top_down:
yield child
if isinstance(child, UniqueTreeContainer):
yield from child.depth_first(top_down=top_down)
if not top_down:
yield child |
<SYSTEM_TASK:>
Load configuration file from xpc file.
<END_TASK>
<USER_TASK:>
Description:
def load_config(self, config_file_name):
""" Load configuration file from xpc file.
:param config_file_name: full path to the configuration file.
""" |
with open(config_file_name) as f:
commands = f.read().splitlines()
for command in commands:
if not command.startswith(';'):
try:
self.send_command(command)
except XenaCommandException as e:
self.logger.war... |
<SYSTEM_TASK:>
Save configuration file to xpc file.
<END_TASK>
<USER_TASK:>
Description:
def save_config(self, config_file_name):
""" Save configuration file to xpc file.
:param config_file_name: full path to the configuration file.
""" |
with open(config_file_name, 'w+') as f:
f.write('P_RESET\n')
for line in self.send_command_return_multilines('p_fullconfig', '?'):
f.write(line.split(' ', 1)[1].lstrip()) |
<SYSTEM_TASK:>
Add stream.
<END_TASK>
<USER_TASK:>
Description:
def add_stream(self, name=None, tpld_id=None, state=XenaStreamState.enabled):
""" Add stream.
:param name: stream description.
:param tpld_id: TPLD ID. If None the a unique value will be set.
:param state: new stream state.... |
stream = XenaStream(parent=self, index='{}/{}'.format(self.index, len(self.streams)), name=name)
stream._create()
tpld_id = tpld_id if tpld_id else XenaStream.next_tpld_id
stream.set_attributes(ps_comment='"{}"'.format(stream.name), ps_tpldid=tpld_id)
XenaStream.next_tpld_id = ... |
<SYSTEM_TASK:>
Get captured packets from chassis.
<END_TASK>
<USER_TASK:>
Description:
def get_packets(self, from_index=0, to_index=None, cap_type=XenaCaptureBufferType.text,
file_name=None, tshark=None):
""" Get captured packets from chassis.
:param from_index: index of first packe... |
to_index = to_index if to_index else len(self.packets)
raw_packets = []
for index in range(from_index, to_index):
raw_packets.append(self.packets[index].get_attribute('pc_packet').split('0x')[1])
if cap_type == XenaCaptureBufferType.raw:
self._save_captue(file... |
<SYSTEM_TASK:>
Register a new rule above a given ``supply`` threshold
<END_TASK>
<USER_TASK:>
Description:
def add(self, rule: ControlRule = None, *, supply: float):
"""
Register a new rule above a given ``supply`` threshold
Registration supports a single-argument form for use as a decorator,
... |
if supply in self._thresholds:
raise ValueError('rule for threshold %s re-defined' % supply)
if rule is not None:
self.rules.append((supply, rule))
self._thresholds.add(supply)
return rule
else:
return partial(self.add, supply=supply) |
<SYSTEM_TASK:>
Generate changes object for ldap object.
<END_TASK>
<USER_TASK:>
Description:
def changeset(python_data: LdapObject, d: dict) -> Changeset:
""" Generate changes object for ldap object. """ |
table: LdapObjectClass = type(python_data)
fields = table.get_fields()
changes = Changeset(fields, src=python_data, d=d)
return changes |
<SYSTEM_TASK:>
Convert a LdapChanges object to a modlist for add operation.
<END_TASK>
<USER_TASK:>
Description:
def _python_to_mod_new(changes: Changeset) -> Dict[str, List[List[bytes]]]:
""" Convert a LdapChanges object to a modlist for add operation. """ |
table: LdapObjectClass = type(changes.src)
fields = table.get_fields()
result: Dict[str, List[List[bytes]]] = {}
for name, field in fields.items():
if field.db_field:
try:
value = field.to_db(changes.get_value_as_list(name))
if len(value) > 0:
... |
<SYSTEM_TASK:>
Convert a LdapChanges object to a modlist for a modify operation.
<END_TASK>
<USER_TASK:>
Description:
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]]]] = {}
for key, l in changes.items():
field = _get_field_by_name(table, key)
if field.db_field:
try:
new_list = [
(... |
<SYSTEM_TASK:>
Search for a object of given type in the database.
<END_TASK>
<USER_TASK:>
Description:
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 da... |
fields = table.get_fields()
db_fields = {
name: field
for name, field in fields.items()
if field.db_field
}
database = get_database(database)
connection = database.connection
search_options = table.get_search_options(database)
iterator = tldap.query.search(
... |
<SYSTEM_TASK:>
Get exactly one result from the database or fail.
<END_TASK>
<USER_TASK:>
Description:
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, query, database, base_dn)
try:
result = next(results)
except StopIteration:
raise ObjectDoesNotExist(f"Cannot find result for {query}.")
try:
next(results)
raise MultipleObjectsReturned(f"Found multiple results for {query}.")
except StopIter... |
<SYSTEM_TASK:>
Preload all NotLoaded fields in LdapObject.
<END_TASK>
<USER_TASK:>
Description:
def preload(python_data: LdapObject, database: Optional[Database] = None) -> LdapObject:
""" Preload all NotLoaded fields in LdapObject. """ |
changes = {}
# Load objects within lists.
def preload_item(value: Any) -> Any:
if isinstance(value, NotLoaded):
return value.load(database)
else:
return value
for name in python_data.keys():
value_list = python_data.get_as_list(name)
# Check f... |
<SYSTEM_TASK:>
Insert a new python_data object in the database.
<END_TASK>
<USER_TASK:>
Description:
def insert(python_data: LdapObject, database: Optional[Database] = None) -> LdapObject:
""" Insert a new python_data object in the database. """ |
assert isinstance(python_data, LdapObject)
table: LdapObjectClass = type(python_data)
# ADD NEW ENTRY
empty_data = table()
changes = changeset(empty_data, python_data.to_dict())
return save(changes, database) |
<SYSTEM_TASK:>
Save all changes in a LdapChanges.
<END_TASK>
<USER_TASK:>
Description:
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)
connection = database.connection
table = type(changes._src)
# Run hooks on changes
changes = table.on_save(changes, data... |
<SYSTEM_TASK:>
Delete a LdapObject from the database.
<END_TASK>
<USER_TASK:>
Description:
def delete(python_data: LdapObject, database: Optional[Database] = None) -> None:
""" Delete a LdapObject from the database. """ |
dn = python_data.get_as_single('dn')
assert dn is not None
database = get_database(database)
connection = database.connection
connection.delete(dn) |
<SYSTEM_TASK:>
Lookup a field by its name.
<END_TASK>
<USER_TASK:>
Description:
def _get_field_by_name(table: LdapObjectClass, name: str) -> tldap.fields.Field:
""" Lookup a field by its name. """ |
fields = table.get_fields()
return fields[name] |
<SYSTEM_TASK:>
return a dictionary with all items of l being the keys of the dictionary
<END_TASK>
<USER_TASK:>
Description:
def _list_dict(l: Iterator[str], case_insensitive: bool = False):
"""
return a dictionary with all items of l being the keys of the dictionary
If argument case_insensitive is non-zer... |
if case_insensitive:
raise NotImplementedError()
d = tldap.dict.CaseInsensitiveDict()
else:
d = {}
for i in l:
d[i] = None
return d |
<SYSTEM_TASK:>
Convert the rdn to a fully qualified DN for the specified LDAP
<END_TASK>
<USER_TASK:>
Description:
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 lo... |
dn = changes.get_value_as_single('dn')
if dn is not None:
return changes
value = changes.get_value_as_single(name)
if value is None:
raise tldap.exceptions.ValidationError(
"Cannot use %s in dn as it is None" % name)
if isinstance(value, list):
raise tldap.excep... |
<SYSTEM_TASK:>
Loads up the given survey in the given dir.
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Return the choices in string form.
<END_TASK>
<USER_TASK:>
Description:
def format_choices(self):
"""Return the choices in string form.""" |
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) |
<SYSTEM_TASK:>
Validate user's answer against available choices.
<END_TASK>
<USER_TASK:>
Description:
def is_answer_valid(self, ans):
"""Validate user's answer against available choices.""" |
return ans in [str(i+1) for i in range(len(self.choices))] |
<SYSTEM_TASK:>
Return the vector for this survey.
<END_TASK>
<USER_TASK:>
Description:
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])
vec[dim] = dict(dim_vec)
return vec |
<SYSTEM_TASK:>
Updates line types for a block's span.
<END_TASK>
<USER_TASK:>
Description:
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.
... |
first_block_line, last_block_line = span
for i in range(first_block_line, last_block_line + 1):
try:
self.__setitem__(i, line_type)
except ValueError as error:
raise ValidationError(i + self.fn_offset, 1, 'AAA99 {}'.format(error)) |
<SYSTEM_TASK:>
Checks there is a clear single line between ``first_block_type`` and
<END_TASK>
<USER_TASK:>
Description:
def check_block_spacing(
self,
first_block_type: LineType,
second_block_type: LineType,
error_message: str,
) -> typing.Generator[AAAError, None, None]:
""... |
numbered_lines = list(enumerate(self))
first_block_lines = filter(lambda l: l[1] is first_block_type, numbered_lines)
try:
first_block_lineno = list(first_block_lines)[-1][0]
except IndexError:
# First block has no lines
return
second_block_l... |
<SYSTEM_TASK:>
Given 2 vectors of multiple dimensions, calculate the euclidean
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Function list
<END_TASK>
<USER_TASK:>
Description:
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,
self.parentKey,
self.objName,
),
limit=limit)
... |
<SYSTEM_TASK:>
Build a repr string for ``expr`` from its vars and signature.
<END_TASK>
<USER_TASK:>
Description:
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, ... |
signature = _get_object_signature(expr)
if signature is None:
return "{}()".format(type(expr).__name__)
defaults = {}
for name, parameter in signature.parameters.items():
if parameter.default is not inspect._empty:
defaults[name] = parameter.default
args, var_args, kwa... |
<SYSTEM_TASK:>
Get ``args``, ``var args`` and ``kwargs`` for an object ``expr``.
<END_TASK>
<USER_TASK:>
Description:
def get_vars(expr):
"""
Get ``args``, ``var args`` and ``kwargs`` for an object ``expr``.
::
>>> class MyObject:
... def __init__(self, arg1, arg2, *var_args, foo=None,... |
# print('TYPE?', type(expr))
signature = _get_object_signature(expr)
if signature is None:
return ({}, [], {})
# print('SIG?', signature)
args = collections.OrderedDict()
var_args = []
kwargs = {}
if expr is None:
return args, var_args, kwargs
for i, (name, parameter... |
<SYSTEM_TASK:>
Find all the Glitter App configurations in the current project.
<END_TASK>
<USER_TASK:>
Description:
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_module(module_name)
if hasattr(glitter_apps_module, 'apps'):
self.glitter_apps.update(glitter_... |
<SYSTEM_TASK:>
Schedules this publish action as a Celery task.
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Get the version object for the related object.
<END_TASK>
<USER_TASK:>
Description:
def get_version(self):
"""
Get the version object for the related object.
""" |
return Version.objects.get(
content_type=self.content_type,
object_id=self.object_id,
version_number=self.publish_version,
) |
<SYSTEM_TASK:>
Process a publish action on the related object, returns a boolean if a change is made.
<END_TASK>
<USER_TASK:>
Description:
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... |
obj = self.content_object
version = self.get_version()
actioned = False
# Only update if needed
if obj.current_version != version:
version = self.get_version()
obj.current_version = version
obj.save(update_fields=['current_version'])
... |
<SYSTEM_TASK:>
Process an unpublish action on the related object, returns a boolean if a change is made.
<END_TASK>
<USER_TASK:>
Description:
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 ve... |
obj = self.content_object
actioned = False
# Only update if needed
if obj.current_version is not None:
obj.current_version = None
obj.save(update_fields=['current_version'])
actioned = True
return actioned |
<SYSTEM_TASK:>
Adds a log entry for this action to the object history in the Django admin.
<END_TASK>
<USER_TASK:>
Description:
def _log_action(self):
"""
Adds a log entry for this action to the object history in the Django admin.
""" |
if self.publish_version == self.UNPUBLISH_CHOICE:
message = 'Unpublished page (scheduled)'
else:
message = 'Published version {} (scheduled)'.format(self.publish_version)
LogEntry.objects.log_action(
user_id=self.user.pk,
content_type_id=self.con... |
<SYSTEM_TASK:>
Process the action and update the related object, returns a boolean if a change is made.
<END_TASK>
<USER_TASK:>
Description:
def process_action(self):
"""
Process the action and update the related object, returns a boolean if a change is made.
""" |
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_action()
return actioned |
<SYSTEM_TASK:>
Function checkAndCreate
<END_TASK>
<USER_TASK:>
Description:
def checkAndCreate(self, key, payload,
hostgroupConf,
hostgroupParent,
puppetClassesId):
""" Function checkAndCreate
check And Create procedure for an hostgrou... |
if key not in self:
self[key] = payload
oid = self[key]['id']
if not oid:
return False
# Create Hostgroup classes
if 'classes' in hostgroupConf.keys():
classList = list()
for c in hostgroupConf['classes']:
classLis... |
<SYSTEM_TASK:>
A decorator which can be used to mark functions
<END_TASK>
<USER_TASK:>
Description:
def deprecated(func, msg=None):
"""
A decorator which can be used to mark functions
as deprecated.It will result in a deprecation warning being shown
when the function is used.
""" |
message = msg or "Use of deprecated function '{}`.".format(func.__name__)
@functools.wraps(func)
def wrapper_func(*args, **kwargs):
warnings.warn(message, DeprecationWarning, stacklevel=2)
return func(*args, **kwargs)
return wrapper_func |
<SYSTEM_TASK:>
Initialise basic logging facilities
<END_TASK>
<USER_TASK:>
Description:
def initialise_logging(level: str, target: str, short_format: bool):
"""Initialise basic logging facilities""" |
try:
log_level = getattr(logging, level)
except AttributeError:
raise SystemExit(
"invalid log level %r, expected any of 'DEBUG', 'INFO', 'WARNING', 'ERROR' or 'CRITICAL'" % level
)
handler = create_handler(target=target)
logging.basicConfig(
level=log_level,... |
<SYSTEM_TASK:>
Crate or update labels in github
<END_TASK>
<USER_TASK:>
Description:
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 isinstance(labels, dict):
raise CommandError(
... |
<SYSTEM_TASK:>
Send a request to the Minut Point API.
<END_TASK>
<USER_TASK:>
Description:
def _request(self, url, request_type='GET', **params):
"""Send a request to the Minut Point API.""" |
try:
_LOGGER.debug('Request %s %s', url, params)
response = self.request(
request_type, url, timeout=TIMEOUT.seconds, **params)
response.raise_for_status()
_LOGGER.debug('Response %s %s %.200s', response.status_code,
resp... |
<SYSTEM_TASK:>
Request list of devices.
<END_TASK>
<USER_TASK:>
Description:
def _request_devices(self, url, _type):
"""Request list of devices.""" |
res = self._request(url)
return res.get(_type) if res else {} |
<SYSTEM_TASK:>
Template tag which renders the glitter CSS and JavaScript. Any resources
<END_TASK>
<USER_TASK:>
Description:
def glitter_head(context):
"""
Template tag which renders the glitter CSS and JavaScript. Any resources
which need to be loaded should be added here. This is only shown to users
w... |
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(context)
return rendered |
<SYSTEM_TASK:>
Template tag which renders the glitter overlay and sidebar. This is only
<END_TASK>
<USER_TASK:>
Description:
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'
rendered = ''
if user is not None and user.is_staff:
templates = [path_body]
# We've got a page with a glitter object:
# - May need a different startbo... |
<SYSTEM_TASK:>
Replace all special characters found in assertion_value
<END_TASK>
<USER_TASK:>
Description:
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 R... |
if isinstance(assertion_value, six.text_type):
assertion_value = assertion_value.encode("utf_8")
s = []
for c in assertion_value:
do_escape = False
if str != bytes: # Python 3
pass
else: # Python 2
c = ord(c)
if escape_mode == 0:
... |
<SYSTEM_TASK:>
filter_template
<END_TASK>
<USER_TASK:>
Description:
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... |
assert isinstance(filter_template, bytes)
return filter_template % (
tuple(map(escape_filter_chars, assertion_values))) |
<SYSTEM_TASK:>
Send command with single line output.
<END_TASK>
<USER_TASK:>
Description:
def send_command_return(self, obj, command, *arguments):
""" Send command with single line output.
:param obj: requested object.
:param command: command to send.
:param arguments: list of command a... |
return self._perform_command('{}/{}'.format(self.session_url, obj.ref), command, OperReturnType.line_output,
*arguments).json() |
<SYSTEM_TASK:>
Returns environment marked as default.
<END_TASK>
<USER_TASK:>
Description:
def default(self):
"""
Returns environment marked as default.
When Zone is set marked default makes no sense, special env with proper Zone is returned.
""" |
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_environment(name=DEFAULT_ENV_NAME(), zone=zone_id)
def_envs =... |
<SYSTEM_TASK:>
Builds a mapping of class paths to URLs.
<END_TASK>
<USER_TASK:>
Description:
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 not None:
uri = child.get("refuri")
package_path = child["reftitle"]
if uri.startswith("http"):
... |
<SYSTEM_TASK:>
Run the daemon and all its services
<END_TASK>
<USER_TASK:>
Description:
def run(configuration: str, level: str, target: str, short_format: bool):
"""Run the daemon and all its services""" |
initialise_logging(level=level, target=target, short_format=short_format)
logger = logging.getLogger(__package__)
logger.info('COBalD %s', cobald.__about__.__version__)
logger.info(cobald.__about__.__url__)
logger.info('%s %s (%s)', platform.python_implementation(), platform.python_version(), sys.e... |
<SYSTEM_TASK:>
Run the daemon from a command line interface
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Starting at this ``node``, check if it's an act node. If it's a context
<END_TASK>
<USER_TASK:>
Description:
def build(cls: Type[AN], node: ast.stmt) -> List[AN]:
"""
Starting at this ``node``, check if it's an act node. If it's a context
manager, recurse into child nodes.
... |
if node_is_result_assignment(node):
return [cls(node, ActNodeType.result_assignment)]
if node_is_pytest_raises(node):
return [cls(node, ActNodeType.pytest_raises)]
if node_is_unittest_raises(node):
return [cls(node, ActNodeType.unittest_raises)]
toke... |
<SYSTEM_TASK:>
Creates application and returns Application object.
<END_TASK>
<USER_TASK:>
Description:
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.application import Application
return Application.new(self, name, manifest, self._router) |
<SYSTEM_TASK:>
Get application object by name or id.
<END_TASK>
<USER_TASK:>
Description:
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] |
<SYSTEM_TASK:>
Launches instance in application and returns Instance object.
<END_TASK>
<USER_TASK:>
Description:
def create_instance(self, application, revision=None, environment=None, name=None, parameters=None, submodules=None,
destroyInterval=None, manifestVersion=None):
""" Launches... |
from qubell.api.private.instance import Instance
return Instance.new(self._router, application, revision, environment, name,
parameters, submodules, destroyInterval, manifestVersion=manifestVersion) |
<SYSTEM_TASK:>
Get instance object by name or id.
<END_TASK>
<USER_TASK:>
Description:
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, organization=self).init_router(self._router)
return Instance.get(self._router, self, name) |
<SYSTEM_TASK:>
Get list of instances in json format converted to list
<END_TASK>
<USER_TASK:>
Description:
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', 'descending': 'true',
'mode': 'short',
'from': '0', 'to': '10000'}
if not show_only_destroyed:
... |
<SYSTEM_TASK:>
Creates environment and returns Environment object.
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Get environment object by name or id.
<END_TASK>
<USER_TASK:>
Description:
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] |
<SYSTEM_TASK:>
Get zone object by name or id.
<END_TASK>
<USER_TASK:>
Description:
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] |
<SYSTEM_TASK:>
Get role object by name or id.
<END_TASK>
<USER_TASK:>
Description:
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] |
<SYSTEM_TASK:>
Get user object by email or id.
<END_TASK>
<USER_TASK:>
Description:
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)
else:
user = self.users[id or name]
return user |
<SYSTEM_TASK:>
Mimics wizard's environment preparation
<END_TASK>
<USER_TASK:>
Description:
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_id=self.organizationId, data='{}')
ca_data = dict(accessKey=access_key, secretKey=secret_key)
self... |
<SYSTEM_TASK:>
Commits and leaves transaction management.
<END_TASK>
<USER_TASK:>
Description:
def process_response(self, request, response):
"""Commits and leaves transaction management.""" |
if tldap.transaction.is_managed():
tldap.transaction.commit()
tldap.transaction.leave_transaction_management()
return response |
<SYSTEM_TASK:>
Format a report as per InfluxDB line protocol
<END_TASK>
<USER_TASK:>
Description:
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 identify... |
output_str = name
if tags:
output_str += ','
output_str += ','.join('%s=%s' % (key, value) for key, value in sorted(tags.items()))
output_str += ' '
output_str += ','.join(('%s=%r' % (key, value)).replace("'", '"') for key, value in sorted(fields.items()))
if timestamp is not None:
... |
<SYSTEM_TASK:>
This gets display on the block header.
<END_TASK>
<USER_TASK:>
Description:
def block_type(self):
""" This gets display on the block header. """ |
return capfirst(force_text(
self.content_block.content_type.model_class()._meta.verbose_name
)) |
<SYSTEM_TASK:>
Return a select widget for blocks which can be added to this column.
<END_TASK>
<USER_TASK:>
Description:
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='', value=None) |
<SYSTEM_TASK:>
Return a list of URLs and titles for blocks which can be added to this column.
<END_TASK>
<USER_TASK:>
Description:
def add_block_options(self, top):
"""
Return a list of URLs and titles for blocks which can be added to this column.
All available blocks are grouped by block categ... |
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]
category_choices = []
for block in category_blocks:
b... |
<SYSTEM_TASK:>
Get correct embed url for Youtube or Vimeo.
<END_TASK>
<USER_TASK:>
Description:
def get_embed_url(self):
""" Get correct embed url for Youtube or Vimeo. """ |
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):
embed_url = youtube_embed_url.format(re.match(YOUTUBE_URL_RE, self.url).grou... |
<SYSTEM_TASK:>
Get all visible dataset infos of user history.
<END_TASK>
<USER_TASK:>
Description:
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 = hc.show_history(history_id, visible=True, contents=True)
return history |
<SYSTEM_TASK:>
Act block is a single node - either the act node itself, or the node
<END_TASK>
<USER_TASK:>
Description:
def build_act(cls: Type[_Block], node: ast.stmt, test_func_node: ast.FunctionDef) -> _Block:
"""
Act block is a single node - either the act node itself, or the node
that wrap... |
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.parent != test_func_node: # type: ignore
act_block_node = act_block_node.parent # type: ignore
return cls([act_block... |
<SYSTEM_TASK:>
Arrange block is all non-pass and non-docstring nodes before the Act
<END_TASK>
<USER_TASK:>
Description:
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 sta... |
return cls(filter_arrange_nodes(nodes, max_line_number), LineType.arrange) |
<SYSTEM_TASK:>
Assert block is all nodes that are after the Act node.
<END_TASK>
<USER_TASK:>
Description:
def build_assert(cls: Type[_Block], nodes: List[ast.stmt], min_line_number: int) -> _Block:
"""
Assert block is all nodes that are after the Act node.
Note:
The filtering is *s... |
return cls(filter_assert_nodes(nodes, min_line_number), LineType._assert) |
<SYSTEM_TASK:>
r"""Developer script program names.
<END_TASK>
<USER_TASK:>
Description:
def cli_program_names(self):
r"""Developer script program names.
""" |
program_names = {}
for cli_class in self.cli_classes:
instance = cli_class()
program_names[instance.program_name] = cli_class
return program_names |
<SYSTEM_TASK:>
Read current ports statistics from chassis.
<END_TASK>
<USER_TASK:>
Description:
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()
return self.statistics |
<SYSTEM_TASK:>
Reset the stats of a term by deleting and re-creating it.
<END_TASK>
<USER_TASK:>
Description:
def reset_term_stats(set_id, term_id, client_id, user_id, access_token):
"""Reset the stats of a term by deleting and re-creating it.""" |
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('{} set(s) found with id {}'.format(len(found_sets), set_id))
found_terms = [term for term in found_sets[0].terms if term.term_id == ter... |
<SYSTEM_TASK:>
Function createController
<END_TASK>
<USER_TASK:>
Description:
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
... |
if key not in self:
self.printer = printer
self.async = False
# Create the VM in foreman
self.__printProgression__('In progress',
key + ' creation: push in Foreman',
eol='\r')
... |
<SYSTEM_TASK:>
Function createVM
<END_TASK>
<USER_TASK:>
Description:
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
... |
self.printer = printer
self.async = False
# Create the VM in foreman
# NOTA: with 1.8 it will return 422 'Failed to login via SSH'
self.__printProgression__('In progress',
key + ' creation: push in Foreman', eol='\r')
asyncCreation = se... |
<SYSTEM_TASK:>
Construct an object from a mapping
<END_TASK>
<USER_TASK:>
Description:
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 ... |
assert '__type__' not in kwargs and '__args__' not in kwargs
mapping = {**mapping, **kwargs}
factory_fqdn = mapping.pop('__type__')
factory = self.load_name(factory_fqdn)
args = mapping.pop('__args__', [])
return factory(*args, **mapping) |
<SYSTEM_TASK:>
Load an object based on an absolute, dotted name
<END_TASK>
<USER_TASK:>
Description:
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:
raise ModuleNotFoundError('No module named %r' % path[0])
else:
for... |
<SYSTEM_TASK:>
Check if longer list starts with shorter list
<END_TASK>
<USER_TASK:>
Description:
def contains_list(longer, shorter):
"""Check if longer list starts with shorter list""" |
if len(longer) <= len(shorter):
return False
for a, b in zip(shorter, longer):
if a != b:
return False
return True |
<SYSTEM_TASK:>
Load and parse toml from a file object
<END_TASK>
<USER_TASK:>
Description:
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(), dict_) |
<SYSTEM_TASK:>
Parse a toml string
<END_TASK>
<USER_TASK:>
Description:
def loads(content, dict_=dict):
"""Parse a toml string
An additional argument `dict_` is used to specify the output type
""" |
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()
return decoder.data |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.