output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Search for entries in LDAP database.
Here you have a function in Python 3, explain what it does def search(self, base, scope, filterstr='(objectClass=*)', attrlist=None, limit=None) -> Generator[Tuple[str, dict], None, None]: """ Search for entries in LDAP database. """ _debug("search", base, scope, filterst...
You are a Python code architect, reviewing and designing scalable and efficient code
def rename(self, dn: str, new_rdn: str, new_base_dn: Optional[str] = None) -> None: """ rename a dn in the ldap database; see ldap module. doesn't return a result if transactions enabled. """ raise NotImplementedError()
Can you create a Python 3 function that renames a dn in the ldap database ; see ldap module. doesn t return a result if transactions enabled.
You are a Python code analyst, evaluating scripts for potential improvements.
Prepares the environment to be used by the user
Here you have a function in Python 3, explain what it does def prepare_env(org): # Add services key_service = org.service(type='builtin:cobalt_secure_store', name='Keystore') wf_service = org.service(type='builtin:workflow_service', name='Workflow', parameters='{}') # Add services to environment e...
As a Python code translator, you convert algorithms and pseudocode into Python.
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...
Can you write a function in Python 3 where it starts the base command line interface
You are a Python code architect, reviewing and designing scalable and efficient code
Duplicate all related objects of obj setting the value field to value.
How would you explain what the following Python 3 function does 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 du...
As a python code expert, you are capable of creating scripts from specifications.
Function getPayloadStruct Get the payload structure to do a creation or modification of the data object
Explain what the following Python 3 code does def getPayloadStruct(self, attributes, objType): payload = {self.payloadObj: attributes, objType + "_class": {self.payloadObj: attributes}} return payload
You are a Python code architect, reviewing and designing scalable and efficient code
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 ...
Write a Python 3 script to enter transaction management for a running thread.
As a Python code analyst, you investigate and solve complex coding mysteries
def leave_transaction_management(using=None): """ Leaves transaction management for a running thread. A dirty flag is carried over to the surrounding block, as a commit will commit all changes, even those from outside. (Commits are on connection level.) """ if using is None: for using in...
Write a Python 3 function that can leave transaction management for a running thread.
As a Python code analyst, you investigate and solve complex coding mysteries
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(): ...
Write a Python 3 script for returning True if the current transaction requires a commit for changes to happen.
You are a Python code architect, reviewing and designing scalable and efficient code
Checks whether the transaction manager is in manual or auto state.
Can you tell what is the following Python 3 function doing def is_managed(using=None): if using is None: managed = False for using in tldap.backend.connections: connection = tldap.backend.connections[using] if connection.is_managed(): managed = True re...
As a Python code translator, you convert algorithms and pseudocode into Python.
Commits the current state of the current language.
How would you explain what the following Python 3 function does def commit(using=None): if using is None: for using in tldap.backend.connections: connection = tldap.backend.connections[using] connection.commit() return connection = tldap.backend.connections[using] con...
You are a Python code generator, capable of creating scripts from specifications.
This function does the rollback itself resets the dirty flag.
Explain what the following Python 3 code does def rollback(using=None): if using is None: for using in tldap.backend.connections: connection = tldap.backend.connections[using] connection.rollback() return connection = tldap.backend.connections[using] connection.rollba...
As a Python code analyst, you investigate and solve complex coding mysteries
def _transaction_func(entering, exiting, using): """ Takes 3 things, an entering function (what to do to start this block of transaction management), an exiting function (what to do to end it, on both success and failure, and using which can be: None, indiciating transaction should occur on all defi...
Can you create a Python 3 function that returns a function that can be used to create a Transaction object.
You are a Python code architect, reviewing and designing scalable and efficient code
A decorator that activates commit on response.
Explain what the following Python 3 code does def commit_on_success(using=None): 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=...
You are a Python code analyst, evaluating scripts for potential improvements.
def run(self) -> Generator[Tuple[int, int, str, type], None, None]: """ Yields: tuple (line_number: int, offset: int, text: str, check: type) """ if is_test_file(self.filename): self.load() for func in self.all_funcs(): try: ...
Create a Python 3 function for yielding all checks for all functions in the database.
As a Python code translator, you convert algorithms and pseudocode into Python.
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...
Create a Python 3 function to reload glitter URL patterns if page URLs change.
You are a Python code architect, reviewing and designing scalable and efficient code
Execute all current and future payloads and execute any orphaned payloads until stop is called.
Can you generate the documentation for the following Python 3 function def run(self): 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()...
As a Python code composer, you craft elegant and concise scripts.
Stop execution of all current and future payloads
How would you explain what the following Python 3 function does def stop(self): if not self.running.wait(0.2): return self._logger.debug('runner disabled: %s', self) with self._lock: self.running.clear() self._stopped.wait()
As a Python code translator, you convert algorithms and pseudocode into Python.
Yields a list of strings that are separated by the words in the given string.
Can you tell what is the following Python 3 function doing def delimit_words(string: str) -> Generator[str, None, None]: # TODO: Reimplement this wordlike_characters = ("<", ">", "!") current_word = "" for i, character in enumerate(string): if ( not character.isalpha() an...
You are a Python code generator, capable of creating scripts from specifications.
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()): ...
Can you implement a function in Python 3 that normalizes whitespace and dedents.
As a Python code composer, you craft elegant and concise scripts.
Convert a string to dash - delimited words.
Can you generate the documentation for the following Python 3 function def to_dash_case(string: str) -> str: string = unidecode.unidecode(string) words = (_.lower() for _ in delimit_words(string)) string = "-".join(words) return string
You are a Python code analyst, evaluating scripts for potential improvements.
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]) ...
Write a Python 3 script for returning a list of all fixers found in the lib2to3 library
As a Python code analyst, you investigate and solve complex coding mysteries
return a single fixer found in the lib2to3 library
How would you explain what the following Python 3 function does 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") ...
You are a Python code analyst, evaluating scripts for potential improvements.
Returns field s single value prepared for saving into a database.
Can you generate the documentation for the following Python 3 function def to_db(self, value): # ensure value is valid self.validate(value) assert isinstance(value, list) value = list(value) for i, v in enumerate(value): value[i] = self.value_to_db(v) # ret...
As a Python code analyst, you investigate and solve complex coding mysteries
Converts the input value into the expected Python data type raising a ValidationException if the data can t be converted.
Explain what the following Python 3 code does def to_python(self, value): 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
You are a Python code architect, reviewing and designing scalable and efficient code
Validates value and throws ValidationError. Subclasses should override this to provide validation logic.
Can you generate the documentation for the following Python 3 function def validate(self, value): # check object type if not isinstance(value, list): raise tldap.exceptions.ValidationError( "is not a list and max_instances is %s" % self._max_instances) ...
You are a Python code architect, reviewing and designing scalable and efficient code
def clean(self, value): """ Convert the value's type and run validation. Validation errors from to_python and validate are propagated. The correct value is returned if no error is raised. """ value = self.to_python(value) self.validate(value) return value
Write a Python 3 script to convert the value s type and run validation.
You are a Python code generator, capable of creating scripts from specifications.
Returns field s single value prepared for saving into a database.
Can you generate the documentation for the following Python 3 function def value_to_db(self, value): if isinstance(value, six.string_types): value = value.encode("utf_8") return value
You are a Python code generator, capable of creating scripts from specifications.
def value_to_python(self, value): """ Converts the input single 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. """ if not isins...
Implement a function in Python 3 to convert the input single value into the expected Python data type raising django. core. exceptions. ValidationError if the data can t be converted.
You are a Python code architect, reviewing and designing scalable and efficient code
Validates value and throws ValidationError.
How would you explain what the following Python 3 function does def value_validate(self, value): if not isinstance(value, six.string_types): raise tldap.exceptions.ValidationError("should be a string")
As a Python code composer, you craft elegant and concise scripts.
Converts the input single value into the expected Python data type raising django. core. exceptions. ValidationError if the data can t be converted.
Can you tell what is the following Python 3 function doing def value_to_python(self, value): if not isinstance(value, bytes): raise tldap.exceptions.ValidationError("should be bytes") if value is None: return value try: return int(value) except (TypeEr...
As a Python code composer, you craft elegant and concise scripts.
Returns field s single value prepared for saving into a database.
Can you generate the documentation for the following Python 3 function def value_to_db(self, value): assert isinstance(value, six.integer_types) return str(value).encode("utf_8")
You are a Python code architect, reviewing and designing scalable and efficient code
Validate that the input value is a valid Python data type.
Given the following Python 3 function, write the documentation def value_validate(self, value): if not isinstance(value, six.integer_types): raise tldap.exceptions.ValidationError("should be a integer") try: return str(value) except (TypeError, ValueError): r...
You are a Python code analyst, evaluating scripts for potential improvements.
def value_to_python(self, value): """ Converts the input single 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. """ if not isins...
Create a Python 3 function for converting the input single value into the expected Python data type raising django. core. exceptions. ValidationError if the data can t be converted.
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns field s single value prepared for saving into a database.
Make a summary of the following Python 3 code def value_to_db(self, value): assert isinstance(value, datetime.date) assert not isinstance(value, datetime.datetime) try: value = value - datetime.date(year=1970, month=1, day=1) except OverflowError: raise tldap.exc...
You are a Python code analyst, evaluating scripts for potential improvements.
def value_validate(self, value): """ Converts the input single 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. """ if not isinst...
Create a Python 3 function for validating that the input value is of the expected Python data type.
As a Python code analyst, you investigate and solve complex coding mysteries
Returns field s single value prepared for saving into a database.
Here you have a function in Python 3, explain what it does def value_to_db(self, value): assert isinstance(value, datetime.datetime) try: value = value - datetime.datetime(1970, 1, 1) except OverflowError: raise tldap.exceptions.ValidationError("is too big a date") ...
You are a Python code analyst, evaluating scripts for potential improvements.
def value_validate(self, value): """ Converts the input single 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. """ if not isinst...
Can you write a function in Python 3 where it validates that the input value is of the expected Python data type.
As a Python code translator, you convert algorithms and pseudocode into Python.
Converts the input single value into the expected Python data type raising django. core. exceptions. ValidationError
Explain what the following Python 3 code does def value_to_python(self, value): if not isinstance(value, bytes): raise tldap.exceptions.ValidationError("should be a bytes") length = len(value) - 8 if length % 4 != 0: raise tldap.exceptions.ValidationError("Invalid sid") ...
As a Python code composer, you craft elegant and concise scripts.
Returns field s single value prepared for saving into a database.
How would you explain what the following Python 3 function does def value_to_db(self, value): assert isinstance(value, str) array = value.split("-") length = len(array) - 3 assert length >= 0 assert array[0] == 'S' array = array[1:2] + [length, 0, 0, 0, 0, 0] + array[...
As a Python code translator, you convert algorithms and pseudocode into Python.
Validates the input single value into the expected Python data type raising django. core. exceptions. ValidationError if the data can t be converted.
Make a summary of the following Python 3 code def value_validate(self, value): if not isinstance(value, str): raise tldap.exceptions.ValidationError("Invalid sid") array = value.split("-") length = len(array) - 3 if length < 1: raise tldap.exceptions.ValidationE...
As a python code expert, you are capable of creating scripts from specifications.
Get data for this component
Here you have a function in Python 3, explain what it does def get(self, id): 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()
You are a Python code analyst, evaluating scripts for potential improvements.
def create(self, data): """Create a new component """ response = self.http.post(str(self), json=data, auth=self.auth) response.raise_for_status() return response.json()
Implement a function in Python 3 to create a new component
As a Python code analyst, you investigate and solve complex coding mysteries
def update(self, id, data): """Update a component """ id = self.as_id(id) response = self.http.patch( '%s/%s' % (self, id), json=data, auth=self.auth ) response.raise_for_status() return response.json()
Can you implement a function in Python 3 that updates a component s related resource attributes.
As a Python code composer, you craft elegant and concise scripts.
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()
How would you implement a function in Python 3 that deletes a component by id
You are a Python code architect, reviewing and designing scalable and efficient code
def get_list(self, url=None, callback=None, limit=100, **data): """Get a list of this github component :param url: full url :param Comp: a :class:`.Component` class :param callback: Optional callback :param limit: Optional number of items to retrieve :param data: addition...
Can you write a function in Python 3 where it gets a list of this github component.
As a Python code composer, you craft elegant and concise scripts.
Return all comments for this issue
Here you have a function in Python 3, explain what it does def comments(self, issue): commit = self.as_id(issue) return self.get_list(url='%s/%s/comments' % (self, commit))
As a Python code analyst, you investigate and solve complex coding mysteries
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). """ ...
How would you implement a function in Python 3 that returns a boolean if the user in the request has edit permission for the object.
You are a Python code analyst, evaluating scripts for potential improvements.
Returns a boolean if the user in the request has publish permission for the object.
Given the following Python 3 function, write the documentation def has_publish_permission(self, request, obj=None): 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 i...
As a Python code translator, you convert algorithms and pseudocode into Python.
Get a valid semantic version for a tag.
Explain what the following Python 3 code does def semantic_version(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.MI...
You are a Python code analyst, evaluating scripts for potential improvements.
def load(self, data): """ Function load Store the object data """ self.clear() self.update(data) self.enhance()
Create a Python 3 function for functioning load Load the object data into the internal cache
You are a Python code generator, capable of creating scripts from specifications.
def enhance(self): """ Function enhance Enhance the object with new item or enhanced items """ if self.objName in ['hosts', 'hostgroups', 'puppet_classes']: from foreman.itemSmartClassParameter\ import ItemSmartClassParameter ...
Create a Python 3 function for functioning enhance Enhance the object with new item or enhanced items
You are a Python code analyst, evaluating scripts for potential improvements.
Function reload Sync the full object with the current object s metadata
How would you explain what the following Python 3 function does def reload(self): self.load(self.api.get(self.objName, self.key))
You are a Python code analyst, evaluating scripts for potential improvements.
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 i...
Implement a Python 3 function for functioning getParamGet Return a dict of parameters or a parameter value
You are a Python code architect, reviewing and designing scalable and efficient code
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...
How would you implement a function in Python 3 that functions checkAndCreateClasses Check and add puppet class to the list of classes and return True if the classes are already present in the list.
As a Python code composer, you craft elegant and concise scripts.
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 param...
Write a Python 3 function that can function checkAndCreateParams Check and add global parameters to the parameters dict
You are a Python code architect, reviewing and designing scalable and efficient code
Turn a version string into a dict with major / minor info.
Make a summary of the following Python 3 code def version_dict(version): match = version_re.match(str(version) or '') letters = 'alpha pre'.split() numbers = 'major minor1 minor2 minor3 alpha_ver pre_ver'.split() if match: d = match.groupdict() for letter in letters: d[letter...
As a Python code analyst, you investigate and solve complex coding mysteries
def get_diff(source, dest): """Get the diff between two records list in this order: - to_create - to_delete """ # First build a dict from the lists, with the ID as the key. source_dict = {record['id']: record for record in source} dest_dict = {record['id']: record for record in dest}...
Write a Python 3 function that can get the diff between two records lists in this order.
As a Python code analyst, you investigate and solve complex coding mysteries
Return a list of form choices for versions of this object which can be published.
Here you have a function in Python 3, explain what it does def object_version_choices(obj): 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....
As a Python code translator, you convert algorithms and pseudocode into Python.
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)...
How would you code a function in Python 3 to load a manifest file and apply template values
You are a Python code generator, capable of creating scripts from specifications.
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 tran...
Implement a function in Python 3 to set the header of the current packet.
You are a Python code generator, capable of creating scripts from specifications.
Add a new modifier to the list.
How would you explain what the following Python 3 function does def add_modifier(self, m_type=XenaModifierType.standard, **kwargs): if m_type == XenaModifierType.standard: modifier = XenaModifier(self, index='{}/{}'.format(self.index, len(self.modifiers))) else: modifier = XenaX...
You are a Python code analyst, evaluating scripts for potential improvements.
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....
How would you implement a function in Python 3 that removes a modifier from the current object.
You are a Python code generator, capable of creating scripts from specifications.
def modifiers(self): """ :return: dictionary {index: object} of standard modifiers. """ if not self.get_objects_by_type('modifier'): for index in range(int(self.get_attribute('ps_modifiercount'))): XenaModifier(self, index='{}/{}'.format(self.index, index)).ge...
Write a Python 3 function that can return a dictionary of standard modifiers.
As a Python code analyst, you investigate and solve complex coding mysteries
def xmodifiers(self): """ :return: dictionary {index: object} of extended modifiers. """ if not self.get_objects_by_type('xmodifier'): try: for index in range(int(self.get_attribute('ps_modifierextcount'))): XenaXModifier(self, index='{}/{}...
Write a Python 3 function that can return dictionary of extended modifiers.
As a python code expert, you are capable of creating scripts from specifications.
def DRAGONS(flat=False, extras=True): """DRAGONS cosmology assumes WMAP7 + BAO + H_0 mean from Komatsu et al. (2011) ApJS 192 18K (arxiv:1001.4538v1) Parameters ---------- flat: boolean If True, sets omega_lambda_0 = 1 - omega_M_0 to ensure omega_k_0 = 0 exactly. Also sets omega_k_0 =...
Create a Python 3 function for returning a DAGONS cosmology for the current WMAP7 + BAO + H_0 mean from a base - set of WMAP7 + BAO + H_0 mean from a base - set of WMAP7 + BAO + H_0 mean from a base - set of WMAP7 + H_0 mean from a base - set of WMAP7 + H_0 mean from a base - set of WMAP7 + H_0.
You are a Python code architect, reviewing and designing scalable and efficient code
def Planck_2015(flat=False, extras=True): """Planck 2015 XII: Cosmological parameters Table 4 column Planck TT, TE, EE + lowP + lensing + ext from Ade et al. (2015) A&A in press (arxiv:1502.01589v1) Parameters ---------- flat: boolean If True, sets omega_lambda_0 = 1 - omega_M_0 to ensu...
Create a Python 3 function to return a base - level Planck - 2015 cosmological parameters table for Ade et al.
You are a Python code architect, reviewing and designing scalable and efficient code
Add a DN to the LDAP database ; See ldap module. Doesn t return a result
Make a summary of the following Python 3 code def add(self, dn: str, mod_list: dict) -> None: return self._do_with_retry(lambda obj: obj.add_s(dn, mod_list))
As a Python code analyst, you investigate and solve complex coding mysteries
Modify a DN in the LDAP database.
Can you generate the documentation for the following Python 3 function def modify(self, dn: str, mod_list: dict) -> None: return self._do_with_retry(lambda obj: obj.modify_s(dn, mod_list))
You are a Python code architect, reviewing and designing scalable and efficient code
Rename a dn in the ldap database ; see ldap module. doesn t return a result if transactions enabled.
Given the following Python 3 function, write the documentation def rename(self, dn: str, new_rdn: str, new_base_dn: Optional[str] = None) -> None: return self._do_with_retry( lambda obj: obj.rename_s(dn, new_rdn, new_base_dn))
As a Python code translator, you convert algorithms and pseudocode into Python.
Get a column name from META api.
How would you explain what the following Python 3 function does def get_column_name(self, column_name): 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...
As a Python code composer, you craft elegant and concise scripts.
Returns the software version of the current repository
Can you generate a brief explanation for the following Python 3 code def version(self): branches = self.branches() if self.info['branch'] == branches.sandbox: try: return self.software_version() except Exception as exc: raise utils.CommandError( ...
As a Python code composer, you craft elegant and concise scripts.
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) ret...
Can you write a function in Python 3 where it validates version by checking if it is a valid semantic version and its value is higher than latest github tag
As a Python code composer, you craft elegant and concise scripts.
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'] )
Implement a Python 3 function for checking if build should be skipped
As a Python code composer, you craft elegant and concise scripts.
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)
How would you code a function in Python 3 to send a message to third party applications
As a Python code composer, you craft elegant and concise scripts.
def get_kinto_records(kinto_client, bucket, collection, permissions, config=None): """Return all the kinto records for this bucket/collection.""" # Create bucket if needed try: kinto_client.create_bucket(id=bucket, if_not_exists=True) except KintoException as e: if ...
Implement a function in Python 3 to return all the kinto records for this bucket and collection.
You are a Python code generator, capable of creating scripts from specifications.
def add_chassis(self, chassis): """ :param ip: chassis object """ self.chassis_list[chassis] = XenaSocket(self.logger, chassis.ip, chassis.port) self.chassis_list[chassis].connect() KeepAliveThread(self.chassis_list[chassis]).start() self.send_command(chassis, 'c...
Implement a Python 3 function for adding a new chassis to the set of chassis list
As a Python code analyst, you investigate and solve complex coding mysteries
Send command and do not parse output.
Can you tell what is the following Python 3 function doing def send_command(self, obj, command, *arguments): index_command = obj._build_index_command(command, *arguments) self.chassis_list[obj.chassis].sendQueryVerify(index_command)
You are a Python code architect, reviewing and designing scalable and efficient code
Send command and wait for single line output.
Can you generate the documentation for the following Python 3 function def send_command_return(self, obj, command, *arguments): index_command = obj._build_index_command(command, *arguments) return obj._extract_return(command, self.chassis_list[obj.chassis].sendQuery(index_command))
As a Python code composer, you craft elegant and concise scripts.
def send_command_return_multilines(self, obj, command, *arguments): """ Send command and wait for multiple lines output. """ index_command = obj._build_index_command(command, *arguments) return self.chassis_list[obj.chassis].sendQuery(index_command, True)
Write a Python 3 function for sending command and wait for multiple lines output.
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns single object attribute.
Can you generate the documentation for the following Python 3 function def get_attribute(self, obj, attribute): 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_ret...
You are a Python code generator, capable of creating scripts from specifications.
Get all object s attributes.
Can you generate the documentation for the following Python 3 function def get_attributes(self, obj): attributes = {} for info_config_command in obj.info_config_commands: index_commands_values = self.send_command_return_multilines(obj, info_config_command, '?') # poor implementa...
You are a Python code architect, reviewing and designing scalable and efficient code
def set_attributes(self, obj, **attributes): """ Set attributes. :param obj: requested object. :param attributes: dictionary of {attribute: value} to set """ for attribute, value in attributes.items(): self.send_command(obj, attribute, value)
How would you code a function in Python 3 to set attributes of the object.
You are a Python code generator, capable of creating scripts from specifications.
Send CLI command that returns list of integer counters.
Can you tell what is the following Python 3 function doing def get_stats(self, obj, stat_name): return [int(v) for v in self.get_attribute(obj, stat_name).split()]
You are a Python code architect, reviewing and designing scalable and efficient code
Iterate depth - first.
Can you generate the documentation for the following Python 3 function def depth_first(self, top_down=True): for child in tuple(self): if top_down: yield child if isinstance(child, UniqueTreeContainer): yield from child.depth_first(top_down=top_down) ...
As a Python code analyst, you investigate and solve complex coding mysteries
def reserve(self, force=False): """ Reserve port. XenaManager-2G -> Reserve/Relinquish Port. :param force: True - take forcefully, False - fail if port is reserved by other user """ p_reservation = self.get_attribute('p_reservation') if p_reservation == 'RESERVED_BY_YO...
Create a Python 3 function to reserve port. XenaManager-2G -> Reserve/Relinquish Port. :param force: True - take forcefully, False - fail if port is reserved by other user
You are a Python code generator, capable of creating scripts from specifications.
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 comm...
How would you code a function in Python 3 to load the configuration file from xpc file.
You are a Python code generator, capable of creating scripts from specifications.
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_fu...
Write a Python 3 function for saving the current configuration file to xpc file.
You are a Python code analyst, evaluating scripts for potential improvements.
Add a new stream to the current entry.
Can you tell what is the following Python 3 function doing def add_stream(self, name=None, tpld_id=None, state=XenaStreamState.enabled): stream = XenaStream(parent=self, index='{}/{}'.format(self.index, len(self.streams)), name=name) stream._create() tpld_id = tpld_id if tpld_id else XenaStream...
You are a Python code architect, reviewing and designing scalable and efficient code
def read_port_stats(self): """ :return: dictionary {group name {stat name: value}}. Sea XenaPort.stats_captions. """ stats_with_captions = OrderedDict() for stat_name in self.stats_captions.keys(): stats_with_captions[stat_name] = self.read_stat(self.stat...
Write a Python 3 function that can read the stats for all the elements in the stats_captions attribute of the Sea XenaPort object.
You are a Python code analyst, evaluating scripts for potential improvements.
def read_stream_stats(self): """ :return: dictionary {stream index {stat name: value}}. Sea XenaStream.stats_captions. """ stream_stats = OrderedDict() for stream in self.streams.values(): stream_stats[stream] = stream.read_stats() return stream_st...
Can you write a function in Python 3 where it reads the stream stats for all the streams in this instance
You are a Python code architect, reviewing and designing scalable and efficient code
def read_tpld_stats(self): """ :return: dictionary {tpld index {group name {stat name: value}}}. Sea XenaTpld.stats_captions. """ payloads_stats = OrderedDict() for tpld in self.tplds.values(): payloads_stats[tpld] = tpld.read_stats() return payloa...
How would you code a function in Python 3 to read the tpld stats for all the items in the tplds.
As a Python code translator, you convert algorithms and pseudocode into Python.
def streams(self): """ :return: dictionary {id: object} of all streams. :rtype: dict of (int, xenamanager.xena_stream.XenaStream) """ if not self.get_objects_by_type('stream'): tpld_ids = [] for index in self.get_attribute('ps_indices').split(): ...
Implement a Python 3 function for returning a dictionary of all streams.
You are a Python code generator, capable of creating scripts from specifications.
Return a dictionary of all current tplds.
Can you generate a brief explanation for the following Python 3 code def tplds(self): # As TPLDs are dynamic we must re-read them each time from the port. self.parent.del_objects_by_type('tpld') for tpld in self.get_attribute('pr_tplds').split(): XenaTpld(parent=self, index='{}/{}'....
You are a Python code generator, capable of creating scripts from specifications.
Reads the stats from the Sea XenaTpld and returns a dictionary of the stats.
Make a summary of the following Python 3 code def read_stats(self): stats_with_captions = OrderedDict() for stat_name in self.stats_captions.keys(): stats_with_captions[stat_name] = self.read_stat(self.stats_captions[stat_name], stat_name) return stats_with_captions
As a Python code translator, you convert algorithms and pseudocode into Python.
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 pa...
Write a Python 3 function for getting captured packets from chassis.
You are a Python code architect, reviewing and designing scalable and efficient code
def packets(self): """ :return: dictionary {id: object} of all packets. :rtype: dict of (int, xenamanager.xena_port.XenaCapturePacket) """ if not self.get_object_by_type('cappacket'): for index in range(0, self.read_stats()['packets']): XenaCapturePac...
How would you code a function in Python 3 to return a dictionary of all packets.
As a Python code composer, you craft elegant and concise scripts.
Register a new rule above a given supply threshold.
Make a summary of the following Python 3 code def add(self, rule: ControlRule = None, *, supply: float): 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._threshold...
You are a Python code analyst, evaluating scripts for potential improvements.
Create an unbound prototype of this class partially applying arguments
How would you explain what the following Python 3 function does def s(self, *args, **kwargs) -> Partial[Stepwise]: return Partial(Stepwise, self.base, *self.rules, *args, **kwargs)
As a python code expert, you are capable of creating scripts from specifications.
Get the revisionId of this object.
Make a summary of the following Python 3 code def revisionId(self): log.warning("'RevisionId' requested, ensure that you are don't need 'id'") revision_id = self.json()['revisionId'] assert revision_id == self.id, "RevisionId differs id-{}!=revisionId-{}".format(self.id, revision_id) ret...
As a Python code composer, you craft elegant and concise scripts.