text_prompt
stringlengths 157
13.1k
| code_prompt
stringlengths 7
19.8k
⌀ |
---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def start(ctx, debug, version, config):
"""Commands for devops operations""" |
ctx.obj = {}
ctx.DEBUG = debug
if os.path.isfile(config):
with open(config) as fp:
agile = json.load(fp)
else:
agile = {}
ctx.obj['agile'] = agile
if version:
click.echo(__version__)
ctx.exit(0)
if not ctx.invoked_subcommand:
click.echo(ctx.get_help()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def duplicate(obj, value=None, field=None, duplicate_order=None):
""" Duplicate all related objects of obj setting field to value. If one of the duplicate objects has an FK to another duplicate object update that as well. Return the duplicate copy of obj. duplicate_order is a list of models which specify how the duplicate objects are saved. For complex objects this can matter. Check to save if objects are being saved correctly and if not just pass in related objects in the order that they should be saved. """ |
using = router.db_for_write(obj._meta.model)
collector = CloneCollector(using=using)
collector.collect([obj])
collector.sort()
related_models = list(collector.data.keys())
data_snapshot = {}
for key in collector.data.keys():
data_snapshot.update({
key: dict(zip(
[item.pk for item in collector.data[key]], [item for item in collector.data[key]]))
})
root_obj = None
# Sometimes it's good enough just to save in reverse deletion order.
if duplicate_order is None:
duplicate_order = reversed(related_models)
for model in duplicate_order:
# Find all FKs on model that point to a related_model.
fks = []
for f in model._meta.fields:
if isinstance(f, ForeignKey) and f.rel.to in related_models:
fks.append(f)
# Replace each `sub_obj` with a duplicate.
if model not in collector.data:
continue
sub_objects = collector.data[model]
for obj in sub_objects:
for fk in fks:
fk_value = getattr(obj, "%s_id" % fk.name)
# If this FK has been duplicated then point to the duplicate.
fk_rel_to = data_snapshot[fk.rel.to]
if fk_value in fk_rel_to:
dupe_obj = fk_rel_to[fk_value]
setattr(obj, fk.name, dupe_obj)
# Duplicate the object and save it.
obj.id = None
if field is not None:
setattr(obj, field, value)
obj.save()
if root_obj is None:
root_obj = obj
return root_obj |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def enter_transaction_management(using=None):
""" Enters transaction management for a running thread. It must be balanced with the appropriate leave_transaction_management call, since the actual state is managed as a stack. The state and dirty flag are carried over from the surrounding block or from the settings, if there is no surrounding block (dirty is always false when no current block is running). """ |
if using is None:
for using in tldap.backend.connections:
connection = tldap.backend.connections[using]
connection.enter_transaction_management()
return
connection = tldap.backend.connections[using]
connection.enter_transaction_management() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_dirty(using=None):
""" Returns True if the current transaction requires a commit for changes to happen. """ |
if using is None:
dirty = False
for using in tldap.backend.connections:
connection = tldap.backend.connections[using]
if connection.is_dirty():
dirty = True
return dirty
connection = tldap.backend.connections[using]
return connection.is_dirty() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_managed(using=None):
""" Checks whether the transaction manager is in manual or in auto state. """ |
if using is None:
managed = False
for using in tldap.backend.connections:
connection = tldap.backend.connections[using]
if connection.is_managed():
managed = True
return managed
connection = tldap.backend.connections[using]
return connection.is_managed() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def commit(using=None):
""" Does the commit itself and resets the dirty flag. """ |
if using is None:
for using in tldap.backend.connections:
connection = tldap.backend.connections[using]
connection.commit()
return
connection = tldap.backend.connections[using]
connection.commit() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rollback(using=None):
""" This function does the rollback itself and resets the dirty flag. """ |
if using is None:
for using in tldap.backend.connections:
connection = tldap.backend.connections[using]
connection.rollback()
return
connection = tldap.backend.connections[using]
connection.rollback() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def commit_on_success(using=None):
""" This decorator activates commit on response. This way, if the view function runs successfully, a commit is made; if the viewfunc produces an exception, a rollback is made. This is one of the most common ways to do transaction control in Web apps. """ |
def entering(using):
enter_transaction_management(using=using)
def exiting(exc_value, using):
try:
if exc_value is not None:
if is_dirty(using=using):
rollback(using=using)
else:
commit(using=using)
finally:
leave_transaction_management(using=using)
return _transaction_func(entering, exiting, using) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def process_request(self, request):
""" Reloads glitter URL patterns if page URLs change. Avoids having to restart the server to recreate the glitter URLs being used by Django. """ |
global _urlconf_pages
page_list = list(
Page.objects.exclude(glitter_app_name='').values_list('id', 'url').order_by('id')
)
with _urlconf_lock:
if page_list != _urlconf_pages:
glitter_urls = 'glitter.urls'
if glitter_urls in sys.modules:
importlib.reload(sys.modules[glitter_urls])
_urlconf_pages = page_list |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delimit_words(string: str) -> Generator[str, None, None]: """ Delimit a string at word boundaries. :: ['i', 'want', 'to', 'believe'] :: ['S3', 'Bucket'] :: ['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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_dash_case(string: str) -> str: """ Convert a string to dash-delimited words. :: to-dac-biet-xe-lua :: alpha-beta-gamma """ |
string = unidecode.unidecode(string)
words = (_.lower() for _ in delimit_words(string))
string = "-".join(words)
return string |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_lib2to3_fixers():
'''returns a list of all fixers found in the lib2to3 library'''
fixers = []
fixer_dirname = fixer_dir.__path__[0]
for name in sorted(os.listdir(fixer_dirname)):
if name.startswith("fix_") and name.endswith(".py"):
fixers.append("lib2to3.fixes." + name[:-3])
return fixers |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_single_fixer(fixname):
'''return a single fixer found in the lib2to3 library'''
fixer_dirname = fixer_dir.__path__[0]
for name in sorted(os.listdir(fixer_dirname)):
if (name.startswith("fix_") and name.endswith(".py")
and fixname == name[4:-3]):
return "lib2to3.fixes." + name[:-3] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def semantic_version(tag):
"""Get a valid semantic version for tag """ |
try:
version = list(map(int, tag.split('.')))
assert len(version) == 3
return tuple(version)
except Exception as exc:
raise CommandError(
'Could not parse "%s", please use '
'MAJOR.MINOR.PATCH' % tag
) from exc |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load(self, data):
""" Function load Store the object data """ |
self.clear()
self.update(data)
self.enhance() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reload(self):
""" Function reload Sync the full object """ |
self.load(self.api.get(self.objName, self.key)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def checkAndCreateClasses(self, classes):
""" Function checkAndCreateClasses Check and add puppet class @param classes: The classes ids list @return RETURN: boolean """ |
actual_classes = self['puppetclasses'].keys()
for i in classes:
if i not in actual_classes:
self['puppetclasses'].append(i)
self.reload()
return set(classes).issubset(set((self['puppetclasses'].keys()))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def checkAndCreateParams(self, params):
""" Function checkAndCreateParams Check and add global parameters @param key: The parameter name @param params: The params dict @return RETURN: boolean """ |
actual_params = self['parameters'].keys()
for k, v in params.items():
if k not in actual_params:
self['parameters'].append({"name": k, "value": v})
self.reload()
return self['parameters'].keys() == params.keys() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def manifest(self, values, *paths, filename: str = None) -> Dict: """Load a manifest file and apply template values """ |
filename = filename or self.filename(*paths)
with open(filename, 'r') as fp:
template = Template(fp.read())
return yaml.load(template.render(values)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_modifier(self, m_type=XenaModifierType.standard, **kwargs):
""" Add modifier. :param m_type: modifier type - standard or extended. :type: xenamanager.xena_stram.ModifierType :return: newly created modifier. :rtype: xenamanager.xena_stream.XenaModifier """ |
if m_type == XenaModifierType.standard:
modifier = XenaModifier(self, index='{}/{}'.format(self.index, len(self.modifiers)))
else:
modifier = XenaXModifier(self, index='{}/{}'.format(self.index, len(self.xmodifiers)))
modifier._create()
modifier.get()
modifier.set(**kwargs)
return modifier |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove_modifier(self, index, m_type=XenaModifierType.standard):
""" Remove modifier. :param m_type: modifier type - standard or extended. :param index: index of modifier to remove. """ |
if m_type == XenaModifierType.standard:
current_modifiers = OrderedDict(self.modifiers)
del current_modifiers[index]
self.set_attributes(ps_modifiercount=0)
self.del_objects_by_type('modifier')
else:
current_modifiers = OrderedDict(self.xmodifiers)
del current_modifiers[index]
self.set_attributes(ps_modifierextcount=0)
self.del_objects_by_type('xmodifier')
for modifier in current_modifiers.values():
self.add_modifier(m_type,
mask=modifier.mask, action=modifier.action, repeat=modifier.repeat,
min_val=modifier.min_val, step=modifier.step, max_val=modifier.max_val) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def depth_first(self, top_down=True):
""" Iterate depth-first. :: :: a outer inner b c d :: 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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _db_to_python(db_data: dict, table: LdapObjectClass, dn: str) -> LdapObject: """ Convert a DbDate object to a LdapObject. """ |
fields = table.get_fields()
python_data = table({
name: field.to_python(db_data[name])
for name, field in fields.items()
if field.db_field
})
python_data = python_data.merge({
'dn': dn,
})
return python_data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def make_driver(loop=None):
''' Returns a stop driver.
The optional loop argument can be provided to use the driver in another
loop than the default one.
Parameters
-----------
loop: BaseEventLoop
The event loop to use instead of the default one.
'''
loop = loop or asyncio.get_event_loop()
def stop(i = None):
loop.stop()
def driver(sink):
''' The stop driver stops the asyncio event loop.
The event loop is stopped as soon as an event is received on the
control observable or when it completes (both in case of success or
error).
Parameters
----------
sink: Sink
'''
sink.control.subscribe(
on_next=stop,
on_error=stop,
on_completed=stop)
return None
return Component(call=driver, input=Sink) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _stdin_(p):
"""Takes input from user. Works for Python 2 and 3.""" |
_v = sys.version[0]
return input(p) if _v is '3' else raw_input(p) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run_question(self, question, input_func=_stdin_):
"""Run the given question.""" |
qi = '[%d/%d] ' % (self.qcount, self.qtotal)
print('%s %s:' % (qi, question['label']))
while True:
# ask for user input until we get a valid one
ans = input_func('%s > ' % self.format_choices())
if self.is_answer_valid(ans):
question['answer'] = int(ans)
break
else:
if ans is '?': print(question['description'])
else: print('Invalid answer.')
self.qcount += 1 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run_section(self, name, input_func=_stdin_):
"""Run the given section.""" |
print('\nStuff %s by the license:\n' % name)
section = self.survey[name]
for question in section:
self.run_question(question, input_func) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run(self, input_func=_stdin_):
"""Run the sections.""" |
# reset question count
self.qcount = 1
for section_name in self.survey:
self.run_section(section_name, input_func) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_repr(expr, multiline=False):
""" Build a repr string for ``expr`` from its vars and signature. :: :: 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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_vars(expr):
""" Get ``args``, ``var args`` and ``kwargs`` for an object ``expr``. :: :: :: OrderedDict([('arg1', 'a'), ('arg2', 'b')]) :: ['c', 'd'] :: {'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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def new(expr, *args, **kwargs):
""" Template an object. :: :: MyObject( 'a', 'b', 'c', 'd', bar=1234, foo=666, quux=['y', 'z'], ) Original object is unchanged: :: MyObject( 'a', 'b', 'c', 'd', foo='x', quux=['y', 'z'], ) """ |
# TODO: Clarify old vs. new variable naming here.
current_args, current_var_args, current_kwargs = get_vars(expr)
new_kwargs = current_kwargs.copy()
recursive_arguments = {}
for key in tuple(kwargs):
if "__" in key:
value = kwargs.pop(key)
key, _, subkey = key.partition("__")
recursive_arguments.setdefault(key, []).append((subkey, value))
for key, pairs in recursive_arguments.items():
recursed_object = current_args.get(key, current_kwargs.get(key))
if recursed_object is None:
continue
kwargs[key] = new(recursed_object, **dict(pairs))
if args:
current_var_args = args
for key, value in kwargs.items():
if key in current_args:
current_args[key] = value
else:
new_kwargs[key] = value
new_args = list(current_args.values()) + list(current_var_args)
return type(expr)(*new_args, **new_kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_glitter_app(self, glitter_app_name):
""" Retrieve the Glitter App config for a specific Glitter App. """ |
if not self.discovered:
self.discover_glitter_apps()
try:
glitter_app = self.glitter_apps[glitter_app_name]
return glitter_app
except KeyError:
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def kong(ctx, namespace, yes):
"""Update the kong configuration """ |
m = KongManager(ctx.obj['agile'], namespace=namespace)
click.echo(utils.niceJson(m.create_kong(yes))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_handler(target: str):
"""Create a handler for logging to ``target``""" |
if target == 'stderr':
return logging.StreamHandler(sys.stderr)
elif target == 'stdout':
return logging.StreamHandler(sys.stdout)
else:
return logging.handlers.WatchedFileHandler(filename=target) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_access_token(self, code):
"""Get new access token.""" |
try:
self._token = super().fetch_token(
MINUT_TOKEN_URL,
client_id=self._client_id,
client_secret=self._client_secret,
code=code,
)
# except Exception as e:
except MissingTokenError as error:
_LOGGER.debug("Token issues: %s", error)
return self._token |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_sensor(self, device_id, sensor_uri):
"""Return sensor value based on sensor_uri.""" |
url = MINUT_DEVICES_URL + "/{device_id}/{sensor_uri}".format(
device_id=device_id, sensor_uri=sensor_uri)
res = self._request(url, request_type='GET', data={'limit': 1})
if not res.get('values'):
return None
return res.get('values')[-1].get('value') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _register_webhook(self, webhook_url, events):
"""Register webhook.""" |
response = self._request(
MINUT_WEBHOOKS_URL,
request_type='POST',
json={
'url': webhook_url,
'events': events,
},
)
return response |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove_webhook(self):
"""Remove webhook.""" |
if self._webhook.get('hook_id'):
self._request(
"{}/{}".format(MINUT_WEBHOOKS_URL, self._webhook['hook_id']),
request_type='DELETE',
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update(self):
"""Update all devices from server.""" |
with self._lock:
devices = self._request_devices(MINUT_DEVICES_URL, 'devices')
if devices:
self._state = {
device['device_id']: device
for device in devices
}
_LOGGER.debug("Found devices: %s", list(self._state.keys()))
# _LOGGER.debug("Device status: %s", devices)
homes = self._request_devices(MINUT_HOMES_URL, 'homes')
if homes:
self._homes = homes
return self.devices |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _set_alarm(self, status, home_id):
"""Set alarm satus.""" |
response = self._request(
MINUT_HOMES_URL + "/{}".format(home_id),
request_type='PUT',
json={'alarm_status': status})
return response.get('alarm_status', '') == status |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sensor(self, sensor_type):
"""Update and return sensor value.""" |
_LOGGER.debug("Reading %s sensor.", sensor_type)
return self._session.read_sensor(self.device_id, sensor_type) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def device_info(self):
"""Info about device.""" |
return {
'connections': {('mac', self.device['device_mac'])},
'identifieres': self.device['device_id'],
'manufacturer': 'Minut',
'model': 'Point v{}'.format(self.device['hardware_version']),
'name': self.device['description'],
'sw_version': self.device['firmware']['installed'],
} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def device_status(self):
"""Status of device.""" |
return {
'active': self.device['active'],
'offline': self.device['offline'],
'last_update': self.last_update,
'battery_level': self.battery_level,
} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.