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 diet(file, configuration, check): """Simple program that either print config customisations for your environment or compresses file FILE."""
config = process.read_yaml_configuration(configuration) process.diet(file, config)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def linspace2(a, b, n, dtype=None): """similar to numpy.linspace but excluding the boundaries this is the normal numpy.linspace: [ 0. 0.25 0.5 0.75 1. ] and this gives excludes the boundaries: [ 0.1 0.3 0.5 0.7 0.9] """
a = linspace(a, b, n + 1, dtype=dtype)[:-1] if len(a) > 1: diff01 = ((a[1] - a[0]) / 2).astype(a.dtype) a += diff01 return a
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send_mail(subject, text_content, from_email, to, html_content=None, attachments=[], cc=[], bcc=[]): """ This function sends mail using EmailMultiAlternatives and attachs all attachments passed as parameters """
msg = EmailMultiAlternatives(subject, text_content, from_email, to, cc=cc, bcc=bcc) if html_content: msg.attach_alternative(html_content, "text/html") if attachments: for att in attachments: if att: mimetype = mimetypes.guess_type(att)[0] if str(mimetype) in ('image/jpeg', 'image/pjpeg', 'image/png', 'image/gif'): try: with open(att, 'r') as f: email_embed_image(msg, att, f.read()) except Exception as e: print(e) else: msg.attach_file(att) return msg.send()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def email_embed_image(email, img_content_id, img_data): """ email is a django.core.mail.EmailMessage object """
img = MIMEImage(img_data) img.add_header('Content-ID', '<%s>' % img_content_id) img.add_header('Content-Disposition', 'inline') email.attach(img)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def safe_mongocall(call): """ Decorator for automatic handling of AutoReconnect-exceptions. """
def _safe_mongocall(*args, **kwargs): for i in range(4): try: return call(*args, **kwargs) except pymongo.errors.AutoReconnect: print ('AutoReconnecting, try %d' % i) time.sleep(pow(2, i)) # Try one more time, but this time, if it fails, let the # exception bubble up to the caller. return call(*args, **kwargs) return _safe_mongocall
<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_username(self): """ Gets the user name. The value can be stored in parameters "username" or "user". :return: the user name. """
username = self.get_as_nullable_string("username") username = username if username != None else self.get_as_nullable_string("user") return username
<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_password(self): """ Get the user password. The value can be stored in parameters "password" or "pass". :return: the user password. """
password = self.get_as_nullable_string("password") password = password if password != None else self.get_as_nullable_string("pass") return password
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_access_id(self): """ Gets the application access id. The value can be stored in parameters "access_id" pr "client_id" :return: the application access id. """
access_id = self.get_as_nullable_string("access_id") access_id = access_id if access_id != None else self.get_as_nullable_string("client_id") return access_id
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_access_key(self): """ Gets the application secret key. The value can be stored in parameters "access_key", "client_key" or "secret_key". :return: the application secret key. """
access_key = self.get_as_nullable_string("access_key") access_key = access_key if access_key != None else self.get_as_nullable_string("access_key") return access_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 many_from_config(config): """ Retrieves all CredentialParams from configuration parameters from "credentials" section. If "credential" section is present instead, than it returns a list with only one CredentialParams. :param config: a configuration parameters to retrieve credentials :return: a list of retrieved CredentialParams """
result = [] # Try to get multiple credentials first credentials = config.get_section("credentials") if len(credentials) > 0: sections_names = credentials.get_section_names() for section in sections_names: credential = credentials.get_section(section) result.append(CredentialParams(credential)) # Then try to get a single credential else: credential = config.get_section("credential") result.append(CredentialParams(credential)) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def energy(q, v): """Compute the kinetic and potential energy of the planetary system"""
# Number of points N: int = len(q) # Initialize arrays to zero of the correct size T: np.ndarray = np.zeros(N) U: np.ndarray = np.zeros(N) # Add up kinetic energy of each body for i in range(B): # Kinetic energy is 1/2 mv^2 m = mass[i] vi = v[:, slices[i]] T += 0.5 * m * np.sum(vi * vi, axis=1) # Add up potential energy of each pair of bodies for i in range(B): for j in range(i+1, B): # Masses of these two bodies mi = mass[i] mj = mass[j] # Positions of body i and j qi: np.ndarray = q[:, slices[i]] qj: np.ndarray = q[:, slices[j]] # Potential energy is -G m1 m2 / r dv_ij = qj - qi r_ij = np.linalg.norm(dv_ij, axis=1) U -= G * mi * mj * 1.0 / r_ij # Total energy H = T + U H = T + U return H, T, 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 make_force(q_vars, mass): """Fluxion with the potential energy of the eight planets sytem"""
# Number of bodies B: int = len(mass) # Build the potential energy fluxion by iterating over distinct pairs of bodies U = fl.Const(0.0) for i in range(B): for j in range(i+1, B): U += U_ij(q_vars, mass, i, j) # Varname arrays for both the coordinate system and U vn_q = np.array([q.var_name for q in q_vars]) vn_fl = np.array(sorted(U.var_names)) # Permutation array for putting variables in q in the order expected by U (alphabetical) q2fl = np.array([np.argmax((vn_q == v)) for v in vn_fl]) # Permutation array for putting results of U.diff() in order of q_vars fl2q = np.array([np.argmax((vn_fl == v)) for v in vn_q]) # Return a force function from this potential force_func = lambda q: -U.diff(q[q2fl]).squeeze()[fl2q] return force_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 tweet(tweet_text_func): ''' A decorator to make a function Tweet Parameters - `tweet_text_func` is a function that takes no parameters and returns a tweetable string For example:: @tweet def total_deposits_this_week(): # ... @tweet def not_an_interesting_tweet(): return 'This tweet is not data-driven.' ''' def tweet_func(): api = _connect_to_twitter() tweet = tweet_text_func() print "Tweeting: %s" % tweet api.update_status(tweet) return tweet return tweet_func
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_perm_name(cls, action, full=True): """ Return the name of the permission for a given model and action. By default it returns the full permission name `app_label.perm_codename`. If `full=False`, it returns only the `perm_codename`. """
codename = "{}_{}".format(action, cls.__name__.lower()) if full: return "{}.{}".format(cls._meta.app_label, codename) return codename
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register(self, correlation_id, connection): """ Registers the given connection in all referenced discovery services. This method can be used for dynamic service discovery. :param correlation_id: (optional) transaction id to trace execution through call chain. :param connection: a connection to register. """
result = self._register_in_discovery(correlation_id, connection) if result: self._connections.append(connection)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sendPartialResponse(self): """ Send a partial response without closing the connection. :return: <void> """
self.requestProtocol.requestResponse["code"] = ( self.responseCode ) self.requestProtocol.requestResponse["content"] = ( self.responseContent ) self.requestProtocol.requestResponse["errors"] = ( self.responseErrors ) self.requestProtocol.sendPartialRequestResponse()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sendFinalResponse(self): """ Send the final response and close the connection. :return: <void> """
self.requestProtocol.requestResponse["code"] = ( self.responseCode ) self.requestProtocol.requestResponse["content"] = ( self.responseContent ) self.requestProtocol.requestResponse["errors"] = ( self.responseErrors ) self.requestProtocol.sendFinalRequestResponse()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add(self, value): """ Add a value to the buffer. """
ind = int(self._ind % self.shape) self._pos = self._ind % self.shape self._values[ind] = value if self._ind < self.shape: self._ind += 1 # fast fill else: self._ind += self._splitValue self._splitPos += self._splitValue self._cached = 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 array(self): """ Returns a numpy array containing the last stored values. """
if self._ind < self.shape: return self._values[:self._ind] if not self._cached: ind = int(self._ind % self.shape) self._cache[:self.shape - ind] = self._values[ind:] self._cache[self.shape - ind:] = self._values[:ind] self._cached = True return self._cache
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def splitPos(self): """return the position of where to split the array to get the values in the right order"""
if self._ind < self.shape: return 0 v = int(self._splitPos) if v >= 1: self._splitPos = 0 return v
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sort(polylines): """ sort points within polyline """
for n, c in enumerate(polylines): l = len(c) if l > 2: # DEFINE FIRST AND LAST INDEX A THOSE TWO POINTS THAT # HAVE THE BIGGEST DIFFERENCE FROM A MIDDLE: mid = c.mean(axis=0) distV = (c - mid) dists = norm(distV, axis=-1) firstI = np.argmax(dists) sign = np.sign(distV[firstI]) dd = np.logical_or(np.sign(distV[:, 0]) != sign[0], np.sign(distV[:, 1]) != sign[1]) dists[~dd] = 0 lastI = np.argmax(dists) ind = _sort(c, firstI, lastI) c = c[ind] polylines[n] = 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 filter(polylines, min_len=20): """ filter polylines shorter than given min length """
filtered = [] for n in range(len(polylines) - 1, -1, -1): if lengths(polylines[n]).sum() < min_len: filtered.append(polylines.pop(n)) return filtered
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def separate(polylines, f_mx_dist=2, mn_group_len=4): """ split polylines wherever crinkles are found """
s = [] for n in range(len(polylines) - 1, -1, -1): c = polylines[n] separated = False start = 0 for m in range(mn_group_len, len(c) - 1): if m - start < mn_group_len: continue m += 1 group = c[m - mn_group_len:m] x, y = group[:, 0], group[:, 1] asc, offs, _, _, _ = linregress(x, y) yfit = asc * x + offs # check whether next point would fit in: p1 = c[m] l = (x[0], yfit[0], p1[-1], asc * p1[-1] + offs) std = np.mean([line.distance(l, g) for g in group]) dist = line.distance(l, p1) if dist > 2 and dist > f_mx_dist * std: separated = True s.append(c[start:m - 1]) start = m - 1 if separated: if len(c) - start >= 2: s.append(c[start:]) polylines.pop(n) polylines.extend(s) return polylines
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def merge(polylines, mx_dist=4): """ point by line segment comparison merge polylines if points are close """
l = len(polylines) to_remove = set() for n in range(l - 1, -1, -1): if n not in to_remove: c = polylines[n] for p0, p1 in zip(c[:-1], c[1:]): # create a line from any subsegment: l0 = p0[0], p0[1], p1[0], p1[1] # for every other polyline: for m in range(l - 1, -1, -1): if m not in to_remove: if n == m: continue remove = False cc = polylines[m] ind = np.zeros(shape=cc.shape[0], dtype=bool) # for every point p in this polyline: for o in range(len(cc) - 1, -1, -1): p = cc[o] if line.segmentDistance(l0, p) < mx_dist: remove = True ind[o] = True if remove: polylines[n] = np.append(c, cc[ind], axis=0) ind = ~ind s = ind.sum() if s < 2: to_remove.add(m) else: polylines[m] = cc[ind] to_remove = sorted(to_remove) to_remove.reverse() for i in to_remove: polylines.pop(i)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def smooth(polylines): """ smooth every polyline using spline interpolation """
for c in polylines: if len(c) < 9: # smoothing wouldn't make sense here continue x = c[:, 0] y = c[:, 1] t = np.arange(x.shape[0], dtype=float) t /= t[-1] x = UnivariateSpline(t, x)(t) y = UnivariateSpline(t, y)(t) c[:, 0] = x c[:, 1] = y
<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_queryset(self): """Query for the most voted messages sorting by the sum of voted and after by date."""
queryset = super(MostVotedManager, self).get_queryset() sql = """ SELECT count(sav.id) FROM colab_superarchives_vote AS sav WHERE colab_superarchives_message.id = sav.message_id """ messages = queryset.extra( select={ 'vote_count': sql, } ) return messages.order_by('-vote_count', 'received_time')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _conf_packages(args): """Runs custom configuration steps for the packages that ship with support in acorn. """
from acorn.config import config_dir from os import path from acorn.base import testmode target = config_dir(True) alternate = path.join(path.abspath(path.expanduser("~")), ".acorn") if not testmode and target != alternate:# pragma: no cover msg.err("Could not configure custom ~/.acorn directory.") exit(0) from acorn.utility import reporoot from glob import glob from os import chdir, getcwd from shutil import copy current = getcwd() source = path.join(reporoot, "acorn", "config") chdir(source) count = 0 #For the unit testing, we don't clobber the local directory, so the copies #are disabled. for json in glob("*.json"): if not testmode:# pragma: no cover copy(json, target) count += 1 for cfg in glob("*.cfg"): if not testmode:# pragma: no cover copy(cfg, target) count += 1 #Switch the directory back to what it was. chdir(current) msg.okay("Copied {0:d} package files to {1}.".format(count, 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 _run_configure(subcmd, args): """Runs the configuration step for the specified sub-command. """
maps = { "packages": _conf_packages } if subcmd in maps: maps[subcmd](args) else: msg.warn("'configure' sub-command {} is not supported.".format(subcmd))
<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_for_legal_children(self, name, elt, mustqualify=1): '''Check if all children of this node are elements or whitespace-only text nodes. ''' inheader = name == "Header" for n in _children(elt): t = n.nodeType if t == _Node.COMMENT_NODE: continue if t != _Node.ELEMENT_NODE: if t == _Node.TEXT_NODE and n.nodeValue.strip() == "": continue raise ParseException("Non-element child in " + name, inheader, elt, self.dom) if mustqualify and not n.namespaceURI: raise ParseException('Unqualified element "' + \ n.nodeName + '" in ' + name, inheader, elt, self.dom)
<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_for_pi_nodes(self, list, inheader): '''Raise an exception if any of the list descendants are PI nodes. ''' list = list[:] while list: elt = list.pop() t = elt.nodeType if t == _Node.PROCESSING_INSTRUCTION_NODE: raise ParseException('Found processing instruction "<?' + \ elt.nodeName + '...>"', inheader, elt.parentNode, self.dom) elif t == _Node.DOCUMENT_TYPE_NODE: raise ParseException('Found DTD', inheader, elt.parentNode, self.dom) list += _children(elt)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def GetElementNSdict(self, elt): '''Get a dictionary of all the namespace attributes for the indicated element. The dictionaries are cached, and we recurse up the tree as necessary. ''' d = self.ns_cache.get(id(elt)) if not d: if elt != self.dom: d = self.GetElementNSdict(elt.parentNode) for a in _attrs(elt): if a.namespaceURI == XMLNS.BASE: if a.localName == "xmlns": d[''] = a.nodeValue else: d[a.localName] = a.nodeValue self.ns_cache[id(elt)] = d return d.copy()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def IsAFault(self): '''Is this a fault message? ''' e = self.body_root if not e: return 0 return e.namespaceURI == SOAP.ENV and e.localName == 'Fault'
<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, how): '''Parse the message. ''' if type(how) == types.ClassType: how = how.typecode return how.parse(self.body_root, self)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def WhatActorsArePresent(self): '''Return a list of URI's of all the actor attributes found in the header. The special actor "next" is ignored. ''' results = [] for E in self.header_elements: a = _find_actor(E) if a not in [ None, SOAP.ACTOR_NEXT ]: results.append(a) return results
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _repr_html_(self): """ Return HTML representation of VDOM object. HTML escaping is performed wherever necessary. """
# Use StringIO to avoid a large number of memory allocations with string concat with io.StringIO() as out: out.write('<{tag}'.format(tag=escape(self.tag_name))) if self.style: # Important values are in double quotes - cgi.escape only escapes double quotes, not single quotes! out.write(' style="{css}"'.format( css=escape(self._to_inline_css(self.style)))) for k, v in self.attributes.items(): k2 = k if k2 == 'class_': k2 = 'class' # Important values are in double quotes - cgi.escape only escapes double quotes, not single quotes! if isinstance(v, string_types): out.write(' {key}="{value}"'.format( key=escape(k2), value=escape(v))) if isinstance(v, bool) and v: out.write(' {key}'.format(key=escape(k2))) out.write('>') for c in self.children: if isinstance(c, string_types): out.write(escape(safe_unicode(c))) else: out.write(c._repr_html_()) out.write('</{tag}>'.format(tag=escape(self.tag_name))) return out.getvalue()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _deploy_helper(filename, module_name, get_module, get_today_fn, hash_check=True, auth=None): """Deploys a file to the Artifactory BEL namespace cache :param str filename: The physical path :param str module_name: The name of the module to deploy to :param tuple[str] auth: A pair of (str username, str password) to give to the auth keyword of the constructor of :class:`artifactory.ArtifactoryPath`. Defaults to the result of :func:`get_arty_auth`. :return: The resource path, if it was deployed successfully, else none. :rtype: Optional[str] """
path = ArtifactoryPath( get_module(module_name), auth=get_arty_auth() if auth is None else auth ) path.mkdir(exist_ok=True) if hash_check: deployed_semantic_hashes = { get_bel_resource_hash(subpath.as_posix()) for subpath in path } semantic_hash = get_bel_resource_hash(filename) if semantic_hash in deployed_semantic_hashes: return # Don't deploy if it's already uploaded target = path / get_today_fn(module_name) target.deploy_file(filename) log.info('deployed %s', module_name) return target.as_posix()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def deploy_namespace(filename, module_name, hash_check=True, auth=None): """Deploy a file to the Artifactory BEL namespace cache. :param str filename: The physical path :param str module_name: The name of the module to deploy to :param bool hash_check: Ensure the hash is unique before deploying :param tuple[str] auth: A pair of (str username, str password) to give to the auth keyword of the constructor of :class:`artifactory.ArtifactoryPath`. Defaults to the result of :func:`get_arty_auth`. :return: The resource path, if it was deployed successfully, else none. :rtype: Optional[str] """
return _deploy_helper( filename, module_name, get_namespace_module_url, get_namespace_today, hash_check=hash_check, auth=auth )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def deploy_annotation(filename, module_name, hash_check=True, auth=None): """Deploy a file to the Artifactory BEL annotation cache. :param str filename: The physical file path :param str module_name: The name of the module to deploy to :param bool hash_check: Ensure the hash is unique before deploying :param tuple[str] auth: A pair of (str username, str password) to give to the auth keyword of the constructor of :class:`artifactory.ArtifactoryPath`. Defaults to the result of :func:`get_arty_auth`. :return: The resource path, if it was deployed successfully, else none. :rtype: Optional[str] """
return _deploy_helper( filename, module_name, get_annotation_module_url, get_annotation_today, hash_check=hash_check, auth=auth )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def deploy_knowledge(filename, module_name, auth=None): """Deploy a file to the Artifactory BEL knowledge cache. :param str filename: The physical file path :param str module_name: The name of the module to deploy to :param tuple[str] auth: A pair of (str username, str password) to give to the auth keyword of the constructor of :class:`artifactory.ArtifactoryPath`. Defaults to the result of :func:`get_arty_auth`. :return: The resource path, if it was deployed successfully, else none. :rtype: Optional[str] """
return _deploy_helper( filename, module_name, get_knowledge_module_url, get_knowledge_today, hash_check=False, auth=auth )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def deploy_directory(directory, auth=None): """Deploy all files in a given directory. :param str directory: the path to a directory :param tuple[str] auth: A pair of (str username, str password) to give to the auth keyword of the constructor of :class:`artifactory.ArtifactoryPath`. Defaults to the result of :func:`get_arty_auth`. """
for file in os.listdir(directory): full_path = os.path.join(directory, file) if file.endswith(BELANNO_EXTENSION): name = file[:-len(BELANNO_EXTENSION)] log.info('deploying annotation %s', full_path) deploy_annotation(full_path, name, auth=auth) elif file.endswith(BELNS_EXTENSION): name = file[:-len(BELNS_EXTENSION)] log.info('deploying namespace %s', full_path) deploy_namespace(full_path, name, auth=auth) elif file.endswith(BEL_EXTENSION): name = file[:-len(BEL_EXTENSION)] log.info('deploying knowledge %s', full_path) deploy_knowledge(full_path, name, auth=auth) else: log.debug('not deploying %s', full_path)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def export_tree(lookup, tree, path): """Exports the given tree object to path. :param lookup: Function to retrieve objects for SHA1 hashes. :param tree: Tree to export. :param path: Output path. """
FILE_PERM = S_IRWXU | S_IRWXG | S_IRWXO for name, mode, hexsha in tree.iteritems(): dest = os.path.join(path, name) if S_ISGITLINK(mode): log.error('Ignored submodule {}; submodules are not yet supported.' .format(name)) # raise ValueError('Does not support submodules') elif S_ISDIR(mode): os.mkdir(dest) os.chmod(dest, 0o0755) export_tree(lookup, lookup(hexsha), dest) elif S_ISLNK(mode): os.symlink(lookup(hexsha).data, dest) elif S_ISREG(mode): with open(dest, 'wb') as out: for chunk in lookup(hexsha).chunked: out.write(chunk) os.chmod(dest, mode & FILE_PERM) else: raise ValueError('Cannot deal with mode of {:o} from {}'.format( mode, name))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def abook2vcf(): """Command line tool to convert from Abook to vCard"""
from argparse import ArgumentParser, FileType from os.path import expanduser from sys import stdout parser = ArgumentParser(description='Converter from Abook to vCard syntax.') parser.add_argument('infile', nargs='?', default=expanduser('~/.abook/addressbook'), help='The Abook file to process (default: ~/.abook/addressbook)') parser.add_argument('outfile', nargs='?', type=FileType('w'), default=stdout, help='Output vCard file (default: stdout)') args = parser.parse_args() args.outfile.write(Abook(args.infile).to_vcf())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def vcf2abook(): """Command line tool to convert from vCard to Abook"""
from argparse import ArgumentParser, FileType from sys import stdin parser = ArgumentParser(description='Converter from vCard to Abook syntax.') parser.add_argument('infile', nargs='?', type=FileType('r'), default=stdin, help='Input vCard file (default: stdin)') parser.add_argument('outfile', nargs='?', default=expanduser('~/.abook/addressbook'), help='Output Abook file (default: ~/.abook/addressbook)') args = parser.parse_args() Abook.abook_file(args.infile, args.outfile)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _update(self): """ Update internal state."""
with self._lock: if getmtime(self._filename) > self._last_modified: self._last_modified = getmtime(self._filename) self._book = ConfigParser(default_section='format') self._book.read(self._filename)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _gen_addr(entry): """Generates a vCard Address object"""
return Address(street=entry.get('address', ''), extended=entry.get('address2', ''), city=entry.get('city', ''), region=entry.get('state', ''), code=entry.get('zip', ''), country=entry.get('country', ''))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _add_photo(self, card, name): """Tries to load a photo and add it to the vCard"""
try: photo_file = join(dirname(self._filename), 'photo/%s.jpeg' % name) jpeg = open(photo_file, 'rb').read() photo = card.add('photo') photo.type_param = 'jpeg' photo.encoding_param = 'b' photo.value = jpeg except IOError: pass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _to_vcard(self, entry): """Return a vCard of the Abook entry"""
card = vCard() card.add('uid').value = Abook._gen_uid(entry) card.add('fn').value = entry['name'] card.add('n').value = Abook._gen_name(entry['name']) if 'email' in entry: for email in entry['email'].split(','): card.add('email').value = email addr_comps = ['address', 'address2', 'city', 'country', 'zip', 'country'] if any(comp in entry for comp in addr_comps): card.add('adr').value = Abook._gen_addr(entry) if 'other' in entry: tel = card.add('tel') tel.value = entry['other'] if 'phone' in entry: tel = card.add('tel') tel.type_param = 'home' tel.value = entry['phone'] if 'workphone' in entry: tel = card.add('tel') tel.type_param = 'work' tel.value = entry['workphone'] if 'mobile' in entry: tel = card.add('tel') tel.type_param = 'cell' tel.value = entry['mobile'] if 'nick' in entry: card.add('nickname').value = entry['nick'] if 'url' in entry: card.add('url').value = entry['url'] if 'notes' in entry: card.add('note').value = entry['notes'] self._add_photo(card, entry['name']) return card
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_vcards(self): """Return a list of vCards"""
self._update() return [self._to_vcard(self._book[entry]) for entry in self._book.sections()]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _conv_adr(adr, entry): """Converts to Abook address format"""
if adr.value.street: entry['address'] = adr.value.street if adr.value.extended: entry['address2'] = adr.value.extended if adr.value.city: entry['city'] = adr.value.city if adr.value.region: entry['state'] = adr.value.region if adr.value.code and adr.value.code != '0': entry['zip'] = adr.value.code if adr.value.country: entry['country'] = adr.value.country
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _conv_tel_list(tel_list, entry): """Converts to Abook phone types"""
for tel in tel_list: if not hasattr(tel, 'TYPE_param'): entry['other'] = tel.value elif tel.TYPE_param.lower() == 'home': entry['phone'] = tel.value elif tel.TYPE_param.lower() == 'work': entry['workphone'] = tel.value elif tel.TYPE_param.lower() == 'cell': entry['mobile'] = tel.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 to_abook(card, section, book, bookfile=None): """Converts a vCard to Abook"""
book[section] = {} book[section]['name'] = card.fn.value if hasattr(card, 'email'): book[section]['email'] = ','.join([e.value for e in card.email_list]) if hasattr(card, 'adr'): Abook._conv_adr(card.adr, book[section]) if hasattr(card, 'tel_list'): Abook._conv_tel_list(card.tel_list, book[section]) if hasattr(card, 'nickname') and card.nickname.value: book[section]['nick'] = card.nickname.value if hasattr(card, 'url') and card.url.value: book[section]['url'] = card.url.value if hasattr(card, 'note') and card.note.value: book[section]['notes'] = card.note.value if hasattr(card, 'photo') and bookfile: try: photo_file = join(dirname(bookfile), 'photo/%s.%s' % (card.fn.value, card.photo.TYPE_param)) open(photo_file, 'wb').write(card.photo.value) except IOError: pass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def abook_file(vcard, bookfile): """Write a new Abook file with the given vcards"""
book = ConfigParser(default_section='format') book['format'] = {} book['format']['program'] = 'abook' book['format']['version'] = '0.6.1' for (i, card) in enumerate(readComponents(vcard.read())): Abook.to_abook(card, str(i), book, bookfile) with open(bookfile, 'w') as fp: book.write(fp, 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 positional_filter(positional_filters, title=''): ''' a method to construct a conditional filter function to test positional arguments :param positional_filters: dictionary or list of dictionaries with query criteria :param title: string with name of function to use instead :return: callable for filter_function NOTE: query criteria architecture each item in the path filters argument must be a dictionary which is composed of integer-value key names that represent the index value of the positional segment to test and key values with the dictionary of conditional operators used to test the string value in the indexed field of the record. eg. positional_filters = [ { 0: { 'must_contain': [ '^lab' ] } } ] this example filter looks at the first segment of each key string in the collection for a string value which starts with the characters 'lab'. as a result, it will match both the following: lab/unittests/1473719695.2165067.json 'laboratory20160912.json' NOTE: the filter function uses a query filters list structure to represent the disjunctive normal form of a logical expression. a record is added to the results list if any query criteria dictionary in the list evaluates to true. within each query criteria dictionary, all declared conditional operators must evaluate to true. in this way, the positional_filters represents a boolean OR operator and each criteria dictionary inside the list represents a boolean AND operator between all keys in the dictionary. each query criteria uses the architecture of query declaration in the jsonModel.query method NOTE: function function will lazy load a dictionary input positional_filters: [ { 0: { conditional operators }, 1: { conditional_operators }, ... } ] conditional operators: "byte_data": false, "discrete_values": [ "" ], "excluded_values": [ "" ], 'equal_to': '', "greater_than": "", "less_than": "", "max_length": 0, "max_value": "", "min_length": 0, "min_value": "", "must_contain": [ "" ], "must_not_contain": [ "" ], "contains_either": [ "" ] ''' # define help text if not title: title = 'positional_filter' filter_arg = '%s(positional_filters=[...])' % title # construct path_filter model filter_schema = { 'schema': { 'byte_data': False, 'discrete_values': [ '' ], 'excluded_values': [ '' ], 'equal_to': '', 'greater_than': '', 'less_than': '', 'max_length': 0, 'max_value': '', 'min_length': 0, 'min_value': '', 'must_contain': [ '' ], 'must_not_contain': [ '' ], 'contains_either': [ '' ] }, 'components': { '.discrete_values': { 'required_field': False }, '.excluded_values': { 'required_field': False }, '.must_contain': { 'required_field': False }, '.must_not_contain': { 'required_field': False }, '.contains_either': { 'required_field': False } } } from jsonmodel.validators import jsonModel filter_model = jsonModel(filter_schema) # lazy load path dictionary if isinstance(positional_filters, dict): positional_filters = [ positional_filters ] # validate input if not isinstance(positional_filters, list): raise TypeError('%s must be a list.' % filter_arg) for i in range(len(positional_filters)): if not isinstance(positional_filters[i], dict): raise TypeError('%s item %s must be a dictionary.' % (filter_arg, i)) for key, value in positional_filters[i].items(): _key_name = '%s : {...}' % key if not isinstance(key, int): raise TypeError('%s key name must be an int.' % filter_arg.replace('...', _key_name)) elif not isinstance(value, dict): raise TypeError('%s key value must be a dictionary' % filter_arg.replace('...', _key_name)) filter_model.validate(value) # construct segment value model segment_schema = { 'schema': { 'segment_value': 'string' } } segment_model = jsonModel(segment_schema) # construct filter function def filter_function(*args): max_index = len(args) - 1 for filter in positional_filters: criteria_match = True for key, value in filter.items(): if key > max_index: criteria_match = False break segment_criteria = { '.segment_value': value } segment_data = { 'segment_value': args[key] } if not segment_model.query(segment_criteria, segment_data): criteria_match = False break if criteria_match: return True return False return filter_function
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_and_check(self, base_settings, prompt=None): """Load settings and check them. Loads the settings from ``base_settings``, then checks them. Returns: (merged settings, True) on success (None, False) on failure """
checker = Checker(self.file_name, self.section, self.registry, self.strategy_type, prompt) settings = self.load(base_settings) if checker.check(settings): return settings, True return None, 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 load(self, base_settings): """Merge local settings from file with ``base_settings``. Returns a new settings dict containing the base settings and the loaded settings. Includes: - base settings - settings from extended file(s), if any - settings from file """
is_valid_key = lambda k: k.isupper() and not k.startswith('_') # Base settings, including `LocalSetting`s, loaded from the # Django settings module. valid_keys = (k for k in base_settings if is_valid_key(k)) base_settings = DottedAccessDict((k, base_settings[k]) for k in valid_keys) # Settings read from the settings file; values are unprocessed. settings_from_file = self.strategy.read_file(self.file_name, self.section) settings_from_file.pop('extends', None) # The fully resolved settings. settings = Settings(base_settings) settings_names = [] settings_not_decoded = set() for name, value in settings_from_file.items(): for prefix in ('PREPEND.', 'APPEND.', 'SWAP.'): if name.startswith(prefix): name = name[len(prefix):] name = '{prefix}({name})'.format(**locals()) break settings_names.append(name) # Attempt to decode raw values. Errors in decoding at this # stage are ignored. try: value = self.strategy.decode_value(value) except ValueError: settings_not_decoded.add(name) settings.set_dotted(name, value) # See if this setting corresponds to a `LocalSetting`. If # so, note that the `LocalSetting` has a value by putting it # in the registry. This also makes it easy to retrieve the # `LocalSetting` later so its value can be set. current_value = base_settings.get_dotted(name, None) if isinstance(current_value, LocalSetting): self.registry[current_value] = name # Interpolate values of settings read from file. When a setting # that couldn't be decoded previously is encountered, its post- # interpolation value will be decoded. for name in settings_names: value = settings.get_dotted(name) value, _ = self._interpolate_values(value, settings) if name in settings_not_decoded: value = self.strategy.decode_value(value) settings.set_dotted(name, value) # Interpolate base settings. self._interpolate_values(settings, settings) self._interpolate_keys(settings, settings) self._prepend_extras(settings, settings.pop('PREPEND', None)) self._append_extras(settings, settings.pop('APPEND', None)) self._swap_list_items(settings, settings.pop('SWAP', None)) self._import_from_string(settings, settings.pop('IMPORT_FROM_STRING', None)) for local_setting, name in self.registry.items(): local_setting.value = settings.get_dotted(name) return settings
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _inject(self, value, settings): """Inject ``settings`` into ``value``. Go through ``value`` looking for ``{{NAME}}`` groups and replace each group with the value of the named item from ``settings``. Args: value (str): The value to inject settings into settings: An object that provides the dotted access interface Returns: (str, bool): The new value and whether the new value is different from the original value """
assert isinstance(value, string_types), 'Expected str; got {0.__class__}'.format(value) begin, end = '{{', '}}' if begin not in value: return value, False new_value = value begin_pos, end_pos = 0, None len_begin, len_end = len(begin), len(end) len_value = len(new_value) while begin_pos < len_value: # Find next {{. begin_pos = new_value.find(begin, begin_pos) if begin_pos == -1: break # Save everything before {{. before = new_value[:begin_pos] # Find }} after {{. begin_pos += len_begin end_pos = new_value.find(end, begin_pos) if end_pos == -1: raise ValueError('Unmatched {begin}...{end} in {value}'.format(**locals())) # Get name between {{ and }}, ignoring leading and trailing # whitespace. name = new_value[begin_pos:end_pos] name = name.strip() if not name: raise ValueError('Empty name in {value}'.format(**locals())) # Save everything after }}. after_pos = end_pos + len_end try: after = new_value[after_pos:] except IndexError: # Reached end of value. after = '' # Retrieve string value for named setting (the "injection # value"). try: injection_value = settings.get_dotted(name) except KeyError: raise KeyError('{name} not found in {settings}'.format(**locals())) if not isinstance(injection_value, string_types): injection_value = self.strategy.encode_value(injection_value) # Combine before, inject value, and after to get the new # value. new_value = ''.join((before, injection_value, after)) # Continue after injected value. begin_pos = len(before) + len(injection_value) len_value = len(new_value) return new_value, (new_value != value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_reporoot(): """Returns the absolute path to the repo root directory on the current system. """
from os import path import acorn medpath = path.abspath(acorn.__file__) return path.dirname(path.dirname(medpath))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def run_and_exit(command_class): '''A shortcut for reading from sys.argv and exiting the interpreter''' cmd = command_class(sys.argv[1:]) if cmd.error: print('error: {0}'.format(cmd.error)) sys.exit(1) else: sys.exit(cmd.run())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def registerParentFlag(self, optionName, value): '''Register a flag of a parent command :Parameters: - `optionName`: String. Name of option - `value`: Mixed. Value of parsed flag` ''' self.parentFlags.update({optionName: value}) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def radialAverage(arr, center=None): """ radial average a 2darray around a center if no center is given, take middle """
# taken from # http://stackoverflow.com/questions/21242011/most-efficient-way-to-calculate-radial-profile s0, s1 = arr.shape[:2] if center is None: center = s0/2, s1/2 y, x = np.indices((s0, s1)) r = np.sqrt((x - center[0])**2 + (y - center[1])**2) r = r.astype(np.int) tbin = np.bincount(r.ravel(), arr.ravel()) nr = np.bincount(r.ravel()) radialprofile = tbin/ nr return radialprofile
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _convert(value, tzto, defaulttz): """Convert datetime.datetime object between timezones"""
if not isinstance(value, datetime): raise ValueError('value must be a datetime.datetime object') if value.tzinfo is None: value = value.replace(tzinfo=defaulttz) return value.astimezone(tzto)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_local(value, defaulttz=None): """Convert datetime.datetime time to local time zone If value doesn't have tzinfo, then defaulttz is set. Default value of defaulttz is UTC. """
if defaulttz is None: defaulttz = tzutc() return _convert(value, tzlocal(), defaulttz)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_utc(value, defaulttz=None): """Convert datetime.datetime time to UTC If value doesn't have tzinfo, then defaulttz is set. Default value of defaulttz is local time zone. """
if defaulttz is None: defaulttz = tzlocal() return _convert(value, tzutc(), defaulttz)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def prettyPrintDictionary(d): '''Pretty print a dictionary as simple keys and values''' maxKeyLength = 0 maxValueLength = 0 for key, value in d.iteritems(): maxKeyLength = max(maxKeyLength, len(key)) maxValueLength = max(maxValueLength, len(key)) for key in sorted(d.keys()): print ("%"+str(maxKeyLength)+"s : %-" + str(maxValueLength)+ "s") % (key,d[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 label(self): '''A human readable label''' if self.__doc__ and self.__doc__.strip(): return self.__doc__.strip().splitlines()[0] return humanize(self.__class__.__name__)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def label_for(self, name): '''Get a human readable label for a method given its name''' method = getattr(self, name) if method.__doc__ and method.__doc__.strip(): return method.__doc__.strip().splitlines()[0] return humanize(name.replace(self._prefix, ''))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def run(self): ''' Collect all tests to run and run them. Each method will be run :attr:`Benchmark.times`. ''' tests = self._collect() if not tests: return self.times self.before_class() for test in tests: func = getattr(self, test) results = self.results[test] = Result() self._before(self, test) self.before() for i in range(self.times): self._before_each(self, test, i) result = self._run_one(func) results.total += result.duration if result.success: results.has_success = True else: results.has_errors = True self._after_each(self, test, i) if self.debug and not result.success: results.error = result.result break self.after() self._after(self, test) self.after_class()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def authorizer(self, schemes, resource, action, request_args): """Construct the Authorization header for a request. Args: schemes (list of str): Authentication schemes supported for the requested action. resource (str): Object upon which an action is being performed. action (str): Action being performed. request_args (list of str): Arguments passed to the action call. Returns: (str, str) A tuple of the auth scheme satisfied, and the credential for the Authorization header or empty strings if none could be satisfied. """
if not schemes: return u'', u'' for scheme in schemes: if scheme in self.schemes and self.has_auth_params(scheme): cred = Context.format_auth_params(self.schemes[scheme][u'params']) if hasattr(self, 'mfa_token'): cred = '{}, mfa_token="{}"'.format(cred, self.mfa_token) return scheme, cred raise AuthenticationError(self, schemes)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def authorize(self, scheme, **params): """Store credentials required to satisfy a given auth scheme. Args: scheme (str): The name of the Authentication scheme. **params: parameters for the specified scheme. Returns: True if parameters are set successfully (note that this doesn't mean the credentials are valid) False if the scheme specified is not supported """
if scheme not in self.schemes: return False for field, value in iteritems(params): setattr(self, field, value) if field in self.schemes[scheme][u'params'].keys() and value: self.schemes[scheme][u'params'][field] = value 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 has_auth_params(self, scheme): """Check whether all information required for a given auth scheme have been supplied. Args: scheme (str): Name of the authentication scheme to check. One of Gem-Identify, Gem-Device, Gem-Application Returns: True if all required parameters for the specified scheme are present or False otherwise. """
for k, v in iteritems(self.schemes[scheme][u'params']): if not v: 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 format_auth_params(params): """Generate the format expected by HTTP Headers from parameters. Args: params (dict): {key: value} to convert to key=value Returns: A formatted header string. """
parts = [] for (key, value) in params.items(): if value: parts.append('{}="{}"'.format(key, value)) return ", ".join(parts)
<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_backend(backend_class=None): """ Get backend instance If no `backend_class` is specified, the backend class is determined from the value of `settings.ROUGHPAGES_BACKEND`. `backend_class` can be a class object or dots separated python import path Returns: backend instance """
cache_name = '_backend_instance' if not hasattr(get_backend, cache_name): backend_class = backend_class or settings.ROUGHPAGES_BACKEND if isinstance(backend_class, basestring): module_path, class_name = backend_class.rsplit(".", 1) module = import_module(module_path) backend_class = getattr(module, class_name) setattr(get_backend, cache_name, backend_class()) return getattr(get_backend, cache_name)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_faderport_input_name(number=0): """ Find the MIDI input name for a connected FaderPort. NOTE! Untested for more than one FaderPort attached. :param number: 0 unless you've got more than one FaderPort attached. In which case 0 is the first, 1 is the second etc :return: Port name or None """
ins = [i for i in mido.get_input_names() if i.lower().startswith('faderport')] if 0 <= number < len(ins): return ins[number] else: return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_faderport_output_name(number=0): """ Find the MIDI output name for a connected FaderPort. NOTE! Untested for more than one FaderPort attached. :param number: 0 unless you've got more than one FaderPort attached. In which case 0 is the first, 1 is the second etc :return: Port name or None """
outs = [i for i in mido.get_output_names() if i.lower().startswith('faderport')] if 0 <= number < len(outs): return outs[number] else: return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _message_callback(self, msg): """Callback function to handle incoming MIDI messages."""
if msg.type == 'polytouch': button = button_from_press(msg.note) if button: self.on_button(button, msg.value != 0) elif msg.note == 127: self.on_fader_touch(msg.value != 0) elif msg.type == 'control_change' and msg.control == 0: self._msb = msg.value elif msg.type == 'control_change' and msg.control == 32: self._fader = (self._msb << 7 | msg.value) >> 4 self.on_fader(self._fader) elif msg.type == 'pitchwheel': self.on_rotary(1 if msg.pitch < 0 else -1) else: print('Unhandled:', msg)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fader(self, value: int): """Move the fader to a new position in the range 0 to 1023."""
self._fader = int(value) if 0 < value < 1024 else 0 self.outport.send(mido.Message('control_change', control=0, value=self._fader >> 7)) self.outport.send(mido.Message('control_change', control=32, value=self._fader & 0x7F))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def light_on(self, button: Button): """Turn the light on for the given Button. NOTE! If yuo turn the "Off" button light on, the fader won't report value updates when it's moved."""
self.outport.send(mido.Message('polytouch', note=button.light, value=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 run(self): """Fetch remote code."""
link = self.content[0] try: r = requests.get(link) r.raise_for_status() self.content = [r.text] return super(RemoteCodeBlock, self).run() except Exception: document = self.state.document err = 'Unable to resolve ' + link return [document.reporter.warning(str(err), line=self.lineno)]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def setUp(self): '''Look for WS-Address ''' toplist = filter(lambda wsa: wsa.ADDRESS==self.wsAddressURI, WSA_LIST) epr = 'EndpointReferenceType' for WSA in toplist+WSA_LIST: if (self.wsAddressURI is not None and self.wsAddressURI != WSA.ADDRESS) or \ _has_type_definition(WSA.ADDRESS, epr) is True: break else: raise EvaluateException,\ 'enabling wsAddressing requires the inclusion of that namespace' self.wsAddressURI = WSA.ADDRESS self.anonymousURI = WSA.ANONYMOUS self._replyTo = WSA.ANONYMOUS
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def setRequest(self, endPointReference, action): '''Call For Request ''' self._action = action self.header_pyobjs = None pyobjs = [] namespaceURI = self.wsAddressURI addressTo = self._addressTo messageID = self._messageID = "uuid:%s" %time.time() # Set Message Information Headers # MessageID typecode = GED(namespaceURI, "MessageID") pyobjs.append(typecode.pyclass(messageID)) # Action typecode = GED(namespaceURI, "Action") pyobjs.append(typecode.pyclass(action)) # To typecode = GED(namespaceURI, "To") pyobjs.append(typecode.pyclass(addressTo)) # From typecode = GED(namespaceURI, "From") mihFrom = typecode.pyclass() mihFrom._Address = self.anonymousURI pyobjs.append(mihFrom) if endPointReference: if hasattr(endPointReference, 'typecode') is False: raise EvaluateException, 'endPointReference must have a typecode attribute' if isinstance(endPointReference.typecode, \ GTD(namespaceURI ,'EndpointReferenceType')) is False: raise EvaluateException, 'endPointReference must be of type %s' \ %GTD(namespaceURI ,'EndpointReferenceType') ReferenceProperties = getattr(endPointReference, '_ReferenceProperties', None) if ReferenceProperties is not None: for v in getattr(ReferenceProperties, '_any', ()): if not hasattr(v,'typecode'): raise EvaluateException, '<any> element, instance missing typecode attribute' pyobjs.append(v) self.header_pyobjs = tuple(pyobjs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def upsert(self, key, value, entry): '''Update or Insert an entry into the list of dictionaries. If a dictionary in the list is found where key matches the value, then the FIRST matching list entry is replaced with entry else the entry is appended to the end of the list. The new entry is not examined in any way. It is, in fact, possible to upsert an entry that does not match the supplied key/value. Example of use: >>> test = [ ... {"name": "Jim", "age": 18, "income": 93000, "wigs": 68 }, ... {"name": "Larry", "age": 18, "wigs": [3, 2, 9]}, ... {"name": "Joe", "age": 20, "income": 15000, "wigs": [1, 2, 3]}, ... {"name": "Bill", "age": 19, "income": 29000 }, ... ] >>> entryA = {"name": "Willie", "age": 77} >>> myPLOD = PLOD(test) >>> print myPLOD.upsert("name", "Willie", entryA).returnString() [ {age: 18, income: 93000, name: 'Jim' , wigs: 68}, {age: 18, income: None , name: 'Larry' , wigs: [3, 2, 9]}, {age: 20, income: 15000, name: 'Joe' , wigs: [1, 2, 3]}, {age: 19, income: 29000, name: 'Bill' , wigs: None }, {age: 77, income: None , name: 'Willie', wigs: None } ] >>> entryB = {"name": "Joe", "age": 20, "income": 30, "wigs": [3, 2, 9]} >>> print myPLOD.upsert("name", "Joe", entryB).returnString() [ {age: 18, income: 93000, name: 'Jim' , wigs: 68}, {age: 18, income: None , name: 'Larry' , wigs: [3, 2, 9]}, {age: 20, income: 30, name: 'Joe' , wigs: [3, 2, 9]}, {age: 19, income: 29000, name: 'Bill' , wigs: None }, {age: 77, income: None , name: 'Willie', wigs: None } ] :param key: The dictionary key to examine. :param value: The value to search for as referenced by the key. :param entry: The replacement (or new) entry for the list. :returns: class ''' index=internal.get_index(self.table, key, self.EQUAL, value) if index is None: self.index_track.append(len(self.table)) self.table.append(entry) else: self.table[index]=entry return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def insert(self, new_entry): '''Insert a new entry to the end of the list of dictionaries. This entry retains the original index tracking but adds this entry incrementally at the end. >>> test = [ ... {"name": "Jim", "age": 18, "income": 93000, "wigs": 68 }, ... {"name": "Larry", "age": 18, "wigs": [3, 2, 9]}, ... {"name": "Joe", "age": 20, "income": 15000, "wigs": [1, 2, 3]}, ... {"name": "Bill", "age": 19, "income": 29000 }, ... ] >>> entryA = {"name": "Willie", "age": 77} >>> print PLOD(test).insert(entryA).returnString() [ {age: 18, income: 93000, name: 'Jim' , wigs: 68}, {age: 18, income: None , name: 'Larry' , wigs: [3, 2, 9]}, {age: 20, income: 15000, name: 'Joe' , wigs: [1, 2, 3]}, {age: 19, income: 29000, name: 'Bill' , wigs: None }, {age: 77, income: None , name: 'Willie', wigs: None } ] :param new_entry: The new list entry to insert. ''' self.index_track.append(len(self.table)) self.table.append(new_entry) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def deleteByOrigIndex(self, index): """Removes a single entry from the list given the index reference. The index, in this instance, is a reference to the *original* list indexing as seen when the list was first inserted into PLOD. An example: [ {age: 19, income: 29000, name: 'Bill' , wigs: None }, {age: 18, income: 93000, name: 'Jim' , wigs: 68}, {age: 20, income: 15000, name: 'Joe' , wigs: [1, 2, 3]}, {age: 18, income: None , name: 'Larry', wigs: [3, 2, 9]} ] [ {age: 19, income: 29000, name: 'Bill' , wigs: None }, {age: 20, income: 15000, name: 'Joe' , wigs: [1, 2, 3]}, {age: 18, income: None , name: 'Larry', wigs: [3, 2, 9]} ] As you can see in the example, the list was sorted by 'name', which placed 'Bill' as the first entry. Yet, when the deleteByOrigIndex was passed a zero (for the first entry), it removed 'Jim' instead since it was the original first entry. :param index: An integer representing the place of entry in the original list of dictionaries. :return: self """
result = [] result_tracker = [] for counter, row in enumerate(self.table): if self.index_track[counter] != index: result.append(row) result_tracker.append(self.index_track[counter]) self.table = result self.index_track = result_tracker return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def deleteByOrigIndexList(self, indexList): """Remove entries from the list given the index references. The index, in this instance, is a reference to the *original* list indexing as seen when the list was first inserted into PLOD. An example: [ {age: 19, income: 29000, name: 'Bill' , wigs: None }, {age: 18, income: 93000, name: 'Jim' , wigs: 68}, {age: 20, income: 15000, name: 'Joe' , wigs: [1, 2, 3]}, {age: 18, income: None , name: 'Larry', wigs: [3, 2, 9]} ] [ {age: 20, income: 15000, name: 'Joe' , wigs: [1, 2, 3]}, {age: 18, income: None , name: 'Larry', wigs: [3, 2, 9]} ] As you can see in the example, the list was sorted by 'name', which rearranged the entries. Yet, when the deleteByOrigIndexList was passed a [0, 1] (for the first and second entries), it removed 'Jim' and "Larry" since those were the original first and second entries. :param indexList: A list of integer representing the places of entry in the original list of dictionaries. :return: self """
result = [] result_tracker = [] counter = 0 for row in self.table: if not counter in indexList: result.append(row) result_tracker.append(self.index_track[counter]) counter += 1 self.table = result self.index_track = result_tracker return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def renumber(self, key, start=1, increment=1, insert=False): '''Incrementally number a key based on the current order of the list. Please note that if an entry in the list does not have the specified key, it is NOT created (unless insert=True is passed). The entry is, however, still counted. Example of use: >>> test = [ ... {"name": "Jim", "age": 18, "income": 93000, "order": 2}, ... {"name": "Larry", "age": 18, "order": 3}, ... {"name": "Joe", "age": 20, "income": 15000, "order": 1}, ... {"name": "Bill", "age": 19, "income": 29000}, ... ] >>> print PLOD(test).renumber("order", start=10).returnString(honorMissing=True) [ {age: 18, income: 93000, name: 'Jim' , order: 10}, {age: 18, name: 'Larry', order: 11}, {age: 20, income: 15000, name: 'Joe' , order: 12}, {age: 19, income: 29000, name: 'Bill' } ] >>> print PLOD(test).renumber("order", increment=2, insert=True).returnString(honorMissing=True) [ {age: 18, income: 93000, name: 'Jim' , order: 1}, {age: 18, name: 'Larry', order: 3}, {age: 20, income: 15000, name: 'Joe' , order: 5}, {age: 19, income: 29000, name: 'Bill' , order: 7} ] .. versionadded:: 0.1.2 :param key: The dictionary key (or cascading list of keys) that should receive the numbering. The previous value is replaced, regardles of type or content. Every entry is still counted; even if the key is missing. :param start: Defaults to 1. The starting number to begin counting with. :param increment: Defaults to 1. The amount to increment by for each entry in the list. :param insert: If True, then the key is inserted if missing. Else, the key is not inserted. Defaults to False. :returns: self ''' result = [] counter = start if insert: self.addKey(key, 0) for row in self.table: if internal.detect_member(row, key): row = internal.modify_member(row, key, counter) result.append(row) counter += increment self.table = result return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def sort(self, key, reverse=False, none_greater=False): '''Sort the list in the order of the dictionary key. Example of use: >>> test = [ ... {"name": "Jim", "age": 18, "income": 93000, "wigs": 68 }, ... {"name": "Larry", "age": 18, "wigs": [3, 2, 9]}, ... {"name": "Joe", "age": 20, "income": 15000, "wigs": [1, 2, 3]}, ... {"name": "Bill", "age": 19, "income": 29000 }, ... ] >>> print PLOD(test).sort("name").returnString() [ {age: 19, income: 29000, name: 'Bill' , wigs: None }, {age: 18, income: 93000, name: 'Jim' , wigs: 68}, {age: 20, income: 15000, name: 'Joe' , wigs: [1, 2, 3]}, {age: 18, income: None , name: 'Larry', wigs: [3, 2, 9]} ] >>> print PLOD(test).sort("income").returnString() [ {age: 18, income: None , name: 'Larry', wigs: [3, 2, 9]}, {age: 20, income: 15000, name: 'Joe' , wigs: [1, 2, 3]}, {age: 19, income: 29000, name: 'Bill' , wigs: None }, {age: 18, income: 93000, name: 'Jim' , wigs: 68} ] >>> print PLOD(test).sort(["age", "income"]).returnString() [ {age: 18, income: None , name: 'Larry', wigs: [3, 2, 9]}, {age: 18, income: 93000, name: 'Jim' , wigs: 68}, {age: 19, income: 29000, name: 'Bill' , wigs: None }, {age: 20, income: 15000, name: 'Joe' , wigs: [1, 2, 3]} ] .. versionadded:: 0.0.2 :param key: A dictionary key (or a list of keys) that should be the basis of the sorting. :param reverse: Defaults to False. If True, then list is sorted decrementally. :param none_greater: Defaults to False. If True, then entries missing the key/value pair are considered be of greater value than the non-missing values. :returns: self ''' for i in range(0, len(self.table)): min = i for j in range(i + 1, len(self.table)): if internal.is_first_lessor(self.table[j], self.table[min], key, none_greater=none_greater, reverse=reverse): min = j if i!=min: self.table[i], self.table[min] = self.table[min], self.table[i] # swap self.index_track[i], self.index_track[min] = self.index_track[min], self.index_track[i] # swap return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def hasKey(self, key, notNone=False): '''Return entries where the key is present. Example of use: >>> test = [ ... {"name": "Jim", "age": 18, "income": 93000, "wigs": 68 }, ... {"name": "Larry", "age": 18, "wigs": [3, 2, 9]}, ... {"name": "Joe", "age": 20, "income": None , "wigs": [1, 2, 3]}, ... {"name": "Bill", "age": 19, "income": 29000 }, ... ] >>> print PLOD(test).hasKey("income").returnString() [ {age: 18, income: 93000, name: 'Jim' , wigs: 68}, {age: 20, income: None , name: 'Joe' , wigs: [1, 2, 3]}, {age: 19, income: 29000, name: 'Bill', wigs: None } ] >>> print PLOD(test).hasKey("income", notNone=True).returnString() [ {age: 18, income: 93000, name: 'Jim' , wigs: 68}, {age: 19, income: 29000, name: 'Bill', wigs: None} ] .. versionadded:: 0.1.2 :param key: The dictionary key (or cascading list of keys) to locate. :param notNone: If True, then None is the equivalent of a missing key. Otherwise, a key with a value of None is NOT considered missing. :returns: self ''' result = [] result_tracker = [] for counter, row in enumerate(self.table): (target, _, value) = internal.dict_crawl(row, key) if target: if notNone==False or not value is None: result.append(row) result_tracker.append(self.index_track[counter]) self.table = result self.index_track = result_tracker return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def returnString(self, limit=False, omitBrackets=False, executable=False, honorMissing=False): '''Return a string containing the list of dictionaries in easy human-readable read format. Each entry is on one line. Key/value pairs are 'spaced' in such a way as to have them all line up vertically if using a monospace font. The fields are normalized to alphabetical order. Missing keys in a dictionary are inserted with a value of 'None' unless *honorMissing* is set to True. Example of use: >>> test = [ ... {"name": "Jim", "age": 18, "income": 93000, "order": 2}, ... {"name": "Larry", "age": 18, "order": 3}, ... {"name": "Joe", "age": 20, "income": 15000, "order": 1}, ... {"name": "Bill", "age": 19, "income": 29000, "order": 4}, ... ] >>> print PLOD(test).returnString() [ {age: 18, income: 93000, name: 'Jim' , order: 2}, {age: 18, income: None , name: 'Larry', order: 3}, {age: 20, income: 15000, name: 'Joe' , order: 1}, {age: 19, income: 29000, name: 'Bill' , order: 4} ] >>> print PLOD(test).returnString(limit=3, omitBrackets=True, executable=True) {'age': 18, 'income': 93000, 'name': 'Jim' , 'order': 2}, {'age': 18, 'income': None , 'name': 'Larry', 'order': 3}, {'age': 20, 'income': 15000, 'name': 'Joe' , 'order': 1} >>> print PLOD(test).returnString(honorMissing=True) [ {age: 18, income: 93000, name: 'Jim' , order: 2}, {age: 18, name: 'Larry', order: 3}, {age: 20, income: 15000, name: 'Joe' , order: 1}, {age: 19, income: 29000, name: 'Bill' , order: 4} ] :param limit: A number limiting the quantity of entries to return. Defaults to False, which means that the full list is returned. :param omitBrackets: If set to True, the outer square brackets representing the entire list are omitted. Defaults to False. :param executable: If set to True, the string is formatted in such a way that it conforms to Python syntax. Defaults to False. :param honorMissing: If set to True, keys that are missing in a dictionary are simply skipped with spaces. If False, then the key is display and given a value of None. Defaults to False. :return: A string containing a formatted textual representation of the list of dictionaries. ''' result = "" # we limit the table if needed if not limit: limit = len(self.table) used_table = [] for i in range(limit): if len(self.table)>i: used_table.append(internal.convert_to_dict(self.table[i])) # we locate all of the attributes and their lengths attr_width = {} # first pass to get the keys themselves for row in used_table: for key in row: if not key in attr_width: attr_width[key] = 0 # get a sorted list of keys attr_order = attr_width.keys() attr_order.sort() # not get minimum widths # (this is done as a seperate step to account for 'None' and other conditions. for row in used_table: for key in attr_width: if not key in row: if not honorMissing: if attr_width[key] < len("None"): attr_width[key] = len("None") else: if len(repr(row[key])) > attr_width[key]: attr_width[key] = len(repr(row[key])) # now we do the pretty print if not omitBrackets: result += "[\n" body = [] for row in used_table: row_string = "" if not omitBrackets: row_string += " " row_string += "{" middle = [] for key in attr_order: if key in row: # build the key if executable: item = "'"+str(key) + "': " else: item = str(key) + ": " # build the value s = repr(row[key]) if type(row[key]) is typemod.IntType: s = s.rjust(attr_width[key]) else: if honorMissing: # build the key item = " "*len(str(key)) if executable: item += " " item += " " # build the value s="" else: # build the key if executable: item = "'"+str(key) + "': " else: item = str(key) + ": " # build the value s = "None" item += s.ljust(attr_width[key]) middle.append(item) # row_string += ", ".join(middle) row_string += internal.special_join(middle) row_string += "}" body.append(row_string) result += ",\n".join(body) if len(body) and not omitBrackets: result += "\n" if not omitBrackets: result += "]" return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def returnIndexList(self, limit=False): '''Return a list of integers that are list-index references to the original list of dictionaries." Example of use: >>> test = [ ... {"name": "Jim", "age": 18, "income": 93000, "order": 2}, ... {"name": "Larry", "age": 18, "order": 3}, ... {"name": "Joe", "age": 20, "income": 15000, "order": 1}, ... {"name": "Bill", "age": 19, "income": 29000, "order": 4}, ... ] >>> print PLOD(test).returnIndexList() [0, 1, 2, 3] >>> print PLOD(test).sort("name").returnIndexList() [3, 0, 2, 1] :param limit: A number limiting the quantity of entries to return. Defaults to False, which means that the full list is returned. :return: A list of integers representing the original indices. ''' if limit==False: return self.index_track result = [] for i in range(limit): if len(self.table)>i: result.append(self.index_track[i]) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def returnOneEntry(self, last=False): '''Return the first entry in the current list. If 'last=True', then the last entry is returned." Returns None is the list is empty. Example of use: >>> test = [ ... {"name": "Jim", "age": 18, "income": 93000, "order": 2}, ... {"name": "Larry", "age": 18, "order": 3}, ... {"name": "Joe", "age": 20, "income": 15000, "order": 1}, ... {"name": "Bill", "age": 19, "income": 29000, "order": 4}, ... ] >>> print PLOD(test).returnOneEntry() {'age': 18, 'order': 2, 'name': 'Jim', 'income': 93000} >>> print PLOD(test).returnOneEntry(last=True) {'age': 19, 'order': 4, 'name': 'Bill', 'income': 29000} :param last: If True, the last entry is returned rather than the first. :return: A list entry, or None if the list is empty. ''' if len(self.table)==0: return None else: if last: return self.table[len(self.table)-1] else: return self.table[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 returnValue(self, key, last=False): '''Return the key's value for the first entry in the current list. If 'last=True', then the last entry is referenced." Returns None is the list is empty or the key is missing. Example of use: >>> test = [ ... {"name": "Jim", "age": 18, "income": 93000, "order": 2}, ... {"name": "Larry", "age": 18, "order": 3}, ... {"name": "Joe", "age": 20, "income": 15000, "order": 1}, ... {"name": "Bill", "age": 19, "income": 29000, "order": 4}, ... ] >>> print PLOD(test).returnValue("name") Jim >>> print PLOD(test).sort("name").returnValue("name", last=True) Larry >>> print PLOD(test).sort("name").returnValue("income", last=True) None :param last: If True, the last entry is used rather than the first. :return: A value, or None if the list is empty or the key is missing. ''' row = self.returnOneEntry(last=last) if not row: return None dict_row = internal.convert_to_dict(row) return dict_row.get(key, 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 returnValueList(self, key_list, last=False): '''Return a list of key values for the first entry in the current list. If 'last=True', then the last entry is referenced." Returns None is the list is empty. If a key is missing, then that entry in the list is None. Example of use: >>> test = [ ... {"name": "Jim", "age": 18, "income": 93000, "order": 2}, ... {"name": "Larry", "age": 18, "order": 3}, ... {"name": "Joe", "age": 20, "income": 15000, "order": 1}, ... {"name": "Bill", "age": 19, "income": 29000, "order": 4}, ... ] >>> print PLOD(test).returnValueList(["name", "income"]) ['Jim', 93000] >>> print PLOD(test).sort("name").returnValueList(["name", "income"], last=True) ['Larry', None] :param last: If True, the last entry is used rather than the first. :return: A value, or None if the list is empty. ''' result = [] row = self.returnOneEntry(last=last) if not row: return None dict_row = internal.convert_to_dict(row) for field in key_list: result.append(dict_row.get(field, None)) return result
<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_queryset(self, request): """Limit to TenantGroups that this user can access."""
qs = super(TenantGroupAdmin, self).get_queryset(request) if not request.user.is_superuser: qs = qs.filter(tenantrole__user=request.user, tenantrole__role=TenantRole.ROLE_GROUP_MANAGER) return qs
<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_queryset(self, request): """Limit to Tenants that this user can access."""
qs = super(TenantAdmin, self).get_queryset(request) if not request.user.is_superuser: tenants_by_group_manager_role = qs.filter( group__tenantrole__user=request.user, group__tenantrole__role=TenantRole.ROLE_GROUP_MANAGER ) tenants_by_tenant_manager_role = qs.filter( tenantrole__user=request.user, tenantrole__role=TenantRole.ROLE_TENANT_MANAGER ) return tenants_by_group_manager_role | tenants_by_tenant_manager_role return qs
<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, stream, media_type=None, parser_context=None): """ Parses the incoming bytestream as a URL encoded form, and returns the resulting QueryDict. """
parser_context = parser_context or {} encoding = parser_context.get('encoding', settings.DEFAULT_CHARSET) data = QueryDict(stream.read(), encoding=encoding) return data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse(self, stream, media_type=None, parser_context=None): """ Parses the incoming bytestream as a multipart encoded form, and returns a DataAndFiles object. `.data` will be a `QueryDict` containing all the form parameters. `.files` will be a `QueryDict` containing all the form files. """
parser_context = parser_context or {} request = parser_context['request'] encoding = parser_context.get('encoding', settings.DEFAULT_CHARSET) meta = request.META.copy() meta['CONTENT_TYPE'] = media_type upload_handlers = request.upload_handlers try: parser = DjangoMultiPartParser(meta, stream, upload_handlers, encoding) data, files = parser.parse() return DataAndFiles(data, files) except MultiPartParserError as exc: raise ParseError('Multipart form parse error - %s' % six.text_type(exc))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse(self, stream, media_type=None, parser_context=None): """ Treats the incoming bytestream as a raw file upload and returns a `DataAndFiles` object. `.data` will be None (we expect request body to be a file content). `.files` will be a `QueryDict` containing one 'file' element. """
parser_context = parser_context or {} request = parser_context['request'] encoding = parser_context.get('encoding', settings.DEFAULT_CHARSET) meta = request.META upload_handlers = request.upload_handlers filename = self.get_filename(stream, media_type, parser_context) # Note that this code is extracted from Django's handling of # file uploads in MultiPartParser. content_type = meta.get('HTTP_CONTENT_TYPE', meta.get('CONTENT_TYPE', '')) try: content_length = int(meta.get('HTTP_CONTENT_LENGTH', meta.get('CONTENT_LENGTH', 0))) except (ValueError, TypeError): content_length = None # See if the handler will want to take care of the parsing. for handler in upload_handlers: result = handler.handle_raw_input(None, meta, content_length, None, encoding) if result is not None: return DataAndFiles({}, {'file': result[1]}) # This is the standard case. possible_sizes = [x.chunk_size for x in upload_handlers if x.chunk_size] chunk_size = min([2 ** 31 - 4] + possible_sizes) chunks = ChunkIter(stream, chunk_size) counters = [0] * len(upload_handlers) for index, handler in enumerate(upload_handlers): try: handler.new_file(None, filename, content_type, content_length, encoding) except StopFutureHandlers: upload_handlers = upload_handlers[:index + 1] break for chunk in chunks: for index, handler in enumerate(upload_handlers): chunk_length = len(chunk) chunk = handler.receive_data_chunk(chunk, counters[index]) counters[index] += chunk_length if chunk is None: break for index, handler in enumerate(upload_handlers): file_obj = handler.file_complete(counters[index]) if file_obj: return DataAndFiles({}, {'file': file_obj}) raise ParseError("FileUpload parse error - " "none of upload handlers can handle the stream")
<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_filename(self, stream, media_type, parser_context): """ Detects the uploaded file name. First searches a 'filename' url kwarg. Then tries to parse Content-Disposition header. """
try: return parser_context['kwargs']['filename'] except KeyError: pass try: meta = parser_context['request'].META disposition = parse_header(meta['HTTP_CONTENT_DISPOSITION'].encode('utf-8')) filename_parm = disposition[1] if 'filename*' in filename_parm: return self.get_encoded_filename(filename_parm) return force_text(filename_parm['filename']) except (AttributeError, KeyError, ValueError): pass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def destandardize(self, estimates, se, **kwargs): """Revert the betas and variance components back to the original scale. """
pvalues = kwargs["pvalues"] v = kwargs["v"] nonmissing=kwargs["nonmissing"] pheno = self.datasource.phenotype_data[self.idx][self.datasource.phenotype_data[self.idx] != PhenoCovar.missing_encoding] covariates = [] mmx = [] ssx = [] a = [1,0] for c in self.datasource.covariate_data: covariates.append(c[c!=PhenoCovar.missing_encoding]) mmx.append(numpy.mean(covariates[-1])) ssx.append(numpy.std(covariates[-1])) a.append(-mmx[-1]/ssx[-1]) if len(mmx) < 1: mmx = 1 ssx = 1 else: mmx = numpy.array(mmx) ssx = numpy.array(ssx) covariates = numpy.array(covariates) ssy = numpy.std(pheno) mmy = numpy.mean(pheno) # Quick scratch pad for Chun's new destandardization ccount = len(covariates) + 2 a=numpy.array(a) meanpar = list([mmy + ssy * (estimates[0] - numpy.sum(estimates[2:ccount]*mmx/ssx)), estimates[1] * ssy]) meanse = [ssy*numpy.sqrt(a.dot(v[0:ccount, 0:ccount]).dot(a.transpose())), ssy * se[1]] varpar = [2*numpy.log(ssy) + estimates[ccount] - numpy.sum(estimates[ccount+2:]*mmx/ssx), estimates[ccount+1]] varse = [numpy.sqrt(a.dot(v[ccount:, ccount:]).dot(a.transpose())), se[ccount+1]] if ccount > 2: meanpar += list(estimates[2:ccount] * ssy / ssx) meanse += list(ssy * se[2:ccount]/ssx) varpar += list(estimates[ccount+2:]/ssx) varse += list(se[ccount+2:]/ssx) pvals = 2*scipy.stats.norm.cdf(-numpy.absolute(numpy.array(meanpar+varpar)/numpy.array(meanse+varse))) return meanpar+varpar, meanse + varse, pvals
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tar(self, appname, appversion): """ Given an app name and version to be used in the tarball name, create a tar.bz2 file with all of this folder's contents inside. Return a Build object with attributes for appname, appversion, time, and path. """
name_tmpl = '%(app)s-%(version)s-%(time)s.tar.bz2' time = utc.now() name = name_tmpl % {'app': appname, 'version': appversion, 'time': time.strftime('%Y-%m-%dT%H-%M')} if not os.path.exists(TARBALL_HOME): os.mkdir(TARBALL_HOME) tarball = os.path.join(TARBALL_HOME, name) tar_params = {'filename': tarball, 'folder': self.folder} tar_result = run('tar -C %(folder)s -cjf %(filename)s .' % tar_params) tar_result.raise_for_status() return Build(appname, appversion, time, tarball)