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 getSet(self, setID): ''' Gets the information of one specific build using its Brickset set ID. :param str setID: The ID of the build from Brickset. :returns: A single Build object. :rtype: :class:`brickfront.build.Build` :raises brickfront.errors.InvalidSetID: If no sets exist by that ID. ''' params = { 'apiKey': self.apiKey, 'userHash': self.userHash, 'setID': setID } url = Client.ENDPOINT.format('getSet') returned = get(url, params=params) self.checkResponse(returned) # Put it into a Build class root = ET.fromstring(returned.text) v = [Build(i, self) for i in root] # Return to user try: return v[0] except IndexError: raise InvalidSetID('There is no set with the ID of `{}`.'.format(setID))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def getRecentlyUpdatedSets(self, minutesAgo): ''' Gets the information of recently updated sets. :param int minutesAgo: The amount of time ago that the set was updated. :returns: A list of Build instances that were updated within the given time. :rtype: list .. warning:: An empty list will be returned if there are no sets in the given time limit. ''' params = { 'apiKey': self.apiKey, 'minutesAgo': minutesAgo } url = Client.ENDPOINT.format('getRecentlyUpdatedSets') returned = get(url, params=params) self.checkResponse(returned) # Parse them in to build objects root = ET.fromstring(returned.text) return [Build(i, self) for i in root]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def getAdditionalImages(self, setID): ''' Gets a list of URLs containing images of the set. :param str setID: The ID of the set you want to grab the images for. :returns: A list of URL strings. :rtype: list .. warning:: An empty list will be returned if there are no additional images, or if the set ID is invalid. ''' params = { 'apiKey': self.apiKey, 'setID': setID } url = Client.ENDPOINT.format('getAdditionalImages') returned = get(url, params=params) self.checkResponse(returned) # I really fuckin hate XML root = ET.fromstring(returned.text) urlList = [] for imageHolder in root: urlList.append(imageHolder[-1].text) return urlList
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def getReviews(self, setID): ''' Get the reviews for a set. :param str setID: The ID of the set you want to get the reviews of. :returns: A list of reviews. :rtype: List[:class:`brickfront.review.Review`] .. warning:: An empty list will be returned if there are no reviews, or if the set ID is invalid. ''' params = { 'apiKey': self.apiKey, 'setID': setID } url = Client.ENDPOINT.format('getReviews') returned = get(url, params=params) self.checkResponse(returned) # Parse into review objects root = ET.fromstring(returned.text) return [Review(i) for i in root]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def results(cls, function, group=None): """ Returns a numpy nparray representing the benchmark results of a function in a group. """
return numpy.array(cls._results[group][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 mixin_class(target, cls): """Mix cls content in target."""
for name, field in getmembers(cls): Mixin.mixin(target, field, 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 mixin_function_or_method(target, routine, name=None, isbound=False): """Mixin a routine into the target. :param routine: routine to mix in target. :param str name: mixin name. Routine name by default. :param bool isbound: If True (False by default), the mixin result is a bound method to target. """
function = None if isfunction(routine): function = routine elif ismethod(routine): function = get_method_function(routine) else: raise Mixin.MixInError( "{0} must be a function or a method.".format(routine)) if name is None: name = routine.__name__ if not isclass(target) or isbound: _type = type(target) method_args = [function, target] if PY2: method_args += _type result = MethodType(*method_args) else: if PY2: result = MethodType(function, None, target) else: result = function Mixin.set_mixin(target, result, name) 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 mixin(target, resource, name=None): """Do the correct mixin depending on the type of input resource. - Method or Function: mixin_function_or_method. - class: mixin_class. - other: set_mixin. And returns the result of the choosen method (one or a list of mixins). """
result = None if ismethod(resource) or isfunction(resource): result = Mixin.mixin_function_or_method(target, resource, name) elif isclass(resource): result = list() for name, content in getmembers(resource): if isclass(content): mixin = Mixin.set_mixin(target, content, name) else: mixin = Mixin.mixin(target, content, name) result.append(mixin) else: result = Mixin.set_mixin(target, resource, name) 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 remove_mixins(target): """Tries to get back target in a no mixin consistent state. """
mixedins_by_name = Mixin.get_mixedins_by_name(target).copy() for _name in mixedins_by_name: # for all named mixins while True: # remove all mixins named _name try: Mixin.remove_mixin(target, _name) except Mixin.MixInError: break
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def error403(error): """ Custom 403 page. """
tb = error.traceback if isinstance(tb, dict) and "name" in tb and "uuid" in tb: return SimpleTemplate(PRIVATE_ACCESS_MSG).render( name=error.traceback["name"], uuid=error.traceback["uuid"] ) return "Access denied!"
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def render_trees(trees, path_composer): """ Render list of `trees` to HTML. Args: trees (list): List of :class:`.Tree`. path_composer (fn reference): Function used to compose paths from UUID. Look at :func:`.compose_tree_path` from :mod:`.web_tools`. Returns: str: HTML representation of trees. """
trees = list(trees) # by default, this is set def create_pub_cache(trees): """ Create uuid -> DBPublication cache from all uuid's linked from `trees`. Args: trees (list): List of :class:`.Tree`. Returns: dict: {uuid: DBPublication} """ sub_pubs_uuids = sum((x.collect_publications() for x in trees), []) uuid_mapping = { uuid: search_pubs_by_uuid(uuid) for uuid in set(sub_pubs_uuids) } # cleaned dict without blank matches return { uuid: pub[0] for uuid, pub in uuid_mapping.iteritems() if pub } # create uuid -> DBPublication cache pub_cache = create_pub_cache(trees) def render_tree(tree, ind=1): """ Render the tree into HTML using :attr:`TREE_TEMPLATE`. Private trees are ignored. Args: tree (obj): :class:`.Tree` instance. ind (int, default 1): Indentation. This function is called recursively. Returns: str: Rendered string. """ if not tree.is_public: return "" rendered_tree = SimpleTemplate(TREE_TEMPLATE).render( tree=tree, render_tree=render_tree, ind=ind, path_composer=path_composer, pub_cache=pub_cache, ) # keep nice indentation ind_txt = ind * " " return ind_txt + ("\n" + ind_txt).join(rendered_tree.splitlines()) # this is used to get reference for back button parent = tree_handler().get_parent(trees[0]) link_up = path_composer(parent) if parent else None return SimpleTemplate(TREES_TEMPLATE).render( trees=trees, render_tree=render_tree, link_up=link_up, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_publications(): """ Return list of all publications in basic graphic HTML render. """
publications = search_publications( DBPublication(is_public=True) ) return SimpleTemplate(INDEX_TEMPLATE).render( publications=publications, compose_path=web_tools.compose_path, delimiter=":", )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_theme(theme=None, for_code=None): """ set md and code theme """
try: if theme == 'default': return theme = theme or os.environ.get('AXC_THEME', 'random') # all the themes from here: themes = read_themes() if theme == 'random': rand = randint(0, len(themes)-1) theme = themes.keys()[rand] t = themes.get(theme) if not t or len(t.get('ct')) != 5: # leave defaults: return _for = '' if for_code: _for = ' (code)' if is_app: print >> sys.stderr, low('theme%s: %s (%s)' % (_for, theme, t.get('name'))) t = t['ct'] cols = (t[0], t[1], t[2], t[3], t[4]) if for_code: global CH1, CH2, CH3, CH4, CH5 CH1, CH2, CH3, CH4, CH5 = cols else: global H1, H2, H3, H4, H5 # set the colors now from the ansi codes in the theme: H1, H2, H3, H4, H5 = cols finally: if for_code: build_hl_by_token()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def style_ansi(raw_code, lang=None): """ actual code hilite """
lexer = 0 if lang: try: lexer = get_lexer_by_name(lang) except ValueError: print col(R, 'Lexer for %s not found' % lang) lexer = None if not lexer: try: if guess_lexer: lexer = pyg_guess_lexer(raw_code) except: pass if not lexer: lexer = get_lexer_by_name(def_lexer) tokens = lex(raw_code, lexer) cod = [] for t, v in tokens: if not v: continue _col = code_hl_tokens.get(t) if _col: cod.append(col(v, _col)) else: cod.append(v) return ''.join(cod)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rewrap(el, t, ind, pref): """ Reasonably smart rewrapping checking punctuations """
global term_columns cols = term_columns - len(ind + pref) if el.tag == 'code' or len(t) <= cols: return t # wrapping: # we want to keep existing linebreaks after punctuation # marks. the others we rewrap: puncs = ',', '.', '?', '!', '-', ':' parts = [] origp = t.splitlines() if len(origp) > 1: pos = -1 while pos < len(origp) - 1: pos += 1 # last char punctuation? if origp[pos][-1] not in puncs and \ not pos == len(origp) -1: # concat: parts.append(origp[pos].strip() + ' ' + \ origp[pos+1].strip()) pos += 1 else: parts.append(origp[pos].strip()) t = '\n'.join(parts) # having only the linebreaks with puncs before we rewrap # now: parts = [] for part in t.splitlines(): parts.extend([part[i:i+cols] \ for i in range(0, len(part), cols)]) # last remove leading ' ' (if '\n' came just before): t = [] for p in parts: t.append(p.strip()) return '\n'.join(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 monitor(args): """ file monitor mode """
filename = args.get('MDFILE') if not filename: print col('Need file argument', 2) raise SystemExit last_err = '' last_stat = 0 while True: if not os.path.exists(filename): last_err = 'File %s not found. Will continue trying.' % filename else: try: stat = os.stat(filename)[8] if stat != last_stat: parsed = run_args(args) print parsed last_stat = stat last_err = '' except Exception, ex: last_err = str(ex) if last_err: print 'Error: %s' % last_err sleep()
<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_changed_file_cmd(cmd, fp, pretty): """ running commands on changes. pretty the parsed file """
with open(fp) as f: raw = f.read() # go sure regarding quotes: for ph in (dir_mon_filepath_ph, dir_mon_content_raw, dir_mon_content_pretty): if ph in cmd and not ('"%s"' % ph) in cmd \ and not ("'%s'" % ph) in cmd: cmd = cmd.replace(ph, '"%s"' % ph) cmd = cmd.replace(dir_mon_filepath_ph, fp) print col('Running %s' % cmd, H1) for r, what in ((dir_mon_content_raw, raw), (dir_mon_content_pretty, pretty)): cmd = cmd.replace(r, what.encode('base64')) # yeah, i know, sub bla bla... if os.system(cmd): print col('(the command failed)', R)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def monitor_dir(args): """ displaying the changed files """
def show_fp(fp): args['MDFILE'] = fp pretty = run_args(args) print pretty print "(%s)" % col(fp, L) cmd = args.get('change_cmd') if cmd: run_changed_file_cmd(cmd, fp=fp, pretty=pretty) ftree = {} d = args.get('-M') # was a change command given? d += '::' d, args['change_cmd'] = d.split('::')[:2] args.pop('-M') # collides: args.pop('-m') d, exts = (d + ':md,mdown,markdown').split(':')[:2] exts = exts.split(',') if not os.path.exists(d): print col('Does not exist: %s' % d, R) sys.exit(2) dir_black_list = ['.', '..'] def check_dir(d, ftree): check_latest = ftree.get('latest_ts') d = os.path.abspath(d) if d in dir_black_list: return if len(ftree) > mon_max_files: # too deep: print col('Max files (%s) reached' % c(mon_max_files, R)) dir_black_list.append(d) return try: files = os.listdir(d) except Exception, ex: print '%s when scanning dir %s' % (col(ex, R), d) dir_black_list.append(d) return for f in files: fp = j(d, f) if os.path.isfile(fp): f_ext = f.rsplit('.', 1)[-1] if f_ext == f: f_ext == '' if not f_ext in exts: continue old = ftree.get(fp) # size: now = os.stat(fp)[6] if check_latest: if os.stat(fp)[7] > ftree['latest_ts']: ftree['latest'] = fp ftree['latest_ts'] = os.stat(fp)[8] if now == old: continue # change: ftree[fp] = now if not old: # At first time we don't display ALL the files...: continue # no binary. make sure: if 'text' in os.popen('file "%s"' % fp).read(): show_fp(fp) elif os.path.isdir(fp): check_dir(j(d, fp), ftree) ftree['latest_ts'] = 1 while True: check_dir(d, ftree) if 'latest_ts' in ftree: ftree.pop('latest_ts') fp = ftree.get('latest') if fp: show_fp(fp) else: print 'sth went wrong, no file found' sleep()
<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_args(args): """ call the lib entry function with CLI args """
return main(filename = args.get('MDFILE') ,theme = args.get('-t', 'random') ,cols = args.get('-c') ,from_txt = args.get('-f') ,c_theme = args.get('-T') ,c_no_guess = args.get('-x') ,do_html = args.get('-H') ,no_colors = args.get('-A') ,display_links = args.get('-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 code(_, s, from_fenced_block = None, **kw): """ md code AND ``` style fenced raw code ends here"""
lang = kw.get('lang') raw_code = s if have_pygments: s = style_ansi(raw_code, lang=lang) # outest hir is 2, use it for fenced: ind = ' ' * kw.get('hir', 2) #if from_fenced_block: ... WE treat equal. # shift to the far left, no matter the indent (screenspace matters): firstl = s.split('\n')[0] del_spaces = ' ' * (len(firstl) - len(firstl.lstrip())) s = ('\n' + s).replace('\n%s' % del_spaces, '\n')[1:] # we want an indent of one and low vis prefix. this does it: code_lines = ('\n' + s).splitlines() prefix = ('\n%s%s %s' % (ind, low(code_pref), col('', C, no_reset=1))) code = prefix.join(code_lines) return code + '\n' + reset_col
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bestfit_func(self, bestfit_x): """ Returns y value """
if not self.bestfit_func: raise KeyError("Do do_bestfit first") return self.args["func"](self.fit_args, bestfit_x)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_bestfit(self): """ do bestfit using scipy.odr """
self.check_important_variables() x = np.array(self.args["x"]) y = np.array(self.args["y"]) if self.args.get("use_RealData", True): realdata_kwargs = self.args.get("RealData_kwargs", {}) data = RealData(x, y, **realdata_kwargs) else: data_kwargs = self.args.get("Data_kwargs", {}) data = Data(x, y, **data_kwargs) model = self.args.get("Model", None) if model is None: if "func" not in self.args.keys(): raise KeyError("Need fitting function") model_kwargs = self.args.get("Model_kwargs", {}) model = Model(self.args["func"], **model_kwargs) odr_kwargs = self.args.get("ODR_kwargs", {}) odr = ODR(data, model, **odr_kwargs) self.output = odr.run() if self.args.get("pprint", False): self.output.pprint() self.fit_args = self.output.beta return self.fit_args
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def change_in_longitude(lat, miles): """Given a latitude and a distance west, return the change in longitude."""
# Find the radius of a circle around the earth at given latitude. r = earth_radius * math.cos(lat * degrees_to_radians) return (miles / r) * radians_to_degrees
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def disconnect(self): """ Close all connections that are set on this wire """
if self.connection_receive: self.connection_receive.close() if self.connection_respond: self.connection_respond.close() if self.connection_send: self.connection_send.close()
<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_and_wait(self, path, message, timeout=0, responder=None): """ Send a message and block until a response is received. Return response message """
message.on("response", lambda x,event_origin,source:None, once=True) if timeout > 0: ts = time.time() else: ts = 0 sent = False while not message.response_received: if not sent: self.send(path, message) sent = True if ts: if time.time() - ts > timeout: raise exceptions.TimeoutError("send_and_wait(%s)"%path, timeout) return message.response_message
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wire(self, name, receive=None, send=None, respond=None, **kwargs): """ Wires the link to a connection. Can be called multiple times to set up wires to different connections After creation wire will be accessible on the link via its name as an attribute. You can undo this action with the cut() method Arguments: - name (str): unique name for the wire Keyword Arguments: - receive (Connection): wire receiver to this connection - respond (Connection): wire responder to this connection - send (Connection): wire sender to this connection - meta (dict): attach these meta variables to any message sent from this wire Returns: - Wire: the created wire instance """
if hasattr(self, name) and name != "main": raise AttributeError("cannot use '%s' as name for wire, attribute already exists") if send: self.log_debug("Wiring '%s'.send: %s" % (name, send)) if respond: self.log_debug("Wiring '%s'.respond: %s" % (name, respond)) if receive: self.log_debug("Wiring '%s'.receive: %s" % (name, receive)) wire = Wire(receive=receive, send=send, respond=respond) wire.name = "%s.%s" % (self.name, name) wire.meta = kwargs.get("meta",{}) wire.on("receive", self.on_receive) setattr(self, name, wire) if not self.main: self.main = wire return wire
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def disconnect(self): """ Cut all wires and disconnect all connections established on this link """
for name, wire in self.wires(): self.cut(name, disconnect=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 call(self, task, decorators=None): """ Call given task on service layer. :param task: task to be called. task will be decorated with TaskDecorator's contained in 'decorators' list :type task: instance of Task class :param decorators: list of TaskDecorator's / TaskResultDecorator's inherited classes :type decorators: list :return task_result: result of task call decorated with TaskResultDecorator's contained in 'decorators' list :rtype TaskResult instance """
if decorators is None: decorators = [] task = self.apply_task_decorators(task, decorators) data = task.get_data() name = task.get_name() result = self._inner_call(name, data) task_result = RawTaskResult(task, result) return self.apply_task_result_decorators(task_result, decorators)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _resource_context(fn): """ Compose path to the ``resources`` directory for given `fn`. Args: fn (str): Filename of file in ``resources`` directory. Returns: str: Absolute path to the file in resources directory. """
return os.path.join( os.path.dirname(__file__), DES_DIR, fn )
<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_contract(firma, pravni_forma, sidlo, ic, dic, zastoupen): """ Compose contract and create PDF. Args: firma (str): firma pravni_forma (str): pravni_forma sidlo (str): sidlo ic (str): ic dic (str): dic zastoupen (str): zastoupen Returns: obj: StringIO file instance containing PDF file. """
contract_fn = _resource_context( "Licencni_smlouva_o_dodavani_elektronickych_publikaci" "_a_jejich_uziti.rst" ) # load contract with open(contract_fn) as f: contract = f.read()#.decode("utf-8").encode("utf-8") # make sure that `firma` has its heading mark firma = firma.strip() firma = firma + "\n" + ((len(firma) + 1) * "-") # patch template contract = Template(contract).substitute( firma=firma, pravni_forma=pravni_forma.strip(), sidlo=sidlo.strip(), ic=ic.strip(), dic=dic.strip(), zastoupen=zastoupen.strip(), resources_path=RES_PATH ) return gen_pdf( contract, open(_resource_context("style.json")).read(), )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def render_tag(self, tag_func): """ Creates a tag using the decorated func as the render function for the template tag node. The render function takes two arguments - the template context and the tag token. """
@wraps(tag_func) def tag_wrapper(parser, token): class RenderTagNode(template.Node): def render(self, context): return tag_func(context, token) return RenderTagNode() return self.tag(tag_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 inclusion_tag(self, name, context_class=Context, takes_context=False): """ Replacement for Django's ``inclusion_tag`` which looks up device specific templates at render time. """
def tag_decorator(tag_func): @wraps(tag_func) def tag_wrapper(parser, token): class InclusionTagNode(template.Node): def render(self, context): if not getattr(self, "nodelist", False): try: request = context["request"] except KeyError: t = get_template(name) else: ts = templates_for_device(request, name) t = select_template(ts) self.template = t parts = [template.Variable(part).resolve(context) for part in token.split_contents()[1:]] if takes_context: parts.insert(0, context) result = tag_func(*parts) autoescape = context.autoescape context = context_class(result, autoescape=autoescape) return self.template.render(context) return InclusionTagNode() return self.tag(tag_wrapper) return tag_decorator
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def user_list(self, params=None): """Lists all users within the tenant."""
uri = 'openstack/users' if params: uri += '?%s' % urllib.urlencode(params) resp, body = self.get(uri) self.expected_success(200, resp.status) body = json.loads(body) return rest_client.ResponseBody(resp, body)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def user_invite(self, username, email, roles): """ Invite a user to the tenant. """
uri = 'openstack/users' data = { "username": username, "email": email, "roles": list(set(roles)) } post_body = json.dumps(data) resp, body = self.post(uri, body=post_body) self.expected_success(200, resp.status) body = json.loads(body) return rest_client.ResponseBody(resp, body)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def revoke_user(self, user_id): """ Revoke a user from the tenant This will remove pending or approved roles but will not not delete the user from Keystone. """
uri = 'openstack/users/%s' % user_id try: resp = self.delete(uri) except AttributeError: # note: this breaks. stacktask returns a string, not json. return self.expected_success(200, resp.status) return rest_client.ResponseBody(resp, 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 get_tokens(self, filters={}): """ Returns dict of tokens matching the provided filters """
uri = 'tokens' if filters: filters = {'filters': json.dumps(filters)} uri += "?%s" % urllib.urlencode(filters, True) resp, body = self.get(uri) self.expected_success(200, resp.status) body = json.loads(body) return rest_client.ResponseBody(resp, body)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def token_submit(self, token_id, json_data={}): """ Submits a given token, along with optional data """
uri = 'tokens/%s' % token_id post_body = json.dumps(json_data) resp, body = self.post(uri, post_body) self.expected_success(200, resp.status) body = json.loads(body) return rest_client.ResponseBody(resp, body)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def approve_task(self, task_id): """ Returns dict of tasks matching the provided filters """
uri = 'tasks/%s' % task_id data = {"approved": True} resp, body = self.post(uri, json.dumps(data)) self.expected_success(200, resp.status) body = json.loads(body) return rest_client.ResponseBody(resp, body)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def signup(self, project_name, email): """ Signup for a new project. """
uri = 'openstack/sign-up' data = { "project_name": project_name, "email": email, } post_body = json.dumps(data) resp, body = self.post(uri, body=post_body) self.expected_success(200, resp.status) body = json.loads(body) return rest_client.ResponseBody(resp, body)
<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_event(self, name, default=_sentinel): """ Lookup an event by name. :param str item: Event name :return Event: Event instance under key """
if name not in self.events: if self.create_events_on_access: self.add_event(name) elif default is not _sentinel: return default return self.events[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 _add_internal_event(self, name, send_event=False, internal_event_factory=None): """ This is only here to ensure my constant hatred for Python 2's horrid variable argument support. """
if not internal_event_factory: internal_event_factory = self.internal_event_factory return self.add_event(names, send_event=send_event, event_factory=internal_event_factory)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _attach_handler_events(self, handler, events=None): """ Search handler for methods named after events, attaching to event handlers as applicable. :param object handler: Handler instance :param list events: List of event names to look for. If not specified, will do all known event names. """
if not events: events = self for name in events: meth = getattr(handler, name, None) if meth: self.events[name] += meth
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _remove(self, handler, send_event=True): """ Remove handler instance and detach any methods bound to it from uninhibited. :param object handler: handler instance :return object: The handler you added is given back so this can be used as a decorator. """
for event in self: event.remove_handlers_bound_to_instance(handler) self.handlers.remove(handler) if send_event: self.on_handler_remove(handler)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fire(self, event, *args, **kwargs): """ Fire event. call event's handlers using given arguments, return a list of results. :param str name: Event name :param tuple args: positional arguments to call each handler with :param dict kwargs: keyword arguments to call each handler with :return list: a list of tuples of handler, return value """
if not self._maybe_create_on_fire(event): return return self[event].fire(*args, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ifire(self, event, *args, **kwargs): """ Iteratively fire event, returning generator. Calls each handler using given arguments, upon iteration, yielding each result. :param str name: Event name :param tuple args: positional arguments to call each handler with :param dict kwargs: keyword arguments to call each handler with :return generator: a generator yielding a tuple of handler, return value """
if not self._maybe_create_on_fire(event): return # Wrap the generator per item to force that this method be a generator # Python 3.x of course has yield from, which would be great here. # for x in self[event].ifire(*args, **kwargs) # yield x return self[event].ifire(*args, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def active(context, pattern_or_urlname, class_name='active', *args, **kwargs): """Based on a URL Pattern or name, determine if it is the current page. This is useful if you're creating a navigation component and want to give the active URL a specific class for UI purposes. It will accept a named URL or a regex pattern. If you have a URL which accepts args or kwargs then you may pass them into the tag and they will be picked up for matching as well. Usage: {% load custom_tags %} <li class="nav-home {% active 'url-name' %}"> <a href="#">Home</a> </li> OR <li class="nav-home {% active '^/regex/' %}"> <a href="#">Home</a> </li> OR <li class="nav-home {% active 'url-name' class_name='current' %}"> <a href="#">Home</a> </li> OR <li class="nav-home {% active 'url-name' username=user.username %}"> <a href="#">Home</a> </li> """
request = context.dicts[1].get('request') try: pattern = '^%s$' % reverse(pattern_or_urlname, args=args, kwargs=kwargs) except NoReverseMatch: pattern = pattern_or_urlname if request and re.search(pattern, request.path): return class_name 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 run(sub_command, exit_handle=None, **options): """Run a command"""
command = Command(sub_command, exit_handle) return command.run(**options)
<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_extensions_dot(exts): """trim leading dots from extensions and drop any empty strings."""
if exts is None: return None res = [] for i in range(0, len(exts)): if exts[i] == "": continue res.append(__trim_extension_dot(exts[i])) return res
<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_just_in_time_genome_alignment(path, ref_spec, extensions=None, index_exts=None, fail_no_index=True, verbose=False): """Load a just-in-time genome alignment from a directory."""
if index_exts is None and fail_no_index: raise ValueError("Failure on no index specified for loading genome " + "alignment, but no index extensions specified") extensions = __trim_extensions_dot(extensions) index_exts = __trim_extensions_dot(index_exts) partial_chrom_files = {} whole_chrom_files = {} for fn in os.listdir(path): pth = os.path.join(path, fn) if os.path.isfile(pth): base, ext = os.path.splitext(pth) ext = __trim_extension_dot(ext) if extensions is None or ext in extensions: idx_path = __find_index(pth, index_exts) if idx_path is None and fail_no_index: raise PyokitIOError("No index file for " + fn) chrom, start, end = __split_genomic_interval_filename(fn) assert((start is None and end is None) or (start is not None and end is not None)) if start is None: if chrom in whole_chrom_files: raise PyokitIOError("multiple files for chrom " + chrom) whole_chrom_files[chrom] = (pth, idx_path) else: k = (chrom, start, end) if k in partial_chrom_files: other_pth = partial_chrom_files[k][0] raise PyokitIOError("multiple files for " + str(k) + " --> " + pth + " and " + other_pth) partial_chrom_files[k] = (pth, idx_path) def factory(k): pth, idx = k return build_genome_alignment_from_file(pth, ref_spec, idx, verbose) return JustInTimeGenomeAlignment(whole_chrom_files, partial_chrom_files, factory)
<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_index(alig_file_pth, idx_extensions): """ Find an index file for a genome alignment file in the same directory. :param alig_file_path: path to the alignment file. :param idx_extensions: check for index files with these extensions :return: path to first index file that matches the name of the alignment file and has one of the specified extensions. """
if idx_extensions is None: return None base, _ = os.path.splitext(alig_file_pth) for idx_ext in idx_extensions: candidate = base + os.extsep + idx_ext if os.path.isfile(candidate): return candidate 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 build_genome_alignment_from_directory(d_name, ref_spec, extensions=None, index_exts=None, fail_no_index=False): """ build a genome aligment by loading all files in a directory. Fiel without indexes are loaded immediately; those with indexes are loaded on-demand. Not recursive (i.e. subdirectories are not parsed). :param d_name: directory to load from. :param ref_spec: which species in the alignemnt files is the reference? :param extensions: list or set of acceptable extensions; treat any files with these extensions as part of the alignment. If None, treat any file which has an extension that is NOT in index_extensions as part of the alignment. :param index_exts: treat any files with these extensions as index files. :param fail_no_index: fail if index extensions are provided and an alignment file has no index file. """
if index_exts is None and fail_no_index: raise ValueError("Failure on no index specified for loading genome " + "alignment, but no index extensions specified") blocks = [] for fn in os.listdir(d_name): pth = os.path.join(d_name, fn) if os.path.isfile(pth): _, ext = os.path.splitext(pth) if extensions is None or ext in extensions: idx_path = __find_index(pth, index_exts) if idx_path is None and fail_no_index: raise PyokitIOError("No index file for " + fn) for b in genome_alignment_iterator(pth, ref_spec, idx_path): blocks.append(b) return GenomeAlignment(blocks)
<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_genome_alignment_from_file(ga_path, ref_spec, idx_path=None, verbose=False): """ build a genome alignment by loading from a single MAF file. :param ga_path: the path to the file to load. :param ref_spec: which species in the MAF file is the reference? :param idx_path: if provided, use this index to generate a just-in-time genome alignment, instead of loading the file immediately. """
blocks = [] if (idx_path is not None): bound_iter = functools.partial(genome_alignment_iterator, reference_species=ref_spec) hash_func = JustInTimeGenomeAlignmentBlock.build_hash factory = IndexedFile(None, bound_iter, hash_func) factory.read_index(idx_path, ga_path, verbose=verbose) pind = None for k in factory: if verbose: if pind is None: total = len(factory) pind = ProgressIndicator(totalToDo=total, messagePrefix="completed", messageSuffix="building alignment blocks ") pind.done += 1 pind.showProgress() blocks.append(JustInTimeGenomeAlignmentBlock(factory, k)) else: for b in genome_alignment_iterator(ga_path, ref_spec, verbose=verbose): blocks.append(b) return GenomeAlignment(blocks, verbose)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def genome_alignment_iterator(fn, reference_species, index_friendly=False, verbose=False): """ build an iterator for an MAF file of genome alignment blocks. :param fn: filename or stream-like object to iterate over. :param reference_species: which species in the alignment should be treated as the reference? :param index_friendly: if True, buffering is disabled to support using the iterator to build an index. :return an iterator that yields GenomeAlignment objects """
kw_args = {"reference_species": reference_species} for e in maf.maf_iterator(fn, index_friendly=index_friendly, yield_class=GenomeAlignmentBlock, yield_kw_args=kw_args, verbose=verbose): yield e
<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_index(maf_strm, ref_spec): """Build an index for a MAF genome alig file and return StringIO of it."""
idx_strm = StringIO.StringIO() bound_iter = functools.partial(genome_alignment_iterator, reference_species=ref_spec) hash_func = JustInTimeGenomeAlignmentBlock.build_hash idx = IndexedFile(maf_strm, bound_iter, hash_func) idx.write_index(idx_strm) idx_strm.seek(0) # seek to the start return idx_strm
<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, addr, raw_addr, name=None, rssi=None): """Updates the collection of results with a newly received scan response. Args: addr (str): Device hardware address in xx:xx:xx:xx:xx:xx format. raw_addr (bytearray): Device hardware address as raw bytes. name (str): Device name (if available) as ASCII text. May be None. rssi (float): Latest RSSI from the scan result for the device. May be 0. Returns: True if an existing device was updated, False if a new entry was created. """
if addr in self._devices: # logger.debug('UPDATE scan result: {} / {}'.format(addr, name)) self._devices[addr].update(name, rssi) return False else: self._devices[addr] = ScanResult(addr, raw_addr, name, rssi) logger.debug('Scan result: {} / {}'.format(addr, name)) 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 set_calibration(self, enabled, imus): """Set calibration state for attached IMUs. Args: enabled (bool): True to apply calibration to IMU data (if available). False to output uncalibrated data. imus (list): indicates which IMUs the calibration state should be set on. Empty list or [0, 1, 2, 3, 4] will apply to all IMUs, [0, 1] only to first 2 IMUs, etc. """
if len(imus) == 0: imus = list(range(MAX_IMUS)) for i in imus: if i < 0 or i >= MAX_IMUS: logger.warn('Invalid IMU index {} in set_calibration'.format(i)) continue self.imus[i]._use_calibration = enabled
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def disconnect(self): """Disconnect the dongle from this SK8. Simply closes the active BLE connection to the device represented by the current instance. Returns: bool. True if connection was closed, False if not (e.g. if already closed). """
result = False logger.debug('SK8.disconnect({})'.format(self.conn_handle)) if self.conn_handle >= 0: logger.debug('Calling dongle disconnect') result = self.dongle._disconnect(self.conn_handle) self.conn_handle = -1 self.packets = 0 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 set_extana_callback(self, callback, data=None): """Register a callback for incoming data packets from the SK8-ExtAna board. This method allows you to pass in a callable which will be called on receipt of each packet sent from the SK8-ExtAna board. Set to `None` to disable it again. Args: callback: a callable with the following signature: (ana1, ana2, temp, seq, timestamp, data) where: ana1, ana2 = current values of the two analogue inputs temp = temperature sensor reading seq = packet sequence number (int, 0-255) timestamp = value of time.time() when packet received data = value of `data` parameter passed to this method data: an optional arbitrary object that will be passed as a parameter to the callback """
self.extana_callback = callback self.extana_callback_data = 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 enable_extana_streaming(self, include_imu=False, enabled_sensors=SENSOR_ALL): """Configures and enables sensor data streaming from the SK8-ExtAna device. By default this will cause the SK8 to only stream data from the analog sensors on the SK8-ExtAna, but if `include_imu` is set to True, it will also send data from the internal IMU in the SK8. NOTE: only one streaming mode can be active at any time, so e.g. if you want to stream IMU data normally, you must disable SK8-ExtAna streaming first. Args: include_imu (bool): If False, only SK8-ExtAna packets will be streamed. If True, the device will also stream data from the SK8's internal IMU. enabled_sensors (int): If `include_imu` is True, this can be used to select which IMU sensors will be active. Returns: bool. True if successful, False if an error occurred. """
if not self.dongle._enable_extana_streaming(self, include_imu, enabled_sensors): logger.warn('Failed to enable SK8-ExtAna streaming!') return False # have to add IMU #0 to enabled_imus if include_imu is True if include_imu: self.enabled_imus = [0] 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 set_extana_led(self, r, g, b, check_state=True): """Update the colour of the RGB LED on the SK8-ExtAna board. Args: r (int): red channel, 0-255 g (int): green channel, 0-255 b (int): blue channel, 0-255 check_state (bool): if True (default) and the locally cached LED state matches the given (r, g, b) triplet, pysk8 will NOT send any LED update command to the SK8. If you want to force the command to be sent even if the local state matches the new colour, set this to False. Returns: True on success, False if an error occurred. """
r, g, b = map(int, [r, g, b]) if min([r, g, b]) < LED_MIN or max([r, g, b]) > LED_MAX: logger.warn('RGB channel values must be {}-{}'.format(LED_MIN, LED_MAX)) return False if check_state and (r, g, b) == self.led_state: return True # internally range is 0-3000 ir, ig, ib = map(lambda x: int(x * (INT_LED_MAX / LED_MAX)), [r, g, b]) val = struct.pack('<HHH', ir, ig, ib) extana_led = self.get_characteristic_handle_from_uuid(UUID_EXTANA_LED) if extana_led is None: logger.warn('Failed to find handle for ExtAna LED') return None if not self.dongle._write_attribute(self.conn_handle, extana_led, val): return False # update cached LED state if successful self.led_state = (r, g, b) 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 set_imu_callback(self, callback, data=None): """Register a callback for incoming IMU data packets. This method allows you to pass in a callbable which will be called on receipt of each IMU data packet sent by this SK8 device. Set to `None` to disable it again. Args: callback: a callable with the following signature: (acc, gyro, mag, imu_index, seq, timestamp, data) where: acc, gyro, mag = sensor data ([x,y,z] in each case) imu_index = originating IMU number (int, 0-4) seq = packet sequence number (int, 0-255) timestamp = value of time.time() when packet received data = value of `data` parameter passed to this method data: an optional arbitrary object that will be passed as a parameter to the callback """
self.imu_callback = callback self.imu_callback_data = 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 enable_imu_streaming(self, enabled_imus, enabled_sensors=SENSOR_ALL): """Configures and enables IMU sensor data streaming. NOTE: only one streaming mode can be active at any time, so e.g. if you want to stream IMU data, you must disable SK8-ExtAna streaming first. Args: enabled_imus (list): a list of distinct ints in the range `0`-`4` inclusive identifying the IMU. `0` is the SK8 itself, and `1`-`4` are the subsidiary IMUs on the USB chain, starting from the end closest to the SK8. enabled_sensors (int): to save battery, you can choose to enable some or all of the sensors on each enabled IMU. By default, the accelerometer, magnetometer, and gyroscope are all enabled. Pass a bitwise OR of one or more of :const:`SENSOR_ACC`, :const:`SENSOR_MAG`, and :const:`SENSOR_GYRO` to gain finer control over the active sensors. Returns: bool. True if successful, False if an error occurred. """
imus_enabled = 0 for imu in enabled_imus: imus_enabled |= (1 << imu) if enabled_sensors == 0: logger.warn('Not enabling IMUs, no sensors enabled!') return False if not self.dongle._enable_imu_streaming(self, imus_enabled, enabled_sensors): logger.warn('Failed to enable IMU streaming (imus_enabled={}, enabled_sensors={}'.format(imus_enabled, enabled_sensors)) return False self.enabled_imus = enabled_imus self.enabled_sensors = enabled_sensors 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 disable_imu_streaming(self): """Disable IMU streaming for this device. Returns: True on success, False if an error occurred. """
self.enabled_imus = [] # reset IMU data state for imu in self.imus: imu.reset() return self.dongle._disable_imu_streaming(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 get_battery_level(self): """Reads the battery level descriptor on the device. Returns: int. If successful this will be a positive value representing the current battery level as a percentage. On error, -1 is returned. """
battery_level = self.get_characteristic_handle_from_uuid(UUID_BATTERY_LEVEL) if battery_level is None: logger.warn('Failed to find handle for battery level') return None level = self.dongle._read_attribute(self.conn_handle, battery_level) if level is None: return -1 return ord(level)
<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_device_name(self, cached=True): """Returns the SK8 device BLE name. Args: cached (bool): if True, returns the locally cached copy of the name. If this is set to False, or the name is not cached, it will read from the device instead. Returns: str. The current device name. May be `None` if an error occurs. """
if cached and self.name is not None: return self.name device_name = self.get_characteristic_handle_from_uuid(UUID_DEVICE_NAME) if device_name is None: logger.warn('Failed to find handle for device name') return None self.name = self.dongle._read_attribute(self.conn_handle, device_name) return self.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 set_device_name(self, new_name): """Sets a new BLE device name for this SK8. Args: new_name (str): the new device name as an ASCII string, max 20 characters. Returns: True if the name was updated successfully, False otherwise. """
device_name = self.get_characteristic_handle_from_uuid(UUID_DEVICE_NAME) if device_name is None: logger.warn('Failed to find handle for device name') return False if len(new_name) > MAX_DEVICE_NAME_LEN: logger.error('Device name exceeds maximum length ({} > {})'.format(len(new_name), MAX_DEVICE_NAME_LEN)) return False if self.dongle._write_attribute(self.conn_handle, device_name, new_name.encode('ascii')): self.name = new_name 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 get_firmware_version(self, cached=True): """Returns the SK8 device firmware version. Args: cached (bool): if True, returns the locally cached copy of the firmware version. If this is set to False, or the version is not cached, it will read from the device instead. Returns: str. The current firmware version string. May be `None` if an error occurs. """
if cached and self.firmware_version != 'unknown': return self.firmware_version firmware_version = self.get_characteristic_handle_from_uuid(UUID_FIRMWARE_REVISION) if firmware_version is None: logger.warn('Failed to find handle for firmware version') return None self.firmware_version = self.dongle._read_attribute(self.conn_handle, firmware_version) return self.firmware_version
<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_service(self, uuid): """Lookup information about a given GATT service. Args: uuid (str): a string containing the hex-encoded service UUID Returns: None if an error occurs, otherwise a :class:`Service` object. """
if uuid in self.services: return self.services[uuid] if pp_hex(uuid) in self.services: return self.services[pp_hex(uuid)] 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 get_polling_override(self): """Get the current polling override value in milliseconds. See :meth:`set_polling_override` for more information. Returns: None on error, otherwise the current override period in milliseconds (0 = disabled). """
polling_override = self.get_characteristic_handle_from_uuid(UUID_POLLING_OVERRIDE) if polling_override is None: logger.warn('Failed to find handle for polling override') return None override_ms = self.dongle._read_attribute(self.conn_handle, polling_override, True) return None if override_ms is None else ord(override_ms)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_polling_override(self, override): """Set the sensor polling timer override value in milliseconds. Due to the time it takes to poll all the sensors on up to 5 IMUs, it's not possible for the SK8 firmware to define a single fixed rate for reading new samples without it being artificially low for most configurations. Instead the firmware tries to define a sensible default value for each combination of IMUs and sensors that can be enabled (any combination of 1-5 IMUs and 1-3 sensors on each IMU). In most cases this should work well, but for example if you have multiple SK8s connected through the same dongle and have multiple IMUs enabled on each, you may find packets start to be dropped quite frequently. To mitigate this, you can adjust the period of the timer used by the firmware to poll for new sensor data (and send data packets to the host device). The value should be in integer milliseconds, and have a minimum value of 20. Values below 20 will be treated as a request to disable the override and return to the default polling period. The method can be called before or after streaming is activated, and will take effect immediately. NOTE1: the value is stored in RAM and will not persist across reboots, although it should persist for multiple connections. NOTE2: once set, the override applies to ALL sensor configurations, so for example if you set it while using 5 IMUs on 2 SK8s, then switch to using 1 IMU on each SK8, you will probably want to disable it again as the latter configuration should work fine with the default period. Args: override (int): polling timer override period in milliseconds. Values below 20 are treated as 0, and have the effect of disabling the override in favour of the default periods. Returns: True on success, False on error. """
polling_override = self.get_characteristic_handle_from_uuid(UUID_POLLING_OVERRIDE) if polling_override is None: logger.warn('Failed to find handle for device name') return False if self.dongle._write_attribute(self.conn_handle, polling_override, struct.pack('B', override)): 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 init(self, address, hard_reset=False): """Open the serial connection to a dongle at the supplied address. Args: address (str): the serial port address of the BLED112 dongle, e.g. 'COM5' hard_reset (bool): not currently used Returns: True if a connection with the dongle was established, False otherwise. """
self.address = address if hard_reset: # TODO (needs more work to be usable) # if not Dongle._hard_reset(address): # return False # time.sleep(2.0) pass # TODO timeout not working if opened on valid, non Bluegiga port for i in range(Dongle.PORT_RETRIES): try: logger.debug('Setting up BGAPI, attempt {}/{}'.format(i + 1, Dongle.PORT_RETRIES)) self.api = BlueGigaAPI(port=self.address, callbacks=self, baud=Dongle.BAUDRATE, timeout=DEF_TIMEOUT) self.api.start_daemon() break except serial.serialutil.SerialException as e: logger.debug('Failed to init BlueGigaAPI: {}, attempt {}/{}'.format(e, i + 1, Dongle.PORT_RETRIES)) time.sleep(0.1) if self.api is None: return False time.sleep(0.5) # TODO self.get_supported_connections() logger.info('Dongle supports {} connections'.format(self.supported_connections)) if self.supported_connections == -1: logger.error('Failed to retrieve number of supported connections from the dongle! (try reinserting it)') return False self.conn_state = {x: self._STATE_IDLE for x in range(self.supported_connections)} self.reset() self._cbthread = threading.Thread(target=self._cbthreadfunc) self._cbthread.setDaemon(True) self._cbthread_q = Queue() self._cbthread.start() 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 find_dongle_port(): """Convenience method which attempts to find the port where a BLED112 dongle is connected. This relies on the `pyserial.tools.list_ports.grep method <https://pyserial.readthedocs.io/en/latest/tools.html#serial.tools.list_ports.grep>`_, and simply searches for a port containing the string "Bluegiga" in its description. (This probably only works on Windows at the moment (TODO)). Returns: A string containing the detected port address, or `None` if no matching port was found. """
logger.debug('Attempting to find Bluegiga dongle...') # TODO this will probably only work on Windows at the moment ports = list(serial.tools.list_ports.grep('Bluegiga')) if len(ports) == 0: logger.debug('No Bluegiga-named serial ports discovered') return None # just return the first port even if multiple dongles logger.debug('Found "Bluegiga" serial port at {}'.format(ports[0].device)) return ports[0].device
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reset(self): """Attempts to reset the dongle to a known state. When called, this method will reset the internal state of the object, and disconnect any active connections. """
logger.debug('resetting dongle state') self._clear() if self.api is not None: self._set_state(Dongle._STATE_RESET) self.api.ble_cmd_gap_set_mode(gap_discoverable_mode['gap_non_discoverable'], gap_connectable_mode['gap_non_connectable']) self._wait_for_state(self._STATE_RESET) for i in range(self.supported_connections): self._set_conn_state(i, self._STATE_DISCONNECTING) self.api.ble_cmd_connection_disconnect(i) self._wait_for_conn_state(i, self._STATE_DISCONNECTING) logger.debug('reset completed')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_reconnect_parameters(self, interval, attempts, restore_state=True): """Sets the behaviour of the automatic reconnect feature. When a connected SK8 is disconnected unexpectedly (in other words not by a user-triggered action), an automatic attempt to reconnect to the device can be made. If successful this will typically resume the connection with an interruption of only a few seconds. This method allows the application to configure some aspects of the automatic reconnect functionality. Args: interval (float): time in seconds between successive attempts to reconnect. Also applies to the delay between the initial disconnection and the first attempt to reconnect. attempts (int): the number of attempts to make to recreate the connection. This can be set to zero in order to disable the reconnection feature. restore_state (bool): if True, the streaming state of the device will also be restored if possible. For example, the IMU configuration will be re-applied after the reconnection attempt succeeds, to return the SK8 to the same state it was in before the disconnection occurred. Returns: None """
self._reconnect_attempts = max(0, attempts) self._reconnect_interval = max(0, interval) self._reconnect_restore_state = restore_state
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def scan_and_connect(self, devnames, timeout=DEF_TIMEOUT, calibration=True): """Scan for and then connect to a set of one or more SK8s. This method is intended to be a simple way to combine the steps of running a BLE scan, checking the results and connecting to one or more devices. When called, a scan is started for a period equal to `timeout`, and a list of devices is collected. If at any point during the scan all of the supplied devices are detected, the scan will be ended immediately. After the scan has completed, the method will only proceed to creating connections if the scan results contain all the specified devices. Args: devnames (list): a list of device names (1 or more) timeout (float): a time period in seconds to run the scanning process (will be terminated early if all devices in `devnames` are discovered) Returns: Returns the same results as :meth:`connect`. """
responses = self.scan_devices(devnames, timeout) for dev in devnames: if dev not in responses: logger.error('Failed to find device {} during scan'.format(dev)) return (False, []) return self.connect([responses.get_device(dev) for dev in devnames], calibration)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def begin_scan(self, callback=None, interval=DEF_SCAN_INTERVAL, window=DEF_SCAN_WINDOW): """Begins a BLE scan and returns immediately. Using this method you can begin a BLE scan and leave the dongle in scanning mode in the background. It will remain in scanning mode until you call the :meth:`end_scan` method or the :meth:`reset` method. Args: callback (callbable): a callback that will be called for each new device discovered by the scanning process. Will be passed a single argument, a :class:`ScanResult` object. May be None if not needed. interval (int): BLE scan interval, in units of 625us window (int): BLE scan window, in units of 625us Returns: True on success, False otherwise. """
# TODO validate params and current state logger.debug('configuring scan parameters') self.api.ble_cmd_gap_set_scan_parameters(interval, window, 1) self._set_state(self._STATE_CONFIGURE_SCAN) self.api.ble_cmd_gap_discover(1) # any discoverable devices self._wait_for_state(self._STATE_CONFIGURE_SCAN) # TODO check state logger.debug('starting async scan for devices') self.scan_targets = None self.scan_callback = callback self._set_state(self._STATE_SCANNING) 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 connect(self, devicelist, calibration=True): """Establish a connection to one or more SK8 devices. Given a list of 1 or more :class:`ScanResult` objects, this method will attempt to create a connection to each SK8 in sequence. It will return when all connections have been attempted, although they may not all have succeeded. In addition, the dongle has a limit on simultaneous connections, which you can retrieve by calling :meth:`get_supported_connections`. If the number of supplied device names exceeds this value then the method will abort immediately. Args: devicelist (list): a list of :class:`ScanResult` instances, one for each SK8 you wish to create a connection to. calibration (bool): True if calibration data should be loaded post-connection, for each device (if available). Returns: tuple (`result`, `devices`), where `result` is a bool indicating if connections were successfully made to all given devices. If True, `devices` will contain a list of :class:`SK8` instances representing the connected SK8 devices. If False, `devices` will contain a smaller number of :class:`SK8` instances depending on the number of connections that succeeded (possibly 0). """
if not isinstance(devicelist, list): devicelist = [devicelist] logger.debug('Connecting to {} devices'.format(len(devicelist))) if len(devicelist) > self.supported_connections: logging.error('Dongle firmware supports max {} connections, {} device connections requested!'.format(self.supported_connections, len(devicelist))) return (False, []) # TODO check number of active connections and fail if exceeds max connected_devices = [] all_connected = True for dev in devicelist: logger.info('Connecting to {} (name={})...'.format(dev.addr, dev.name)) self._set_state(self._STATE_CONNECTING) self.api.ble_cmd_gap_connect_direct(dev.raw_addr, 0, 6, 14, 100, 50) self._wait_for_state(self._STATE_CONNECTING, 5) if self.state != self._STATE_CONNECTED: logger.warn('Connection failed!') # send end procedure to cancel connection attempt self._set_state(self._STATE_GAP_END) self.api.ble_cmd_gap_end_procedure() self._wait_for_state(self._STATE_GAP_END) all_connected = False continue conn_handle = self.conn_handles[-1] logger.info('Connection OK, handle is 0x{:02X}'.format(conn_handle)) sk8 = SK8(self, conn_handle, dev, calibration) self._add_device(sk8) connected_devices.append(sk8) sk8._discover_services() time.sleep(0.1) # TODO return (all_connected, connected_devices)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def connect_direct(self, device, calibration=True): """Establish a connection to a single SK8. Args: device: either a :class:`ScanResult` or a plain hardware address string in xx:xx:xx:xx:xx:xx format. calibration (bool): True to attempt to load calibration data for this device after connection, False otherwise. See :meth:`SK8.load_calibration`. Returns: tuple (`result`, `device`), where `result` is a bool indicating if a connection was created successfully. If `result` is True, `device` will be set to a new :class:`SK8` instance. Otherwise it will be None. """
# convert string address into a ScanResult if needed if not isinstance(device, ScanResult): if isinstance(device, str): device = ScanResult(device, fmt_addr_raw(device)) elif isinstance(device, unicode): device = device.encode('ascii') device = ScanResult(device, fmt_addr_raw(device)) else: logger.warn('Expected ScanResult, found type {} instead!'.format(type(device))) return (False, None) logger.debug('Connecting directly to device address'.format(device.addr)) # TODO check number of active connections and fail if exceeds max self._set_state(self._STATE_CONNECTING) # TODO parameters here = ??? self.api.ble_cmd_gap_connect_direct(device.raw_addr, 0, 6, 14, 100, 50) self._wait_for_state(self._STATE_CONNECTING, 5) if self.state != self._STATE_CONNECTED: logger.warn('Connection failed!') # send end procedure to cancel connection attempt self._set_state(self._STATE_GAP_END) self.api.ble_cmd_gap_end_procedure() self._wait_for_state(self._STATE_GAP_END) return (False, None) conn_handle = self.conn_handles[-1] logger.info('Connection OK, handle is 0x{:02X}'.format(conn_handle)) sk8 = SK8(self, conn_handle, device, calibration) self._add_device(sk8) sk8._discover_services() return (True, sk8)
<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_supported_connections(self): """Returns the number of supported simultaneous BLE connections. The BLED112 is capable of supporting up to 8 simultaneous BLE connections. However, the default firmware image has a limit of just 3 devices, which is a lot easier to run up against. This method retrieves the current value of this setting. Returns: int. The number of supported simultaneous connections, or -1 on error """
if self.supported_connections != -1: return self.supported_connections if self.api is None: return -1 self._set_state(self._STATE_DONGLE_COMMAND) self.api.ble_cmd_system_get_connections() self._wait_for_state(self._STATE_DONGLE_COMMAND) return self.supported_connections
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def httpapi_request(client, **params) -> 'Response': """Send a request to AniDB HTTP API. https://wiki.anidb.net/w/HTTP_API_Definition """
return requests.get( _HTTPAPI, params={ 'client': client.name, 'clientver': client.version, 'protover': 1, **params })
<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_xml(text) -> ET.ElementTree: """Unpack an XML string from AniDB API."""
etree: ET.ElementTree = ET.parse(io.StringIO(text)) _check_for_errors(etree) return etree
<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_errors(etree: ET.ElementTree): """Check AniDB response XML tree for errors."""
if etree.getroot().tag == 'error': raise APIError(etree.getroot().text)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extract_fields(lines, delim, searches, match_lineno=1, **kwargs): """Return generator of fields matching `searches`. Parameters lines : iterable Provides line number (1-based) and line (str) delim : str Delimiter to split line by to produce fields searches : iterable Returns search (str) to match against line fields. match_lineno : int Line number of line to split and search fields Remaining keyword arguments are passed to `match_fields`. """
keep_idx = [] for lineno, line in lines: if lineno < match_lineno or delim not in line: if lineno == match_lineno: raise WcutError('Delimter not found in line {}'.format( match_lineno)) yield [line] continue fields = line.split(delim) if lineno == match_lineno: keep_idx = list(match_fields(fields, searches, **kwargs)) keep_fields = [fields[i] for i in keep_idx] if keep_fields: yield keep_fields
<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_fields(fields, searches, ignore_case=False, wholename=False, complement=False): """Return fields that match searches. Parameters fields : iterable searches : iterable ignore_case, wholename, complement : boolean """
if ignore_case: fields = [f.lower() for f in fields] searches = [s.lower() for s in searches] if wholename: match_found = _complete_match else: match_found = _partial_match fields = [(i, field) for i, field in enumerate(fields)] matched = [] for search, (idx, field) in itertools.product(searches, fields): if not search: ## don't return all fields for '' continue if match_found(search, field) and idx not in matched: matched.append(idx) if complement: matched = [idx for idx in list(zip(*fields))[0] if idx not in matched] return matched
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def connect(cls, dbname): """Create a new connection to the SQLite3 database. :param dbname: The database name :type dbname: str """
test_times_schema = """ CREATE TABLE IF NOT EXISTS test_times ( file text, module text, class text, func text, elapsed float ) """ setup_times_schema = """ CREATE TABLE IF NOT EXISTS setup_times ( file text, module text, class text, func text, elapsed float ) """ schemas = [test_times_schema, setup_times_schema] db_file = '{}.db'.format(dbname) cls.connection = sqlite3.connect(db_file) for s in schemas: cls.connection.execute(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 get(cls, dbname="perfdump"): """Returns the singleton connection to the SQLite3 database. :param dbname: The database name :type dbname: str """
try: return cls.connection except: cls.connect(dbname) return cls.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 before_scenario(context, scenario): """Prepare a fresh environment for each scenario."""
# Prepare a new temporary directory. context.directory = testfixtures.TempDirectory(create=True) context.old_cwd = os.getcwd() context.new_cwd = context.directory.path # Move into our new working directory. os.chdir(context.new_cwd)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def after_scenario(context, scenario): """Leave the environment fresh after each scenario."""
# Move back into the original working directory. os.chdir(context.old_cwd) # Delete all content generated by the test. context.directory.cleanup()
<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(self, name): """Get a parameter object by name. :param name: Name of the parameter object. :type name: str :return: The parameter. :rtype: Parameter """
parameter = next((p for p in self.parameters if p.name == name), None) if parameter is None: raise LookupError("Cannot find parameter '" + name + "'.") return parameter
<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_parameter(self, name, value, meta=None): """Add a parameter to the parameter list. :param name: New parameter's name. :type name: str :param value: New parameter's value. :type value: float :param meta: New parameter's meta property. :type meta: dict """
parameter = Parameter(name, value) if meta: parameter.meta = meta self.parameters.append(parameter)
<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_file(self, path): """Load a YAML file with parameter data and other metadata. :param path: Path to YAML file. :type path: str The data in the YAML file is used to set the properties for the instance. The YAML file must contain a ``parameters`` key. It may optionally include any keys defined in :attr:`.property_keys`. .. code-block:: yaml # data.yml --- name: Shield frequencies parameters: - name: a value: 24.50 - name: β value: 42.10 meta: phase_inverted: true .. code-block:: python parameters = Parameters('data.yml') parameters.name #=> 'Shield frequencies' parameters.get_value('a') #=> 24.50 parameters.get_meta('β')['phase_inverted'] #=> true """
data = yaml.load(open(path, 'r')) for key in self.property_keys: if key in data: setattr(self, key, data[key]) self.parameters = self.parameter_list(data['parameters'])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parameter_list(data): """Create a list of parameter objects from a dict. :param data: Dictionary to convert to parameter list. :type data: dict :return: Parameter list. :rtype: dict """
items = [] for item in data: param = Parameter(item['name'], item['value']) if 'meta' in item: param.meta = item['meta'] items.append(param) return items
<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_blueprint(self, blueprint, **options): """ Specify a blueprint to be registered with the application. Additional options will be passed to :meth:`~Flask.register_blueprint` when the application is created. .. code-block:: python factory = Factory() factory.add_blueprint('myapp.views:blueprint', url_prefix='/foo') :param blueprint: import path to blueprint object :type blueprint: str :param options: options to pass to the blueprint :type options: dict """
instance = werkzeug.utils.import_string(blueprint) self._blueprints.append((instance, options))
<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_extension(self, extension): """ Specify a broadway extension to initialise .. code-block:: python factory = Factory() factory.add_extension('broadway_sqlalchemy') :param extension: import path to extension :type extension: str """
instance = werkzeug.utils.import_string(extension) if hasattr(instance, 'register'): instance.register(self) self._extensions.append(instance)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def newkeys(nbits=1024): """ Create a new pair of public and private key pair to use. """
pubkey, privkey = rsa.newkeys(nbits, poolsize=1) return pubkey, privkey
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def encrypt(self, binary, use_sign=True): """ Encrypt binary data. **中文文档** - 发送消息时只需要对方的pubkey - 如需使用签名, 则双方都需要持有对方的pubkey """
token = rsa.encrypt(binary, self.his_pubkey) # encrypt it if use_sign: self.sign = rsa.sign(binary, self.my_privkey, "SHA-1") # sign it return token
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decrypt(self, token, signature=None): """ Decrypt binary data. **中文文档** - 接收消息时只需要自己的privkey - 如需使用签名, 则双方都需要持有对方的pubkey """
binary = rsa.decrypt(token, self.my_privkey) if signature: rsa.verify(binary, signature, self.his_pubkey) return binary
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def encrypt_file(self, path, output_path=None, overwrite=False, enable_verbose=True): """ Encrypt a file using rsa. RSA for big file encryption is very slow. For big file, I recommend to use symmetric encryption and use RSA to encrypt the password. """
path, output_path = files.process_dst_overwrite_args( src=path, dst=output_path, overwrite=overwrite, src_to_dst_func=files.get_encrpyted_path, ) with open(path, "rb") as infile, open(output_path, "wb") as outfile: encrypt_bigfile(infile, outfile, self.his_pubkey)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decrypt_file(self, path, output_path=None, overwrite=False, enable_verbose=True): """ Decrypt a file using rsa. """
path, output_path = files.process_dst_overwrite_args( src=path, dst=output_path, overwrite=overwrite, src_to_dst_func=files.get_decrpyted_path, ) with open(path, "rb") as infile, open(output_path, "wb") as outfile: decrypt_bigfile(infile, outfile, self.my_privkey)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def print_subcommands(self): """Print the subcommand part of the help."""
lines = ["Call"] lines.append('-'*len(lines[-1])) lines.append('') lines.append("> jhubctl <subcommand> <resource-type> <resource-name>") lines.append('') lines.append("Subcommands") lines.append('-'*len(lines[-1])) lines.append('') for name, subcommand in self.subcommands.items(): lines.append(name) lines.append(indent(subcommand[1])) lines.append('') print(os.linesep.join(lines))