text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _jit(function): """ Compile a function using a jit compiler. The function is always compiled to check errors, but is only used outside tests, so that code co...
import sys compiled = numba.jit(function) if hasattr(sys, '_called_from_test'): return function else: # pragma: no cover return compiled
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _sqrt(x): """ Return square root of an ndarray. This sqrt function for ndarrays tries to use the exponentiation operator if the objects stored do not supply ...
x = np.clip(x, a_min=0, a_max=None) try: return np.sqrt(x) except AttributeError: exponent = 0.5 try: exponent = np.take(x, 0).from_float(exponent) except AttributeError: pass return x ** exponent
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _transform_to_2d(t): """Convert vectors to column matrices, to always have a 2d shape."""
t = np.asarray(t) dim = len(t.shape) assert dim <= 2 if dim < 2: t = np.atleast_2d(t).T return t
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _can_be_double(x): """ Return if the array can be safely converted to double. That happens when the dtype is a float with the same size of a double or narrow...
return ((np.issubdtype(x.dtype, np.floating) and x.dtype.itemsize <= np.dtype(float).itemsize) or (np.issubdtype(x.dtype, np.signedinteger) and np.can_cast(x, float)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _cdist_naive(x, y, exponent=1): """Pairwise distance, custom implementation."""
squared_norms = ((x[_np.newaxis, :, :] - y[:, _np.newaxis, :]) ** 2).sum(2) exponent = exponent / 2 try: exponent = squared_norms.take(0).from_float(exponent) except AttributeError: pass return squared_norms ** exponent
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _cdist_scipy(x, y, exponent=1): """Pairwise distance between the points in two sets."""
metric = 'euclidean' if exponent != 1: metric = 'sqeuclidean' distances = _spatial.distance.cdist(x, y, metric=metric) if exponent != 1: distances **= exponent / 2 return distances
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _cdist(x, y, exponent=1): """ Pairwise distance between points in two sets. As Scipy converts every value to double, this wrapper uses a less efficient imple...
if _can_be_double(x) and _can_be_double(y): return _cdist_scipy(x, y, exponent) else: return _cdist_naive(x, y, exponent)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def respond(self, content=EmptyValue, content_type=EmptyValue, always_hash_content=True, ext=None): """ Respond to the request. This generates the :attr:`mohawk....
log.debug('generating response header') resource = Resource(url=self.resource.url, credentials=self.resource.credentials, ext=ext, app=self.parsed_header.get('app', None), dlg=self.parsed_h...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calculate_payload_hash(payload, algorithm, content_type): """Calculates a hash for a given payload."""
p_hash = hashlib.new(algorithm) parts = [] parts.append('hawk.' + str(HAWK_VER) + '.payload\n') parts.append(parse_content_type(content_type) + '\n') parts.append(payload or '') parts.append('\n') for i, p in enumerate(parts): # Make sure we are about to hash binary strings. ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def normalize_string(mac_type, resource, content_hash): """Serializes mac_type and resource into a HAWK string."""
normalized = [ 'hawk.' + str(HAWK_VER) + '.' + mac_type, normalize_header_attr(resource.timestamp), normalize_header_attr(resource.nonce), normalize_header_attr(resource.method or ''), normalize_header_attr(resource.name or ''), normalize_header_attr(resource.host),...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_bewit(resource): """ Returns a bewit identifier for the resource as a string. :param resource: Resource to generate a bewit for :type resource: `mohawk.b...
if resource.method != 'GET': raise ValueError('bewits can only be generated for GET requests') if resource.nonce != '': raise ValueError('bewits must use an empty nonce') mac = calculate_mac( 'bewit', resource, None, ) if isinstance(mac, six.binary_type): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def strip_bewit(url): """ Strips the bewit parameter out of a url. Returns (encoded_bewit, stripped_url) Raises InvalidBewit if no bewit found. :param url: The u...
m = re.search('[?&]bewit=([^&]+)', url) if not m: raise InvalidBewit('no bewit data found') bewit = m.group(1) stripped_url = url[:m.start()] + url[m.end():] return bewit, stripped_url
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_bewit(url, credential_lookup, now=None): """ Validates the given bewit. Returns True if the resource has a valid bewit parameter attached, or raises a ...
raw_bewit, stripped_url = strip_bewit(url) bewit = parse_bewit(raw_bewit) try: credentials = credential_lookup(bewit.id) except LookupError: raise CredentialsLookupError('Could not find credentials for ID {0}' .format(bewit.id)) res = Resource(u...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def accept_response(self, response_header, content=EmptyValue, content_type=EmptyValue, accept_untrusted_content=False, localtime_offset_in_seconds=0, timestamp_s...
log.debug('accepting response {header}' .format(header=response_header)) parsed_header = parse_authorization_header(response_header) resource = Resource(ext=parsed_header.get('ext', None), content=content, content_type=...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def current_state(self): """ Returns a ``field -> value`` dict of the current state of the instance. """
field_names = set() [field_names.add(f.name) for f in self._meta.local_fields] [field_names.add(f.attname) for f in self._meta.local_fields] return dict([(field_name, getattr(self, field_name)) for field_name in field_names])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _trim(cls, s): """ Remove trailing colons from the URI back to the first non-colon. :param string s: input URI string :returns: URI string with trailing colo...
reverse = s[::-1] idx = 0 for i in range(0, len(reverse)): if reverse[i] == ":": idx += 1 else: break # Return the substring after all trailing colons, # reversed back to its original character order. new_s = rever...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_attribute_components(self, att): """ Returns the component list of input attribute. :param string att: Attribute name to get :returns: List of Component...
lc = [] if not CPEComponent.is_valid_attribute(att): errmsg = "Invalid attribute name '{0}' is not exist".format(att) raise ValueError(errmsg) for pk in CPE.CPE_PART_KEYS: elements = self.get(pk) for elem in elements: lc.append(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _pack_edition(self): """ Pack the values of the five arguments into the simple edition component. If all the values are blank, just return a blank. :returns:...
COMP_KEYS = (CPEComponent.ATT_EDITION, CPEComponent.ATT_SW_EDITION, CPEComponent.ATT_TARGET_SW, CPEComponent.ATT_TARGET_HW, CPEComponent.ATT_OTHER) separator = CPEComponent2_3_URI_edpacked.SEPARATOR_COMP pack...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def as_uri_2_3(self): """ Returns the CPE Name as URI string of version 2.3. :returns: CPE Name as URI string of version 2.3 :rtype: string :exception: TypeError...
uri = [] uri.append("cpe:/") ordered_comp_parts = { 0: CPEComponent.ATT_PART, 1: CPEComponent.ATT_VENDOR, 2: CPEComponent.ATT_PRODUCT, 3: CPEComponent.ATT_VERSION, 4: CPEComponent.ATT_UPDATE, 5: CPEComponent.ATT_EDITION, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def as_wfn(self): """ Returns the CPE Name as Well-Formed Name string of version 2.3. :return: CPE Name as WFN string :rtype: string :exception: TypeError - inco...
from .cpe2_3_wfn import CPE2_3_WFN wfn = [] wfn.append(CPE2_3_WFN.CPE_PREFIX) for i in range(0, len(CPEComponent.ordered_comp_parts)): ck = CPEComponent.ordered_comp_parts[i] lc = self._get_attribute_components(ck) if len(lc) > 1: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def as_fs(self): """ Returns the CPE Name as formatted string of version 2.3. :returns: CPE Name as formatted string :rtype: string :exception: TypeError - incom...
fs = [] fs.append("cpe:2.3:") for i in range(0, len(CPEComponent.ordered_comp_parts)): ck = CPEComponent.ordered_comp_parts[i] lc = self._get_attribute_components(ck) if len(lc) > 1: # Incompatible version 1.1, there are two or more element...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _is_alphanum(cls, c): """ Returns True if c is an uppercase letter, a lowercase letter, a digit or an underscore, otherwise False. :param string c: Character...
alphanum_rxc = re.compile(CPEComponentSimple._ALPHANUM_PATTERN) return (alphanum_rxc.match(c) is not None)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _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 o...
errmsg = "Invalid attribute '{0}'".format(comp_att) if not CPEComponent.is_valid_attribute(comp_att): raise ValueError(errmsg) comp_str = self._encoded_value errmsg = "Invalid value of attribute '{0}': {1}".format( comp_att, comp_str) # Check part (s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def as_fs(self): """ Returns the value of component encoded as formatted string. Inspect each character in value of component. Certain nonalpha characters pass t...
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 result.append(c) else: # Escaped ch...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 alphanu...
s = self._standard_value result = [] idx = 0 while (idx < len(s)): thischar = s[idx] # get the idx'th character of s # alphanumerics (incl. underscore) pass untouched if (CPEComponentSimple._is_alphanum(thischar)): result.append(thi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _is_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 ...
comp_str = self._encoded_value value_pattern = [] value_pattern.append("^((") value_pattern.append("~[") value_pattern.append(CPEComponent1_1._STRING) value_pattern.append("]+") value_pattern.append(")|(") value_pattern.append("[") value_pattern...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _create_component(cls, att, value): """ Returns a component with value "value". :param string att: Attribute name :param string value: Attribute value :retur...
if value == CPEComponent2_3_URI.VALUE_UNDEFINED: comp = CPEComponentUndefined() elif (value == CPEComponent2_3_URI.VALUE_ANY or value == CPEComponent2_3_URI.VALUE_EMPTY): comp = CPEComponentAnyValue() elif (value == CPEComponent2_3_URI.VALUE_NA): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def as_wfn(self): """ Returns the CPE Name as Well-Formed Name string of version 2.3. If edition component is not packed, only shows the first seven components, ...
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 CPEComponent.CPE_COMP_KEYS: lc = self._get_attribute_components...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _is_valid_edition(self): """ Return True if the input value of attribute "edition" is valid, and otherwise False. :returns: True if value is valid, False oth...
comp_str = self._standard_value[0] packed = [] packed.append("(") packed.append(CPEComponent2_3_URI.SEPARATOR_PACKED_EDITION) packed.append(CPEComponent2_3_URI._string) packed.append("){5}") value_pattern = [] value_pattern.append("^(") value_p...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _compare_strings(cls, source, target): """ Compares a source string to a target string, and addresses the condition in which the source string includes unquo...
start = 0 end = len(source) begins = 0 ends = 0 # Reading of initial wildcard in source if source.startswith(CPEComponent2_3_WFN.WILDCARD_MULTI): # Source starts with "*" start = 1 begins = -1 else: while ((start ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compare_wfns(cls, source, target): """ Compares two WFNs and returns a generator of pairwise attribute-value comparison results. It provides full access to t...
# 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: # Not a logical value: del double quotes value_src = value_src[1:-1] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cpe_disjoint(cls, source, target): """ Compares two WFNs and returns True if the set-theoretic relation between the names is DISJOINT. :param CPE2_3_WFN sour...
# 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 == CPESet2_3.LOGICAL_VALUE_DISJOINT if isDisjoint: return True return ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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: fi...
# If any pairwise comparison returned EQUAL then # the overall name relationship is EQUAL for att, result in CPESet2_3.compare_wfns(source, target): isEqual = result == CPESet2_3.LOGICAL_VALUE_EQUAL if not isEqual: return False return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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 ...
if cpe.VERSION != CPE2_3.VERSION: errmsg = "CPE Name version {0} not valid, version 2.3 expected".format( cpe.VERSION) raise ValueError(errmsg) for k in self.K: if cpe._str == k._str: return None if isinstance(cpe, CPE2_3_WF...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. :p...
for N in self.K: if CPESet2_3.cpe_superset(wfn, N): return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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" raise ValueError(msg) # Partitioning of CPE Name parts_match = CPE2_2._parts_rxc.match(self._str) # Validation of CPE Name pa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 :e...
wfn = [] wfn.append(CPE2_3_WFN.CPE_PREFIX) for ck in CPEComponent.CPE_COMP_KEYS: lc = self._get_attribute_components(ck) comp = lc[0] if (isinstance(comp, CPEComponentUndefined) or isinstance(comp, CPEComponentEmpty)): # Do...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_...
try: fs = CPE2_3_FS(boundname) except: # CPE name is not formatted string try: uri = CPE2_3_URI(boundname) except: # CPE name is not URI but WFN return CPE2_3_WFN(boundname) else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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...
components = 0 marks = dict([(node, 0) for node in ids]) q = [] for node in ids: if marks[node] == 0: components += 1 q.append(node) if components > 1: return False while q: node = q.pop() marks[node] = compone...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_contiguity(w, neighbors, leaver): """Check if contiguity is maintained if leaver is removed from neighbors Parameters w : spatial weights object simple...
ids = neighbors[:] ids.remove(leaver) return is_component(w, ids)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def jsonapi(f): """ Declare the view as a JSON API method This converts view return value into a :cls:JsonResponse. The following return types are supported: - t...
@wraps(f) def wrapper(*args, **kwargs): rv = f(*args, **kwargs) return make_json_response(rv) return wrapper
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _unpack(c, tmp, package, version, git_url=None): """ Download + unpack given package into temp dir ``tmp``. Return ``(real_version, source)`` where ``real_ve...
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 SHA-ish: # in the checkout, obtain SHA from that branch # set real_version to that value els...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_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 because we must be in the Travis group to access the # (created by Travis for us) virtualenv and other contents within # /home/travis. c.sudo("us...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_sshable(c): """ Set up passwordless SSH keypair & authorized_hosts access to localhost. """
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 using '&&' instead of doing this? for cmd in ("mkdir {0}", "chmod 0700 {0}"): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def blacken(c): """ Install and execute ``black`` under appropriate circumstances, with diffs. Installs and runs ``black`` under Python 3.6 (the first version it...
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 config = c.config.get("travis", {}).get("black", {}) version = config.get("ve...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 methods, {} given'.format(func)) return func
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def matches(self, verb, params): """ Test if the method matches the provided set of arguments :param verb: HTTP verb. Uppercase :type verb: str :param params: Ex...
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _match_view(self, method, route_params): """ Detect a view matching the query :param method: HTTP method :param route_params: Route parameters dict :return: ...
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(method, route_params): return getattr(self, view_name) else: return Non...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ...
v, d = la.eig(np.transpose(P)) d = np.array(d) # for a regular P maximum eigenvalue will be 1 mv = max(v) # find its position i = v.tolist().index(mv) row = abs(d[:, i]) # normalize eigenvector corresponding to the eigenvalue 1 return row / sum(row)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fmpt(P): """ Calculates the matrix of first mean passage times for an ergodic transition probability matrix. Parameters P : array (k, k), an ergodic Markov t...
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.diag(A) A_diag = A_diag + (A_diag == 0) D = np.diag...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def var_fmpt(P): """ Variances of first mean passage times for an ergodic transition probability matrix. Parameters P : array (k, k), an ergodic Markov transitio...
P = np.matrix(P) A = P ** 1000 n, k = A.shape I = np.identity(k) Z = la.inv(I - P + A) E = np.ones_like(Z) D = np.diag(1. / np.diag(A)) Zdg = np.diag(np.diag(Z)) M = (I - Z + E * Zdg) * D ZM = Z * M ZMdg = np.diag(np.diag(ZM)) W = M * (2 * Zdg * D - I) + 2 * (ZM - E * Z...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _converge(c): """ Examine world state, returning data on what needs updating for release. :param c: Invoke ``Context`` object or subclass. :returns: Two dict...
# # 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 type is undefined; we can't do useful work for that. if release_type is Release.UNDEF...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prepare(c): """ Edit changelog & version, git commit, and git tag, to set up for release. """
# 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, re: just making them non-enum classes period. # TODO: otherwise, we at...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: - ``...
# TODO: I don't _think_ this technically overlaps with Releases (because # that only ever deals with changelog contents, and therefore full release # version numbers) but in case it does, move it there sometime. # TODO: this and similar calls in this module may want to be given an # explicit pointe...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _versions_from_changelog(changelog): """ Return all released versions from given ``changelog``, sorted. :param dict changelog: A changelog dict as returned b...
versions = [Version(x) for x in changelog if BUGFIX_RELEASE_RE.match(x)] return sorted(versions)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _release_and_issues(changelog, branch, release_type): """ Return most recent branch-appropriate release, if any, and its contents. :param dict changelog: Cha...
# Bugfix lines just use the branch to find issues bucket = branch # Features need a bit more logic if release_type is Release.FEATURE: bucket = _latest_feature_bucket(changelog) # Issues is simply what's in the bucket issues = changelog[bucket] # Latest release is undefined for feat...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_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 # tags, and even if they are, we can't reason about anything # non-semver anyways...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
# TODO: is there a way to get this from the same place setup.py does w/o # setup.py barfing (since setup() runs at import time and assumes CLI use)? configured_value = c.get("packaging", {}).get("package", None) if configured_value: return configured_value # TODO: tests covering this stuff ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def publish( c, sdist=True, wheel=False, index=None, sign=False, dry_run=False, directory=None, dual_wheels=False, alt_python=None, check_desc=False, ): """ Publ...
# Don't hide by default, this step likes to be verbose most of the time. c.config.run.hide = False # Config hooks config = c.config.get("packaging", {}) index = config.get("index", index) sign = config.get("sign", sign) dual_wheels = config.get("dual_wheels", dual_wheels) check_desc = c...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tmpdir(skip_cleanup=False, explicit=None): """ Context-manage a temporary directory. Can be given ``skip_cleanup`` to skip cleanup, and ``explicit`` to choos...
tmp = explicit if explicit is not None else mkdtemp() try: yield tmp finally: if not skip_cleanup: rmtree(tmp)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def permute(self, permutations=99, alternative='two.sided'): """ Generate ransom spatial permutations for inference on LISA vectors. Parameters permutations : in...
rY = self.Y.copy() idxs = np.arange(len(rY)) counts = np.zeros((permutations, len(self.counts))) for m in range(permutations): np.random.shuffle(idxs) res = self._calc(rY[idxs, :], self.w, self.k) counts[m] = res['counts'] self.counts_perm = c...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plot(self, attribute=None, ax=None, **kwargs): """ Plot the rose diagram. Parameters attribute : (n,) ndarray, optional Variable to specify colors of the col...
from splot.giddy import dynamic_lisa_rose fig, ax = dynamic_lisa_rose(self, attribute=attribute, ax=ax, **kwargs) return fig, ax
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plot_origin(self): # TODO add attribute option to color vectors """ Plot vectors of positional transition of LISA values starting from the same origin. """
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(), self._dy.max()] for x, y in zip(self._dx, self._dy): xs = [0, x] ys = [0, y] plt.plot(xs, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plot_vectors(self, arrows=True): """ Plot vectors of positional transition of LISA values within quadrant in scatterplot in a polar plot. Parameters ax : Mat...
from splot.giddy import dynamic_lisa_vectors fig, ax = dynamic_lisa_vectors(self, arrows=arrows) return fig, ax
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _clean(c): """ Nuke docs build target directory so next build is clean. """
if isdir(c.sphinx.target): rmtree(c.sphinx.target)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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} {1} {2}".format( (" " + opts) if opts else "", source or c.sphinx.source, target or c.sphinx.target, ) c.run(cmd, pty=True) if browse: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tree(c): """ Display documentation contents with the 'tree' program. """
ignore = ".git|*.pyc|*.swp|dist|*.egg-info|_static|_build|_templates" c.run('tree -Ca -I "{0}" {1}'.format(ignore, c.sphinx.source))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def watch_docs(c): """ Watch both doc trees & rebuild them if files change. This includes e.g. rebuilding the API docs if the source code changes; rebuilding the...
# 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 & WWW triggers WWW www_c = Context(config=c.config.clone()) www_c.update(**www.co...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shuffle_matrix(X, ids): """ Random permutation of rows and columns of a matrix Parameters X : array (k, k), array to be permutated. ids : array range (k, ). ...
np.random.shuffle(ids) return X[ids, :][:, ids]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def markov_mobility(p, measure="P", ini=None): """ Markov-based mobility index. Parameters p : array (k, k), Markov transition probability matrix. measure : stri...
p = np.array(p) k = p.shape[1] if measure == "P": t = np.trace(p) mobi = (k - t) / (k - 1) elif measure == "D": mobi = 1 - abs(la.det(p)) elif measure == "L2": w, v = la.eig(p) eigen_value_abs = abs(w) mobi = 1 - np.sort(eigen_value_abs)[-2] elif...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def chi2(T1, T2): """ chi-squared test of difference between two transition matrices. Parameters T1 : array (k, k), matrix of transitions (counts). T2 : array (k...
rs2 = T2.sum(axis=1) rs1 = T1.sum(axis=1) rs2nz = rs2 > 0 rs1nz = rs1 > 0 dof1 = sum(rs1nz) dof2 = sum(rs2nz) rs2 = rs2 + (rs2 == 0) dof = (dof1 - 1) * (dof2 - 1) p = np.diag(1 / rs2) * np.matrix(T2) E = np.diag(rs1) * np.matrix(p) num = T1 - E num = np.multiply(num, num...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def kullback(F): """ Kullback information based test of Markov Homogeneity. Parameters F : array (s, r, r), values are transitions (not probabilities) for s stra...
F1 = F == 0 F1 = F + F1 FLF = F * np.log(F1) T1 = 2 * FLF.sum() FdJK = F.sum(axis=0) FdJK1 = FdJK + (FdJK == 0) FdJKLFdJK = FdJK * np.log(FdJK1) T2 = 2 * FdJKLFdJK.sum() FdJd = F.sum(axis=0).sum(axis=1) FdJd1 = FdJd + (FdJd == 0) T3 = 2 * (FdJd * np.log(FdJd1)).sum() ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prais(pmat): """ Prais conditional mobility measure. Parameters pmat : matrix (k, k), Markov probability transition matrix. Returns ------- pr : matrix (1, k...
pmat = np.array(pmat) pr = 1 - np.diag(pmat) return pr
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def homogeneity(transition_matrices, regime_names=[], class_names=[], title="Markov Homogeneity Test"): """ Test for homogeneity of Markov transition probabiliti...
return Homogeneity_Results(transition_matrices, regime_names=regime_names, class_names=class_names, title=title)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sojourn_time(p): """ Calculate sojourn time based on a given transition probability matrix. Parameters p : array (k, k), a Markov transition probability matr...
p = np.asarray(p) pii = p.diagonal() if not (1 - pii).all(): print("Sojourn times are infinite for absorbing states!") return 1 / (1 - pii)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _calc(self, y, w): '''Helper to estimate spatial lag conditioned Markov transition probability matrices based on maximum likelihood techniques. ''' if self.discrete: self.lclass_ids = weights.lag_categorical(w, self.class_ids, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def summary(self, file_name=None): """ A summary method to call the Markov homogeneity test to test for temporally lagged spatial dependence. To learn more about...
class_names = ["C%d" % i for i in range(self.k)] regime_names = ["LAG%d" % i for i in range(self.k)] ht = homogeneity(self.T, class_names=class_names, regime_names=regime_names) title = "Spatial Markov Test" if self.variable_name: title = ti...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _maybe_classify(self, y, k, cutoffs): '''Helper method for classifying continuous data. ''' rows, cols = y.shape if cutoffs is None: if self.fixed: mcyb = mc.Quantiles(y.flatten(), k=k) yb = mcyb.yb.reshape(y.shape) cutoff...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def spillover(self, quadrant=1, neighbors_on=False): """ Detect spillover locations for diffusion in LISA Markov. Parameters quadrant : int which quadrant in the...
n, k = self.q.shape if self.permutations: spill_over = np.zeros((n, k - 1)) components = np.zeros((n, k)) i2id = {} # handle string keys for key in list(self.w.neighbors.keys()): idx = self.w.id2i[key] i2id[idx] = key ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_entity_propnames(entity): """ Get entity property names :param entity: Entity :type entity: sqlalchemy.ext.declarative.api.DeclarativeMeta :returns: Set ...
ins = entity if isinstance(entity, InstanceState) else inspect(entity) return set( ins.mapper.column_attrs.keys() + # Columns ins.mapper.relationships.keys() # Relationships )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
clone = self.clone() clone.minor += 1 clone.patch = 0 return clone
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def encoding_for(source_path, encoding='automatic', fallback_encoding=None): """ The encoding used by the text file stored in ``source_path``. The algorithm used...
assert encoding is not None if encoding == 'automatic': with open(source_path, 'rb') as source_file: heading = source_file.read(128) result = None if len(heading) == 0: # File is empty, assume a dummy encoding. result = 'utf-8' if result is N...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def polynomial(img, mask, inplace=False, replace_all=False, max_dev=1e-5, max_iter=20, order=2): ''' replace all masked values calculate flatField from 2d-polynomal fit filling all high gradient areas within averaged fit-image returns flatField, average background level, fitte...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def SNR_IEC(i1, i2, ibg=0, allow_color_images=False): ''' Calculate the averaged signal-to-noise ratio SNR50 as defined by IEC NP 60904-13 needs 2 reference EL images and one background image ''' # ensure images are type float64 (double precision): i1 = np.asfarray(i1) i2 = np....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _evaluate(x, y, weights): ''' get the parameters of the, needed by 'function' through curve fitting ''' i = _validI(x, y, weights) xx = x[i] y = y[i] try: fitParams = _fit(xx, y) # bound noise fn to min defined y value: minY = function(xx[0], *fit...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def function(x, ax, ay): ''' general square root function ''' with np.errstate(invalid='ignore'): return ay * (x - ax)**0.5
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _validI(x, y, weights): ''' return indices that have enough data points and are not erroneous ''' # density filter: i = np.logical_and(np.isfinite(y), weights > np.median(weights)) # filter outliers: try: grad = np.abs(np.gradient(y[i])) max_gradient = 4 * np.me...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def smooth(x, y, weights): ''' in case the NLF cannot be described by a square root function commit bounded polynomial interpolation ''' # Spline hard to smooth properly, therefore solfed with # bounded polynomal interpolation # ext=3: no extrapolation, but boundary value # ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def oneImageNLF(img, img2=None, signal=None): ''' Estimate the NLF from one or two images of the same kind ''' x, y, weights, signal = calcNLF(img, img2, signal) _, fn, _ = _evaluate(x, y, weights) return fn, signal
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _getMinMax(img): ''' Get the a range of image intensities that most pixels are in with ''' av = np.mean(img) std = np.std(img) # define range for segmentation: mn = av - 3 * std mx = av + 3 * std return max(img.min(), mn, 0), min(img.max(), mx)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def polyfit2d(x, y, z, order=3 #bounds=None ): ''' fit unstructured data ''' ncols = (order + 1)**2 G = np.zeros((x.size, ncols)) ij = itertools.product(list(range(order+1)), list(range(order+1))) for k, (i,j) in enumerate(ij): G[:,k] = x**i * y**j m = np...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def polyfit2dGrid(arr, mask=None, order=3, replace_all=False, copy=True, outgrid=None): ''' replace all masked values with polynomial fitted ones ''' s0,s1 = arr.shape if mask is None: if outgrid is None: y,x = np.mgrid[:float(s0),:float(s1)] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def reconstructImage(self): ''' do inverse Fourier transform and return result ''' f_ishift = np.fft.ifftshift(self.fshift) return np.real(np.fft.ifft2(f_ishift))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def relativeAreaSTE(self): ''' return STE area - relative to image area ''' s = self.noSTE.shape return np.sum(self.mask_STE) / (s[0] * s[1])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def intensityDistributionSTE(self, bins=10, range=None): ''' return distribution of STE intensity ''' v = np.abs(self._last_diff[self.mask_STE]) return np.histogram(v, bins, range)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def toFloatArray(img): ''' transform an unsigned integer array into a float array of the right size ''' _D = {1: np.float32, # uint8 2: np.float32, # uint16 4: np.float64, # uint32 8: np.float64} # uint64 return img.astype(_D[img.itemsize])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def toNoUintArray(arr): ''' cast array to the next higher integer array if dtype=unsigned integer ''' d = arr.dtype if d.kind == 'u': arr = arr.astype({1: np.int16, 2: np.int32, 4: np.int64}[d.itemsize]) return arr
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def rot90(img): ''' rotate one or multiple grayscale or color images 90 degrees ''' s = img.shape if len(s) == 3: if s[2] in (3, 4): # color image out = np.empty((s[1], s[0], s[2]), dtype=img.dtype) for i in range(s[2]): out[:, :, i] = np.rot...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _insertDateIndex(date, l): ''' returns the index to insert the given date in a list where each items first value is a date ''' return next((i for i, n in enumerate(l) if n[0] < date), len(l))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _getFromDate(l, date): ''' returns the index of given or best fitting date ''' try: date = _toDate(date) i = _insertDateIndex(date, l) - 1 if i == -1: return l[0] return l[i] except (ValueError, TypeError): # ValueError: date invalid...