output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Returns True if the value of component in attribute language is valid False otherwise.
Given the following Python 3 function, write the documentation def _is_valid_language(self): comp_str = self._encoded_value.lower() lang_rxc = re.compile(CPEComponentSimple._LANGTAG_PATTERN) return lang_rxc.match(comp_str) is not None
As a python code expert, you are capable of creating scripts from specifications.
def _is_valid_part(self): """ Return True if the value of component in attribute "part" is valid, and otherwise False. :returns: True if value of component is valid, False otherwise :rtype: boolean """ comp_str = self._encoded_value.lower() part_rxc = re...
Write a Python 3 script for returning True if the value of component in attribute part is valid False otherwise.
As a Python code translator, you convert algorithms and pseudocode into Python.
def _parse(self, comp_att): """ Check if the value of component is correct in the attribute "comp_att". :param string comp_att: attribute associated with value of component :returns: None :exception: ValueError - incorrect value of component """ errmsg = "Invali...
Create a Python 3 function to parse the value of component and return the component s value.
You are a Python code architect, reviewing and designing scalable and efficient code
Returns the value of component encoded as a string.
Can you tell what is the following Python 3 function doing def as_fs(self): s = self._standard_value result = [] idx = 0 while (idx < len(s)): c = s[idx] # get the idx'th character of s if c != "\\": # unquoted characters pass thru unharmed ...
As a python code expert, you are capable of creating scripts from specifications.
def as_uri_2_3(self): """ Returns the value of component encoded as URI string. Scans an input string s and applies the following transformations: - Pass alphanumeric characters thru untouched - Percent-encode quoted non-alphanumerics as needed - Unquoted special charac...
Can you create a Python 3 function that returns the value of component encoded as URI string.
As a python code expert, you are capable of creating scripts from specifications.
def set_value(self, comp_str, comp_att): """ Set the value of component. By default, the component has a simple value. :param string comp_str: new value of component :param string comp_att: attribute associated with value of component :returns: None :exception: V...
Can you implement a function in Python 3 that sets the value of component. By default the component has a simple value.
As a Python code analyst, you investigate and solve complex coding mysteries
def _decode(self): """ Convert the characters of string s to standard value (WFN value). Inspect each character in value of component. Copy quoted characters, with their escaping, into the result. Look for unquoted non alphanumerics and if not "*" or "?", add escaping. :...
Create a Python 3 function to convert the characters of string s to standard value (WFN value). Inspect each character in value of component. Copy quoted characters, with their escaping, into the result. Look for unquoted non alphanumerics and if not "*" or "?", add escaping. :exception: ValueError - invalid character ...
As a Python code analyst, you investigate and solve complex coding mysteries
Checks if the CPE Name is valid.
How would you explain what the following Python 3 function does def _parse(self): # CPE Name must not have whitespaces if (self.cpe_str.find(" ") != -1): errmsg = "Bad-formed CPE Name: it must not have whitespaces" raise ValueError(errmsg) # Partitioning of CPE Name in ...
You are a Python code generator, capable of creating scripts from specifications.
def get_attribute_values(self, att_name): """ Returns the values of attribute "att_name" of CPE Name. By default a only element in each part. :param string att_name: Attribute name to get :returns: List of attribute values :rtype: list :exception: ValueError - in...
Implement a Python 3 function for returning the values of attribute att_name of CPE Name.
You are a Python code generator, capable of creating scripts from specifications.
Set the value of component.
Can you generate a brief explanation for the following Python 3 code def set_value(self, comp_str): self._is_negated = False self._encoded_value = comp_str self._standard_value = super( CPEComponent2_3_URI_edpacked, self)._decode()
You are a Python code architect, reviewing and designing scalable and efficient code
def _decode(self): """ Convert the encoded value of component to standard value (WFN value). """ s = self._encoded_value elements = s.replace('~', '').split('!') dec_elements = [] for elem in elements: result = [] idx = 0 whil...
Create a Python 3 function for decoding the encoded value of component into a standard value.
As a Python code composer, you craft elegant and concise scripts.
def _is_valid_value(self): """ Return True if the value of component in generic attribute is valid, and otherwise False. :returns: True if value is valid, False otherwise :rtype: boolean """ comp_str = self._encoded_value value_pattern = [] valu...
Can you implement a function in Python 3 that returns True if the value of generic attribute is valid and otherwise False.
You are a Python code analyst, evaluating scripts for potential improvements.
Set the value of component. By default the component has a simple value.
Make a summary of the following Python 3 code def set_value(self, comp_str, comp_att): super(CPEComponent1_1, self).set_value(comp_str, comp_att) self._is_negated = comp_str.startswith('~')
As a Python code translator, you convert algorithms and pseudocode into Python.
Create a component object with value value.
How would you explain what the following Python 3 function does def _create_component(cls, att, value): if value == CPEComponent2_3_URI.VALUE_UNDEFINED: comp = CPEComponentUndefined() elif (value == CPEComponent2_3_URI.VALUE_ANY or value == CPEComponent2_3_URI.VALUE_EMPTY): ...
As a python code expert, you are capable of creating scripts from specifications.
def _unpack_edition(cls, value): """ Unpack its elements and set the attributes in wfn accordingly. Parse out the five elements: ~ edition ~ software edition ~ target sw ~ target hw ~ other :param string value: Value of edition attribute :returns: Dictionary with parts ...
Implement a Python 3 function for unpacking the edition attribute and sets the attributes in wfn accordingly.
As a Python code translator, you convert algorithms and pseudocode into Python.
def _parse(self): """ Checks if the CPE Name is valid. :returns: None :exception: ValueError - bad-formed CPE Name """ # CPE Name must not have whitespaces if (self._str.find(" ") != -1): msg = "Bad-formed CPE Name: it must not have whitespaces" ...
Can you create a Python 3 function that parses the CPE Name and returns a dictionary of components and edition parts.
You are a Python code generator, capable of creating scripts from specifications.
Returns the CPE Name as Well - Formed Name string of version 2. 3.
Can you tell what is the following Python 3 function doing def as_wfn(self): if self._str.find(CPEComponent2_3_URI.SEPARATOR_PACKED_EDITION) == -1: # Edition unpacked, only show the first seven components wfn = [] wfn.append(CPE2_3_WFN.CPE_PREFIX) for ck in CPE...
As a Python code composer, you craft elegant and concise scripts.
def _decode(self): """ Convert the characters of character in value of component to standard value (WFN value). This function scans the value of component and returns a copy with all percent-encoded characters decoded. :exception: ValueError - invalid character in value ...
Can you write a function in Python 3 where it converts the characters of character in value of component to standard value (WFN value). This function scans the value of component and returns a copy with all percent-encoded characters decoded. :exception: ValueError - invalid character in value of component
You are a Python code architect, reviewing and designing scalable and efficient code
def _is_valid_edition(self): """ Return True if the input value of attribute "edition" is valid, and otherwise False. :returns: True if value is valid, False otherwise :rtype: boolean """ comp_str = self._standard_value[0] packed = [] packed.app...
Can you create a Python 3 function that returns True if the input value of attribute edition is valid and otherwise False.
As a python code expert, you are capable of creating scripts from specifications.
Checks if the value of component in attribute language is valid and if it is valid.
Make a summary of the following Python 3 code def _is_valid_language(self): def check_generic_language(self, value): """ Check possible values in language part when region part exists or not in language value. Possible values of language attribute: a=letter ...
As a Python code analyst, you investigate and solve complex coding mysteries
def _is_valid_part(self): """ Return True if the value of component in attribute "part" is valid, and otherwise False. :returns: True if value of component is valid, False otherwise :rtype: boolean """ comp_str = self._encoded_value # Check if value of ...
Write a Python 3 function for checking if the value of component in attribute part is valid and if otherwise False.
As a python code expert, you are capable of creating scripts from specifications.
Compares two values associated with a attribute of two WFNs and returns the attribute comparison relation.
How would you explain what the following Python 3 function does def _compare(cls, source, target): if (CPESet2_3._is_string(source)): source = source.lower() if (CPESet2_3._is_string(target)): target = target.lower() # In this specification, unquoted wildcard characters...
You are a Python code analyst, evaluating scripts for potential improvements.
def _compare_strings(cls, source, target): """ Compares a source string to a target string, and addresses the condition in which the source string includes unquoted special characters. It performs a simple regular expression match, with the assumption that (as required) ...
How would you code a function in Python 3 to compare a source string to a target string, and addresses the condition in which the source string includes unquoted special characters. It performs a simple regular expression match, with the assumption that (as required) unquoted special characters appear only at the begin...
As a python code expert, you are capable of creating scripts from specifications.
def _contains_wildcards(cls, s): """ Return True if the string contains any unquoted special characters (question-mark or asterisk), otherwise False. Ex: _contains_wildcards("foo") => FALSE Ex: _contains_wildcards("foo\?") => FALSE Ex: _contains_wildcards("foo?") => TRUE...
Create a Python 3 function for returning True if the string contains any unquoted special characters and otherwise False.
As a Python code composer, you craft elegant and concise scripts.
Checks if the string str contains even wildcards.
Can you generate a brief explanation for the following Python 3 code def _is_even_wildcards(cls, str, idx): result = 0 while ((idx > 0) and (str[idx - 1] == "\\")): idx -= 1 result += 1 isEvenNumber = (result % 2) == 0 return isEvenNumber
As a python code expert, you are capable of creating scripts from specifications.
Checks if the given string value is a string value.
Explain what the following Python 3 code does def _is_string(cls, arg): isAny = arg == CPEComponent2_3_WFN.VALUE_ANY isNa = arg == CPEComponent2_3_WFN.VALUE_NA return not (isAny or isNa)
As a python code expert, you are capable of creating scripts from specifications.
Compares two set of WFNs and returns a generator of pairwise attribute - value - comparison results.
Given the following Python 3 function, write the documentation def compare_wfns(cls, source, target): # Compare results using the get() function in WFN for att in CPEComponent.CPE_COMP_KEYS_EXTENDED: value_src = source.get_attribute_values(att)[0] if value_src.find('"') > -1: ...
As a python code expert, you are capable of creating scripts from specifications.
Checks if the set - theoretic relation between two WFNs is DISJOINT.
Can you generate a brief explanation for the following Python 3 code def cpe_disjoint(cls, source, target): # If any pairwise comparison returned DISJOINT then # the overall name relationship is DISJOINT for att, result in CPESet2_3.compare_wfns(source, target): isDisjoint = result...
You are a Python code generator, capable of creating scripts from specifications.
def cpe_equal(cls, source, target): """ Compares two WFNs and returns True if the set-theoretic relation between the names is EQUAL. :param CPE2_3_WFN source: first WFN CPE Name :param CPE2_3_WFN target: seconds WFN CPE Name :returns: True if the set relation between sou...
Create a Python 3 function to compare two set - theoretic WFNs and returns True if the set - theoretic relation between the names is EQUAL otherwise False.
You are a Python code generator, capable of creating scripts from specifications.
def cpe_subset(cls, source, target): """ Compares two WFNs and returns True if the set-theoretic relation between the names is (non-proper) SUBSET. :param CPE2_3_WFN source: first WFN CPE Name :param CPE2_3_WFN target: seconds WFN CPE Name :returns: True if the set relat...
Can you write a function in Python 3 where it returns True if the set - theoretic relation between source and target is SUBSET otherwise False.
As a Python code composer, you craft elegant and concise scripts.
Returns True if the set - theoretic relation between two WFNs is SUPERSET otherwise False.
Can you tell what is the following Python 3 function doing def cpe_superset(cls, source, target): # If any pairwise comparison returned something other than SUPERSET # or EQUAL, then SUPERSET is False. for att, result in CPESet2_3.compare_wfns(source, target): isSuperset = result ==...
You are a Python code analyst, evaluating scripts for potential improvements.
def append(self, cpe): """ Adds a CPE element to the set if not already. Only WFN CPE Names are valid, so this function converts the input CPE object of version 2.3 to WFN style. :param CPE cpe: CPE Name to store in set :returns: None :exception: ValueError - inv...
Create a Python 3 function to add a CPE element to the set if not already.
You are a Python code architect, reviewing and designing scalable and efficient code
def name_match(self, wfn): """ Accepts a set of CPE Names K and a candidate CPE Name X. It returns 'True' if X matches any member of K, and 'False' otherwise. :param CPESet self: A set of m known CPE Names K = {K1, K2, …, Km}. :param CPE cpe: A candidate CPE Name X. :ret...
Create a Python 3 function for returning True if X matches any member of K False otherwise.
As a Python code translator, you convert algorithms and pseudocode into Python.
def _parse(self): """ Checks if the CPE Name is valid. :returns: None :exception: ValueError - bad-formed CPE Name """ # Check prefix and initial bracket of WFN if self._str[0:5] != CPE2_3_WFN.CPE_PREFIX: errmsg = "Bad-formed CPE Name: WFN prefix not...
Create a Python 3 function for checking if the CPE Name is valid.
As a python code expert, you are capable of creating scripts from specifications.
Returns True if the expression matches with the set False otherwise.
Can you generate the documentation for the following Python 3 function def language_match(self, cpeset, cpel_dom=None): # Root element tag TAG_ROOT = '#document' # A container for child platform definitions TAG_PLATSPEC = 'cpe:platform-specification' # Information about a platf...
As a Python code translator, you convert algorithms and pseudocode into Python.
def append(self, cpe): """ Adds a CPE Name to the set if not already. :param CPE cpe: CPE Name to store in set :returns: None :exception: ValueError - invalid version of CPE Name TEST: >>> from .cpeset2_2 import CPESet2_2 >>> from .cpe2_2 import CPE2_2...
Write a Python 3 script to add a CPE Name to the set if not already.
As a python code expert, you are capable of creating scripts from specifications.
Set the value of component.
Given the following Python 3 function, write the documentation def set_value(self, comp_str, comp_att): # Del double quotes of value str = comp_str[1:-1] self._standard_value = str # Parse the value super(CPEComponent2_3_WFN, self).set_value(str, comp_att)
As a python code expert, you are capable of creating scripts from specifications.
def append(self, cpe): """ Adds a CPE Name to the set if not already. :param CPE cpe: CPE Name to store in set :returns: None :exception: ValueError - invalid version of CPE Name TEST: >>> from .cpeset1_1 import CPESet1_1 >>> from .cpe1_1 import CPE1_1 ...
How would you code a function in Python 3 to add a CPE Name to the set if not already.
As a Python code translator, you convert algorithms and pseudocode into Python.
def name_match(self, cpe): """ Accepts a set of known instances of CPE Names and a candidate CPE Name, and returns 'True' if the candidate can be shown to be an instance based on the content of the known instances. Otherwise, it returns 'False'. :param CPESet self: A set...
Create a Python 3 function to test if a set of known instances of a candidate CPE Name X matches a set of known instances of a candidate CPE Name X and returns True if the candidate can be shown to be otherwise False.
You are a Python code analyst, evaluating scripts for potential improvements.
Checks if the CPE Name is valid.
Can you generate the documentation for the following Python 3 function def _parse(self): # CPE Name must not have whitespaces if (self._str.find(" ") != -1): msg = "Bad-formed CPE Name: it must not have whitespaces" raise ValueError(msg) # Partitioning of CPE Name ...
As a python code expert, you are capable of creating scripts from specifications.
def get_attribute_values(self, att_name): """ Returns the values of attribute "att_name" of CPE Name. By default a only element in each part. :param string att_name: Attribute name to get :returns: List of attribute values :rtype: list :exception: ValueError - in...
Can you write a function in Python 3 where it returns the values of attribute att_name of CPE Name. By default a only element in each part.
You are a Python code generator, capable of creating scripts from specifications.
def _parse(self): """ Checks if CPE Name is valid. :returns: None :exception: ValueError - bad-formed CPE Name """ # CPE Name must not have whitespaces if (self._str.find(" ") != -1): msg = "Bad-formed CPE Name: it must not have whitespaces" ...
Write a Python 3 function that can check if the CPE Name is valid.
As a Python code analyst, you investigate and solve complex coding mysteries
def as_wfn(self): """ Returns the CPE Name as WFN string of version 2.3. Only shows the first seven components. :return: CPE Name as WFN string :rtype: string :exception: TypeError - incompatible version """ wfn = [] wfn.append(CPE2_3_WFN.CPE_PRE...
Implement a function in Python 3 to return the CPE Name as WFN string of version 2. 3.
As a Python code translator, you convert algorithms and pseudocode into Python.
def _fact_ref_eval(cls, cpeset, wfn): """ Returns True if wfn is a non-proper superset (True superset or equal to) any of the names in cpeset, otherwise False. :param CPESet cpeset: list of CPE bound Names. :param CPE2_3_WFN wfn: WFN CPE Name. :returns: True if wfn is a ...
Can you create a Python 3 function that returns True if wfn is a proper superset of any of the names in cpeset False otherwise.
You are a Python code generator, capable of creating scripts from specifications.
def _check_fact_ref_eval(cls, cpel_dom): """ Returns the result (True, False, Error) of performing the specified check, unless the check isn’t supported, in which case it returns False. Error is a catch-all for all results other than True and False. :param string cpel_do...
How would you code a function in Python 3 to return the result (True, False, Error) of performing the specified check, unless the check isn’t supported, in which case it returns False. Error is a catch-all for all results other than True and False. :param string cpel_dom: XML infoset for the check_fact_ref element. :re...
As a Python code composer, you craft elegant and concise scripts.
def _unbind(cls, boundname): """ Unbinds a bound form to a WFN. :param string boundname: CPE name :returns: WFN object associated with boundname. :rtype: CPE2_3_WFN """ try: fs = CPE2_3_FS(boundname) except: # CPE name is not form...
Write a Python 3 script to unbind a bound form to a WFN object.
As a Python code analyst, you investigate and solve complex coding mysteries
def language_match(self, cpeset, cpel_dom=None): """ Accepts a set of known CPE Names and an expression in the CPE language, and delivers the answer True if the expression matches with the set. Otherwise, it returns False. :param CPELanguage self: An expression in the CPE Applic...
Write a Python 3 function for returning True if the expression can be satisfied by the language matching with the set.
You are a Python code generator, capable of creating scripts from specifications.
Returns True if the set of known instances of a candidate CPE Name X matches the set of known instances of a candidate CPE Name X.
Can you generate a brief explanation for the following Python 3 code def name_match(self, cpe): # An empty set not matching with any CPE if len(self) == 0: return False # If input CPE Name string is in set of CPE Name strings # not do searching more because there is a match...
You are a Python code architect, reviewing and designing scalable and efficient code
def _decode(self): """ Convert the encoded value of component to standard value (WFN value). """ result = [] idx = 0 s = self._encoded_value while (idx < len(s)): # Get the idx'th character of s c = s[idx] if (c in CPECompone...
Write a Python 3 function that can decode the encoded value of component into a standard value.
As a python code expert, you are capable of creating scripts from specifications.
def is_component(w, ids): """Check if the set of ids form a single connected component Parameters ---------- w : spatial weights boject ids : list identifiers of units that are tested to be a single connected component Returns ------- True : if the list of ...
Can you create a Python 3 function that checks if the set of ids form a single connected component. Returns True if the set of ids form a single connected component False otherwise
As a Python code translator, you convert algorithms and pseudocode into Python.
def check_contiguity(w, neighbors, leaver): """Check if contiguity is maintained if leaver is removed from neighbors Parameters ---------- w : spatial weights object simple contiguity based weights neighbors : list nodes that are to be checked if th...
Implement a Python 3 function for checking if a node is contiguity based on a set of neighbors.
As a Python code translator, you convert algorithms and pseudocode into Python.
def confirm(question, assume_yes=True): """ Ask user a yes/no question and return their response as a boolean. ``question`` should be a simple, grammatically complete question such as "Do you wish to continue?", and will have a string similar to ``" [Y/n] "`` appended automatically. This function w...
Write a Python 3 function for asking user a yes or no question and return their response as a boolean.
You are a Python code architect, reviewing and designing scalable and efficient code
Declare the view as a JSON API method
Can you tell what is the following Python 3 function doing def jsonapi(f): @wraps(f) def wrapper(*args, **kwargs): rv = f(*args, **kwargs) return make_json_response(rv) return wrapper
You are a Python code analyst, evaluating scripts for potential improvements.
Download + unpack given package into temp dir tmp and return the real_version and source directory.
Given the following Python 3 function, write the documentation def _unpack(c, tmp, package, version, git_url=None): real_version = version[:] source = None if git_url: pass # git clone into tempdir # git checkout <version> # set target to checkout # if version does not look S...
As a Python code translator, you convert algorithms and pseudocode into Python.
Vendorize a Python package into a specific version of a Crate or PyPI package.
How would you explain what the following Python 3 function does def vendorize( c, distribution, version, vendor_dir, package=None, git_url=None, license=None, ): """ Vendorize Python package ``distribution`` at version/SHA ``version``. Specify the vendor folder (e.g. ``<mypackag...
You are a Python code generator, capable of creating scripts from specifications.
def make_sudouser(c): """ Create a passworded sudo-capable user. Used by other tasks to execute the test suite so sudo tests work. """ user = c.travis.sudo.user password = c.travis.sudo.password # --create-home because we need a place to put conf files, keys etc # --groups travis becaus...
Write a Python 3 script for creating a passworded sudo - capable user.
You are a Python code analyst, evaluating scripts for potential improvements.
Create a new SSH directory and authorized_hosts for the current user.
Can you tell what is the following Python 3 function doing def make_sshable(c): user = c.travis.sudo.user home = "~{0}".format(user) # Run sudo() as the new sudo user; means less chown'ing, etc. c.config.sudo.user = user ssh_dir = "{0}/.ssh".format(home) # TODO: worth wrapping in 'sh -c' and usi...
As a python code expert, you are capable of creating scripts from specifications.
def sudo_run(c, command): """ Run some command under Travis-oriented sudo subshell/virtualenv. :param str command: Command string to run, e.g. ``inv coverage``, ``inv integration``, etc. (Does not necessarily need to be an Invoke task, but...) """ # NOTE: explicit shell wrapper beca...
Implement a function in Python 3 to run some command under Travis - oriented sudo subshell.
You are a Python code analyst, evaluating scripts for potential improvements.
Blacken the base node.
Can you generate a brief explanation for the following Python 3 code def blacken(c): if not PYTHON.startswith("3.6"): msg = "Not blackening, since Python {} != Python 3.6".format(PYTHON) print(msg, file=sys.stderr) return # Install, allowing config override of hardcoded default version ...
As a Python code composer, you craft elegant and concise scripts.
def _calc(self, x, y): """ List based implementation of binary tree algorithm for concordance measure after :cite:`Christensen2005`. """ x = np.array(x) y = np.array(y) n = len(y) perm = list(range(n)) perm.sort(key=lambda a: (x[a], y[a])) ...
Write a Python 3 script to calculate the concordance binary tree for a given set of nodes and their associated values.
As a Python code composer, you craft elegant and concise scripts.
def decorator(self, func): """ Wrapper function to decorate a function """ if inspect.isfunction(func): func._methodview = self elif inspect.ismethod(func): func.__func__._methodview = self else: raise AssertionError('Can only decorate function and met...
Can you implement a function in Python 3 that wraps function to decorate a function
You are a Python code architect, reviewing and designing scalable and efficient code
Test if the method matches the provided set of arguments.
Here you have a function in Python 3, explain what it does def matches(self, verb, params): return (self.ifset is None or self.ifset <= params) and \ (self.ifnset is None or self.ifnset.isdisjoint(params)) and \ (self.methods is None or verb in self.methods)
As a Python code translator, you convert algorithms and pseudocode into Python.
Detect a view matching the method and route_params.
Can you tell what is the following Python 3 function doing def _match_view(self, method, route_params): method = method.upper() route_params = frozenset(k for k, v in route_params.items() if v is not None) for view_name, info in self.methods_map[method].items(): if info.matches(meth...
You are a Python code analyst, evaluating scripts for potential improvements.
def route_as_view(cls, app, name, rules, *class_args, **class_kwargs): """ Register the view with an URL route :param app: Flask application :type app: flask.Flask|flask.Blueprint :param name: Unique view name :type name: str :param rules: List of route rules to use ...
Write a Python 3 script for registering the view with an URL rule
As a Python code translator, you convert algorithms and pseudocode into Python.
def steady_state(P): """ Calculates the steady state probability vector for a regular Markov transition matrix P. Parameters ---------- P : array (k, k), an ergodic Markov transition probability matrix. Returns ------- : array (k, ), st...
Write a Python 3 function that can calculate the steady state probability vector for a regular Markov transition matrix P.
You are a Python code analyst, evaluating scripts for potential improvements.
Calculates the matrix of first mean passage times for an ergodic Markov transition probability matrix.
Make a summary of the following Python 3 code def fmpt(P): P = np.matrix(P) k = P.shape[0] A = np.zeros_like(P) ss = steady_state(P).reshape(k, 1) for i in range(k): A[:, i] = ss A = A.transpose() I = np.identity(k) Z = la.inv(I - P + A) E = np.ones_like(Z) A_diag = np.d...
As a python code expert, you are capable of creating scripts from specifications.
Return the state of the current release.
Can you generate a brief explanation for the following Python 3 code def _converge(c): # # Data/state gathering # # Get data about current repo context: what branch are we on & what kind of # release does it appear to represent? branch, release_type = _release_line(c) # Short-circuit if typ...
You are a Python code architect, reviewing and designing scalable and efficient code
Print current release version changelog tag etc.
How would you explain what the following Python 3 function does def status(c): # TODO: wants some holistic "you don't actually HAVE any changes to # release" final status - i.e. all steps were at no-op status. actions, state = _converge(c) table = [] # NOTE: explicit 'sensible' sort (in rough order ...
As a python code expert, you are capable of creating scripts from specifications.
Prepare the contents of the a .
Can you tell what is the following Python 3 function doing def prepare(c): # Print dry-run/status/actions-to-take data & grab programmatic result # TODO: maybe expand the enum-based stuff to have values that split up # textual description, command string, etc. See the TODO up by their # definition too, ...
You are a Python code analyst, evaluating scripts for potential improvements.
def _release_line(c): """ Examine current repo state to determine what type of release to prep. :returns: A two-tuple of ``(branch-name, line-type)`` where: - ``branch-name`` is the current branch name, e.g. ``1.1``, ``master``, ``gobbledygook`` (or, usually, ``HEAD`` if not on a...
Write a Python 3 function for examining current repo state to determine what type of release to prep.
As a python code expert, you are capable of creating scripts from specifications.
def _versions_from_changelog(changelog): """ Return all released versions from given ``changelog``, sorted. :param dict changelog: A changelog dict as returned by ``releases.util.parse_changelog``. :returns: A sorted list of `semantic_version.Version` objects. """ versions = [Version(x...
Can you implement a function in Python 3 that returns all released versions from given changelog dict sorted.
You are a Python code architect, reviewing and designing scalable and efficient code
def _release_and_issues(changelog, branch, release_type): """ Return most recent branch-appropriate release, if any, and its contents. :param dict changelog: Changelog contents, as returned by ``releases.util.parse_changelog``. :param str branch: Branch name. :param release_type: ...
How would you implement a function in Python 3 that returns most recent release and issue numbers for a given branch.
You are a Python code architect, reviewing and designing scalable and efficient code
def _get_tags(c): """ Return sorted list of release-style tags as semver objects. """ tags_ = [] for tagstr in c.run("git tag", hide=True).stdout.strip().split("\n"): try: tags_.append(Version(tagstr)) # Ignore anything non-semver; most of the time they'll be non-release ...
Create a Python 3 function to return sorted list of release - style tags as semver objects.
As a Python code analyst, you investigate and solve complex coding mysteries
def _find_package(c): """ Try to find 'the' One True Package for this project. Mostly for obtaining the ``_version`` file within it. Uses the ``packaging.package`` config setting if defined. If not defined, fallback is to look for a single top-level Python package (directory containing ``__ini...
Create a Python 3 function to try to find the One True Package for this project.
As a python code expert, you are capable of creating scripts from specifications.
Build a new sdist and wheel archives.
Here you have a function in Python 3, explain what it does def build(c, sdist=True, wheel=False, directory=None, python=None, clean=True): # Config hooks config = c.config.get("packaging", {}) # TODO: update defaults to be None, then flip the below so non-None runtime # beats config. sdist = config....
As a Python code translator, you convert algorithms and pseudocode into Python.
def publish( c, sdist=True, wheel=False, index=None, sign=False, dry_run=False, directory=None, dual_wheels=False, alt_python=None, check_desc=False, ): """ Publish code to PyPI or index of choice. All parameters save ``dry_run`` and ``directory`` honor config settin...
Write a Python 3 script for publishing a single entry to PyPI or index of choice.
You are a Python code analyst, evaluating scripts for potential improvements.
Upload all build artifacts in a directory.
Can you generate a brief explanation for the following Python 3 code def upload(c, directory, index=None, sign=False, dry_run=False): # Obtain list of archive filenames, then ensure any wheels come first # so their improved metadata is what PyPI sees initially (otherwise, it # only honors the sdist's lesser...
As a Python code translator, you convert algorithms and pseudocode into Python.
def permute(self, permutations=99, alternative='two.sided'): """ Generate ransom spatial permutations for inference on LISA vectors. Parameters ---------- permutations : int, optional Number of random permutations of observations. alternative : string, option...
Can you write a function in Python 3 where it generates ransom spatial permutations for inference on LISA vectors.
As a python code expert, you are capable of creating scripts from specifications.
def plot(self, attribute=None, ax=None, **kwargs): """ Plot the rose diagram. Parameters ---------- attribute : (n,) ndarray, optional Variable to specify colors of the colorbars. ax : Matplotlib Axes instance, optional If given, the figure will b...
Implement a Python 3 function for plotting the rose diagram of the current object.
You are a Python code analyst, evaluating scripts for potential improvements.
Plot the LISA values starting from the same origin.
How would you explain what the following Python 3 function does def plot_origin(self): # TODO add attribute option to color vectors import matplotlib.cm as cm import matplotlib.pyplot as plt ax = plt.subplot(111) xlim = [self._dx.min(), self._dx.max()] ylim = [self._dy.min(), se...
As a python code expert, you are capable of creating scripts from specifications.
Plots the vectors of positional transition of LISA values in a scatterplot.
Given the following Python 3 function, write the documentation def plot_vectors(self, arrows=True): from splot.giddy import dynamic_lisa_vectors fig, ax = dynamic_lisa_vectors(self, arrows=arrows) return fig, ax
As a Python code analyst, you investigate and solve complex coding mysteries
Clean the target directory of the Nuke docs build.
Given the following Python 3 function, write the documentation def _clean(c): if isdir(c.sphinx.target): rmtree(c.sphinx.target)
You are a Python code generator, capable of creating scripts from specifications.
def _browse(c): """ Open build target's index.html in a browser (using 'open'). """ index = join(c.sphinx.target, c.sphinx.target_file) c.run("open {0}".format(index))
Write a Python 3 function for opening build target s index. html in a browser.
You are a Python code analyst, evaluating scripts for potential improvements.
def build( c, clean=False, browse=False, nitpick=False, opts=None, source=None, target=None, ): """ Build the project's Sphinx docs. """ if clean: _clean(c) if opts is None: opts = "" if nitpick: opts += " -n -W -T" cmd = "sphinx-build{0} {...
Write a Python 3 function that can build the project s Sphinx docs.
As a Python code translator, you convert algorithms and pseudocode into Python.
Display documentation contents with the tree program.
Can you tell what is the following Python 3 function doing def tree(c): ignore = ".git|*.pyc|*.swp|dist|*.egg-info|_static|_build|_templates" c.run('tree -Ca -I "{0}" {1}'.format(ignore, c.sphinx.source))
As a Python code translator, you convert algorithms and pseudocode into Python.
def sites(c): """ Build both doc sites w/ maxed nitpicking. """ # TODO: This is super lolzy but we haven't actually tackled nontrivial # in-Python task calling yet, so we do this to get a copy of 'our' context, # which has been updated with the per-collection config data of the # docs/www su...
Can you write a function in Python 3 where it builds both doc sites w/ maxed nitpicking.
You are a Python code analyst, evaluating scripts for potential improvements.
Watch both doc trees & rebuild them if files change.
Can you generate the documentation for the following Python 3 function def watch_docs(c): # TODO: break back down into generic single-site version, then create split # tasks as with docs/www above. Probably wants invoke#63. # NOTE: 'www'/'docs' refer to the module level sub-collections. meh. # Readme ...
As a Python code composer, you craft elegant and concise scripts.
Flattens the lower part of an n x n matrix into an n x n x 1 vector.
Given the following Python 3 function, write the documentation def get_lower(matrix): n = matrix.shape[0] lowerlist = [] for i in range(n): for j in range(n): if i > j: lowerlist.append(matrix[i, j]) veclen = n * (n - 1) / 2 lowvec = np.reshape(np.array(lowerlist)...
As a Python code composer, you craft elegant and concise scripts.
r Runs black on the current source tree.
How would you explain what the following Python 3 function does def blacken( c, line_length=79, folders=None, check=False, diff=False, find_opts=None ): r""" Run black on the current source tree (all ``.py`` files). .. warning:: ``black`` only runs on Python 3.6 or above. (However, it can be ...
As a Python code analyst, you investigate and solve complex coding mysteries
Normalizes the response value into a 3 - tuple
Can you tell what is the following Python 3 function doing def normalize_response_value(rv): status = headers = None if isinstance(rv, tuple): rv, status, headers = rv + (None,) * (3 - len(rv)) return rv, status, headers
As a Python code composer, you craft elegant and concise scripts.
def make_json_response(rv): """ Make JsonResponse :param rv: Response: the object to encode, or tuple (response, status, headers) :type rv: tuple|* :rtype: JsonResponse """ # Tuple of (response, status, headers) rv, status, headers = normalize_response_value(rv) # JsonResponse if is...
Write a Python 3 script to make a JsonResponse object from a response.
You are a Python code architect, reviewing and designing scalable and efficient code
def markov_mobility(p, measure="P", ini=None): """ Markov-based mobility index. Parameters ---------- p : array (k, k), Markov transition probability matrix. measure : string If measure= "P", :math:`M_{P} = \\frac{m-\sum_{i=1}^m P_{ii}}{m-1}`; ...
Create a Python 3 function to return a Markov - based mobility index.
You are a Python code architect, reviewing and designing scalable and efficient code
Returns a Prais conditional mobility measure for each class in the k - class hierarchy.
How would you explain what the following Python 3 function does def prais(pmat): pmat = np.array(pmat) pr = 1 - np.diag(pmat) return pr
As a Python code analyst, you investigate and solve complex coding mysteries
def homogeneity(transition_matrices, regime_names=[], class_names=[], title="Markov Homogeneity Test"): """ Test for homogeneity of Markov transition probabilities across regimes. Parameters ---------- transition_matrices : list of transition matrices for r...
Can you create a Python 3 function that tests for homogeneity of Markov transition probabilities across regimes.
As a python code expert, you are capable of creating scripts from specifications.
def sojourn_time(p): """ Calculate sojourn time based on a given transition probability matrix. Parameters ---------- p : array (k, k), a Markov transition probability matrix. Returns ------- : array (k, ), sojourn times. Each element is th...
Can you implement a function in Python 3 that calculates sojourn time based on a given transition probability matrix.
As a Python code translator, you convert algorithms and pseudocode into Python.
def spillover(self, quadrant=1, neighbors_on=False): """ Detect spillover locations for diffusion in LISA Markov. Parameters ---------- quadrant : int which quadrant in the scatterplot should form the core of a cluster. n...
Write a Python 3 function that can detect spillover locations for diffusion in LISA Markov.
As a Python code composer, you craft elegant and concise scripts.
def get_entity_propnames(entity): """ Get entity property names :param entity: Entity :type entity: sqlalchemy.ext.declarative.api.DeclarativeMeta :returns: Set of entity property names :rtype: set """ ins = entity if isinstance(entity, InstanceState) else inspect(entity) ...
Can you implement a function in Python 3 that gets entity property names
You are a Python code architect, reviewing and designing scalable and efficient code
Get the set of property names that are loaded in the entity.
Given the following Python 3 function, write the documentation def get_entity_loaded_propnames(entity): ins = inspect(entity) keynames = get_entity_propnames(ins) # If the entity is not transient -- exclude unloaded keys # Transient entities won't load these anyway, so it's safe to include all columns ...
You are a Python code generator, capable of creating scripts from specifications.
def next_minor(self): """ Return a Version whose minor number is one greater than self's. .. note:: The new Version will always have a zeroed-out bugfix/tertiary version number, because the "next minor release" of e.g. 1.2.1 is 1.3.0, not 1.3.1. """ clone = self.clone() ...
Write a Python 3 script to return a new version with a minor number greater than self s. version .
As a Python code composer, you craft elegant and concise scripts.
Checks that the encoding of the given name is valid Python encoding.
Given the following Python 3 function, write the documentation def _check_encoding(name, encoding_to_check, alternative_encoding, source=None): assert name is not None if encoding_to_check not in (alternative_encoding, 'chardet', None): try: ''.encode(encoding_to_check) except Looku...
You are a Python code analyst, evaluating scripts for potential improvements.