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(ct...
<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 object...
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( ...
<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_...
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.i...
<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 vi...
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: ...
<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 ...
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....
<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 ...
self._logger.info('runner started: %s', self) try: with self._lock: assert not self.running.is_set() and self._stopped.is_set(), 'cannot re-run: %s' % self self.running.set() self._stopped.clear() self._run() except Excepti...
<SYSTEM_TASK:> 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'] :: ['...
# TODO: Reimplement this wordlike_characters = ("<", ">", "!") current_word = "" for i, character in enumerate(string): if ( not character.isalpha() and not character.isdigit() and character not in wordlike_characters ): if current_word: ...
<SYSTEM_TASK:> 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"...
<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]) ...
<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...
<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 ...
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 ...
# Has the edit permission for this object type permission_name = '{}.edit_{}'.format(self.opts.app_label, self.opts.model_name) has_permission = request.user.has_perm(permission_name) if obj is not None and has_permission is False: has_permission = request.user.has_perm(per...
<SYSTEM_TASK:> 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_permissio...
<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 para...
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: bool...
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 param...
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), ...
<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...
bin_headers = '0x' + binascii.hexlify(headers.bin()).decode('utf-8') self.set_attributes(ps_packetheader=bin_headers) body_handler = headers ps_headerprotocol = [] while body_handler: segment = pypacker_2_xena.get(str(body_handler).split('(')[0].lower(), None) ...
<SYSTEM_TASK:> 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.xen...
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() mo...
<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...
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.xmo...
<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 ' ...
<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. :retu...
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.war...
<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 t...
stream = XenaStream(parent=self, index='{}/{}'.format(self.index, len(self.streams)), name=name) stream._create() tpld_id = tpld_id if tpld_id else XenaStream.next_tpld_id stream.set_attributes(ps_comment='"{}"'.format(stream.name), ps_tpldid=tpld_id) XenaStream.next_tpld_id = ...
<SYSTEM_TASK:> 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. :par...
to_index = to_index if to_index else len(self.packets) raw_packets = [] for index in range(from_index, to_index): raw_packets.append(self.packets[index].get_attribute('pc_packet').split('0x')[1]) if cap_type == XenaCaptureBufferType.raw: self._save_captue(file...
<SYSTEM_TASK:> 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 for...
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: ...
<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 operat...
table: LdapObjectClass = type(changes.src) changes = changes.changes result: Dict[str, List[Tuple[Operation, List[bytes]]]] = {} for key, l in changes.items(): field = _get_field_by_name(table, key) if field.db_field: try: new_list = [ (...
<SYSTEM_TASK:> 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]: """ Sea...
fields = table.get_fields() db_fields = { name: field for name, field in fields.items() if field.db_field } database = get_database(database) connection = database.connection search_options = table.get_search_options(database) iterator = tldap.query.search( ...
<SYSTEM_TASK:> 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 ...
results = search(table, query, database, base_dn) try: result = next(results) except StopIteration: raise ObjectDoesNotExist(f"Cannot find result for {query}.") try: next(results) raise MultipleObjectsReturned(f"Found multiple results for {query}.") except StopIter...
<SYSTEM_TASK:> 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 f...
<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, 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_i...
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 asynci...
<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 cha...
dn = changes.get_value_as_single('dn') if dn is not None: return changes value = changes.get_value_as_single(name) if value is None: raise tldap.exceptions.ValidationError( "Cannot use %s in dn as it is None" % name) if isinstance(value, list): raise tldap.excep...
<SYSTEM_TASK:> 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'...
<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 n...
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]: """ Check...
numbered_lines = list(enumerate(self)) first_block_lines = filter(lambda l: l[1] is first_block_type, numbered_lines) try: first_block_lineno = list(first_block_lines)[-1][0] except IndexError: # First block has no lines return second_block_l...
<SYSTEM_TASK:> 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 R...
subItemList = self.api.list('{}/{}/{}'.format(self.parentObjName, self.parentKey, self.objName, ), limit=limit) ...
<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, kwa...
<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'] :: {...
# print('TYPE?', type(expr)) signature = _get_object_signature(expr) if signature is None: return ({}, [], {}) # print('SIG?', signature) args = collections.OrderedDict() var_args = [] kwargs = {} if expr is None: return args, var_args, kwargs for i, (name, parameter...
<SYSTEM_TASK:> 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: :...
# 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.parti...
<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_...
<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...
obj = self.content_object version = self.get_version() actioned = False # Only update if needed if obj.current_version != version: version = self.get_version() obj.current_version = version obj.save(update_fields=['current_version']) ...
<SYSTEM_TASK:> 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 wi...
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.con...
<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 ...
if key not in self: self[key] = payload oid = self[key]['id'] if not oid: return False # Create Hostgroup classes if 'classes' in hostgroupConf.keys(): classList = list() for c in hostgroupConf['classes']: classLis...
<SYSTEM_TASK:> 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 fu...
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,...
<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( ...
<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: _LO...
<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, resp...
<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...
<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'...
<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 onl...
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 startbo...