output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
r Test if a node is in the tree.
How would you explain what the following Python 3 function does def in_tree(self, name): if self._validate_node_name(name): raise RuntimeError("Argument `name` is not valid") return name in self._db
As a Python code translator, you convert algorithms and pseudocode into Python.
r Test if a node is a leaf node.
Explain what the following Python 3 code does def is_leaf(self, name): if self._validate_node_name(name): raise RuntimeError("Argument `name` is not valid") self._node_in_tree(name) return not self._db[name]["children"]
As a Python code composer, you craft elegant and concise scripts.
def make_root(self, name): # noqa: D302 r""" Make a sub-node the root node of the tree. All nodes not belonging to the sub-tree are deleted :param name: New root node name :type name: :ref:`NodeName` :raises: * RuntimeError (Argument \`name\` is not valid) ...
Implement a function in Python 3 to make a sub - node the root node of the tree.
As a Python code analyst, you investigate and solve complex coding mysteries
r""" Print node information (parent, children and data). :param name: Node name :type name: :ref:`NodeName` :raises: * RuntimeError (Argument \`name\` is not valid) * RuntimeError (Node *[name]* not in tree) Using the same example tree created in :p...
Given the following Python 3 function, write the documentation def print_node(self, name): # noqa: D302 if self._validate_node_name(name): raise RuntimeError("Argument `name` is not valid") self._node_in_tree(name) node = self._db[name] children = ( [self._split_...
As a Python code translator, you convert algorithms and pseudocode into Python.
This method renames a node in the tree.
How would you explain what the following Python 3 function does def rename_node(self, name, new_name): # noqa: D302 if self._validate_node_name(name): raise RuntimeError("Argument `name` is not valid") if self._validate_node_name(new_name): raise RuntimeError("Argument `new_name...
As a Python code translator, you convert algorithms and pseudocode into Python.
def search_tree(self, name): # noqa: D302 r""" Search tree for all nodes with a specific name. :param name: Node name to search for :type name: :ref:`NodeName` :raises: RuntimeError (Argument \`name\` is not valid) For example: >>> from __future__ import...
Write a Python 3 function that can search the tree for all nodes with a specific name.
You are a Python code generator, capable of creating scripts from specifications.
def find_root(filename, target='bids'): """Find base directory (root) for a filename. Parameters ---------- filename : instance of Path search the root for this file target: str 'bids' (the directory containing 'participants.tsv'), 'subject' (the directory starting with 'sub...
Implement a Python 3 function for finding the base directory of a file.
You are a Python code architect, reviewing and designing scalable and efficient code
Find nearest file in the hierarchy of directories.
Can you generate a brief explanation for the following Python 3 code def find_in_bids(filename, pattern=None, generator=False, upwards=False, wildcard=True, **kwargs): """Find nearest file matching some criteria. Parameters ---------- filename : instance of Path search the root...
You are a Python code generator, capable of creating scripts from specifications.
Define the format of the log entry.
Here you have a function in Python 3, explain what it does def define_format(self, plotStyle, plotSize): #Default sizes for computer sizing_dict = {} sizing_dict['figure.figsize'] = (14, 8) sizing_dict['legend.fontsize'] = 15 sizing_dict['axes.labelsize'] = 20 sizing_dic...
As a python code expert, you are capable of creating scripts from specifications.
def get_xyz(self, list_of_names=None): """Get xyz coordinates for these electrodes Parameters ---------- list_of_names : list of str list of electrode names to use Returns ------- list of tuples of 3 floats (x, y, z) list of xyz coordinat...
Write a Python 3 function that can get xyz coordinates for all the electrodes in the current locale.
You are a Python code architect, reviewing and designing scalable and efficient code
This function calculates the bces regression for 4 slopes.
Given the following Python 3 function, write the documentation def bces(y1,y1err,y2,y2err,cerr): # Arrays holding the code main results for each method: # Elements: 0-Y|X, 1-X|Y, 2-bisector, 3-orthogonal a,b,avar,bvar,covarxiz,covar_ba=numpy.zeros(4),numpy.zeros(4),numpy.zeros(4),numpy.zeros(4),numpy.zeros(4),numpy....
As a python code expert, you are capable of creating scripts from specifications.
Constructs Monte Carlo simulated data set using the Bootstrap algorithm.
Here you have a function in Python 3, explain what it does def bootstrap(v): if type(v)==list: vboot=[] # list of boostrapped arrays n=v[0].size iran=scipy.random.randint(0,n,n) # Array of random indexes for x in v: vboot.append(x[iran]) else: # if v is an array, not a list of arrays n=v.size iran=scipy.r...
You are a Python code analyst, evaluating scripts for potential improvements.
def bcesboot(y1,y1err,y2,y2err,cerr,nsim=10000): """ Does the BCES with bootstrapping. Usage: >>> a,b,aerr,berr,covab=bcesboot(x,xerr,y,yerr,cov,nsim) :param x,y: data :param xerr,yerr: measurement errors affecting x and y :param cov: covariance between the measurement errors (all are arrays) :param ns...
Write a Python 3 script to do the BCES with bootstrapping. Usage: >>> a,b,aerr,berr,covab=bcesboot(x,xerr,y,yerr,cov,nsim) :param x,y: data :param xerr,yerr: measurement errors affecting x and y :param cov: covariance between the measurement errors (all are arrays) :param nsim: number of Monte Carlo simulations (bootst...
As a Python code composer, you craft elegant and concise scripts.
This function is used to create a backup of the BCES with bootstrapping.
Can you generate the documentation for the following Python 3 function def bcesboot_backup(y1,y1err,y2,y2err,cerr,nsim=10000): import fish # Progress bar initialization peixe = fish.ProgressFish(total=nsim) print "Bootstrapping progress:" """ My convention for storing the results of the bces code below as m...
As a Python code composer, you craft elegant and concise scripts.
This function is a parallel version of the BCES with bootstrapping. It will create a list of lists that will be distributed among the cores of the current system.
Given the following Python 3 function, write the documentation def bcesp(y1,y1err,y2,y2err,cerr,nsim=10000): import time # for benchmarking import multiprocessing print "BCES,", nsim,"trials... ", tic=time.time() # Find out number of cores available ncores=multiprocessing.cpu_count() # We will divide the pro...
As a Python code composer, you craft elegant and concise scripts.
def mean(data): """Return the sample arithmetic mean of data.""" #: http://stackoverflow.com/a/27758326 n = len(data) if n < 1: raise ValueError('mean requires at least one data point') return sum(data)/n
Write a Python 3 script for returning the sample arithmetic mean of data.
As a Python code translator, you convert algorithms and pseudocode into Python.
def pstdev(data): """Calculates the population standard deviation.""" #: http://stackoverflow.com/a/27758326 n = len(data) if n < 2: raise ValueError('variance requires at least two data points') ss = _ss(data) pvar = ss/n # the population variance return pvar**0.5
Write a Python 3 script for calculating the population standard deviation.
You are a Python code architect, reviewing and designing scalable and efficient code
Sends an email to the specified recipients.
How would you explain what the following Python 3 function does def send_email(recipients: list, subject: str, text: str, html: str='', sender: str='', files: list=[], exceptions: bool=False): import sendgrid from sendgrid.helpers.mail import Content, Mail, Attachment from django.conf import settings fr...
You are a Python code architect, reviewing and designing scalable and efficient code
Unsafely removes HTML whitespace from a string.
How would you explain what the following Python 3 function does def remove_whitespace(s): ignores = {} for ignore in html_ignore_whitespace_re.finditer(s): name = "{}{}{}".format(r"{}", uuid.uuid4(), r"{}") ignores[name] = ignore.group() s = s.replace(ignore.group(), name) s = whites...
You are a Python code architect, reviewing and designing scalable and efficient code
Turn hashtag - like strings into HTML links
Make a summary of the following Python 3 code def hashtag_links(uri, s): for tag, after in hashtag_re.findall(s): _uri = '/' + (uri or "").lstrip("/") + quote(tag) link = '<a href="{}">#{}</a>{}'.format(_uri.lower(), tag, after) s = s.replace('#' + tag, link) return s
As a Python code composer, you craft elegant and concise scripts.
def mentions_links(uri, s): """ Turns mentions-like strings into HTML links, @uri: /uri/ root for the hashtag-like @s: the #str string you're looking for |@|mentions in -> #str HTML link |<a href="/uri/mention">mention</a>| """ for username, after in mentions_re.findall(s): ...
How would you code a function in Python 3 to turn mentions - like strings into HTML links
You are a Python code analyst, evaluating scripts for potential improvements.
def filter(self, query: Query): """Return a new filtered query. Use the tree to filter the query and return a new query "filtered". This query can be filtered again using another tree or even a manual filter. To manually filter query see : - https://docs.sqlalch...
Write a Python 3 script for returning a new filtered query.
As a Python code translator, you convert algorithms and pseudocode into Python.
Print a progress bar for a given iteration and total.
Here you have a function in Python 3, explain what it does def print_progress_bar(iteration, total, prefix='', suffix='', decimals=1, length=100, fill='█'): percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total))) # filled_length = int(length * iteration // total) # bar = fill * fi...
You are a Python code architect, reviewing and designing scalable and efficient code
def print_progress_bar_multi_threads(nb_threads, suffix='', decimals=1, length=15, fill='█'): """ Call in a loop to create terminal progress bar @params: iteration - Required : current iteration (Int) total - Required : total iterations (Int) ...
Write a Python 3 script for printing a progress bar for nb_threads threads.
As a python code expert, you are capable of creating scripts from specifications.
def upload(target): # type: (str) -> None """ Upload the release to a pypi server. TODO: Make sure the git directory is clean before allowing a release. Args: target (str): pypi target as defined in ~/.pypirc """ log.info("Uploading to pypi server <33>{}".format(target)) ...
Can you implement a function in Python 3 that uploads the release to a pypi server.
You are a Python code generator, capable of creating scripts from specifications.
def gen_pypirc(username=None, password=None): # type: (str, str) -> None """ Generate ~/.pypirc with the given credentials. Useful for CI builds. Can also get credentials through env variables ``PYPI_USER`` and ``PYPI_PASS``. Args: username (str): pypi username. If not given it...
Write a Python 3 script to generate a new. pypirc file with the given credentials.
You are a Python code analyst, evaluating scripts for potential improvements.
Returns a full path to the chosen SDF file.
How would you explain what the following Python 3 function does def pick_sdf(filename, directory=None): if directory is None: directory = utils.get_undecorated_calling_module() # If the 'cwd' is not '/output' (which indicates we're in a Container) # then remove the CWD and the anticipated '/...
As a python code expert, you are capable of creating scripts from specifications.
def set_text(self, text): """Sets the text attribute of the payload :param text: (str) Text of the message :return: None """ log = logging.getLogger(self.cls_logger + '.set_text') if not isinstance(text, basestring): msg = 'text arg must be a string' ...
Write a Python 3 function for setting the text attribute of the payload of the message Taxonomy object.
As a python code expert, you are capable of creating scripts from specifications.
def set_icon(self, icon_url): """Sets the icon_url for the message :param icon_url: (str) Icon URL :return: None """ log = logging.getLogger(self.cls_logger + '.set_icon') if not isinstance(icon_url, basestring): msg = 'icon_url arg must be a string' ...
Can you write a function in Python 3 where it sets the icon_url for the message
You are a Python code architect, reviewing and designing scalable and efficient code
def add_attachment(self, attachment): """Adds an attachment to the SlackMessage payload This public method adds a slack message to the attachment list. :param attachment: SlackAttachment object :return: None """ log = logging.getLogger(self.cls_logger + '.add_at...
Implement a function in Python 3 to add an attachment to the payload
You are a Python code architect, reviewing and designing scalable and efficient code
def send(self): """Sends the Slack message This public method sends the Slack message along with any attachments, then clears the attachments array. :return: None :raises: OSError """ log = logging.getLogger(self.cls_logger + '.send') if self.attachment...
Can you write a function in Python 3 where it sends the Slack message along with any availabe attachments.
You are a Python code architect, reviewing and designing scalable and efficient code
Sends a Slack message with an attachment for each cons3rt agent log file
Here you have a function in Python 3, explain what it does def send_cons3rt_agent_logs(self): log = logging.getLogger(self.cls_logger + '.send_cons3rt_agent_logs') log.debug('Searching for log files in directory: {d}'.format(d=self.dep.cons3rt_agent_log_dir)) for item in os.listdir(self.dep.con...
As a Python code analyst, you investigate and solve complex coding mysteries
Sends a Slack message with the contents of a text file.
Here you have a function in Python 3, explain what it does def send_text_file(self, text_file): log = logging.getLogger(self.cls_logger + '.send_text_file') if not isinstance(text_file, basestring): msg = 'arg text_file must be a string, found type: {t}'.format(t=text_file.__class__.__name_...
As a Python code analyst, you investigate and solve complex coding mysteries
def deploy(project, version, promote, quiet): """ Deploy the app to the target environment. The target environments can be configured using the ENVIRONMENTS conf variable. This will also collect all static files and compile translation messages """ from . import logic logic.deploy(project,...
Write a Python 3 function for deploying the app to the target environment.
You are a Python code analyst, evaluating scripts for potential improvements.
Calls the step method on each plugin in the list of plugins.
Can you generate the documentation for the following Python 3 function def call_plugins(self, step): ''' For each plugins, check if a "step" method exist on it, and call it Args: step (str): The method to search and call on each plugin ''' for plugin in self.plugins:...
As a Python code composer, you craft elegant and concise scripts.
Decorator to add a pretend option to any click command.
Make a summary of the following Python 3 code def pretend_option(fn): # type: (FunctionType) -> FunctionType """ Decorator to add a --pretend option to any click command. The value won't be passed down to the command, but rather handled in the callback. The value will be accessible through `peltak.core...
You are a Python code architect, reviewing and designing scalable and efficient code
Decorator to add a verbose option to any click command.
Can you tell what is the following Python 3 function doing def verbose_option(fn): def set_verbose(ctx, param, value): # pylint: disable=missing-docstring # type: (click.Context, str, Any) -> None from peltak.core import context context.set('verbose', value or 0) return click.optio...
As a Python code analyst, you investigate and solve complex coding mysteries
Print the changelog since last release.
Given the following Python 3 function, write the documentation def changelog(): # type: () -> str """ Print change log since last release. """ # Skip 'v' prefix versions = [x for x in git.tags() if versioning.is_valid(x[1:])] cmd = 'git log --format=%H' if versions: cmd += ' {}..HEAD'.f...
As a Python code analyst, you investigate and solve complex coding mysteries
Extracts all tagged items from a given text list item.
How would you explain what the following Python 3 function does def extract_changelog_items(text, tags): # type: (str) -> Dict[str, List[str]] """ Extract all tagged items from text. Args: text (str): Text to extract the tagged items from. Each tagged item is a paragraph tha...
You are a Python code generator, capable of creating scripts from specifications.
Method to generate real metaclass to be used
Can you generate the documentation for the following Python 3 function def _(mcs, cls_name="Object", with_meta=None): if with_meta is not None: class EXType(with_meta, mcs): _cls_name = cls_name _base_classes = [] _generated_class = None else: ...
As a Python code analyst, you investigate and solve complex coding mysteries
def get_class(mcs): """ Generates new class to gether logic of all available extensions :: mc = ExtensibleType._("MyClass") @six.add_metaclass(mc) class MyClassBase(object): pass # get class with all extensions ena...
Create a Python 3 function for returning the class that will be used to gether logic of all available extensions of the current object.
As a Python code translator, you convert algorithms and pseudocode into Python.
Adds new class cls to base classes
Can you tell what is the following Python 3 function doing def _add_base_class(mcs, cls): # Do all magic only if subclass had defined required attributes if getattr(mcs, '_base_classes_hash', None) is not None: meta = getattr(cls, 'Meta', None) _hash = getattr(meta, mcs._hashattr...
As a Python code translator, you convert algorithms and pseudocode into Python.
Method to generate real metaclass for the base class of the extended class.
Explain what the following Python 3 code does def _(mcs, cls_name='Object', with_meta=None, hashattr='_name'): extype = super(ExtensibleByHashType, mcs)._(cls_name=cls_name, with_meta=with_meta) class EXHType(extype): _hashattr = hashattr ...
As a Python code composer, you craft elegant and concise scripts.
def get_class(mcs, name, default=False): """ Generates new class to gether logic of all available extensions :: # Create metaclass *mc* mc = ExtensibleByHashType._("MyClass", hashattr='name') # Use metaclass *mc* to create base class for extensions ...
How would you code a function in Python 3 to return the class for the given key.
As a Python code composer, you craft elegant and concise scripts.
Return s list of names registered in this tree.
Make a summary of the following Python 3 code def get_registered_names(mcs): return [k for k, v in six.iteritems(mcs._base_classes_hash) if v]
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_last_day_of_month(t: datetime) -> int: """ Returns day number of the last day of the month :param t: datetime :return: int """ tn = t + timedelta(days=32) tn = datetime(year=tn.year, month=tn.month, day=1) tt = tn - timedelta(hours=1) return tt.day
Can you implement a function in Python 3 that returns the day number of the last day of the month
You are a Python code architect, reviewing and designing scalable and efficient code
def localize_time_range(begin: datetime, end: datetime, tz=None) -> (datetime, datetime): """ Localizes time range. Uses pytz.utc if None provided. :param begin: Begin datetime :param end: End datetime :param tz: pytz timezone or None (default UTC) :return: begin, end """ if not tz: ...
Write a Python 3 function that can localize the given time range. Uses pytz. utc if None provided.
You are a Python code generator, capable of creating scripts from specifications.
Returns this week begin and end.
Can you generate a brief explanation for the following Python 3 code def this_week(today: datetime=None, tz=None): if today is None: today = datetime.utcnow() begin = today - timedelta(days=today.weekday()) begin = datetime(year=begin.year, month=begin.month, day=begin.day) return localize_time_...
You are a Python code analyst, evaluating scripts for potential improvements.
def this_month(today: datetime=None, tz=None): """ Returns current month begin (inclusive) and end (exclusive). :param today: Some date in the month (defaults current datetime) :param tz: Timezone (defaults pytz UTC) :return: begin (inclusive), end (exclusive) """ if today is None: t...
Create a Python 3 function to return the current month begin and end.
You are a Python code analyst, evaluating scripts for potential improvements.
def next_month(today: datetime=None, tz=None): """ Returns next month begin (inclusive) and end (exclusive). :param today: Some date in the month (defaults current datetime) :param tz: Timezone (defaults pytz UTC) :return: begin (inclusive), end (exclusive) """ if today is None: toda...
Write a Python 3 function that can return next month begin and end.
As a Python code analyst, you investigate and solve complex coding mysteries
def last_year(today: datetime=None, tz=None): """ Returns last year begin (inclusive) and end (exclusive). :param today: Some date (defaults current datetime) :param tz: Timezone (defaults pytz UTC) :return: begin (inclusive), end (exclusive) """ if today is None: today = datetime.ut...
Implement a Python 3 function for returning last year begin and end.
As a Python code analyst, you investigate and solve complex coding mysteries
def add_month(t: datetime, n: int=1) -> datetime: """ Adds +- n months to datetime. Clamps to number of days in given month. :param t: datetime :param n: count :return: datetime """ t2 = t for count in range(abs(n)): if n > 0: t2 = datetime(year=t2.year, month=t2....
Implement a function in Python 3 to add + - n months to datetime.
You are a Python code architect, reviewing and designing scalable and efficient code
def per_delta(start: datetime, end: datetime, delta: timedelta): """ Iterates over time range in steps specified in delta. :param start: Start of time range (inclusive) :param end: End of time range (exclusive) :param delta: Step interval :return: Iterable collection of [(start+td*0, start+td*...
Create a Python 3 function to iterate over time range in steps specified in delta.
As a python code expert, you are capable of creating scripts from specifications.
Iterate over time range in one month steps.
Given the following Python 3 function, write the documentation def per_month(start: datetime, end: datetime, n: int=1): curr = start.replace(day=1, hour=0, minute=0, second=0, microsecond=0) while curr < end: curr_end = add_month(curr, n) yield curr, curr_end curr = curr_end
You are a Python code analyst, evaluating scripts for potential improvements.
def get_requirements() -> List[str]: """Return the requirements as a list of string.""" requirements_path = os.path.join( os.path.dirname(__file__), 'requirements.txt' ) with open(requirements_path) as f: return f.read().split()
How would you implement a function in Python 3 that returns the requirements as a list of string.
As a Python code analyst, you investigate and solve complex coding mysteries
def project_dev_requirements(): """ List requirements for peltak commands configured for the project. This list is dynamic and depends on the commands you have configured in your project's pelconf.yaml. This will be the combined list of packages needed to be installed in order for all the configured co...
Create a Python 3 function for listing requirements for peltak commands configured for the project.
As a Python code analyst, you investigate and solve complex coding mysteries
Get the parameters of a function.
Can you tell what is the following Python 3 function doing def get_func_params(method, called_params): insp = inspect.getfullargspec(method) if not isinstance(called_params, dict): raise UserWarning() _called_params = called_params.copy() params = {} arg_count = len(insp.args) arg_def_co...
As a python code expert, you are capable of creating scripts from specifications.
Builds all docker images for the project.
Can you generate a brief explanation for the following Python 3 code def build_images(): # type: () -> None """ Build all docker images for the project. """ registry = conf.get('docker.registry') docker_images = conf.get('docker.images', []) for image in docker_images: build_image(registry,...
You are a Python code generator, capable of creating scripts from specifications.
def push_images(): # type: () -> None """ Push all project docker images to a remote registry. """ registry = conf.get('docker.registry') docker_images = conf.get('docker.images', []) if registry is None: log.err("You must define docker.registry conf variable to push images") sys.ex...
Can you write a function in Python 3 where it pushes all project docker images to a remote registry.
As a Python code translator, you convert algorithms and pseudocode into Python.
def docker_list(registry_pass): # type: (str) -> None """ List docker images stored in the remote registry. Args: registry_pass (str): Remote docker registry password. """ registry = conf.get('docker.registry', None) if registry is None: log.err("You must define doc...
Can you implement a function in Python 3 that lists docker images stored in the remote registry.
You are a Python code architect, reviewing and designing scalable and efficient code
Builds a docker image.
Here you have a function in Python 3, explain what it does def build_image(registry, image): # type: (str, Dict[str, Any]) -> None """ Build docker image. Args: registry (str): The name of the registry this image belongs to. If not given, the resulting image will have a name...
You are a Python code generator, capable of creating scripts from specifications.
Push the given image to the given registry.
Given the following Python 3 function, write the documentation def push_image(registry, image): # type: (str, Dict[str, Any]) -> None """ Push the given image to selected repository. Args: registry (str): The name of the registry we're pushing to. This is the address of the ...
As a Python code composer, you craft elegant and concise scripts.
Builds a well formatted OPR data dictionary
How would you explain what the following Python 3 function does def _build_opr_data(self, data, store): return { "invoice_data": { "invoice": { "total_amount": data.get("total_amount"), "description": data.get("description") }, ...
You are a Python code analyst, evaluating scripts for potential improvements.
def create(self, data={}, store=None): """Initiazes an OPR First step in the OPR process is to create the OPR request. Returns the OPR token """ _store = store or self.store _data = self._build_opr_data(data, _store) if data else self._opr_data return self._proce...
Create a Python 3 function to create an OPR token.
As a Python code translator, you convert algorithms and pseudocode into Python.
def charge(self, data): """Second stage of an OPR request""" token = data.get("token", self._response["token"]) data = { "token": token, "confirm_token": data.get("confirm_token") } return self._process('opr/charge', data)
Can you implement a function in Python 3 that seconds stage of an OPR request
You are a Python code architect, reviewing and designing scalable and efficient code
def get_value(self, field, quick): # type: (Field, bool) -> Any """ Ask user the question represented by this instance. Args: field (Field): The field we're asking the user to provide the value for. quick (bool): Enable quick mode. In quic...
Can you create a Python 3 function that asks user the user to provide the value for the specified field.
As a python code expert, you are capable of creating scripts from specifications.
This method deletes an existing AMI ID and replaces an existing AMI with an image created from the provided instance ID.
Given the following Python 3 function, write the documentation def update_image(self, ami_id, instance_id): log = logging.getLogger(self.cls_logger + '.update_image') if not isinstance(ami_id, basestring): msg = 'Arg ami_id must be of type basestring, found: {t}'.format(t=ami_id.__class__.__...
You are a Python code generator, capable of creating scripts from specifications.
Create a CONS3RT - ready template from an instance ID
Can you generate the documentation for the following Python 3 function def create_cons3rt_template(self, instance_id, name, description='CONS3RT OS template'): log = logging.getLogger(self.cls_logger + '.create_cons3rt_template') if not isinstance(instance_id, basestring): msg = 'Arg instanc...
As a Python code translator, you convert algorithms and pseudocode into Python.
Copy the cons3rt template from the AMI to the new AMI.
Can you tell what is the following Python 3 function doing def copy_cons3rt_template(self, ami_id): log = logging.getLogger(self.cls_logger + '.copy_cons3rt_template') # Get the current AMI info try: ami_info = self.ec2.describe_images(DryRun=False, ImageIds=[ami_id], Owners=[self.o...
As a python code expert, you are capable of creating scripts from specifications.
This function will convert a string or bytes object into a base64 - encoded version of the object.
Can you generate a brief explanation for the following Python 3 code def uniorbytes(s, result=str, enc="utf-8", err="strict"): if isinstance(s, result): # the input is the desired one, return as is return s if isinstance(s, (bytes, str)): # the input is either a byte or a string, conver...
As a Python code analyst, you investigate and solve complex coding mysteries
Recode unicode strings to unicode
How would you explain what the following Python 3 function does def recode_unicode(s, encoding='utf-8'): if isinstance(s, str): return s.encode().decode(encoding) return s
As a Python code analyst, you investigate and solve complex coding mysteries
This function fixes the Unicode character that is not in the correct Unicode format.
Make a summary of the following Python 3 code def fix_bad_unicode(text): if not isinstance(text, str): return text if len(text) == 0: return text maxord = max(ord(char) for char in text) tried_fixing = [] if maxord < 128: # Hooray! It's ASCII! return text else: ...
As a Python code translator, you convert algorithms and pseudocode into Python.
u Given a string text returns a list of badness values.
Can you generate the documentation for the following Python 3 function def text_badness(text): u''' Look for red flags that text is encoded incorrectly: Obvious problems: - The replacement character \ufffd, indicating a decoding error - Unassigned or private-use Unicode characters Very weird t...
You are a Python code generator, capable of creating scripts from specifications.
def get_pycons3rt_home_dir(): """Returns the pycons3rt home directory based on OS :return: (str) Full path to pycons3rt home :raises: OSError """ if platform.system() == 'Linux': return os.path.join(os.path.sep, 'etc', 'pycons3rt') elif platform.system() == 'Windows': return os....
How would you implement a function in Python 3 that returns the full path to the pycons3rt home directory based on OS
You are a Python code architect, reviewing and designing scalable and efficient code
def initialize_pycons3rt_dirs(): """Initializes the pycons3rt directories :return: None :raises: OSError """ for pycons3rt_dir in [get_pycons3rt_home_dir(), get_pycons3rt_user_dir(), get_pycons3rt_conf_dir(), get_pycons3r...
Create a Python 3 function to initialize the pycons3rt directories
As a Python code analyst, you investigate and solve complex coding mysteries
Main function for the pycons3rt - logging.
Make a summary of the following Python 3 code def main(): # Create the pycons3rt directories try: initialize_pycons3rt_dirs() except OSError as ex: traceback.print_exc() return 1 # Replace log directory paths log_dir_path = get_pycons3rt_log_dir() + os.path.sep conf_co...
You are a Python code analyst, evaluating scripts for potential improvements.
Add git hooks for commit and push to run linting and tests.
Can you tell what is the following Python 3 function doing def add_hooks(): # type: () -> None """ Add git hooks for commit and push to run linting and tests. """ # Detect virtualenv the hooks should use # Detect virtualenv virtual_env = conf.getenv('VIRTUAL_ENV') if virtual_env is None: ...
As a python code expert, you are capable of creating scripts from specifications.
Starts working on a new feature by branching off develop.
Can you tell what is the following Python 3 function doing def start(name): # type: (str) -> None """ Start working on a new feature by branching off develop. This will create a new branch off develop called feature/<name>. Args: name (str): The name of the new feature. """ ...
You are a Python code architect, reviewing and designing scalable and efficient code
Update the feature with updates committed to develop.
How would you explain what the following Python 3 function does def update(): # type: () -> None """ Update the feature with updates committed to develop. This will merge current develop into the current branch. """ branch = git.current_branch(refresh=True) develop = conf.get('git.devel_branch'...
You are a Python code analyst, evaluating scripts for potential improvements.
def clean(exclude): # type: (bool, List[str]) -> None """ Remove all unnecessary files. Args: pretend (bool): If set to **True**, do not delete any files, just show what would be deleted. exclude (list[str]): A list of path patterns to exclude from deleti...
Create a Python 3 function to remove all unnecessary files in the current project.
You are a Python code generator, capable of creating scripts from specifications.
def init(quick): # type: () -> None """ Create an empty pelconf.yaml from template """ config_file = 'pelconf.yaml' prompt = "-- <35>{} <32>already exists. Wipe it?<0>".format(config_file) if exists(config_file) and not click.confirm(shell.fmt(prompt)): log.info("Canceled") return ...
Implement a Python 3 function for creating an empty pelconf. yaml from template
As a Python code translator, you convert algorithms and pseudocode into Python.
Generator that yields tracebacks found in a file object.
Explain what the following Python 3 code does def tracebacks_from_file(fileobj, reverse=False): if reverse: lines = deque() for line in BackwardsReader(fileobj): lines.appendleft(line) if tb_head in line: yield next(tracebacks_from_lines(lines)) ...
You are a Python code analyst, evaluating scripts for potential improvements.
Read a file line by line backwards.
Can you tell what is the following Python 3 function doing def BackwardsReader(file, BLKSIZE = 4096): buf = "" file.seek(0, 2) lastchar = file.read(1) trailing_newline = (lastchar == "\n") while 1: newline_pos = buf.rfind("\n") pos = file.tell() if newline_pos != -1: ...
You are a Python code analyst, evaluating scripts for potential improvements.
r Returns the numerical inverse of a function.
Make a summary of the following Python 3 code def inversefunc(func, y_values=None, domain=None, image=None, open_domain=None, args=(), accuracy=2): r"""Obtain the inverse of a function. Returns the numerical inverse...
You are a Python code generator, capable of creating scripts from specifications.
def progressed_bar(count, total=100, status=None, suffix=None, bar_len=10): """render a progressed.io like progress bar""" status = status or '' suffix = suffix or '%' assert isinstance(count, int) count_normalized = count if count <= total else total filled_len = int(round(bar_len * count_norma...
Write a Python 3 function for rendering a progressed. io like progress bar
As a Python code translator, you convert algorithms and pseudocode into Python.
def prettify(string): """ replace markup emoji and progressbars with actual things # Example ```python from habitipy.util import prettify print(prettify('Write thesis :book: ![progress](http://progressed.io/bar/0 "progress")')) ``` ``` Write thesis 📖 ██████████0% ``` """ ...
Can you implement a function in Python 3 that prettifies a string with markup emoji and progressbars.
As a python code expert, you are capable of creating scripts from specifications.
def assert_secure_file(file): """checks if a file is stored securely""" if not is_secure_file(file): msg = """ File {0} can be read by other users. This is not secure. Please run 'chmod 600 "{0}"'""" raise SecurityError(dedent(msg).replace('\n', ' ').format(file)) return True
Write a Python 3 function that can check if a file is stored securely
As a Python code translator, you convert algorithms and pseudocode into Python.
find and return gettext translation for package
Can you generate a brief explanation for the following Python 3 code def get_translation_for(package_name: str) -> gettext.NullTranslations: localedir = None for localedir in pkg_resources.resource_filename(package_name, 'i18n'), None: localefile = gettext.find(package_name, localedir) # type: ignore ...
As a Python code translator, you convert algorithms and pseudocode into Python.
finds and installs translation functions for package
Can you generate a brief explanation for the following Python 3 code def get_translation_functions(package_name: str, names: Tuple[str, ...] = ('gettext',)): translation = get_translation_for(package_name) return [getattr(translation, x) for x in names]
You are a Python code analyst, evaluating scripts for potential improvements.
append _ to all python keywords
How would you explain what the following Python 3 function does def escape_keywords(arr): for i in arr: i = i if i not in kwlist else i + '_' i = i if '-' not in i else i.replace('-', '_') yield i
You are a Python code analyst, evaluating scripts for potential improvements.
def download_api(branch=None) -> str: """download API documentation from _branch_ of Habitica\'s repo on Github""" habitica_github_api = 'https://api.github.com/repos/HabitRPG/habitica' if not branch: branch = requests.get(habitica_github_api + '/releases/latest').json()['tag_name'] curl = local...
Implement a Python 3 function for downloading API documentation from Habitica s repo on Github
As a Python code translator, you convert algorithms and pseudocode into Python.
save text to apidoc cache
Can you generate the documentation for the following Python 3 function def save_apidoc(text: str) -> None: apidoc_local = local.path(APIDOC_LOCAL_FILE) if not apidoc_local.dirname.exists(): apidoc_local.dirname.mkdir() with open(apidoc_local, 'w') as f: f.write(text)
As a Python code translator, you convert algorithms and pseudocode into Python.
def parse_apidoc( file_or_branch, from_github=False, save_github_version=True ) -> List['ApiEndpoint']: """read file and parse apiDoc lines""" apis = [] # type: List[ApiEndpoint] regex = r'(?P<group>\([^)]*\)){0,1} *(?P<type_>{[^}]*}){0,1} *' regex += r'(?P<field>[^ ]*) *(?P<description>.*)...
Write a Python 3 script to read file and parse apiDoc lines
As a python code expert, you are capable of creating scripts from specifications.
def into(self, val: str) -> Union['ApiNode', 'ApiEndpoint']: """Get another leaf node with name `val` if possible""" if val in self.paths: return self.paths[val] if self.param: return self.param raise IndexError(_("Value {} is missing from api").format(val))
Implement a Python 3 function for getting another leaf node with name val if possible
You are a Python code analyst, evaluating scripts for potential improvements.
def can_into(self, val: str) -> bool: """Determine if there is a leaf node with name `val`""" return val in self.paths or (self.param and self.param_name == val)
Implement a Python 3 function for determining if the node with name val can be inserted into this node.
You are a Python code analyst, evaluating scripts for potential improvements.
def place(self, part: str, val: Union['ApiNode', 'ApiEndpoint']): """place a leaf node""" if part.startswith(':'): if self.param and self.param != part: err = """Cannot place param '{}' as '{self.param_name}' exist on node already!""" raise ParamAlreadyExist(e...
Write a Python 3 script to place a leaf node
As a Python code composer, you craft elegant and concise scripts.
def keys(self) -> Iterator[str]: """return all possible paths one can take from this ApiNode""" if self.param: yield self.param_name yield from self.paths.keys()
Write a Python 3 script for returning all possible paths one can take from this ApiNode
You are a Python code analyst, evaluating scripts for potential improvements.
def add_param(self, group=None, type_='', field='', description=''): """parse and append a param""" group = group or '(Parameter)' group = group.lower()[1:-1] p = Param(type_, field, description) self.params[group][p.field] = p
Can you implement a function in Python 3 that parses and append a param
You are a Python code generator, capable of creating scripts from specifications.
def add_success(self, group=None, type_='', field='', description=''): """parse and append a success data param""" group = group or '(200)' group = int(group.lower()[1:-1]) self.retcode = self.retcode or group if group != self.retcode: raise ValueError('Two or more re...
Create a Python 3 function for parsing and append a success data param
As a python code expert, you are capable of creating scripts from specifications.
make a nice docstring for ipython
Given the following Python 3 function, write the documentation def render_docstring(self): res = '{{{self.method}}} {self.uri} {self.title}\n'.format(self=self) if self.params: for group, params in self.params.items(): res += '\n' + group + ' params:\n' for pa...
As a Python code composer, you craft elegant and concise scripts.