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 Exception:
self._logger.exception('runner aborted: %s', self)
raise
else:
self._logger.info('runner stopped: %s', self)
finally:
with self._lock:
self.running.clear()
self._stopped.set() |
<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', 'want', 'to', 'believe']
::
>>> list(uqbar.strings.delimit_words("S3Bucket"))
['S3', 'Bucket']
::
>>> list(uqbar.strings.delimit_words("Route53"))
['Route', '53']
""" |
# 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:
yield current_word
current_word = ""
elif not current_word:
current_word += character
elif character.isupper():
if current_word[-1].isupper():
current_word += character
else:
yield current_word
current_word = character
elif character.islower():
if current_word[-1].isalpha():
current_word += character
else:
yield current_word
current_word = character
elif character.isdigit():
if current_word[-1].isdigit() or current_word[-1].isupper():
current_word += character
else:
yield current_word
current_word = character
elif character in wordlike_characters:
if current_word[-1] in wordlike_characters:
current_word += character
else:
yield current_word
current_word = character
if current_word:
yield 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".join(lines)
string = textwrap.dedent(string)
return string |
<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.
Returns the converted value. Subclasses should override this.
""" |
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 passed a version object to check if the user has permission to edit a version
of the object (if they own it).
""" |
# 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(permission_name, obj=obj)
if has_permission and version is not None:
# Version must not be saved, and must belong to this user
if version.version_number or version.owner != request.user:
has_permission = False
return has_permission |
<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_permission |
<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),
object_id=obj.pk,
).exclude(
version_number=None,
)
for version in saved_versions:
choices.append((version.version_number, version))
return choices |
<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.
This is mainly for information purposes, and the stream will transmit the packet header bytes even if no
protocol segments are specified.
If the method fails to set some segment it will log a warning and skip setup.
:param headers: current packet headers
:type headers: pypacker.layer12.ethernet.Ethernet
""" |
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)
if not segment:
self.logger.warning('pypacker header {} not in conversion list'.format(segment))
return
ps_headerprotocol.append(segment)
if type(body_handler) is Ethernet and body_handler.vlan:
ps_headerprotocol.append('vlan')
body_handler = body_handler.body_handler
self.set_attributes(ps_headerprotocol=' '.join(ps_headerprotocol)) |
<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 '
'with version entry?\n%s' % exc
)
else:
branch = self.info['branch'].lower()
branch = re.sub('[^a-z0-9_-]+', '-', branch)
return f"{branch}-{self.info['head']['id'][:8]}" |
<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")
>>> outer_container = UniqueTreeContainer(name="outer")
>>> inner_container = UniqueTreeContainer(name="inner")
>>> node_a = UniqueTreeNode(name="a")
>>> node_b = UniqueTreeNode(name="b")
>>> node_c = UniqueTreeNode(name="c")
>>> node_d = UniqueTreeNode(name="d")
>>> root_container.extend([node_a, outer_container])
>>> outer_container.extend([inner_container, node_d])
>>> inner_container.extend([node_b, node_c])
::
>>> for node in root_container.depth_first():
... print(node.name)
...
a
outer
inner
b
c
d
::
>>> for node in root_container.depth_first(top_down=False):
... print(node.name)
...
a
b
c
inner
d
outer
""" |
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.warning(str(e)) |
<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.
:type state: xenamanager.xena_stream.XenaStreamState
:return: newly created stream.
:rtype: xenamanager.xena_stream.XenaStream
""" |
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 = max(XenaStream.next_tpld_id + 1, tpld_id + 1)
stream.set_state(state)
return stream |
<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 packet to read.
:param to_index: index of last packet to read. If None - read all packets.
:param cap_type: returned capture format. If pcap then file name and tshark must be provided.
:param file_name: if specified, capture will be saved in file.
:param tshark: tshark object for pcap type only.
:type: xenamanager.xena_tshark.Tshark
:return: list of requested packets, None for pcap type.
""" |
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_name, raw_packets)
return raw_packets
text_packets = []
for raw_packet in raw_packets:
text_packet = ''
for c, b in zip(range(len(raw_packet)), raw_packet):
if c % 32 == 0:
text_packet += '\n{:06x} '.format(int(c / 2))
elif c % 2 == 0:
text_packet += ' '
text_packet += b
text_packets.append(text_packet)
if cap_type == XenaCaptureBufferType.text:
self._save_captue(file_name, text_packets)
return text_packets
temp_file_name = file_name + '_'
self._save_captue(temp_file_name, text_packets)
tshark.text_to_pcap(temp_file_name, file_name)
os.remove(temp_file_name) |
<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,
as well as a two-argument form for direct application.
Use the former for ``def`` or ``class`` definitions,
and the later for ``lambda`` functions and existing callables.
.. code:: python
@control.add(supply=10)
def linear(pool, interval):
if pool.utilisation < 0.75:
return pool.supply - interval
elif pool.allocation > 0.95:
return pool.supply + interval
control.add(
lambda pool, interval: pool.supply * (1.2 if pool.allocation > 0.75 else 0.9),
supply=100
)
""" |
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:
result[name] = value
except ValidationError as e:
raise ValidationError(f"{name}: {e}.")
return result |
<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 = [
(operation, field.to_db(value))
for operation, value in l
]
result[key] = new_list
except ValidationError as e:
raise ValidationError(f"{key}: {e}.")
return result |
<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 database. """ |
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(
connection=connection,
query=query,
fields=db_fields,
base_dn=base_dn or search_options.base_dn,
object_classes=search_options.object_class,
pk=search_options.pk_field,
)
for dn, data in iterator:
python_data = _db_to_python(data, table, dn)
python_data = table.on_load(python_data, database)
yield python_data |
<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 StopIteration:
pass
return result |
<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 for errors.
if isinstance(value_list, NotLoadedObject):
raise RuntimeError(f"{name}: Unexpected NotLoadedObject outside list.")
elif isinstance(value_list, NotLoadedList):
value_list = value_list.load(database)
else:
if any(isinstance(v, NotLoadedList) for v in value_list):
raise RuntimeError(f"{name}: Unexpected NotLoadedList in list.")
elif any(isinstance(v, NotLoadedObject) for v in value_list):
value_list = [preload_item(value) for value in value_list]
else:
value_list = None
if value_list is not None:
changes[name] = value_list
return python_data.merge(changes) |
<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, database)
# src dn | changes dn | result | action
# ---------------------------------------|--------
# None | None | error | error
# None | provided | use changes dn | create
# provided | None | use src dn | modify
# provided | provided | error | error
src_dn = changes.src.get_as_single('dn')
if src_dn is None and 'dn' not in changes:
raise RuntimeError("No DN was given")
elif src_dn is None and 'dn' in changes:
dn = changes.get_value_as_single('dn')
assert dn is not None
create = True
elif src_dn is not None and 'dn' not in changes:
dn = src_dn
assert dn is not None
create = False
else:
raise RuntimeError("Changes to DN are not supported.")
assert dn is not None
if create:
# Add new entry
mod_list = _python_to_mod_new(changes)
try:
connection.add(dn, mod_list)
except ldap3.core.exceptions.LDAPEntryAlreadyExistsResult:
raise ObjectAlreadyExists(
"Object with dn %r already exists doing add" % dn)
else:
mod_list = _python_to_mod_modify(changes)
if len(mod_list) > 0:
try:
connection.modify(dn, mod_list)
except ldap3.core.exceptions.LDAPNoSuchObjectResult:
raise ObjectDoesNotExist(
"Object with dn %r doesn't already exist doing modify" % dn)
# get new values
python_data = table(changes.src.to_dict())
python_data = python_data.merge(changes.to_dict())
python_data = python_data.on_load(python_data, database)
return python_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-zero ldap.cidict.cidict will be
used for case-insensitive string keys
""" |
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 lookup.
:param name: rdn to convert.
:param base_dn: The base_dn to lookup.
:return: fully qualified DN.
""" |
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.exceptions.ValidationError(
"Cannot use %s in dn as it is a list" % name)
assert base_dn is not None
split_base = str2dn(base_dn)
split_new_dn = [[(name, value, 1)]] + split_base
new_dn = dn2str(split_new_dn)
return changes.set('dn', new_dn) |
<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.
line_type: The type of line to update to.
Raises:
ValidationError: A special error on collision. This prevents Flake8
from crashing because it is converted to a Flake8 error tuple,
but it indicates to the user that something went wrong with
processing the function.
""" |
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]:
"""
Checks there is a clear single line between ``first_block_type`` and
``second_block_type``.
Note:
Is tested via ``check_arrange_act_spacing()`` and
``check_act_assert_spacing()``.
""" |
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_lines = filter(lambda l: l[1] is second_block_type, numbered_lines)
try:
second_block_lineno = next(second_block_lines)[0]
except StopIteration:
# Second block has no lines
return
blank_lines = [
bl for bl in numbered_lines[first_block_lineno + 1:second_block_lineno] if bl[1] is LineType.blank_line
]
if not blank_lines:
# Point at line above second block
yield AAAError(
line_number=self.fn_offset + second_block_lineno - 1,
offset=0,
text=error_message.format('none'),
)
return
if len(blank_lines) > 1:
# Too many blank lines - point at the first extra one, the 2nd
yield AAAError(
line_number=self.fn_offset + blank_lines[1][0],
offset=0,
text=error_message.format(len(blank_lines)),
) |
<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)
if self.objName == 'puppetclass_ids':
subItemList = list(map(lambda x: {'id': x}, subItemList))
if self.objName == 'puppetclasses':
sil_tmp = subItemList.values()
subItemList = []
for i in sil_tmp:
subItemList.extend(i)
return {x[self.index]: self.objType(self.api, x['id'],
self.parentObjName,
self.parentPayloadObj,
self.parentKey,
x)
for x in subItemList} |
<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, foo=None, bar=None, **kwargs):
... self.arg1 = arg1
... self.arg2 = arg2
... self.var_args = var_args
... self.foo = foo
... self.bar = bar
... self.kwargs = kwargs
...
>>> my_object = MyObject('a', 'b', 'c', 'd', foo='x', quux=['y', 'z'])
::
>>> import uqbar
>>> print(uqbar.objects.get_repr(my_object))
MyObject(
'a',
'b',
'c',
'd',
foo='x',
quux=['y', 'z'],
)
""" |
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, kwargs = get_vars(expr)
args_parts = collections.OrderedDict()
var_args_parts = []
kwargs_parts = {}
has_lines = multiline
parts = []
# Format keyword-optional arguments.
# print(type(expr), args)
for i, (key, value) in enumerate(args.items()):
arg_repr = _dispatch_formatting(value)
if "\n" in arg_repr:
has_lines = True
args_parts[key] = arg_repr
# Format *args
for arg in var_args:
arg_repr = _dispatch_formatting(arg)
if "\n" in arg_repr:
has_lines = True
var_args_parts.append(arg_repr)
# Format **kwargs
for key, value in sorted(kwargs.items()):
if key in defaults and value == defaults[key]:
continue
value = _dispatch_formatting(value)
arg_repr = "{}={}".format(key, value)
has_lines = True
kwargs_parts[key] = arg_repr
for _, part in args_parts.items():
parts.append(part)
parts.extend(var_args_parts)
for _, part in sorted(kwargs_parts.items()):
parts.append(part)
# If we should format on multiple lines, add the appropriate formatting.
if has_lines and parts:
for i, part in enumerate(parts):
parts[i] = "\n".join(" " + line for line in part.split("\n"))
parts.append(" )")
parts = ",\n".join(parts)
return "{}(\n{}".format(type(expr).__name__, parts)
parts = ", ".join(parts)
return "{}({})".format(type(expr).__name__, parts) |
<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, bar=None, **kwargs):
... self.arg1 = arg1
... self.arg2 = arg2
... self.var_args = var_args
... self.foo = foo
... self.bar = bar
... self.kwargs = kwargs
...
>>> my_object = MyObject('a', 'b', 'c', 'd', foo='x', quux=['y', 'z'])
::
>>> import uqbar
>>> args, var_args, kwargs = uqbar.objects.get_vars(my_object)
::
>>> args
OrderedDict([('arg1', 'a'), ('arg2', 'b')])
::
>>> var_args
['c', 'd']
::
>>> kwargs
{'foo': 'x', 'quux': ['y', 'z']}
""" |
# 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) in enumerate(signature.parameters.items()):
# print(' ', parameter)
if i == 0 and name in ("self", "cls", "class_", "klass"):
continue
if parameter.kind is inspect._POSITIONAL_ONLY:
try:
args[name] = getattr(expr, name)
except AttributeError:
args[name] = expr[name]
elif (
parameter.kind is inspect._POSITIONAL_OR_KEYWORD
or parameter.kind is inspect._KEYWORD_ONLY
):
found = False
for x in (name, "_" + name):
try:
value = getattr(expr, x)
found = True
break
except AttributeError:
try:
value = expr[x]
found = True
break
except (KeyError, TypeError):
pass
if not found:
raise ValueError("Cannot find value for {!r}".format(name))
if parameter.default is inspect._empty:
args[name] = value
elif parameter.default != value:
kwargs[name] = value
elif parameter.kind is inspect._VAR_POSITIONAL:
value = None
try:
value = expr[:]
except TypeError:
value = getattr(expr, name)
if value:
var_args.extend(value)
elif parameter.kind is inspect._VAR_KEYWORD:
items = {}
if hasattr(expr, "items"):
items = expr.items()
elif hasattr(expr, name):
mapping = getattr(expr, name)
if not isinstance(mapping, dict):
mapping = dict(mapping)
items = mapping.items()
elif hasattr(expr, "_" + name):
mapping = getattr(expr, "_" + name)
if not isinstance(mapping, dict):
mapping = dict(mapping)
items = mapping.items()
for key, value in items:
if key not in args:
kwargs[key] = value
return args, var_args, kwargs |
<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_apps_module.apps)
except ImportError:
pass
self.discovered = True |
<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 will be updated.
""" |
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'])
actioned = True
return actioned |
<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 version will be updated.
""" |
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.content_type.pk,
object_id=self.object_id,
object_repr=force_text(self.content_object),
action_flag=CHANGE,
change_message=message
) |
<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 hostgroup
- check the hostgroup is not existing
- create the hostgroup
- Add puppet classes from puppetClassesId
- Add params from hostgroupConf
@param key: The hostgroup name or ID
@param payload: The description of the hostgroup
@param hostgroupConf: The configuration of the host group from the
foreman.conf
@param hostgroupParent: The id of the parent hostgroup
@param puppetClassesId: The dict of puppet classes ids in foreman
@return RETURN: The ItemHostsGroup object of an host
""" |
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']:
classList.append(puppetClassesId[c])
if not self[key].checkAndCreateClasses(classList):
print("Failed in classes")
return False
# Set params
if 'params' in hostgroupConf.keys():
if not self[key].checkAndCreateParams(hostgroupConf['params']):
print("Failed in params")
return False
return oid |
<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,
format='%(asctime)-15s (%(process)d) %(message)s' if not short_format else '%(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
handlers=[handler]
) |
<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(
'You need to specify the "labels" dictionary in the config'
)
git = GithubApi()
for repo in repos:
repo = git.repo(repo)
for label, color in labels.items():
if repo.label(label, color):
click.echo('Created label "%s" @ %s' % (label, repo))
else:
click.echo('Updated label "%s" @ %s' % (label, repo)) |
<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,
response.headers['content-type'], response.json())
response = response.json()
if 'error' in response:
raise OSError(response['error'])
return response
except OSError as error:
_LOGGER.warning('Failed request: %s', error) |
<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
with permission to edit the page.
""" |
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 startbody template
# - Check if user has permission to add
glitter = context.get('glitter')
if glitter is not None:
opts = glitter.obj._meta.app_label, glitter.obj._meta.model_name
template_path = path_plus % opts
templates.insert(0, template_path)
template = context.template.engine.select_template(templates)
rendered = template.render(context)
return rendered |
<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 RFC 4515 are escaped.
If 1 all NON-ASCII chars are escaped.
If 2 all chars are escaped.
""" |
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:
if c == ord('\\') or c == ord('*') \
or c == ord('(') or c == ord(')') \
or c == ord('\x00'):
do_escape = True
elif escape_mode == 1:
if c < '0' or c > 'z' or c in "\\*()":
do_escape = True
elif escape_mode == 2:
do_escape = True
else:
raise ValueError('escape_mode must be 0, 1 or 2.')
if do_escape:
s.append(b"\\%02x" % c)
else:
b = None
if str != bytes: # Python 3
b = bytes([c])
else: # Python 2
b = chr(c)
s.append(b)
return b''.join(s) |
<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 %s in filter_template.
""" |
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 arguments.
:return: command output.
""" |
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 = [env_j["id"] for env_j in self.json() if env_j["isDefault"]]
if len(def_envs) > 1:
log.warning('Found more than one default environment. Picking last.')
return self[def_envs[-1]]
elif len(def_envs) == 1:
return self[def_envs[0]]
raise exceptions.NotFoundError('Unable to get default environment') |
<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"):
_, _, package_path = uri.partition("#")
else:
uri = (
pathlib.Path("..")
/ pathlib.Path(current_filename).parent
/ pathlib.Path(uri)
)
uri = str(uri).replace(os.path.sep, "/")
urls[package_path] = uri
# Same document
elif child.get("refid") is not None:
urls[child["reftitle"]] = (
"../" + current_filename + "#" + child.get("refid")
)
return urls |
<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.executable)
logger.debug(cobald.__file__)
logger.info('Using configuration %s', configuration)
with load(configuration):
logger.info('Starting daemon services...')
runtime.accept() |
<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.
Returns:
List of all act nodes found.
""" |
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)]
token = node.first_token # type: ignore
# Check if line marked with '# act'
if token.line.strip().endswith('# act'):
return [cls(node, ActNodeType.marked_act)]
# Recurse (downwards) if it's a context manager
if isinstance(node, ast.With):
return cls.build_body(node.body)
return [] |
<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 instance in application and returns Instance object.
""" |
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:
q_filter['showDestroyed'] = 'false'
else:
q_filter['showDestroyed'] = 'true'
q_filter['showRunning'] = 'false'
q_filter['showError'] = 'false'
q_filter['showLaunching'] = 'false'
if application:
q_filter["applicationFilterId"] = application.applicationId
resp_json = self._router.get_instances(org_id=self.organizationId, params=q_filter).json()
if type(resp_json) == dict:
instances = [instance for g in resp_json['groups'] for instance in g['records']]
else: # TODO: This is compatibility fix for platform < 37.1
instances = resp_json
return instances |
<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._router.post_init_custom_cloud_account(org_id=self.organizationId, data=json.dumps(ca_data)) |
<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 identifying the specific report
:param fields: measurements of the report
:param timestamp: when the measurement was taken, in **seconds** since the epoch
""" |
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:
# line protocol requires nanosecond precision, python uses seconds
output_str += ' %d' % (timestamp * 1E9)
return output_str + '\n' |
<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 category.
""" |
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:
base_url = reverse('block_admin:{}_{}_add'.format(
block._meta.app_label, block._meta.model_name,
), kwargs={
'version_id': self.glitter_page.version.id,
})
block_qs = {
'column': self.name,
'top': top,
}
block_url = '{}?{}'.format(base_url, urlencode(block_qs))
block_text = capfirst(force_text(block._meta.verbose_name))
category_choices.append((block_url, block_text))
category_choices = sorted(category_choices, key=lambda x: x[1])
block_choices.append((category, category_choices))
return block_choices |
<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).group(2))
if re.match(VIMEO_URL_RE, self.url):
embed_url = vimeo_embed_url.format(re.match(VIMEO_URL_RE, self.url).group(3))
return embed_url |
<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 wraps the act node.
""" |
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_node], LineType.act) |
<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 start.
""" |
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 *still* running off the line number of the Act
node, when instead it should be using the last line of the Act
block.
""" |
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 == term_id]
if len(found_terms) != 1:
raise ValueError('{} term(s) found with id {}'.format(len(found_terms), term_id))
term = found_terms[0]
if term.image.url:
# Creating a term with an image requires an "image identifier", which you get by uploading
# an image via https://quizlet.com/api/2.0/docs/images , which can only be used by Quizlet
# PLUS members.
raise NotImplementedError('"{}" has an image and is thus not supported'.format(term))
print('Deleting "{}"...'.format(term))
delete_term(set_id, term_id, access_token)
print('Re-creating "{}"...'.format(term))
add_term(set_id, term, access_token)
print('Done') |
<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
@param printer: - False for no creation progression message
- True to get creation progression printed on STDOUT
- Printer class containig a status method for enhanced
print. def printer.status(status, msg, eol=eol)
@return RETURN: The API result
""" |
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')
self.api.create('hosts', attributes, async=self.async)
self[key]['interfaces'].append(ipmi)
# Wait for puppet catalog to be applied
# self.waitPuppetCatalogToBeApplied(key)
self.reload()
self[key]['build'] = 'true'
self[key]['boot'] = 'pxe'
self[key]['power'] = 'cycle'
return self[key] |
<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
the result of the creation.
To do so, we make async calls to the API and check the results
@param key: The host name or ID
@param attributes:The payload of the host creation
@param printer: - False for no creation progression message
- True to get creation progression printed on STDOUT
- Printer class containig a status method for enhanced
print. def printer.status(status, msg, eol=eol)
@return RETURN: The API result
""" |
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 = self.api.create('hosts', attributes, async=self.async)
# Wait before asking to power on the VM
# sleep = 5
# for i in range(0, sleep):
# time.sleep(1)
# self.__printProgression__('In progress',
# key + ' creation: start in {0}s'
# .format(sleep - i),
# eol='\r')
# Power on the VM
self.__printProgression__('In progress',
key + ' creation: starting', eol='\r')
powerOn = self[key].powerOn()
# Show Power on result
if powerOn['power']:
self.__printProgression__('In progress',
key + ' creation: wait for end of boot',
eol='\r')
else:
self.__printProgression__(False,
key + ' creation: Error - ' +
str(powerOn))
return False
# Show creation result
# NOTA: with 1.8 it will return 422 'Failed to login via SSH'
# if asyncCreation.result().status_code is 200:
# self.__printProgression__('In progress',
# key + ' creation: created',
# eol='\r')
# else:
# self.__printProgression__(False,
# key + ' creation: Error - ' +
# str(asyncCreation.result()
# .status_code) + ' - ' +
# str(asyncCreation.result().text))
# return False
# Wait for puppet catalog to be applied
self.waitPuppetCatalogToBeApplied(key)
return self[key]['id'] |
<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 keyword arguments to pass to the constructor
""" |
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 component in path[1:]:
try:
obj = getattr(obj, component)
except AttributeError as err:
raise ConfigurationError(what='no such object %r: %s' % (absolute_name, err))
return obj
else: # ImportError is not raised if ``absolute_name`` points to a valid module
return sys.modules[absolute_name] |
<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 |