repo
stringlengths
7
54
path
stringlengths
4
192
url
stringlengths
87
284
code
stringlengths
78
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
flowersteam/explauto
explauto/sensorimotor_model/inverse/sciopt.py
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/sciopt.py#L17-L40
def infer_x(self, y): """Infer probable x from input y @param y the desired output for infered x. @return a list of probable x """ OptimizedInverseModel.infer_x(self, y) if self.fmodel.size() == 0: return self._random_x() x_guesses = [self._guess_x_simple(y)[0]] result = [] for i, xg in enumerate(x_guesses): res = scipy.optimize.minimize(self._error, xg, args = (), method = self.algo, bounds = self.constraints, options = self.conf ) d = self._error(res.x) result.append((d, i, res.x)) return [self._enforce_bounds(xi) for fi, i, xi in sorted(result)]
[ "def", "infer_x", "(", "self", ",", "y", ")", ":", "OptimizedInverseModel", ".", "infer_x", "(", "self", ",", "y", ")", "if", "self", ".", "fmodel", ".", "size", "(", ")", "==", "0", ":", "return", "self", ".", "_random_x", "(", ")", "x_guesses", "...
Infer probable x from input y @param y the desired output for infered x. @return a list of probable x
[ "Infer", "probable", "x", "from", "input", "y" ]
python
train
Trebek/pydealer
pydealer/stack.py
https://github.com/Trebek/pydealer/blob/2ac583dd8c55715658c740b614387775f4dda333/pydealer/stack.py#L344-L386
def find(self, term, limit=0, sort=False, ranks=None): """ Searches the stack for cards with a value, suit, name, or abbreviation matching the given argument, 'term'. :arg str term: The search term. Can be a card full name, value, suit, or abbreviation. :arg int limit: The number of items to retrieve for each term. ``0`` equals no limit. :arg bool sort: Whether or not to sort the results. :arg dict ranks: The rank dict to reference for sorting. If ``None``, it will default to ``DEFAULT_RANKS``. :returns: A list of stack indices for the cards matching the given terms, if found. """ ranks = ranks or self.ranks found_indices = [] count = 0 if not limit: for i, card in enumerate(self.cards): if check_term(card, term): found_indices.append(i) else: for i, card in enumerate(self.cards): if count < limit: if check_term(card, term): found_indices.append(i) count += 1 else: break if sort: found_indices = sort_card_indices(self, found_indices, ranks) return found_indices
[ "def", "find", "(", "self", ",", "term", ",", "limit", "=", "0", ",", "sort", "=", "False", ",", "ranks", "=", "None", ")", ":", "ranks", "=", "ranks", "or", "self", ".", "ranks", "found_indices", "=", "[", "]", "count", "=", "0", "if", "not", ...
Searches the stack for cards with a value, suit, name, or abbreviation matching the given argument, 'term'. :arg str term: The search term. Can be a card full name, value, suit, or abbreviation. :arg int limit: The number of items to retrieve for each term. ``0`` equals no limit. :arg bool sort: Whether or not to sort the results. :arg dict ranks: The rank dict to reference for sorting. If ``None``, it will default to ``DEFAULT_RANKS``. :returns: A list of stack indices for the cards matching the given terms, if found.
[ "Searches", "the", "stack", "for", "cards", "with", "a", "value", "suit", "name", "or", "abbreviation", "matching", "the", "given", "argument", "term", "." ]
python
train
Erotemic/utool
utool/util_import.py
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_import.py#L272-L317
def check_module_installed(modname): """ Check if a python module is installed without attempting to import it. Note, that if ``modname`` indicates a child module, the parent module is always loaded. Args: modname (str): module name Returns: bool: found References: http://stackoverflow.com/questions/14050281/module-exists-without-importing CommandLine: python -m utool.util_import check_module_installed --show --verbimp --modname=this python -m utool.util_import check_module_installed --show --verbimp --modname=guitool python -m utool.util_import check_module_installed --show --verbimp --modname=guitool.__PYQT__ python -m utool.util_import check_module_installed --show --verbimp --modname=ibeis.scripts.iccv Example: >>> # ENABLE_DOCTEST >>> from utool.util_import import * # NOQA >>> import utool as ut >>> modname = ut.get_argval('--modname', default='this') >>> is_installed = check_module_installed(modname) >>> is_imported = modname in sys.modules >>> print('module(%r).is_installed = %r' % (modname, is_installed)) >>> print('module(%r).is_imported = %r' % (modname, is_imported)) >>> assert 'this' not in sys.modules, 'module(this) should not have ever been imported' """ import pkgutil if '.' in modname: # Prevent explicit import if possible parts = modname.split('.') base = parts[0] submods = parts[1:] loader = pkgutil.find_loader(base) if loader is not None: # TODO: check to see if path to the submod exists submods return True loader = pkgutil.find_loader(modname) is_installed = loader is not None return is_installed
[ "def", "check_module_installed", "(", "modname", ")", ":", "import", "pkgutil", "if", "'.'", "in", "modname", ":", "# Prevent explicit import if possible", "parts", "=", "modname", ".", "split", "(", "'.'", ")", "base", "=", "parts", "[", "0", "]", "submods", ...
Check if a python module is installed without attempting to import it. Note, that if ``modname`` indicates a child module, the parent module is always loaded. Args: modname (str): module name Returns: bool: found References: http://stackoverflow.com/questions/14050281/module-exists-without-importing CommandLine: python -m utool.util_import check_module_installed --show --verbimp --modname=this python -m utool.util_import check_module_installed --show --verbimp --modname=guitool python -m utool.util_import check_module_installed --show --verbimp --modname=guitool.__PYQT__ python -m utool.util_import check_module_installed --show --verbimp --modname=ibeis.scripts.iccv Example: >>> # ENABLE_DOCTEST >>> from utool.util_import import * # NOQA >>> import utool as ut >>> modname = ut.get_argval('--modname', default='this') >>> is_installed = check_module_installed(modname) >>> is_imported = modname in sys.modules >>> print('module(%r).is_installed = %r' % (modname, is_installed)) >>> print('module(%r).is_imported = %r' % (modname, is_imported)) >>> assert 'this' not in sys.modules, 'module(this) should not have ever been imported'
[ "Check", "if", "a", "python", "module", "is", "installed", "without", "attempting", "to", "import", "it", ".", "Note", "that", "if", "modname", "indicates", "a", "child", "module", "the", "parent", "module", "is", "always", "loaded", "." ]
python
train
clld/cdstarcat
src/cdstarcat/catalog.py
https://github.com/clld/cdstarcat/blob/41f33f59cdde5e30835d2f3accf2d1fbe5332cab/src/cdstarcat/catalog.py#L175-L188
def add(self, obj, metadata=None, update=False): """ Add an existing CDSTAR object to the catalog. :param obj: A pycdstar.resource.Object instance """ if (obj not in self) or update: self[obj.id] = Object.fromdict( obj.id, dict( metadata=obj.metadata.read() if metadata is None else metadata, bitstreams=[bs._properties for bs in obj.bitstreams])) time.sleep(0.1) return self.objects[obj.id]
[ "def", "add", "(", "self", ",", "obj", ",", "metadata", "=", "None", ",", "update", "=", "False", ")", ":", "if", "(", "obj", "not", "in", "self", ")", "or", "update", ":", "self", "[", "obj", ".", "id", "]", "=", "Object", ".", "fromdict", "("...
Add an existing CDSTAR object to the catalog. :param obj: A pycdstar.resource.Object instance
[ "Add", "an", "existing", "CDSTAR", "object", "to", "the", "catalog", "." ]
python
train
quantopian/pgcontents
pgcontents/hybridmanager.py
https://github.com/quantopian/pgcontents/blob/ed36268b7917332d16868208e1e565742a8753e1/pgcontents/hybridmanager.py#L118-L130
def path_dispatch_kwarg(mname, path_default, returns_model): """ Parameterized decorator for methods that accept path as a second argument. """ def _wrapper(self, path=path_default, **kwargs): prefix, mgr, mgr_path = _resolve_path(path, self.managers) result = getattr(mgr, mname)(path=mgr_path, **kwargs) if returns_model and prefix: return _apply_prefix(prefix, result) else: return result return _wrapper
[ "def", "path_dispatch_kwarg", "(", "mname", ",", "path_default", ",", "returns_model", ")", ":", "def", "_wrapper", "(", "self", ",", "path", "=", "path_default", ",", "*", "*", "kwargs", ")", ":", "prefix", ",", "mgr", ",", "mgr_path", "=", "_resolve_path...
Parameterized decorator for methods that accept path as a second argument.
[ "Parameterized", "decorator", "for", "methods", "that", "accept", "path", "as", "a", "second", "argument", "." ]
python
test
caffeinehit/django-oauth2-provider
provider/views.py
https://github.com/caffeinehit/django-oauth2-provider/blob/6b5bc0d3ad706d2aaa47fa476f38406cddd01236/provider/views.py#L222-L246
def error_response(self, request, error, **kwargs): """ Return an error to be displayed to the resource owner if anything goes awry. Errors can include invalid clients, authorization denials and other edge cases such as a wrong ``redirect_uri`` in the authorization request. :param request: :attr:`django.http.HttpRequest` :param error: ``dict`` The different types of errors are outlined in :rfc:`4.2.2.1` """ ctx = {} ctx.update(error) # If we got a malicious redirect_uri or client_id, remove all the # cached data and tell the resource owner. We will *not* redirect back # to the URL. if error['error'] in ['redirect_uri', 'unauthorized_client']: ctx.update(next='/') return self.render_to_response(ctx, **kwargs) ctx.update(next=self.get_redirect_url(request)) return self.render_to_response(ctx, **kwargs)
[ "def", "error_response", "(", "self", ",", "request", ",", "error", ",", "*", "*", "kwargs", ")", ":", "ctx", "=", "{", "}", "ctx", ".", "update", "(", "error", ")", "# If we got a malicious redirect_uri or client_id, remove all the", "# cached data and tell the res...
Return an error to be displayed to the resource owner if anything goes awry. Errors can include invalid clients, authorization denials and other edge cases such as a wrong ``redirect_uri`` in the authorization request. :param request: :attr:`django.http.HttpRequest` :param error: ``dict`` The different types of errors are outlined in :rfc:`4.2.2.1`
[ "Return", "an", "error", "to", "be", "displayed", "to", "the", "resource", "owner", "if", "anything", "goes", "awry", ".", "Errors", "can", "include", "invalid", "clients", "authorization", "denials", "and", "other", "edge", "cases", "such", "as", "a", "wron...
python
train
bspaans/python-mingus
mingus/containers/note.py
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/note.py#L111-L115
def change_octave(self, diff): """Change the octave of the note to the current octave + diff.""" self.octave += diff if self.octave < 0: self.octave = 0
[ "def", "change_octave", "(", "self", ",", "diff", ")", ":", "self", ".", "octave", "+=", "diff", "if", "self", ".", "octave", "<", "0", ":", "self", ".", "octave", "=", "0" ]
Change the octave of the note to the current octave + diff.
[ "Change", "the", "octave", "of", "the", "note", "to", "the", "current", "octave", "+", "diff", "." ]
python
train
inspirehep/harvesting-kit
harvestingkit/inspire_cds_package/from_cds.py
https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/inspire_cds_package/from_cds.py#L173-L189
def add_cms_link(self): """Special handling if record is a CMS NOTE.""" intnote = record_get_field_values(self.record, '690', filter_subfield_code="a", filter_subfield_value='INTNOTE') if intnote: val_088 = record_get_field_values(self.record, tag='088', filter_subfield_code="a") for val in val_088: if 'CMS' in val: url = ('http://weblib.cern.ch/abstract?CERN-CMS' + val.split('CMS', 1)[-1]) record_add_field(self.record, tag='856', ind1='4', subfields=[('u', url)])
[ "def", "add_cms_link", "(", "self", ")", ":", "intnote", "=", "record_get_field_values", "(", "self", ".", "record", ",", "'690'", ",", "filter_subfield_code", "=", "\"a\"", ",", "filter_subfield_value", "=", "'INTNOTE'", ")", "if", "intnote", ":", "val_088", ...
Special handling if record is a CMS NOTE.
[ "Special", "handling", "if", "record", "is", "a", "CMS", "NOTE", "." ]
python
valid
aarongarrett/inspyred
inspyred/benchmarks.py
https://github.com/aarongarrett/inspyred/blob/d5976ab503cc9d51c6f586cbb7bb601a38c01128/inspyred/benchmarks.py#L1016-L1033
def evaluator(self, candidates, args): """Return the fitness values for the given candidates.""" fitness = [] if self._use_ants: for candidate in candidates: total = 0 for c in candidate: total += self.weights[c.element[0]][c.element[1]] last = (candidate[-1].element[1], candidate[0].element[0]) total += self.weights[last[0]][last[1]] fitness.append(1 / total) else: for candidate in candidates: total = 0 for src, dst in zip(candidate, candidate[1:] + [candidate[0]]): total += self.weights[src][dst] fitness.append(1 / total) return fitness
[ "def", "evaluator", "(", "self", ",", "candidates", ",", "args", ")", ":", "fitness", "=", "[", "]", "if", "self", ".", "_use_ants", ":", "for", "candidate", "in", "candidates", ":", "total", "=", "0", "for", "c", "in", "candidate", ":", "total", "+=...
Return the fitness values for the given candidates.
[ "Return", "the", "fitness", "values", "for", "the", "given", "candidates", "." ]
python
train
blockstack/blockstack-core
blockstack/lib/nameset/namedb.py
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/namedb.py#L1306-L1316
def get_namespace_reveal( self, namespace_id, include_history=True ): """ Given the name of a namespace, get it if it is currently being revealed. Return the reveal record on success. Return None if it is not being revealed, or is expired. """ cur = self.db.cursor() namespace_reveal = namedb_get_namespace_reveal( cur, namespace_id, self.lastblock, include_history=include_history ) return namespace_reveal
[ "def", "get_namespace_reveal", "(", "self", ",", "namespace_id", ",", "include_history", "=", "True", ")", ":", "cur", "=", "self", ".", "db", ".", "cursor", "(", ")", "namespace_reveal", "=", "namedb_get_namespace_reveal", "(", "cur", ",", "namespace_id", ","...
Given the name of a namespace, get it if it is currently being revealed. Return the reveal record on success. Return None if it is not being revealed, or is expired.
[ "Given", "the", "name", "of", "a", "namespace", "get", "it", "if", "it", "is", "currently", "being", "revealed", "." ]
python
train
cloud9ers/gurumate
environment/lib/python2.7/site-packages/nose/suite.py
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/suite.py#L196-L232
def run(self, result): """Run tests in suite inside of suite fixtures. """ # proxy the result for myself log.debug("suite %s (%s) run called, tests: %s", id(self), self, self._tests) #import pdb #pdb.set_trace() if self.resultProxy: result, orig = self.resultProxy(result, self), result else: result, orig = result, result try: self.setUp() except KeyboardInterrupt: raise except: self.error_context = 'setup' result.addError(self, self._exc_info()) return try: for test in self._tests: if result.shouldStop: log.debug("stopping") break # each nose.case.Test will create its own result proxy # so the cases need the original result, to avoid proxy # chains test(orig) finally: self.has_run = True try: self.tearDown() except KeyboardInterrupt: raise except: self.error_context = 'teardown' result.addError(self, self._exc_info())
[ "def", "run", "(", "self", ",", "result", ")", ":", "# proxy the result for myself", "log", ".", "debug", "(", "\"suite %s (%s) run called, tests: %s\"", ",", "id", "(", "self", ")", ",", "self", ",", "self", ".", "_tests", ")", "#import pdb", "#pdb.set_trace()"...
Run tests in suite inside of suite fixtures.
[ "Run", "tests", "in", "suite", "inside", "of", "suite", "fixtures", "." ]
python
test
vburenin/xjpath
xjpath/xjpath.py
https://github.com/vburenin/xjpath/blob/98a19fd6e6d0bcdc5ecbd3651ffa8915f06d7d44/xjpath/xjpath.py#L118-L155
def split(inp_str, sep_char, maxsplit=-1, escape_char='\\'): """Separates a string on a character, taking into account escapes. :param str inp_str: string to split. :param str sep_char: separator character. :param int maxsplit: maximum number of times to split from left. :param str escape_char: escape character. :rtype: __generator[str] :return: sub-strings generator separated on the `sep_char`. """ word_chars = [] word_chars_append = word_chars.append inp_str_iter = iter(inp_str) for c in inp_str_iter: word_chars_append(c) if c == escape_char: try: next_char = next(inp_str_iter) except StopIteration: continue if next_char == sep_char: word_chars[-1] = next_char else: word_chars.append(next_char) elif c == sep_char: word_chars.pop() yield ''.join(word_chars) maxsplit -= 1 if maxsplit == 0: yield ''.join(inp_str_iter) return del word_chars[:] yield ''.join(word_chars)
[ "def", "split", "(", "inp_str", ",", "sep_char", ",", "maxsplit", "=", "-", "1", ",", "escape_char", "=", "'\\\\'", ")", ":", "word_chars", "=", "[", "]", "word_chars_append", "=", "word_chars", ".", "append", "inp_str_iter", "=", "iter", "(", "inp_str", ...
Separates a string on a character, taking into account escapes. :param str inp_str: string to split. :param str sep_char: separator character. :param int maxsplit: maximum number of times to split from left. :param str escape_char: escape character. :rtype: __generator[str] :return: sub-strings generator separated on the `sep_char`.
[ "Separates", "a", "string", "on", "a", "character", "taking", "into", "account", "escapes", "." ]
python
train
hydraplatform/hydra-base
hydra_base/lib/scenario.py
https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/scenario.py#L1062-L1074
def delete_resourcegroupitems(scenario_id, item_ids, **kwargs): """ Delete specified items in a group, in a scenario. """ user_id = int(kwargs.get('user_id')) #check the scenario exists _get_scenario(scenario_id, user_id) for item_id in item_ids: rgi = db.DBSession.query(ResourceGroupItem).\ filter(ResourceGroupItem.id==item_id).one() db.DBSession.delete(rgi) db.DBSession.flush()
[ "def", "delete_resourcegroupitems", "(", "scenario_id", ",", "item_ids", ",", "*", "*", "kwargs", ")", ":", "user_id", "=", "int", "(", "kwargs", ".", "get", "(", "'user_id'", ")", ")", "#check the scenario exists", "_get_scenario", "(", "scenario_id", ",", "u...
Delete specified items in a group, in a scenario.
[ "Delete", "specified", "items", "in", "a", "group", "in", "a", "scenario", "." ]
python
train
NetEaseGame/aircv
aircv/__init__.py
https://github.com/NetEaseGame/aircv/blob/d479e49ef98347bbbe6ac2e4aa9119cecc15c8ca/aircv/__init__.py#L174-L181
def find_sift(im_source, im_search, min_match_count=4): ''' SIFT特征点匹配 ''' res = find_all_sift(im_source, im_search, min_match_count, maxcnt=1) if not res: return None return res[0]
[ "def", "find_sift", "(", "im_source", ",", "im_search", ",", "min_match_count", "=", "4", ")", ":", "res", "=", "find_all_sift", "(", "im_source", ",", "im_search", ",", "min_match_count", ",", "maxcnt", "=", "1", ")", "if", "not", "res", ":", "return", ...
SIFT特征点匹配
[ "SIFT特征点匹配" ]
python
train
shichao-an/homura
homura.py
https://github.com/shichao-an/homura/blob/87d1b698e1196963a23fc1c615c12020daf77dcc/homura.py#L304-L311
def download(url, path=None, headers=None, session=None, show_progress=True, resume=True, auto_retry=True, max_rst_retries=5, pass_through_opts=None, cainfo=None, user_agent=None, auth=None): """Main download function""" hm = Homura(url, path, headers, session, show_progress, resume, auto_retry, max_rst_retries, pass_through_opts, cainfo, user_agent, auth) hm.start()
[ "def", "download", "(", "url", ",", "path", "=", "None", ",", "headers", "=", "None", ",", "session", "=", "None", ",", "show_progress", "=", "True", ",", "resume", "=", "True", ",", "auto_retry", "=", "True", ",", "max_rst_retries", "=", "5", ",", "...
Main download function
[ "Main", "download", "function" ]
python
train
openstack/proliantutils
proliantutils/redfish/resources/system/ethernet_interface.py
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/redfish/resources/system/ethernet_interface.py#L36-L56
def summary(self): """property to return the summary MAC addresses and state This filters the MACs whose health is OK, and in 'Enabled' State would be returned. The returned format will be {<port_id>: <mac_address>}. This is because RIBCL returns the data in format {'Port 1': 'aa:bb:cc:dd:ee:ff'} and ironic ilo drivers inspection consumes the data in this format. Note: 'Id' is referred to as "Port number". """ mac_dict = {} for eth in self.get_members(): if eth.mac_address is not None: if (eth.status is not None and eth.status.health == sys_cons.HEALTH_OK and eth.status.state == sys_cons.HEALTH_STATE_ENABLED): mac_dict.update( {'Port ' + eth.identity: eth.mac_address}) return mac_dict
[ "def", "summary", "(", "self", ")", ":", "mac_dict", "=", "{", "}", "for", "eth", "in", "self", ".", "get_members", "(", ")", ":", "if", "eth", ".", "mac_address", "is", "not", "None", ":", "if", "(", "eth", ".", "status", "is", "not", "None", "a...
property to return the summary MAC addresses and state This filters the MACs whose health is OK, and in 'Enabled' State would be returned. The returned format will be {<port_id>: <mac_address>}. This is because RIBCL returns the data in format {'Port 1': 'aa:bb:cc:dd:ee:ff'} and ironic ilo drivers inspection consumes the data in this format. Note: 'Id' is referred to as "Port number".
[ "property", "to", "return", "the", "summary", "MAC", "addresses", "and", "state" ]
python
train
fracpete/python-weka-wrapper3
python/weka/core/classes.py
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/core/classes.py#L949-L961
def next_int(self, n=None): """ Next random integer. if n is provided, then between 0 and n-1. :param n: the upper limit (minus 1) for the random integer :type n: int :return: the next random integer :rtype: int """ if n is None: return javabridge.call(self.jobject, "nextInt", "()I") else: return javabridge.call(self.jobject, "nextInt", "(I)I", n)
[ "def", "next_int", "(", "self", ",", "n", "=", "None", ")", ":", "if", "n", "is", "None", ":", "return", "javabridge", ".", "call", "(", "self", ".", "jobject", ",", "\"nextInt\"", ",", "\"()I\"", ")", "else", ":", "return", "javabridge", ".", "call"...
Next random integer. if n is provided, then between 0 and n-1. :param n: the upper limit (minus 1) for the random integer :type n: int :return: the next random integer :rtype: int
[ "Next", "random", "integer", ".", "if", "n", "is", "provided", "then", "between", "0", "and", "n", "-", "1", "." ]
python
train
xmunoz/sodapy
sodapy/__init__.py
https://github.com/xmunoz/sodapy/blob/dad2ca9560cde0acb03bdb4423260e891ca40d7b/sodapy/__init__.py#L258-L267
def update_metadata(self, dataset_identifier, update_fields, content_type="json"): ''' Update the metadata for a particular dataset. update_fields is a dictionary containing [metadata key:new value] pairs. This method performs a full replace for the key:value pairs listed in `update_fields`, and returns all of the metadata with the updates applied. ''' resource = _format_old_api_request(dataid=dataset_identifier, content_type=content_type) return self._perform_update("put", resource, update_fields)
[ "def", "update_metadata", "(", "self", ",", "dataset_identifier", ",", "update_fields", ",", "content_type", "=", "\"json\"", ")", ":", "resource", "=", "_format_old_api_request", "(", "dataid", "=", "dataset_identifier", ",", "content_type", "=", "content_type", ")...
Update the metadata for a particular dataset. update_fields is a dictionary containing [metadata key:new value] pairs. This method performs a full replace for the key:value pairs listed in `update_fields`, and returns all of the metadata with the updates applied.
[ "Update", "the", "metadata", "for", "a", "particular", "dataset", ".", "update_fields", "is", "a", "dictionary", "containing", "[", "metadata", "key", ":", "new", "value", "]", "pairs", "." ]
python
train
SoCo/SoCo
soco/music_services/music_service.py
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/music_services/music_service.py#L783-L799
def get_extended_metadata(self, item_id): """Get extended metadata for a media item, such as related items. Args: item_id (str): The item for which metadata is required. Returns: ~collections.OrderedDict: The item's extended metadata or None. See also: The Sonos `getExtendedMetadata API <http://musicpartners.sonos.com/node/128>`_ """ response = self.soap_client.call( 'getExtendedMetadata', [('id', item_id)]) return response.get('getExtendedMetadataResult', None)
[ "def", "get_extended_metadata", "(", "self", ",", "item_id", ")", ":", "response", "=", "self", ".", "soap_client", ".", "call", "(", "'getExtendedMetadata'", ",", "[", "(", "'id'", ",", "item_id", ")", "]", ")", "return", "response", ".", "get", "(", "'...
Get extended metadata for a media item, such as related items. Args: item_id (str): The item for which metadata is required. Returns: ~collections.OrderedDict: The item's extended metadata or None. See also: The Sonos `getExtendedMetadata API <http://musicpartners.sonos.com/node/128>`_
[ "Get", "extended", "metadata", "for", "a", "media", "item", "such", "as", "related", "items", "." ]
python
train
d0c-s4vage/pfp
pfp/interp.py
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L730-L738
def get_curr_lines(self): """Return the current line number in the template, as well as the surrounding source lines """ start = max(0, self._coord.line - 5) end = min(len(self._template_lines), self._coord.line + 4) lines = [(x, self._template_lines[x]) for x in six.moves.range(start, end, 1)] return self._coord.line, lines
[ "def", "get_curr_lines", "(", "self", ")", ":", "start", "=", "max", "(", "0", ",", "self", ".", "_coord", ".", "line", "-", "5", ")", "end", "=", "min", "(", "len", "(", "self", ".", "_template_lines", ")", ",", "self", ".", "_coord", ".", "line...
Return the current line number in the template, as well as the surrounding source lines
[ "Return", "the", "current", "line", "number", "in", "the", "template", "as", "well", "as", "the", "surrounding", "source", "lines" ]
python
train
prometheus/client_python
prometheus_client/decorator.py
https://github.com/prometheus/client_python/blob/31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb/prometheus_client/decorator.py#L229-L239
def decorate(func, caller): """ decorate(func, caller) decorates a function using a caller. """ evaldict = dict(_call_=caller, _func_=func) fun = FunctionMaker.create( func, "return _call_(_func_, %(shortsignature)s)", evaldict, __wrapped__=func) if hasattr(func, '__qualname__'): fun.__qualname__ = func.__qualname__ return fun
[ "def", "decorate", "(", "func", ",", "caller", ")", ":", "evaldict", "=", "dict", "(", "_call_", "=", "caller", ",", "_func_", "=", "func", ")", "fun", "=", "FunctionMaker", ".", "create", "(", "func", ",", "\"return _call_(_func_, %(shortsignature)s)\"", ",...
decorate(func, caller) decorates a function using a caller.
[ "decorate", "(", "func", "caller", ")", "decorates", "a", "function", "using", "a", "caller", "." ]
python
train
JukeboxPipeline/jukebox-core
src/jukeboxcore/addons/guerilla/guerillamgmt.py
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/addons/guerilla/guerillamgmt.py#L2372-L2386
def user_remove_prj(self, *args, **kwargs): """Remove the selected project from the user :returns: None :rtype: None :raises: None """ if not self.cur_user: return i = self.user_prj_tablev.currentIndex() item = i.internalPointer() if item: prj = item.internal_data() prj.users.remove(self.cur_user) item.set_parent(None)
[ "def", "user_remove_prj", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "cur_user", ":", "return", "i", "=", "self", ".", "user_prj_tablev", ".", "currentIndex", "(", ")", "item", "=", "i", ".", "internal...
Remove the selected project from the user :returns: None :rtype: None :raises: None
[ "Remove", "the", "selected", "project", "from", "the", "user" ]
python
train
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/arrayeditor.py
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/arrayeditor.py#L585-L598
def change_format(self): """Change display format""" format, valid = QInputDialog.getText(self, _( 'Format'), _( "Float formatting"), QLineEdit.Normal, self.model.get_format()) if valid: format = str(format) try: format % 1.1 except: QMessageBox.critical(self, _("Error"), _("Format (%s) is incorrect") % format) return self.model.set_format(format)
[ "def", "change_format", "(", "self", ")", ":", "format", ",", "valid", "=", "QInputDialog", ".", "getText", "(", "self", ",", "_", "(", "'Format'", ")", ",", "_", "(", "\"Float formatting\"", ")", ",", "QLineEdit", ".", "Normal", ",", "self", ".", "mod...
Change display format
[ "Change", "display", "format" ]
python
train
andrewda/frc-livescore
livescore/simpleocr_utils/processor.py
https://github.com/andrewda/frc-livescore/blob/71594cd6d2c8b6c5feb3889bb05552d09b8128b1/livescore/simpleocr_utils/processor.py#L13-L22
def _broadcast(src_processor, src_atr_name, dest_processors, dest_atr_name, transform_function): """ To be used exclusively by create_broadcast. A broadcast function gets an attribute on the src_processor and sets it (possibly under a different name) on dest_processors """ value = getattr(src_processor, src_atr_name) value = transform_function(value) for d in dest_processors: setattr(d, dest_atr_name, value)
[ "def", "_broadcast", "(", "src_processor", ",", "src_atr_name", ",", "dest_processors", ",", "dest_atr_name", ",", "transform_function", ")", ":", "value", "=", "getattr", "(", "src_processor", ",", "src_atr_name", ")", "value", "=", "transform_function", "(", "va...
To be used exclusively by create_broadcast. A broadcast function gets an attribute on the src_processor and sets it (possibly under a different name) on dest_processors
[ "To", "be", "used", "exclusively", "by", "create_broadcast", ".", "A", "broadcast", "function", "gets", "an", "attribute", "on", "the", "src_processor", "and", "sets", "it", "(", "possibly", "under", "a", "different", "name", ")", "on", "dest_processors" ]
python
train
libtcod/python-tcod
scripts/tag_release.py
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/scripts/tag_release.py#L29-L45
def parse_changelog(args: Any) -> Tuple[str, str]: """Return an updated changelog and and the list of changes.""" with open("CHANGELOG.rst", "r") as file: match = re.match( pattern=r"(.*?Unreleased\n---+\n)(.+?)(\n*[^\n]+\n---+\n.*)", string=file.read(), flags=re.DOTALL, ) assert match header, changes, tail = match.groups() tag = "%s - %s" % (args.tag, datetime.date.today().isoformat()) tagged = "\n%s\n%s\n%s" % (tag, "-" * len(tag), changes) if args.verbose: print(tagged) return "".join((header, tagged, tail)), changes
[ "def", "parse_changelog", "(", "args", ":", "Any", ")", "->", "Tuple", "[", "str", ",", "str", "]", ":", "with", "open", "(", "\"CHANGELOG.rst\"", ",", "\"r\"", ")", "as", "file", ":", "match", "=", "re", ".", "match", "(", "pattern", "=", "r\"(.*?Un...
Return an updated changelog and and the list of changes.
[ "Return", "an", "updated", "changelog", "and", "and", "the", "list", "of", "changes", "." ]
python
train
apache/spark
python/pyspark/rdd.py
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L1876-L1891
def aggregateByKey(self, zeroValue, seqFunc, combFunc, numPartitions=None, partitionFunc=portable_hash): """ Aggregate the values of each key, using given combine functions and a neutral "zero value". This function can return a different result type, U, than the type of the values in this RDD, V. Thus, we need one operation for merging a V into a U and one operation for merging two U's, The former operation is used for merging values within a partition, and the latter is used for merging values between partitions. To avoid memory allocation, both of these functions are allowed to modify and return their first argument instead of creating a new U. """ def createZero(): return copy.deepcopy(zeroValue) return self.combineByKey( lambda v: seqFunc(createZero(), v), seqFunc, combFunc, numPartitions, partitionFunc)
[ "def", "aggregateByKey", "(", "self", ",", "zeroValue", ",", "seqFunc", ",", "combFunc", ",", "numPartitions", "=", "None", ",", "partitionFunc", "=", "portable_hash", ")", ":", "def", "createZero", "(", ")", ":", "return", "copy", ".", "deepcopy", "(", "z...
Aggregate the values of each key, using given combine functions and a neutral "zero value". This function can return a different result type, U, than the type of the values in this RDD, V. Thus, we need one operation for merging a V into a U and one operation for merging two U's, The former operation is used for merging values within a partition, and the latter is used for merging values between partitions. To avoid memory allocation, both of these functions are allowed to modify and return their first argument instead of creating a new U.
[ "Aggregate", "the", "values", "of", "each", "key", "using", "given", "combine", "functions", "and", "a", "neutral", "zero", "value", ".", "This", "function", "can", "return", "a", "different", "result", "type", "U", "than", "the", "type", "of", "the", "val...
python
train
push-things/wallabag_api
wallabag_api/wallabag.py
https://github.com/push-things/wallabag_api/blob/8d1e10a6ebc03d1ac9af2b38b57eb69f29b4216e/wallabag_api/wallabag.py#L236-L276
async def patch_entries(self, entry, **kwargs): """ PATCH /api/entries/{entry}.{_format} Change several properties of an entry :param entry: the entry to 'patch' / update :param kwargs: can contain one of the following title: string tags: a list of tags tag1,tag2,tag3 archive: '0' or '1', default '0' archived the entry. starred: '0' or '1', default '0' starred the entry In case that you don't want to *really* remove it.. :return data related to the ext """ # default values params = {'access_token': self.token, 'title': '', 'tags': []} if 'title' in kwargs: params['title'] = kwargs['title'] if 'tags' in kwargs and isinstance(kwargs['tags'], list): params['tags'] = ', '.join(kwargs['tags']) params['archive'] = self.__get_attr(what='archive', type_attr=int, value_attr=(0, 1), **kwargs) params['starred'] = self.__get_attr(what='starred', type_attr=int, value_attr=(0, 1), **kwargs) params['order'] = self.__get_attr(what='order', type_attr=str, value_attr=('asc', 'desc'), **kwargs) path = '/api/entries/{entry}.{ext}'.format( entry=entry, ext=self.format) return await self.query(path, "patch", **params)
[ "async", "def", "patch_entries", "(", "self", ",", "entry", ",", "*", "*", "kwargs", ")", ":", "# default values", "params", "=", "{", "'access_token'", ":", "self", ".", "token", ",", "'title'", ":", "''", ",", "'tags'", ":", "[", "]", "}", "if", "'...
PATCH /api/entries/{entry}.{_format} Change several properties of an entry :param entry: the entry to 'patch' / update :param kwargs: can contain one of the following title: string tags: a list of tags tag1,tag2,tag3 archive: '0' or '1', default '0' archived the entry. starred: '0' or '1', default '0' starred the entry In case that you don't want to *really* remove it.. :return data related to the ext
[ "PATCH", "/", "api", "/", "entries", "/", "{", "entry", "}", ".", "{", "_format", "}" ]
python
train
pandas-dev/pandas
pandas/core/sparse/series.py
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/sparse/series.py#L268-L284
def _ixs(self, i, axis=0): """ Return the i-th value or values in the SparseSeries by location Parameters ---------- i : int, slice, or sequence of integers Returns ------- value : scalar (int) or Series (slice, sequence) """ label = self.index[i] if isinstance(label, Index): return self.take(i, axis=axis) else: return self._get_val_at(i)
[ "def", "_ixs", "(", "self", ",", "i", ",", "axis", "=", "0", ")", ":", "label", "=", "self", ".", "index", "[", "i", "]", "if", "isinstance", "(", "label", ",", "Index", ")", ":", "return", "self", ".", "take", "(", "i", ",", "axis", "=", "ax...
Return the i-th value or values in the SparseSeries by location Parameters ---------- i : int, slice, or sequence of integers Returns ------- value : scalar (int) or Series (slice, sequence)
[ "Return", "the", "i", "-", "th", "value", "or", "values", "in", "the", "SparseSeries", "by", "location" ]
python
train
ryanjdillon/pyotelem
pyotelem/plots/plotutils.py
https://github.com/ryanjdillon/pyotelem/blob/816563a9c3feb3fa416f1c2921c6b75db34111ad/pyotelem/plots/plotutils.py#L42-L63
def hourminsec(n_seconds): '''Generate a string of hours and minutes from total number of seconds Args ---- n_seconds: int Total number of seconds to calculate hours, minutes, and seconds from Returns ------- hours: int Number of hours in `n_seconds` minutes: int Remaining minutes in `n_seconds` after number of hours seconds: int Remaining seconds in `n_seconds` after number of minutes ''' hours, remainder = divmod(n_seconds, 3600) minutes, seconds = divmod(remainder, 60) return abs(hours), abs(minutes), abs(seconds)
[ "def", "hourminsec", "(", "n_seconds", ")", ":", "hours", ",", "remainder", "=", "divmod", "(", "n_seconds", ",", "3600", ")", "minutes", ",", "seconds", "=", "divmod", "(", "remainder", ",", "60", ")", "return", "abs", "(", "hours", ")", ",", "abs", ...
Generate a string of hours and minutes from total number of seconds Args ---- n_seconds: int Total number of seconds to calculate hours, minutes, and seconds from Returns ------- hours: int Number of hours in `n_seconds` minutes: int Remaining minutes in `n_seconds` after number of hours seconds: int Remaining seconds in `n_seconds` after number of minutes
[ "Generate", "a", "string", "of", "hours", "and", "minutes", "from", "total", "number", "of", "seconds" ]
python
train
xapple/plumbing
plumbing/slurm/job.py
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/slurm/job.py#L263-L267
def wait_locally(self): """If you have run the query in a non-blocking way, call this method to pause until the query is finished.""" try: self.thread.join(sys.maxint) # maxint timeout so that we can Ctrl-C them except KeyboardInterrupt: print "Stopped waiting on job '%s'" % self.kwargs['job_name']
[ "def", "wait_locally", "(", "self", ")", ":", "try", ":", "self", ".", "thread", ".", "join", "(", "sys", ".", "maxint", ")", "# maxint timeout so that we can Ctrl-C them", "except", "KeyboardInterrupt", ":", "print", "\"Stopped waiting on job '%s'\"", "%", "self", ...
If you have run the query in a non-blocking way, call this method to pause until the query is finished.
[ "If", "you", "have", "run", "the", "query", "in", "a", "non", "-", "blocking", "way", "call", "this", "method", "to", "pause", "until", "the", "query", "is", "finished", "." ]
python
train
google/openhtf
openhtf/util/console_output.py
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/console_output.py#L136-L160
def cli_print(msg, color='', end=None, file=sys.stdout, logger=_LOG): """Print the message to file and also log it. This function is intended as a 'tee' mechanism to enable the CLI interface as a first-class citizen, while ensuring that everything the operator sees also has an analogous logging entry in the test record for later inspection. Args: msg: The message to print/log. color: Optional colorama color string to be applied to the message. You can concatenate colorama color strings together in order to get any set of effects you want. end: A custom line-ending string to print instead of newline. file: A file object to which the baracketed text will be written. Intended for use with CLI output file objects like sys.stdout. logger: A logger to use, or None to disable logging. """ if logger: logger.debug('-> {}'.format(msg)) if CLI_QUIET: return if end is None: end = _linesep_for_file(file) file.write('{color}{msg}{reset}{end}'.format( color=color, msg=msg, reset=colorama.Style.RESET_ALL, end=end))
[ "def", "cli_print", "(", "msg", ",", "color", "=", "''", ",", "end", "=", "None", ",", "file", "=", "sys", ".", "stdout", ",", "logger", "=", "_LOG", ")", ":", "if", "logger", ":", "logger", ".", "debug", "(", "'-> {}'", ".", "format", "(", "msg"...
Print the message to file and also log it. This function is intended as a 'tee' mechanism to enable the CLI interface as a first-class citizen, while ensuring that everything the operator sees also has an analogous logging entry in the test record for later inspection. Args: msg: The message to print/log. color: Optional colorama color string to be applied to the message. You can concatenate colorama color strings together in order to get any set of effects you want. end: A custom line-ending string to print instead of newline. file: A file object to which the baracketed text will be written. Intended for use with CLI output file objects like sys.stdout. logger: A logger to use, or None to disable logging.
[ "Print", "the", "message", "to", "file", "and", "also", "log", "it", "." ]
python
train
tensorflow/tensorboard
tensorboard/compat/tensorflow_stub/io/gfile.py
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/compat/tensorflow_stub/io/gfile.py#L161-L169
def bucket_and_path(self, url): """Split an S3-prefixed URL into bucket and path.""" url = compat.as_str_any(url) if url.startswith("s3://"): url = url[len("s3://"):] idx = url.index("/") bucket = url[:idx] path = url[(idx + 1):] return bucket, path
[ "def", "bucket_and_path", "(", "self", ",", "url", ")", ":", "url", "=", "compat", ".", "as_str_any", "(", "url", ")", "if", "url", ".", "startswith", "(", "\"s3://\"", ")", ":", "url", "=", "url", "[", "len", "(", "\"s3://\"", ")", ":", "]", "idx"...
Split an S3-prefixed URL into bucket and path.
[ "Split", "an", "S3", "-", "prefixed", "URL", "into", "bucket", "and", "path", "." ]
python
train
michal-stuglik/django-blastplus
blastplus/forms.py
https://github.com/michal-stuglik/django-blastplus/blob/4f5e15fb9f8069c3bed5f8fd941c4b9891daad4b/blastplus/forms.py#L138-L174
def validate_sequence(sequence: str, sequence_is_as_nucleotide=True): """Validate sequence in blast/tblastn form. """ tmp_seq = tempfile.NamedTemporaryFile(mode="wb+", delete=False) if len(str(sequence).strip()) == 0: raise forms.ValidationError(blast_settings.BLAST_CORRECT_SEQ_ERROR_MSG) if str(sequence).strip()[0] != ">": tmp_seq.write(">seq1\n".encode()) tmp_seq.write(sequence.encode()) tmp_seq.close() records = SeqIO.index(tmp_seq.name, "fasta") record_count = len(records) if record_count == 0: raise forms.ValidationError(blast_settings.BLAST_CORRECT_SEQ_ERROR_MSG) if record_count > blast_settings.BLAST_MAX_NUMBER_SEQ_IN_INPUT: raise forms.ValidationError(blast_settings.BLAST_CORRECT_SEQ_MAX_SEQ_NUMB_ERROR_MSG) # read query sequence from temporary file first_sequence_list_in_file = SeqIO.parse(tmp_seq.name, "fasta") for sequence in first_sequence_list_in_file: if len(sequence.seq) <= 10: raise forms.ValidationError(blast_settings.BLAST_CORRECT_SEQ_TOO_SHORT_ERROR_MSG) if sequence_is_as_nucleotide: check_allowed_letters(str(sequence.seq), ALLOWED_NUCL) else: check_allowed_letters(str(sequence.seq), ALLOWED_AMINOACIDS) return tmp_seq
[ "def", "validate_sequence", "(", "sequence", ":", "str", ",", "sequence_is_as_nucleotide", "=", "True", ")", ":", "tmp_seq", "=", "tempfile", ".", "NamedTemporaryFile", "(", "mode", "=", "\"wb+\"", ",", "delete", "=", "False", ")", "if", "len", "(", "str", ...
Validate sequence in blast/tblastn form.
[ "Validate", "sequence", "in", "blast", "/", "tblastn", "form", "." ]
python
train
jbrudvik/yahooscraper
yahooscraper/fantasy/team.py
https://github.com/jbrudvik/yahooscraper/blob/e880323fea0dd25f03410eea9d088760ba7c3528/yahooscraper/fantasy/team.py#L83-L91
def start_active_players_path(page): """ Return the path in the "Start Active Players" button """ soup = BeautifulSoup(page) try: return soup.find('a', href=True, text='Start Active Players')['href'] except: return None
[ "def", "start_active_players_path", "(", "page", ")", ":", "soup", "=", "BeautifulSoup", "(", "page", ")", "try", ":", "return", "soup", ".", "find", "(", "'a'", ",", "href", "=", "True", ",", "text", "=", "'Start Active Players'", ")", "[", "'href'", "]...
Return the path in the "Start Active Players" button
[ "Return", "the", "path", "in", "the", "Start", "Active", "Players", "button" ]
python
train
quantopian/zipline
zipline/pipeline/loaders/synthetic.py
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/loaders/synthetic.py#L319-L329
def expected_bar_value(asset_id, date, colname): """ Check that the raw value for an asset/date/column triple is as expected. Used by tests to verify data written by a writer. """ from_asset = asset_id * 100000 from_colname = OHLCV.index(colname) * 1000 from_date = (date - PSEUDO_EPOCH).days return from_asset + from_colname + from_date
[ "def", "expected_bar_value", "(", "asset_id", ",", "date", ",", "colname", ")", ":", "from_asset", "=", "asset_id", "*", "100000", "from_colname", "=", "OHLCV", ".", "index", "(", "colname", ")", "*", "1000", "from_date", "=", "(", "date", "-", "PSEUDO_EPO...
Check that the raw value for an asset/date/column triple is as expected. Used by tests to verify data written by a writer.
[ "Check", "that", "the", "raw", "value", "for", "an", "asset", "/", "date", "/", "column", "triple", "is", "as", "expected", "." ]
python
train
pyviz/geoviews
geoviews/data/iris.py
https://github.com/pyviz/geoviews/blob/cc70ac2d5a96307769bc6192eaef8576c3d24b30/geoviews/data/iris.py#L328-L335
def add_dimension(cls, columns, dimension, dim_pos, values, vdim): """ Adding value dimensions not currently supported by iris interface. Adding key dimensions not possible on dense interfaces. """ if not vdim: raise Exception("Cannot add key dimension to a dense representation.") raise NotImplementedError
[ "def", "add_dimension", "(", "cls", ",", "columns", ",", "dimension", ",", "dim_pos", ",", "values", ",", "vdim", ")", ":", "if", "not", "vdim", ":", "raise", "Exception", "(", "\"Cannot add key dimension to a dense representation.\"", ")", "raise", "NotImplemente...
Adding value dimensions not currently supported by iris interface. Adding key dimensions not possible on dense interfaces.
[ "Adding", "value", "dimensions", "not", "currently", "supported", "by", "iris", "interface", ".", "Adding", "key", "dimensions", "not", "possible", "on", "dense", "interfaces", "." ]
python
train
spyder-ide/spyder
spyder/plugins/onlinehelp/onlinehelp.py
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/onlinehelp/onlinehelp.py#L83-L88
def closing_plugin(self, cancelable=False): """Perform actions before parent main window is closed""" self.save_history() self.set_option('zoom_factor', self.pydocbrowser.webview.get_zoom_factor()) return True
[ "def", "closing_plugin", "(", "self", ",", "cancelable", "=", "False", ")", ":", "self", ".", "save_history", "(", ")", "self", ".", "set_option", "(", "'zoom_factor'", ",", "self", ".", "pydocbrowser", ".", "webview", ".", "get_zoom_factor", "(", ")", ")"...
Perform actions before parent main window is closed
[ "Perform", "actions", "before", "parent", "main", "window", "is", "closed" ]
python
train
kensho-technologies/graphql-compiler
graphql_compiler/schema_generation/schema_graph.py
https://github.com/kensho-technologies/graphql-compiler/blob/f6079c6d10f64932f6b3af309b79bcea2123ca8f/graphql_compiler/schema_generation/schema_graph.py#L371-L381
def validate_properties_exist(self, classname, property_names): """Validate that the specified property names are indeed defined on the given class.""" schema_element = self.get_element_by_class_name(classname) requested_properties = set(property_names) available_properties = set(schema_element.properties.keys()) non_existent_properties = requested_properties - available_properties if non_existent_properties: raise InvalidPropertyError( u'Class "{}" does not have definitions for properties "{}": ' u'{}'.format(classname, non_existent_properties, property_names))
[ "def", "validate_properties_exist", "(", "self", ",", "classname", ",", "property_names", ")", ":", "schema_element", "=", "self", ".", "get_element_by_class_name", "(", "classname", ")", "requested_properties", "=", "set", "(", "property_names", ")", "available_prope...
Validate that the specified property names are indeed defined on the given class.
[ "Validate", "that", "the", "specified", "property", "names", "are", "indeed", "defined", "on", "the", "given", "class", "." ]
python
train
saltstack/salt
salt/cloud/clouds/azurearm.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/azurearm.py#L1744-L1769
def list_blobs(call=None, kwargs=None): # pylint: disable=unused-argument ''' List blobs. ''' if kwargs is None: kwargs = {} if 'container' not in kwargs: raise SaltCloudSystemExit( 'A container must be specified' ) storageservice = _get_block_blob_service(kwargs) ret = {} try: for blob in storageservice.list_blobs(kwargs['container']).items: ret[blob.name] = { 'blob_type': blob.properties.blob_type, 'last_modified': blob.properties.last_modified.isoformat(), 'server_encrypted': blob.properties.server_encrypted, } except Exception as exc: log.warning(six.text_type(exc)) return ret
[ "def", "list_blobs", "(", "call", "=", "None", ",", "kwargs", "=", "None", ")", ":", "# pylint: disable=unused-argument", "if", "kwargs", "is", "None", ":", "kwargs", "=", "{", "}", "if", "'container'", "not", "in", "kwargs", ":", "raise", "SaltCloudSystemEx...
List blobs.
[ "List", "blobs", "." ]
python
train
evhub/coconut
coconut/compiler/compiler.py
https://github.com/evhub/coconut/blob/ff97177344e7604e89a0a98a977a87ed2a56fc6d/coconut/compiler/compiler.py#L451-L455
def set_skips(self, skips): """Set the line skips.""" skips.sort() internal_assert(lambda: len(set(skips)) == len(skips), "duplicate line skip(s) in skips", skips) self.skips = skips
[ "def", "set_skips", "(", "self", ",", "skips", ")", ":", "skips", ".", "sort", "(", ")", "internal_assert", "(", "lambda", ":", "len", "(", "set", "(", "skips", ")", ")", "==", "len", "(", "skips", ")", ",", "\"duplicate line skip(s) in skips\"", ",", ...
Set the line skips.
[ "Set", "the", "line", "skips", "." ]
python
train
poldracklab/niworkflows
niworkflows/interfaces/masks.py
https://github.com/poldracklab/niworkflows/blob/254f4b4fcc5e6ecb29d2f4602a30786b913ecce5/niworkflows/interfaces/masks.py#L46-L58
def _post_run_hook(self, runtime): ''' generates a report showing slices from each axis of an arbitrary volume of in_file, with the resulting binary brain mask overlaid ''' self._anat_file = self.inputs.in_file self._mask_file = self.aggregate_outputs(runtime=runtime).mask_file self._seg_files = [self._mask_file] self._masked = self.inputs.mask NIWORKFLOWS_LOG.info('Generating report for BET. file "%s", and mask file "%s"', self._anat_file, self._mask_file) return super(BETRPT, self)._post_run_hook(runtime)
[ "def", "_post_run_hook", "(", "self", ",", "runtime", ")", ":", "self", ".", "_anat_file", "=", "self", ".", "inputs", ".", "in_file", "self", ".", "_mask_file", "=", "self", ".", "aggregate_outputs", "(", "runtime", "=", "runtime", ")", ".", "mask_file", ...
generates a report showing slices from each axis of an arbitrary volume of in_file, with the resulting binary brain mask overlaid
[ "generates", "a", "report", "showing", "slices", "from", "each", "axis", "of", "an", "arbitrary", "volume", "of", "in_file", "with", "the", "resulting", "binary", "brain", "mask", "overlaid" ]
python
train
dnanexus/dx-toolkit
src/python/dxpy/bindings/dxapplet.py
https://github.com/dnanexus/dx-toolkit/blob/74befb53ad90fcf902d8983ae6d74580f402d619/src/python/dxpy/bindings/dxapplet.py#L384-L394
def run(self, applet_input, *args, **kwargs): """ Creates a new job that executes the function "main" of this applet with the given input *applet_input*. See :meth:`dxpy.bindings.dxapplet.DXExecutable.run` for the available args. """ # Rename applet_input arg to preserve API compatibility when calling # DXApplet.run(applet_input=...) return super(DXApplet, self).run(applet_input, *args, **kwargs)
[ "def", "run", "(", "self", ",", "applet_input", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Rename applet_input arg to preserve API compatibility when calling", "# DXApplet.run(applet_input=...)", "return", "super", "(", "DXApplet", ",", "self", ")", ".", ...
Creates a new job that executes the function "main" of this applet with the given input *applet_input*. See :meth:`dxpy.bindings.dxapplet.DXExecutable.run` for the available args.
[ "Creates", "a", "new", "job", "that", "executes", "the", "function", "main", "of", "this", "applet", "with", "the", "given", "input", "*", "applet_input", "*", "." ]
python
train
pyamg/pyamg
pyamg/krylov/_gmres_mgs.py
https://github.com/pyamg/pyamg/blob/89dc54aa27e278f65d2f54bdaf16ab97d7768fa6/pyamg/krylov/_gmres_mgs.py#L41-L365
def gmres_mgs(A, b, x0=None, tol=1e-5, restrt=None, maxiter=None, xtype=None, M=None, callback=None, residuals=None, reorth=False): """Generalized Minimum Residual Method (GMRES) based on MGS. GMRES iteratively refines the initial solution guess to the system Ax = b Modified Gram-Schmidt version Parameters ---------- A : array, matrix, sparse matrix, LinearOperator n x n, linear system to solve b : array, matrix right hand side, shape is (n,) or (n,1) x0 : array, matrix initial guess, default is a vector of zeros tol : float relative convergence tolerance, i.e. tol is scaled by the norm of the initial preconditioned residual restrt : None, int - if int, restrt is max number of inner iterations and maxiter is the max number of outer iterations - if None, do not restart GMRES, and max number of inner iterations is maxiter maxiter : None, int - if restrt is None, maxiter is the max number of inner iterations and GMRES does not restart - if restrt is int, maxiter is the max number of outer iterations, and restrt is the max number of inner iterations xtype : type dtype for the solution, default is automatic type detection M : array, matrix, sparse matrix, LinearOperator n x n, inverted preconditioner, i.e. solve M A x = M b. callback : function User-supplied function is called after each iteration as callback(xk), where xk is the current solution vector residuals : list residuals contains the preconditioned residual norm history, including the initial residual. reorth : boolean If True, then a check is made whether to re-orthogonalize the Krylov space each GMRES iteration Returns ------- (xNew, info) xNew : an updated guess to the solution of Ax = b info : halting status of gmres == ============================================= 0 successful exit >0 convergence to tolerance not achieved, return iteration count instead. This value is precisely the order of the Krylov space. <0 numerical breakdown, or illegal input == ============================================= Notes ----- - The LinearOperator class is in scipy.sparse.linalg.interface. Use this class if you prefer to define A or M as a mat-vec routine as opposed to explicitly constructing the matrix. A.psolve(..) is still supported as a legacy. - For robustness, modified Gram-Schmidt is used to orthogonalize the Krylov Space Givens Rotations are used to provide the residual norm each iteration Examples -------- >>> from pyamg.krylov import gmres >>> from pyamg.util.linalg import norm >>> import numpy as np >>> from pyamg.gallery import poisson >>> A = poisson((10,10)) >>> b = np.ones((A.shape[0],)) >>> (x,flag) = gmres(A,b, maxiter=2, tol=1e-8, orthog='mgs') >>> print norm(b - A*x) >>> 6.5428213057 References ---------- .. [1] Yousef Saad, "Iterative Methods for Sparse Linear Systems, Second Edition", SIAM, pp. 151-172, pp. 272-275, 2003 http://www-users.cs.umn.edu/~saad/books.html .. [2] C. T. Kelley, http://www4.ncsu.edu/~ctk/matlab_roots.html """ # Convert inputs to linear system, with error checking A, M, x, b, postprocess = make_system(A, M, x0, b) dimen = A.shape[0] # Ensure that warnings are always reissued from this function import warnings warnings.filterwarnings('always', module='pyamg\.krylov\._gmres_mgs') # Choose type if not hasattr(A, 'dtype'): Atype = upcast(x.dtype, b.dtype) else: Atype = A.dtype if not hasattr(M, 'dtype'): Mtype = upcast(x.dtype, b.dtype) else: Mtype = M.dtype xtype = upcast(Atype, x.dtype, b.dtype, Mtype) if restrt is not None: restrt = int(restrt) if maxiter is not None: maxiter = int(maxiter) # Get fast access to underlying BLAS routines # dotc is the conjugate dot, dotu does no conjugation [lartg] = get_lapack_funcs(['lartg'], [x]) if np.iscomplexobj(np.zeros((1,), dtype=xtype)): [axpy, dotu, dotc, scal] =\ get_blas_funcs(['axpy', 'dotu', 'dotc', 'scal'], [x]) else: # real type [axpy, dotu, dotc, scal] =\ get_blas_funcs(['axpy', 'dot', 'dot', 'scal'], [x]) # Make full use of direct access to BLAS by defining own norm def norm(z): return np.sqrt(np.real(dotc(z, z))) # Should norm(r) be kept if residuals == []: keep_r = True else: keep_r = False # Set number of outer and inner iterations if restrt: if maxiter: max_outer = maxiter else: max_outer = 1 if restrt > dimen: warn('Setting number of inner iterations (restrt) to maximum\ allowed, which is A.shape[0] ') restrt = dimen max_inner = restrt else: max_outer = 1 if maxiter > dimen: warn('Setting number of inner iterations (maxiter) to maximum\ allowed, which is A.shape[0] ') maxiter = dimen elif maxiter is None: maxiter = min(dimen, 40) max_inner = maxiter # Is this a one dimensional matrix? if dimen == 1: entry = np.ravel(A*np.array([1.0], dtype=xtype)) return (postprocess(b/entry), 0) # Prep for method r = b - np.ravel(A*x) # Apply preconditioner r = np.ravel(M*r) normr = norm(r) if keep_r: residuals.append(normr) # Check for nan, inf # if isnan(r).any() or isinf(r).any(): # warn('inf or nan after application of preconditioner') # return(postprocess(x), -1) # Check initial guess ( scaling by b, if b != 0, # must account for case when norm(b) is very small) normb = norm(b) if normb == 0.0: normb = 1.0 if normr < tol*normb: return (postprocess(x), 0) # Scale tol by ||r_0||_2, we use the preconditioned residual # because this is left preconditioned GMRES. if normr != 0.0: tol = tol*normr # Use separate variable to track iterations. If convergence fails, we # cannot simply report niter = (outer-1)*max_outer + inner. Numerical # error could cause the inner loop to halt while the actual ||r|| > tol. niter = 0 # Begin GMRES for outer in range(max_outer): # Preallocate for Givens Rotations, Hessenberg matrix and Krylov Space # Space required is O(dimen*max_inner). # NOTE: We are dealing with row-major matrices, so we traverse in a # row-major fashion, # i.e., H and V's transpose is what we store. Q = [] # Givens Rotations # Upper Hessenberg matrix, which is then # converted to upper tri with Givens Rots H = np.zeros((max_inner+1, max_inner+1), dtype=xtype) V = np.zeros((max_inner+1, dimen), dtype=xtype) # Krylov Space # vs store the pointers to each column of V. # This saves a considerable amount of time. vs = [] # v = r/normr V[0, :] = scal(1.0/normr, r) vs.append(V[0, :]) # This is the RHS vector for the problem in the Krylov Space g = np.zeros((dimen,), dtype=xtype) g[0] = normr for inner in range(max_inner): # New Search Direction v = V[inner+1, :] v[:] = np.ravel(M*(A*vs[-1])) vs.append(v) normv_old = norm(v) # Check for nan, inf # if isnan(V[inner+1, :]).any() or isinf(V[inner+1, :]).any(): # warn('inf or nan after application of preconditioner') # return(postprocess(x), -1) # Modified Gram Schmidt for k in range(inner+1): vk = vs[k] alpha = dotc(vk, v) H[inner, k] = alpha v[:] = axpy(vk, v, dimen, -alpha) normv = norm(v) H[inner, inner+1] = normv # Re-orthogonalize if (reorth is True) and (normv_old == normv_old + 0.001*normv): for k in range(inner+1): vk = vs[k] alpha = dotc(vk, v) H[inner, k] = H[inner, k] + alpha v[:] = axpy(vk, v, dimen, -alpha) # Check for breakdown if H[inner, inner+1] != 0.0: v[:] = scal(1.0/H[inner, inner+1], v) # Apply previous Givens rotations to H if inner > 0: apply_givens(Q, H[inner, :], inner) # Calculate and apply next complex-valued Givens Rotation # ==> Note that if max_inner = dimen, then this is unnecessary # for the last inner # iteration, when inner = dimen-1. if inner != dimen-1: if H[inner, inner+1] != 0: [c, s, r] = lartg(H[inner, inner], H[inner, inner+1]) Qblock = np.array([[c, s], [-np.conjugate(s), c]], dtype=xtype) Q.append(Qblock) # Apply Givens Rotation to g, # the RHS for the linear system in the Krylov Subspace. g[inner:inner+2] = np.dot(Qblock, g[inner:inner+2]) # Apply effect of Givens Rotation to H H[inner, inner] = dotu(Qblock[0, :], H[inner, inner:inner+2]) H[inner, inner+1] = 0.0 niter += 1 # Don't update normr if last inner iteration, because # normr is calculated directly after this loop ends. if inner < max_inner-1: normr = np.abs(g[inner+1]) if normr < tol: break # Allow user access to the iterates if callback is not None: callback(x) if keep_r: residuals.append(normr) # end inner loop, back to outer loop # Find best update to x in Krylov Space V. Solve inner x inner system. y = sp.linalg.solve(H[0:inner+1, 0:inner+1].T, g[0:inner+1]) update = np.ravel(np.mat(V[:inner+1, :]).T*y.reshape(-1, 1)) x = x + update r = b - np.ravel(A*x) # Apply preconditioner r = np.ravel(M*r) normr = norm(r) # Check for nan, inf # if isnan(r).any() or isinf(r).any(): # warn('inf or nan after application of preconditioner') # return(postprocess(x), -1) # Allow user access to the iterates if callback is not None: callback(x) if keep_r: residuals.append(normr) # Has GMRES stagnated? indices = (x != 0) if indices.any(): change = np.max(np.abs(update[indices] / x[indices])) if change < 1e-12: # No change, halt return (postprocess(x), -1) # test for convergence if normr < tol: return (postprocess(x), 0) # end outer loop return (postprocess(x), niter)
[ "def", "gmres_mgs", "(", "A", ",", "b", ",", "x0", "=", "None", ",", "tol", "=", "1e-5", ",", "restrt", "=", "None", ",", "maxiter", "=", "None", ",", "xtype", "=", "None", ",", "M", "=", "None", ",", "callback", "=", "None", ",", "residuals", ...
Generalized Minimum Residual Method (GMRES) based on MGS. GMRES iteratively refines the initial solution guess to the system Ax = b Modified Gram-Schmidt version Parameters ---------- A : array, matrix, sparse matrix, LinearOperator n x n, linear system to solve b : array, matrix right hand side, shape is (n,) or (n,1) x0 : array, matrix initial guess, default is a vector of zeros tol : float relative convergence tolerance, i.e. tol is scaled by the norm of the initial preconditioned residual restrt : None, int - if int, restrt is max number of inner iterations and maxiter is the max number of outer iterations - if None, do not restart GMRES, and max number of inner iterations is maxiter maxiter : None, int - if restrt is None, maxiter is the max number of inner iterations and GMRES does not restart - if restrt is int, maxiter is the max number of outer iterations, and restrt is the max number of inner iterations xtype : type dtype for the solution, default is automatic type detection M : array, matrix, sparse matrix, LinearOperator n x n, inverted preconditioner, i.e. solve M A x = M b. callback : function User-supplied function is called after each iteration as callback(xk), where xk is the current solution vector residuals : list residuals contains the preconditioned residual norm history, including the initial residual. reorth : boolean If True, then a check is made whether to re-orthogonalize the Krylov space each GMRES iteration Returns ------- (xNew, info) xNew : an updated guess to the solution of Ax = b info : halting status of gmres == ============================================= 0 successful exit >0 convergence to tolerance not achieved, return iteration count instead. This value is precisely the order of the Krylov space. <0 numerical breakdown, or illegal input == ============================================= Notes ----- - The LinearOperator class is in scipy.sparse.linalg.interface. Use this class if you prefer to define A or M as a mat-vec routine as opposed to explicitly constructing the matrix. A.psolve(..) is still supported as a legacy. - For robustness, modified Gram-Schmidt is used to orthogonalize the Krylov Space Givens Rotations are used to provide the residual norm each iteration Examples -------- >>> from pyamg.krylov import gmres >>> from pyamg.util.linalg import norm >>> import numpy as np >>> from pyamg.gallery import poisson >>> A = poisson((10,10)) >>> b = np.ones((A.shape[0],)) >>> (x,flag) = gmres(A,b, maxiter=2, tol=1e-8, orthog='mgs') >>> print norm(b - A*x) >>> 6.5428213057 References ---------- .. [1] Yousef Saad, "Iterative Methods for Sparse Linear Systems, Second Edition", SIAM, pp. 151-172, pp. 272-275, 2003 http://www-users.cs.umn.edu/~saad/books.html .. [2] C. T. Kelley, http://www4.ncsu.edu/~ctk/matlab_roots.html
[ "Generalized", "Minimum", "Residual", "Method", "(", "GMRES", ")", "based", "on", "MGS", "." ]
python
train
benedictpaten/sonLib
bioio.py
https://github.com/benedictpaten/sonLib/blob/1decb75bb439b70721ec776f685ce98e25217d26/bioio.py#L762-L789
def fastqRead(fileHandleOrFile): """Reads a fastq file iteratively """ fileHandle = _getFileHandle(fileHandleOrFile) line = fileHandle.readline() while line != '': if line[0] == '@': name = line[1:-1] seq = fileHandle.readline()[:-1] plus = fileHandle.readline() if plus[0] != '+': raise RuntimeError("Got unexpected line: %s" % plus) qualValues = [ ord(i) for i in fileHandle.readline()[:-1] ] if len(seq) != len(qualValues): logger.critical("Got a mismatch between the number of sequence characters (%s) and number of qual values (%s) for sequence: %s, ignoring returning None" % (len(seq), len(qualValues), name)) qualValues = None else: for i in qualValues: if i < 33 or i > 126: raise RuntimeError("Got a qual value out of range %s (range is 33 to 126)" % i) for i in seq: #For safety and sanity I only allows roman alphabet characters in fasta sequences. if not ((i >= 'A' and i <= 'Z') or (i >= 'a' and i <= 'z') or i == '-'): raise RuntimeError("Invalid FASTQ character, ASCII code = \'%d\', found in input sequence %s" % (ord(i), name)) yield name, seq, qualValues line = fileHandle.readline() if isinstance(fileHandleOrFile, "".__class__): fileHandle.close()
[ "def", "fastqRead", "(", "fileHandleOrFile", ")", ":", "fileHandle", "=", "_getFileHandle", "(", "fileHandleOrFile", ")", "line", "=", "fileHandle", ".", "readline", "(", ")", "while", "line", "!=", "''", ":", "if", "line", "[", "0", "]", "==", "'@'", ":...
Reads a fastq file iteratively
[ "Reads", "a", "fastq", "file", "iteratively" ]
python
train
LogicalDash/LiSE
allegedb/allegedb/query.py
https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/allegedb/allegedb/query.py#L481-L497
def edge_val_dump(self): """Yield the entire contents of the edge_val table.""" self._flush_edge_val() for ( graph, orig, dest, idx, key, branch, turn, tick, value ) in self.sql('edge_val_dump'): yield ( self.unpack(graph), self.unpack(orig), self.unpack(dest), idx, self.unpack(key), branch, turn, tick, self.unpack(value) )
[ "def", "edge_val_dump", "(", "self", ")", ":", "self", ".", "_flush_edge_val", "(", ")", "for", "(", "graph", ",", "orig", ",", "dest", ",", "idx", ",", "key", ",", "branch", ",", "turn", ",", "tick", ",", "value", ")", "in", "self", ".", "sql", ...
Yield the entire contents of the edge_val table.
[ "Yield", "the", "entire", "contents", "of", "the", "edge_val", "table", "." ]
python
train
fuzeman/PyUPnP
pyupnp/lict.py
https://github.com/fuzeman/PyUPnP/blob/6dea64be299952346a14300ab6cc7dac42736433/pyupnp/lict.py#L337-L341
def setdefault(self, k, d=None): """ D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """ if k not in self._col_dict: self._set_key(k, d) return self._col_dict.get(k)
[ "def", "setdefault", "(", "self", ",", "k", ",", "d", "=", "None", ")", ":", "if", "k", "not", "in", "self", ".", "_col_dict", ":", "self", ".", "_set_key", "(", "k", ",", "d", ")", "return", "self", ".", "_col_dict", ".", "get", "(", "k", ")" ...
D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
[ "D", ".", "setdefault", "(", "k", "[", "d", "]", ")", "-", ">", "D", ".", "get", "(", "k", "d", ")", "also", "set", "D", "[", "k", "]", "=", "d", "if", "k", "not", "in", "D" ]
python
train
ericmjl/hiveplot
hiveplot/hiveplot.py
https://github.com/ericmjl/hiveplot/blob/f465a7118b7f005c83ab054d400deb02bd9f7410/hiveplot/hiveplot.py#L338-L353
def correct_angles(self, start_angle, end_angle): """ This function corrects for the following problems in the edges: """ # Edges going the anti-clockwise direction involves angle = 0. if start_angle == 0 and (end_angle - start_angle > np.pi): start_angle = np.pi * 2 if end_angle == 0 and (end_angle - start_angle < -np.pi): end_angle = np.pi * 2 # Case when start_angle == end_angle: if start_angle == end_angle: start_angle = start_angle - self.minor_angle end_angle = end_angle + self.minor_angle return start_angle, end_angle
[ "def", "correct_angles", "(", "self", ",", "start_angle", ",", "end_angle", ")", ":", "# Edges going the anti-clockwise direction involves angle = 0.", "if", "start_angle", "==", "0", "and", "(", "end_angle", "-", "start_angle", ">", "np", ".", "pi", ")", ":", "st...
This function corrects for the following problems in the edges:
[ "This", "function", "corrects", "for", "the", "following", "problems", "in", "the", "edges", ":" ]
python
valid
metachris/RPIO
source/RPIO/_RPIO.py
https://github.com/metachris/RPIO/blob/be1942a69b2592ddacd9dc833d2668a19aafd8d2/source/RPIO/_RPIO.py#L114-L217
def add_interrupt_callback(self, gpio_id, callback, edge='both', pull_up_down=_GPIO.PUD_OFF, threaded_callback=False, debounce_timeout_ms=None): """ Add a callback to be executed when the value on 'gpio_id' changes to the edge specified via the 'edge' parameter (default='both'). `pull_up_down` can be set to `RPIO.PUD_UP`, `RPIO.PUD_DOWN`, and `RPIO.PUD_OFF`. If `threaded_callback` is True, the callback will be started inside a Thread. """ gpio_id = _GPIO.channel_to_gpio(gpio_id) debug("Adding callback for GPIO %s" % gpio_id) if not edge in ["falling", "rising", "both", "none"]: raise AttributeError("'%s' is not a valid edge." % edge) if not pull_up_down in [_GPIO.PUD_UP, _GPIO.PUD_DOWN, _GPIO.PUD_OFF]: raise AttributeError("'%s' is not a valid pull_up_down." % edge) # Make sure the gpio_id is valid if not gpio_id in set(chain(RPIO.GPIO_LIST_R1, RPIO.GPIO_LIST_R2, \ RPIO.GPIO_LIST_R3)): raise AttributeError("GPIO %s is not a valid gpio-id." % gpio_id) # Require INPUT pin setup; and set the correct PULL_UPDN if RPIO.gpio_function(int(gpio_id)) == RPIO.IN: RPIO.set_pullupdn(gpio_id, pull_up_down) else: debug("- changing gpio function from %s to INPUT" % \ (GPIO_FUNCTIONS[RPIO.gpio_function(int(gpio_id))])) RPIO.setup(gpio_id, RPIO.IN, pull_up_down) # Prepare the callback (wrap in Thread if needed) cb = callback if not threaded_callback else \ partial(_threaded_callback, callback) # Prepare the /sys/class path of this gpio path_gpio = "%sgpio%s/" % (_SYS_GPIO_ROOT, gpio_id) # If initial callback for this GPIO then set everything up. Else make # sure the edge detection is the same. if gpio_id in self._map_gpioid_to_callbacks: with open(path_gpio + "edge", "r") as f: e = f.read().strip() if e != edge: raise AttributeError(("Cannot add callback for gpio %s:" " edge detection '%s' not compatible with existing" " edge detection '%s'.") % (gpio_id, edge, e)) # Check whether edge is the same, else throw Exception debug("- kernel interface already setup for GPIO %s" % gpio_id) self._map_gpioid_to_callbacks[gpio_id].append(cb) else: # If kernel interface already exists unexport first for clean setup if os.path.exists(path_gpio): if self._show_warnings: warn("Kernel interface for GPIO %s already exists." % \ gpio_id) debug("- unexporting kernel interface for GPIO %s" % gpio_id) with open(_SYS_GPIO_ROOT + "unexport", "w") as f: f.write("%s" % gpio_id) time.sleep(0.1) # Export kernel interface /sys/class/gpio/gpioN with open(_SYS_GPIO_ROOT + "export", "w") as f: f.write("%s" % gpio_id) self._gpio_kernel_interfaces_created.append(gpio_id) debug("- kernel interface exported for GPIO %s" % gpio_id) # Configure gpio as input with open(path_gpio + "direction", "w") as f: f.write("in") # Configure gpio edge detection with open(path_gpio + "edge", "w") as f: f.write(edge) debug(("- kernel interface configured for GPIO %s " "(edge='%s', pullupdn=%s)") % (gpio_id, edge, \ _PULL_UPDN[pull_up_down])) # Open the gpio value stream and read the initial value f = open(path_gpio + "value", 'r') val_initial = f.read().strip() debug("- inital gpio value: %s" % val_initial) f.seek(0) # Add callback info to the mapping dictionaries self._map_fileno_to_file[f.fileno()] = f self._map_fileno_to_gpioid[f.fileno()] = gpio_id self._map_fileno_to_options[f.fileno()] = { "debounce_timeout_s": debounce_timeout_ms / 1000.0 if \ debounce_timeout_ms else 0, "interrupt_last": 0, "edge": edge } self._map_gpioid_to_fileno[gpio_id] = f.fileno() self._map_gpioid_to_callbacks[gpio_id] = [cb] # Add to epoll self._epoll.register(f.fileno(), select.EPOLLPRI | select.EPOLLERR)
[ "def", "add_interrupt_callback", "(", "self", ",", "gpio_id", ",", "callback", ",", "edge", "=", "'both'", ",", "pull_up_down", "=", "_GPIO", ".", "PUD_OFF", ",", "threaded_callback", "=", "False", ",", "debounce_timeout_ms", "=", "None", ")", ":", "gpio_id", ...
Add a callback to be executed when the value on 'gpio_id' changes to the edge specified via the 'edge' parameter (default='both'). `pull_up_down` can be set to `RPIO.PUD_UP`, `RPIO.PUD_DOWN`, and `RPIO.PUD_OFF`. If `threaded_callback` is True, the callback will be started inside a Thread.
[ "Add", "a", "callback", "to", "be", "executed", "when", "the", "value", "on", "gpio_id", "changes", "to", "the", "edge", "specified", "via", "the", "edge", "parameter", "(", "default", "=", "both", ")", "." ]
python
train
KarchinLab/probabilistic2020
prob2020/python/gene_sequence.py
https://github.com/KarchinLab/probabilistic2020/blob/5d70583b0a7c07cfe32e95f3a70e05df412acb84/prob2020/python/gene_sequence.py#L153-L195
def _fetch_3ss_fasta(fasta, gene_name, exon_num, chrom, strand, start, end): """Retreives the 3' SS sequence flanking the specified exon. Returns a string in fasta format with the first line containing a ">" and the second line contains the two base pairs of 3' SS. Parameters ---------- fasta : pysam.Fastafile fasta object from pysam gene_name : str gene name used for fasta seq id exon_num : int the `exon_num` exon, used for seq id chrom : str chromsome strand : str strand, {'+', '-'} start : int 0-based start position end : int 0-based end position Returns ------- ss_fasta : str string in fasta format with first line being seq id """ if strand == '-': ss_seq = fasta.fetch(reference=chrom, start=end-1, end=end+3) ss_seq = utils.rev_comp(ss_seq) elif strand == '+': ss_seq = fasta.fetch(reference=chrom, start=start-3, end=start+1) ss_fasta = '>{0};exon{1};3SS\n{2}\n'.format(gene_name, exon_num, ss_seq.upper()) return ss_fasta
[ "def", "_fetch_3ss_fasta", "(", "fasta", ",", "gene_name", ",", "exon_num", ",", "chrom", ",", "strand", ",", "start", ",", "end", ")", ":", "if", "strand", "==", "'-'", ":", "ss_seq", "=", "fasta", ".", "fetch", "(", "reference", "=", "chrom", ",", ...
Retreives the 3' SS sequence flanking the specified exon. Returns a string in fasta format with the first line containing a ">" and the second line contains the two base pairs of 3' SS. Parameters ---------- fasta : pysam.Fastafile fasta object from pysam gene_name : str gene name used for fasta seq id exon_num : int the `exon_num` exon, used for seq id chrom : str chromsome strand : str strand, {'+', '-'} start : int 0-based start position end : int 0-based end position Returns ------- ss_fasta : str string in fasta format with first line being seq id
[ "Retreives", "the", "3", "SS", "sequence", "flanking", "the", "specified", "exon", "." ]
python
train
google/prettytensor
prettytensor/local_trainer.py
https://github.com/google/prettytensor/blob/75daa0b11252590f548da5647addc0ea610c4c45/prettytensor/local_trainer.py#L327-L357
def train_model(self, train_op, cost_to_log, num_steps, feed_vars=(), feed_data=None, print_every=100): """Trains the given model. Args: train_op: The training operation. cost_to_log: A cost to log. num_steps: Number of batches to run. feed_vars: A list or tuple of the variables that will be fed. feed_data: A generator that produces tuples of the same length as feed_vars. print_every: Print and save every so many steps. Returns: `cost_to_log` from the final step. """ costs = [train_op] if (isinstance(cost_to_log, collections.Sequence) and not isinstance(cost_to_log, six.string_types)): costs.extend(cost_to_log) else: costs.append(cost_to_log) return self.run_model(costs, num_steps, feed_vars=feed_vars, feed_data=feed_data, print_every=print_every)[2:]
[ "def", "train_model", "(", "self", ",", "train_op", ",", "cost_to_log", ",", "num_steps", ",", "feed_vars", "=", "(", ")", ",", "feed_data", "=", "None", ",", "print_every", "=", "100", ")", ":", "costs", "=", "[", "train_op", "]", "if", "(", "isinstan...
Trains the given model. Args: train_op: The training operation. cost_to_log: A cost to log. num_steps: Number of batches to run. feed_vars: A list or tuple of the variables that will be fed. feed_data: A generator that produces tuples of the same length as feed_vars. print_every: Print and save every so many steps. Returns: `cost_to_log` from the final step.
[ "Trains", "the", "given", "model", "." ]
python
train
DataDog/integrations-core
tokumx/datadog_checks/tokumx/vendor/pymongo/bulk.py
https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/tokumx/datadog_checks/tokumx/vendor/pymongo/bulk.py#L241-L252
def add_replace(self, selector, replacement, upsert=False, collation=None): """Create a replace document and add it to the list of ops. """ validate_ok_for_replace(replacement) cmd = SON([('q', selector), ('u', replacement), ('multi', False), ('upsert', upsert)]) collation = validate_collation_or_none(collation) if collation is not None: self.uses_collation = True cmd['collation'] = collation self.ops.append((_UPDATE, cmd))
[ "def", "add_replace", "(", "self", ",", "selector", ",", "replacement", ",", "upsert", "=", "False", ",", "collation", "=", "None", ")", ":", "validate_ok_for_replace", "(", "replacement", ")", "cmd", "=", "SON", "(", "[", "(", "'q'", ",", "selector", ")...
Create a replace document and add it to the list of ops.
[ "Create", "a", "replace", "document", "and", "add", "it", "to", "the", "list", "of", "ops", "." ]
python
train
NatLibFi/Skosify
skosify/skosify.py
https://github.com/NatLibFi/Skosify/blob/1d269987f10df08e706272dcf6a86aef4abebcde/skosify/skosify.py#L691-L705
def cleanup_unreachable(rdf): """Remove triples which cannot be reached from the concepts by graph traversal.""" all_subjects = set(rdf.subjects()) logging.debug("total subject resources: %d", len(all_subjects)) reachable = find_reachable(rdf, SKOS.Concept) nonreachable = all_subjects - reachable logging.debug("deleting %s non-reachable resources", len(nonreachable)) for subj in nonreachable: delete_uri(rdf, subj)
[ "def", "cleanup_unreachable", "(", "rdf", ")", ":", "all_subjects", "=", "set", "(", "rdf", ".", "subjects", "(", ")", ")", "logging", ".", "debug", "(", "\"total subject resources: %d\"", ",", "len", "(", "all_subjects", ")", ")", "reachable", "=", "find_re...
Remove triples which cannot be reached from the concepts by graph traversal.
[ "Remove", "triples", "which", "cannot", "be", "reached", "from", "the", "concepts", "by", "graph", "traversal", "." ]
python
train
linkedin/Zopkio
zopkio/deployer.py
https://github.com/linkedin/Zopkio/blob/a06e35a884cd26eedca0aac8ba6b9b40c417a01c/zopkio/deployer.py#L236-L246
def fetch_logs(self, unique_id, logs, directory, pattern=constants.FILTER_NAME_ALLOW_NONE): """ Copies logs from the remote host that the process is running on to the provided directory :Parameter unique_id the unique_id of the process in question :Parameter logs a list of logs given by absolute path from the remote host :Parameter directory the local directory to store the copied logs :Parameter pattern a pattern to apply to files to restrict the set of logs copied """ hostname = self.processes[unique_id].hostname install_path = self.processes[unique_id].install_path self.fetch_logs_from_host(hostname, install_path, unique_id, logs, directory, pattern)
[ "def", "fetch_logs", "(", "self", ",", "unique_id", ",", "logs", ",", "directory", ",", "pattern", "=", "constants", ".", "FILTER_NAME_ALLOW_NONE", ")", ":", "hostname", "=", "self", ".", "processes", "[", "unique_id", "]", ".", "hostname", "install_path", "...
Copies logs from the remote host that the process is running on to the provided directory :Parameter unique_id the unique_id of the process in question :Parameter logs a list of logs given by absolute path from the remote host :Parameter directory the local directory to store the copied logs :Parameter pattern a pattern to apply to files to restrict the set of logs copied
[ "Copies", "logs", "from", "the", "remote", "host", "that", "the", "process", "is", "running", "on", "to", "the", "provided", "directory" ]
python
train
Kane610/axis
axis/port_cgi.py
https://github.com/Kane610/axis/blob/b2b44ce595c7b722b5e13eabcab7b91f048e1808/axis/port_cgi.py#L92-L96
def name(self) -> str: """Return name relevant to direction.""" if self.direction == DIRECTION_IN: return self.raw.get('Input.Name', '') return self.raw.get('Output.Name', '')
[ "def", "name", "(", "self", ")", "->", "str", ":", "if", "self", ".", "direction", "==", "DIRECTION_IN", ":", "return", "self", ".", "raw", ".", "get", "(", "'Input.Name'", ",", "''", ")", "return", "self", ".", "raw", ".", "get", "(", "'Output.Name'...
Return name relevant to direction.
[ "Return", "name", "relevant", "to", "direction", "." ]
python
train
pln-fing-udelar/fast-krippendorff
krippendorff/krippendorff.py
https://github.com/pln-fing-udelar/fast-krippendorff/blob/fbc983f206d41f76a6e8da8cabd7114941634420/krippendorff/krippendorff.py#L88-L110
def _distances(value_domain, distance_metric, n_v): """Distances of the different possible values. Parameters ---------- value_domain : array_like, with shape (V,) Possible values V the units can take. If the level of measurement is not nominal, it must be ordered. distance_metric : callable Callable that return the distance of two given values. n_v : ndarray, with shape (V,) Number of pairable elements for each value. Returns ------- d : ndarray, with shape (V, V) Distance matrix for each value pair. """ return np.array([[distance_metric(v1, v2, i1=i1, i2=i2, n_v=n_v) for i2, v2 in enumerate(value_domain)] for i1, v1 in enumerate(value_domain)])
[ "def", "_distances", "(", "value_domain", ",", "distance_metric", ",", "n_v", ")", ":", "return", "np", ".", "array", "(", "[", "[", "distance_metric", "(", "v1", ",", "v2", ",", "i1", "=", "i1", ",", "i2", "=", "i2", ",", "n_v", "=", "n_v", ")", ...
Distances of the different possible values. Parameters ---------- value_domain : array_like, with shape (V,) Possible values V the units can take. If the level of measurement is not nominal, it must be ordered. distance_metric : callable Callable that return the distance of two given values. n_v : ndarray, with shape (V,) Number of pairable elements for each value. Returns ------- d : ndarray, with shape (V, V) Distance matrix for each value pair.
[ "Distances", "of", "the", "different", "possible", "values", "." ]
python
valid
genialis/resolwe
resolwe/flow/signals.py
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/signals.py#L48-L61
def delete_relation(sender, instance, **kwargs): """Delete the Relation object when the last Entity is removed.""" def process_signal(relation_id): """Get the relation and delete it if it has no entities left.""" try: relation = Relation.objects.get(pk=relation_id) except Relation.DoesNotExist: return if relation.entities.count() == 0: relation.delete() # Wait for partitions to be recreated. transaction.on_commit(lambda: process_signal(instance.relation_id))
[ "def", "delete_relation", "(", "sender", ",", "instance", ",", "*", "*", "kwargs", ")", ":", "def", "process_signal", "(", "relation_id", ")", ":", "\"\"\"Get the relation and delete it if it has no entities left.\"\"\"", "try", ":", "relation", "=", "Relation", ".", ...
Delete the Relation object when the last Entity is removed.
[ "Delete", "the", "Relation", "object", "when", "the", "last", "Entity", "is", "removed", "." ]
python
train
tomplus/kubernetes_asyncio
kubernetes_asyncio/client/api/core_v1_api.py
https://github.com/tomplus/kubernetes_asyncio/blob/f9ab15317ec921409714c7afef11aeb0f579985d/kubernetes_asyncio/client/api/core_v1_api.py#L483-L504
def connect_delete_node_proxy(self, name, **kwargs): # noqa: E501 """connect_delete_node_proxy # noqa: E501 connect DELETE requests to proxy of Node # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.connect_delete_node_proxy(name, async_req=True) >>> result = thread.get() :param async_req bool :param str name: name of the NodeProxyOptions (required) :param str path: Path is the URL path to use for the current proxy request to node. :return: str If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.connect_delete_node_proxy_with_http_info(name, **kwargs) # noqa: E501 else: (data) = self.connect_delete_node_proxy_with_http_info(name, **kwargs) # noqa: E501 return data
[ "def", "connect_delete_node_proxy", "(", "self", ",", "name", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "...
connect_delete_node_proxy # noqa: E501 connect DELETE requests to proxy of Node # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.connect_delete_node_proxy(name, async_req=True) >>> result = thread.get() :param async_req bool :param str name: name of the NodeProxyOptions (required) :param str path: Path is the URL path to use for the current proxy request to node. :return: str If the method is called asynchronously, returns the request thread.
[ "connect_delete_node_proxy", "#", "noqa", ":", "E501" ]
python
train
ehansis/ozelot
ozelot/etl/util.py
https://github.com/ehansis/ozelot/blob/948675e02eb6fca940450f5cb814f53e97159e5b/ozelot/etl/util.py#L130-L161
def sanitize(s, normalize_whitespace=True, normalize_unicode=True, form='NFKC', enforce_encoding=True, encoding='utf-8'): """Normalize a string Args: s (unicode string): input unicode string normalize_whitespace (bool): if True, normalize all whitespace to single spaces (including newlines), strip whitespace at start/end normalize_unicode (bool): if True, normalize unicode form to 'form' form (str): unicode form enforce_encoding (bool): if True, encode string to target encoding and re-decode, ignoring errors and stripping all characters not part of the encoding encoding (str): target encoding for the above Returns: str: unicode output string """ if enforce_encoding: s = s.encode(encoding, errors='ignore').decode(encoding, errors='ignore') if normalize_unicode: s = unicodedata.normalize(form, s) if normalize_whitespace: s = re.sub(r'\s+', ' ', s).strip() return s
[ "def", "sanitize", "(", "s", ",", "normalize_whitespace", "=", "True", ",", "normalize_unicode", "=", "True", ",", "form", "=", "'NFKC'", ",", "enforce_encoding", "=", "True", ",", "encoding", "=", "'utf-8'", ")", ":", "if", "enforce_encoding", ":", "s", "...
Normalize a string Args: s (unicode string): input unicode string normalize_whitespace (bool): if True, normalize all whitespace to single spaces (including newlines), strip whitespace at start/end normalize_unicode (bool): if True, normalize unicode form to 'form' form (str): unicode form enforce_encoding (bool): if True, encode string to target encoding and re-decode, ignoring errors and stripping all characters not part of the encoding encoding (str): target encoding for the above Returns: str: unicode output string
[ "Normalize", "a", "string" ]
python
train
Jammy2211/PyAutoLens
autolens/data/array/grids.py
https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/array/grids.py#L907-L919
def array_2d_from_array_1d(self, padded_array_1d): """ Map a padded 1D array of values to its original 2D array, trimming all edge values. Parameters ----------- padded_array_1d : ndarray A 1D array of values which were computed using the *PaddedRegularGrid*. """ padded_array_2d = self.map_to_2d_keep_padded(padded_array_1d) pad_size_0 = self.mask.shape[0] - self.image_shape[0] pad_size_1 = self.mask.shape[1] - self.image_shape[1] return (padded_array_2d[pad_size_0 // 2:self.mask.shape[0] - pad_size_0 // 2, pad_size_1 // 2:self.mask.shape[1] - pad_size_1 // 2])
[ "def", "array_2d_from_array_1d", "(", "self", ",", "padded_array_1d", ")", ":", "padded_array_2d", "=", "self", ".", "map_to_2d_keep_padded", "(", "padded_array_1d", ")", "pad_size_0", "=", "self", ".", "mask", ".", "shape", "[", "0", "]", "-", "self", ".", ...
Map a padded 1D array of values to its original 2D array, trimming all edge values. Parameters ----------- padded_array_1d : ndarray A 1D array of values which were computed using the *PaddedRegularGrid*.
[ "Map", "a", "padded", "1D", "array", "of", "values", "to", "its", "original", "2D", "array", "trimming", "all", "edge", "values", "." ]
python
valid
senseobservationsystems/commonsense-python-lib
senseapi.py
https://github.com/senseobservationsystems/commonsense-python-lib/blob/aac59a1751ef79eb830b3ca1fab6ef2c83931f87/senseapi.py#L1063-L1076
def UsersChangePassword (self, current_password, new_password): """ Change the password for the current user @param current_password (string) - md5 hash of the current password of the user @param new_password (string) - md5 hash of the new password of the user (make sure to doublecheck!) @return (bool) - Boolean indicating whether ChangePassword was successful. """ if self.__SenseApiCall__('/change_password', "POST", {"current_password":current_password, "new_password":new_password}): return True else: self.__error__ = "api call unsuccessful" return False
[ "def", "UsersChangePassword", "(", "self", ",", "current_password", ",", "new_password", ")", ":", "if", "self", ".", "__SenseApiCall__", "(", "'/change_password'", ",", "\"POST\"", ",", "{", "\"current_password\"", ":", "current_password", ",", "\"new_password\"", ...
Change the password for the current user @param current_password (string) - md5 hash of the current password of the user @param new_password (string) - md5 hash of the new password of the user (make sure to doublecheck!) @return (bool) - Boolean indicating whether ChangePassword was successful.
[ "Change", "the", "password", "for", "the", "current", "user" ]
python
train
SHDShim/pytheos
pytheos/eqn_bm3.py
https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_bm3.py#L184-L202
def cal_g_bm3(p, g, k): """ calculate shear modulus at given pressure :param p: pressure :param g: [g0, g0p] :param k: [v0, k0, k0p] :return: shear modulus at high pressure """ v = cal_v_bm3(p, k) v0 = k[0] k0 = k[1] kp = k[2] g0 = g[0] gp = g[1] f = 0.5 * ((v / v0)**(-2. / 3.) - 1.) return (1. + 2. * f)**(5. / 2.) * (g0 + (3. * k0 * gp - 5. * g0) * f + (6. * k0 * gp - 24. * k0 - 14. * g0 + 9. / 2. * k0 * kp) * f**2.)
[ "def", "cal_g_bm3", "(", "p", ",", "g", ",", "k", ")", ":", "v", "=", "cal_v_bm3", "(", "p", ",", "k", ")", "v0", "=", "k", "[", "0", "]", "k0", "=", "k", "[", "1", "]", "kp", "=", "k", "[", "2", "]", "g0", "=", "g", "[", "0", "]", ...
calculate shear modulus at given pressure :param p: pressure :param g: [g0, g0p] :param k: [v0, k0, k0p] :return: shear modulus at high pressure
[ "calculate", "shear", "modulus", "at", "given", "pressure" ]
python
train
totalgood/nlpia
src/nlpia/transcoders.py
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/transcoders.py#L295-L327
def fix_hunspell_json(badjson_path='en_us.json', goodjson_path='en_us_fixed.json'): """Fix the invalid hunspellToJSON.py json format by inserting double-quotes in list of affix strings Args: badjson_path (str): path to input json file that doesn't properly quote goodjson_path (str): path to output json file with properly quoted strings in list of affixes Returns: list of all words with all possible affixes in *.txt format (simplified .dic format) References: Syed Faisal Ali 's Hunspell dic parser: https://github.com/SyedFaisalAli/HunspellToJSON """ with open(badjson_path, 'r') as fin: with open(goodjson_path, 'w') as fout: for i, line in enumerate(fin): line2 = regex.sub(r'\[(\w)', r'["\1', line) line2 = regex.sub(r'(\w)\]', r'\1"]', line2) line2 = regex.sub(r'(\w),(\w)', r'\1","\2', line2) fout.write(line2) with open(goodjson_path, 'r') as fin: words = [] with open(goodjson_path + '.txt', 'w') as fout: hunspell = json.load(fin) for word, affixes in hunspell['words'].items(): words += [word] fout.write(word + '\n') for affix in affixes: words += [affix] fout.write(affix + '\n') return words
[ "def", "fix_hunspell_json", "(", "badjson_path", "=", "'en_us.json'", ",", "goodjson_path", "=", "'en_us_fixed.json'", ")", ":", "with", "open", "(", "badjson_path", ",", "'r'", ")", "as", "fin", ":", "with", "open", "(", "goodjson_path", ",", "'w'", ")", "a...
Fix the invalid hunspellToJSON.py json format by inserting double-quotes in list of affix strings Args: badjson_path (str): path to input json file that doesn't properly quote goodjson_path (str): path to output json file with properly quoted strings in list of affixes Returns: list of all words with all possible affixes in *.txt format (simplified .dic format) References: Syed Faisal Ali 's Hunspell dic parser: https://github.com/SyedFaisalAli/HunspellToJSON
[ "Fix", "the", "invalid", "hunspellToJSON", ".", "py", "json", "format", "by", "inserting", "double", "-", "quotes", "in", "list", "of", "affix", "strings" ]
python
train
jhermann/rudiments
src/rudiments/reamed/click.py
https://github.com/jhermann/rudiments/blob/028ec7237946115c7b18e50557cbc5f6b824653e/src/rudiments/reamed/click.py#L137-L161
def locations(self, exists=True): """ Return the location of the config file(s). A given directory will be scanned for ``*.conf`` files, in alphabetical order. Any duplicates will be eliminated. If ``exists`` is True, only existing configuration locations are returned. """ result = [] for config_files in self.config_paths: if not config_files: continue if os.path.isdir(config_files): config_files = [os.path.join(config_files, i) for i in sorted(os.listdir(config_files)) if i.endswith('.conf')] else: config_files = [config_files] for config_file in config_files: if not exists or os.path.exists(config_file): config_file = os.path.abspath(config_file) if config_file in result: result.remove(config_file) result.append(config_file) return result
[ "def", "locations", "(", "self", ",", "exists", "=", "True", ")", ":", "result", "=", "[", "]", "for", "config_files", "in", "self", ".", "config_paths", ":", "if", "not", "config_files", ":", "continue", "if", "os", ".", "path", ".", "isdir", "(", "...
Return the location of the config file(s). A given directory will be scanned for ``*.conf`` files, in alphabetical order. Any duplicates will be eliminated. If ``exists`` is True, only existing configuration locations are returned.
[ "Return", "the", "location", "of", "the", "config", "file", "(", "s", ")", "." ]
python
train
pyparsing/pyparsing
examples/pymicko.py
https://github.com/pyparsing/pyparsing/blob/f0264bd8d1a548a50b3e5f7d99cfefd577942d14/examples/pymicko.py#L766-L770
def function_begin(self): """Inserts function name label and function frame initialization""" self.newline_label(self.shared.function_name, False, True) self.push("%14") self.move("%15", "%14")
[ "def", "function_begin", "(", "self", ")", ":", "self", ".", "newline_label", "(", "self", ".", "shared", ".", "function_name", ",", "False", ",", "True", ")", "self", ".", "push", "(", "\"%14\"", ")", "self", ".", "move", "(", "\"%15\"", ",", "\"%14\"...
Inserts function name label and function frame initialization
[ "Inserts", "function", "name", "label", "and", "function", "frame", "initialization" ]
python
train
inveniosoftware-contrib/invenio-workflows
invenio_workflows/tasks.py
https://github.com/inveniosoftware-contrib/invenio-workflows/blob/9c09fd29509a3db975ac2aba337e6760d8cfd3c2/invenio_workflows/tasks.py#L81-L103
def resume(oid, restart_point="continue_next", **kwargs): """Continue workflow for given WorkflowObject id (oid). Depending on `start_point` it may start from previous, current or next task. Special custom keyword arguments can be given to the workflow engine in order to pass certain variables to the tasks in the workflow execution, such as a task-id from BibSched, the current user etc. :param oid: id of WorkflowObject to run. :type oid: str :param start_point: where should the workflow start from? One of: * restart_prev: will restart from the previous task * continue_next: will continue to the next task * restart_task: will restart the current task :type start_point: str :return: UUID of the workflow engine that ran the workflow. """ from .worker_engine import continue_worker return text_type(continue_worker(oid, restart_point, **kwargs).uuid)
[ "def", "resume", "(", "oid", ",", "restart_point", "=", "\"continue_next\"", ",", "*", "*", "kwargs", ")", ":", "from", ".", "worker_engine", "import", "continue_worker", "return", "text_type", "(", "continue_worker", "(", "oid", ",", "restart_point", ",", "*"...
Continue workflow for given WorkflowObject id (oid). Depending on `start_point` it may start from previous, current or next task. Special custom keyword arguments can be given to the workflow engine in order to pass certain variables to the tasks in the workflow execution, such as a task-id from BibSched, the current user etc. :param oid: id of WorkflowObject to run. :type oid: str :param start_point: where should the workflow start from? One of: * restart_prev: will restart from the previous task * continue_next: will continue to the next task * restart_task: will restart the current task :type start_point: str :return: UUID of the workflow engine that ran the workflow.
[ "Continue", "workflow", "for", "given", "WorkflowObject", "id", "(", "oid", ")", "." ]
python
train
xiaocong/uiautomator
uiautomator/__init__.py
https://github.com/xiaocong/uiautomator/blob/9a0c892ffd056713f91aa2153d1533c5b0553a1c/uiautomator/__init__.py#L670-L683
def open(self): ''' Open notification or quick settings. Usage: d.open.notification() d.open.quick_settings() ''' @param_to_property(action=["notification", "quick_settings"]) def _open(action): if action == "notification": return self.server.jsonrpc.openNotification() else: return self.server.jsonrpc.openQuickSettings() return _open
[ "def", "open", "(", "self", ")", ":", "@", "param_to_property", "(", "action", "=", "[", "\"notification\"", ",", "\"quick_settings\"", "]", ")", "def", "_open", "(", "action", ")", ":", "if", "action", "==", "\"notification\"", ":", "return", "self", ".",...
Open notification or quick settings. Usage: d.open.notification() d.open.quick_settings()
[ "Open", "notification", "or", "quick", "settings", ".", "Usage", ":", "d", ".", "open", ".", "notification", "()", "d", ".", "open", ".", "quick_settings", "()" ]
python
train
gboeing/osmnx
osmnx/core.py
https://github.com/gboeing/osmnx/blob/be59fd313bcb68af8fc79242c56194f1247e26e2/osmnx/core.py#L1885-L1919
def graph_from_file(filename, bidirectional=False, simplify=True, retain_all=False, name='unnamed'): """ Create a networkx graph from OSM data in an XML file. Parameters ---------- filename : string the name of a file containing OSM XML data bidirectional : bool if True, create bidirectional edges for one-way streets simplify : bool if True, simplify the graph topology retain_all : bool if True, return the entire graph even if it is not connected name : string the name of the graph Returns ------- networkx multidigraph """ # transmogrify file of OSM XML data into JSON response_jsons = [overpass_json_from_file(filename)] # create graph using this response JSON G = create_graph(response_jsons, bidirectional=bidirectional, retain_all=retain_all, name=name) # simplify the graph topology as the last step. if simplify: G = simplify_graph(G) log('graph_from_file() returning graph with {:,} nodes and {:,} edges'.format(len(list(G.nodes())), len(list(G.edges())))) return G
[ "def", "graph_from_file", "(", "filename", ",", "bidirectional", "=", "False", ",", "simplify", "=", "True", ",", "retain_all", "=", "False", ",", "name", "=", "'unnamed'", ")", ":", "# transmogrify file of OSM XML data into JSON", "response_jsons", "=", "[", "ove...
Create a networkx graph from OSM data in an XML file. Parameters ---------- filename : string the name of a file containing OSM XML data bidirectional : bool if True, create bidirectional edges for one-way streets simplify : bool if True, simplify the graph topology retain_all : bool if True, return the entire graph even if it is not connected name : string the name of the graph Returns ------- networkx multidigraph
[ "Create", "a", "networkx", "graph", "from", "OSM", "data", "in", "an", "XML", "file", "." ]
python
train
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/matrixpilot.py
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/matrixpilot.py#L12903-L12911
def message_interval_send(self, message_id, interval_us, force_mavlink1=False): ''' This interface replaces DATA_STREAM message_id : The ID of the requested MAVLink message. v1.0 is limited to 254 messages. (uint16_t) interval_us : The interval between two messages, in microseconds. A value of -1 indicates this stream is disabled, 0 indicates it is not available, > 0 indicates the interval at which it is sent. (int32_t) ''' return self.send(self.message_interval_encode(message_id, interval_us), force_mavlink1=force_mavlink1)
[ "def", "message_interval_send", "(", "self", ",", "message_id", ",", "interval_us", ",", "force_mavlink1", "=", "False", ")", ":", "return", "self", ".", "send", "(", "self", ".", "message_interval_encode", "(", "message_id", ",", "interval_us", ")", ",", "for...
This interface replaces DATA_STREAM message_id : The ID of the requested MAVLink message. v1.0 is limited to 254 messages. (uint16_t) interval_us : The interval between two messages, in microseconds. A value of -1 indicates this stream is disabled, 0 indicates it is not available, > 0 indicates the interval at which it is sent. (int32_t)
[ "This", "interface", "replaces", "DATA_STREAM" ]
python
train
googleapis/gax-python
google/gax/api_callable.py
https://github.com/googleapis/gax-python/blob/309aedfcfd48e4c8fa22dd60e9c84c3cc71bb20e/google/gax/api_callable.py#L216-L360
def construct_settings( service_name, client_config, config_override, retry_names, bundle_descriptors=None, page_descriptors=None, metrics_headers=(), kwargs=None): """Constructs a dictionary mapping method names to _CallSettings. The ``client_config`` parameter is parsed from a client configuration JSON file of the form: .. code-block:: json { "interfaces": { "google.fake.v1.ServiceName": { "retry_codes": { "idempotent": ["UNAVAILABLE", "DEADLINE_EXCEEDED"], "non_idempotent": [] }, "retry_params": { "default": { "initial_retry_delay_millis": 100, "retry_delay_multiplier": 1.2, "max_retry_delay_millis": 1000, "initial_rpc_timeout_millis": 2000, "rpc_timeout_multiplier": 1.5, "max_rpc_timeout_millis": 30000, "total_timeout_millis": 45000 } }, "methods": { "CreateFoo": { "retry_codes_name": "idempotent", "retry_params_name": "default", "timeout_millis": 30000 }, "Publish": { "retry_codes_name": "non_idempotent", "retry_params_name": "default", "bundling": { "element_count_threshold": 40, "element_count_limit": 200, "request_byte_threshold": 90000, "request_byte_limit": 100000, "delay_threshold_millis": 100 } } } } } } Args: service_name (str): The fully-qualified name of this service, used as a key into the client config file (in the example above, this value would be ``google.fake.v1.ServiceName``). client_config (dict): A dictionary parsed from the standard API client config file. bundle_descriptors (Mapping[str, BundleDescriptor]): A dictionary of method names to BundleDescriptor objects for methods that are bundling-enabled. page_descriptors (Mapping[str, PageDescriptor]): A dictionary of method names to PageDescriptor objects for methods that are page streaming-enabled. config_override (str): A dictionary in the same structure of client_config to override the settings. Usually client_config is supplied from the default config and config_override will be specified by users. retry_names (Mapping[str, object]): A dictionary mapping the strings referring to response status codes to the Python objects representing those codes. metrics_headers (Mapping[str, str]): Dictionary of headers to be passed for analytics. Sent as a dictionary; eventually becomes a space-separated string (e.g. 'foo/1.0.0 bar/3.14.1'). kwargs (dict): The keyword arguments to be passed to the API calls. Returns: dict: A dictionary mapping method names to _CallSettings. Raises: KeyError: If the configuration for the service in question cannot be located in the provided ``client_config``. """ # pylint: disable=too-many-locals # pylint: disable=protected-access defaults = {} bundle_descriptors = bundle_descriptors or {} page_descriptors = page_descriptors or {} kwargs = kwargs or {} # Sanity check: It is possible that we got this far but some headers # were specified with an older library, which sends them as... # kwargs={'metadata': [('x-goog-api-client', 'foo/1.0 bar/3.0')]} # # Note: This is the final format we will send down to GRPC shortly. # # Remove any x-goog-api-client header that may have been present # in the metadata list. if 'metadata' in kwargs: kwargs['metadata'] = [value for value in kwargs['metadata'] if value[0].lower() != 'x-goog-api-client'] # Fill out the metrics headers with GAX and GRPC info, and convert # to a string in the format that the GRPC layer expects. kwargs.setdefault('metadata', []) kwargs['metadata'].append( ('x-goog-api-client', metrics.stringify(metrics.fill(metrics_headers))) ) try: service_config = client_config['interfaces'][service_name] except KeyError: raise KeyError('Client configuration not found for service: {}' .format(service_name)) overrides = config_override.get('interfaces', {}).get(service_name, {}) for method in service_config.get('methods'): method_config = service_config['methods'][method] overriding_method = overrides.get('methods', {}).get(method, {}) snake_name = _upper_camel_to_lower_under(method) if overriding_method and overriding_method.get('timeout_millis'): timeout = overriding_method['timeout_millis'] else: timeout = method_config['timeout_millis'] timeout /= _MILLIS_PER_SECOND bundle_descriptor = bundle_descriptors.get(snake_name) bundling_config = method_config.get('bundling', None) if overriding_method and 'bundling' in overriding_method: bundling_config = overriding_method['bundling'] bundler = _construct_bundling(bundling_config, bundle_descriptor) retry_options = _merge_retry_options( _construct_retry(method_config, service_config['retry_codes'], service_config['retry_params'], retry_names), _construct_retry(overriding_method, overrides.get('retry_codes'), overrides.get('retry_params'), retry_names)) defaults[snake_name] = gax._CallSettings( timeout=timeout, retry=retry_options, page_descriptor=page_descriptors.get(snake_name), bundler=bundler, bundle_descriptor=bundle_descriptor, kwargs=kwargs) return defaults
[ "def", "construct_settings", "(", "service_name", ",", "client_config", ",", "config_override", ",", "retry_names", ",", "bundle_descriptors", "=", "None", ",", "page_descriptors", "=", "None", ",", "metrics_headers", "=", "(", ")", ",", "kwargs", "=", "None", "...
Constructs a dictionary mapping method names to _CallSettings. The ``client_config`` parameter is parsed from a client configuration JSON file of the form: .. code-block:: json { "interfaces": { "google.fake.v1.ServiceName": { "retry_codes": { "idempotent": ["UNAVAILABLE", "DEADLINE_EXCEEDED"], "non_idempotent": [] }, "retry_params": { "default": { "initial_retry_delay_millis": 100, "retry_delay_multiplier": 1.2, "max_retry_delay_millis": 1000, "initial_rpc_timeout_millis": 2000, "rpc_timeout_multiplier": 1.5, "max_rpc_timeout_millis": 30000, "total_timeout_millis": 45000 } }, "methods": { "CreateFoo": { "retry_codes_name": "idempotent", "retry_params_name": "default", "timeout_millis": 30000 }, "Publish": { "retry_codes_name": "non_idempotent", "retry_params_name": "default", "bundling": { "element_count_threshold": 40, "element_count_limit": 200, "request_byte_threshold": 90000, "request_byte_limit": 100000, "delay_threshold_millis": 100 } } } } } } Args: service_name (str): The fully-qualified name of this service, used as a key into the client config file (in the example above, this value would be ``google.fake.v1.ServiceName``). client_config (dict): A dictionary parsed from the standard API client config file. bundle_descriptors (Mapping[str, BundleDescriptor]): A dictionary of method names to BundleDescriptor objects for methods that are bundling-enabled. page_descriptors (Mapping[str, PageDescriptor]): A dictionary of method names to PageDescriptor objects for methods that are page streaming-enabled. config_override (str): A dictionary in the same structure of client_config to override the settings. Usually client_config is supplied from the default config and config_override will be specified by users. retry_names (Mapping[str, object]): A dictionary mapping the strings referring to response status codes to the Python objects representing those codes. metrics_headers (Mapping[str, str]): Dictionary of headers to be passed for analytics. Sent as a dictionary; eventually becomes a space-separated string (e.g. 'foo/1.0.0 bar/3.14.1'). kwargs (dict): The keyword arguments to be passed to the API calls. Returns: dict: A dictionary mapping method names to _CallSettings. Raises: KeyError: If the configuration for the service in question cannot be located in the provided ``client_config``.
[ "Constructs", "a", "dictionary", "mapping", "method", "names", "to", "_CallSettings", "." ]
python
train
rainwoodman/sharedmem
contrib/array.py
https://github.com/rainwoodman/sharedmem/blob/b23e59c1ed0e28f7b6c96c17a04d55c700e06e3a/contrib/array.py#L201-L205
def adapt(cls, source, template): """ adapt source to a packarray according to the layout of template """ if not isinstance(template, packarray): raise TypeError('template must be a packarray') return cls(source, template.start, template.end)
[ "def", "adapt", "(", "cls", ",", "source", ",", "template", ")", ":", "if", "not", "isinstance", "(", "template", ",", "packarray", ")", ":", "raise", "TypeError", "(", "'template must be a packarray'", ")", "return", "cls", "(", "source", ",", "template", ...
adapt source to a packarray according to the layout of template
[ "adapt", "source", "to", "a", "packarray", "according", "to", "the", "layout", "of", "template" ]
python
valid
horazont/aioxmpp
aioxmpp/pubsub/service.py
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/pubsub/service.py#L985-L1020
def change_node_subscriptions(self, jid, node, subscriptions_to_set): """ Update the subscriptions at a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the node to modify :type node: :class:`str` :param subscriptions_to_set: The subscriptions to set at the node. :type subscriptions_to_set: :class:`~collections.abc.Iterable` of tuples consisting of the JID to (un)subscribe and the subscription level to use. :raises aioxmpp.errors.XMPPError: as returned by the service `subscriptions_to_set` must be an iterable of pairs (`jid`, `subscription`), where the `jid` indicates the JID for which the `subscription` is to be set. """ iq = aioxmpp.stanza.IQ( type_=aioxmpp.structs.IQType.SET, to=jid, payload=pubsub_xso.OwnerRequest( pubsub_xso.OwnerSubscriptions( node, subscriptions=[ pubsub_xso.OwnerSubscription( jid, subscription ) for jid, subscription in subscriptions_to_set ] ) ) ) yield from self.client.send(iq)
[ "def", "change_node_subscriptions", "(", "self", ",", "jid", ",", "node", ",", "subscriptions_to_set", ")", ":", "iq", "=", "aioxmpp", ".", "stanza", ".", "IQ", "(", "type_", "=", "aioxmpp", ".", "structs", ".", "IQType", ".", "SET", ",", "to", "=", "j...
Update the subscriptions at a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the node to modify :type node: :class:`str` :param subscriptions_to_set: The subscriptions to set at the node. :type subscriptions_to_set: :class:`~collections.abc.Iterable` of tuples consisting of the JID to (un)subscribe and the subscription level to use. :raises aioxmpp.errors.XMPPError: as returned by the service `subscriptions_to_set` must be an iterable of pairs (`jid`, `subscription`), where the `jid` indicates the JID for which the `subscription` is to be set.
[ "Update", "the", "subscriptions", "at", "a", "node", "." ]
python
train
igorcoding/asynctnt-queue
asynctnt_queue/tube.py
https://github.com/igorcoding/asynctnt-queue/blob/75719b2dd27e8314ae924aea6a7a85be8f48ecc5/asynctnt_queue/tube.py#L141-L154
async def release(self, task_id, *, delay=None): """ Release task (return to queue) with delay if specified :param task_id: Task id :param delay: Time in seconds before task will become ready again :return: Task instance """ opts = {} if delay is not None: opts['delay'] = delay args = (task_id, opts) res = await self.conn.call(self.__funcs['release'], args) return self._create_task(res.body)
[ "async", "def", "release", "(", "self", ",", "task_id", ",", "*", ",", "delay", "=", "None", ")", ":", "opts", "=", "{", "}", "if", "delay", "is", "not", "None", ":", "opts", "[", "'delay'", "]", "=", "delay", "args", "=", "(", "task_id", ",", ...
Release task (return to queue) with delay if specified :param task_id: Task id :param delay: Time in seconds before task will become ready again :return: Task instance
[ "Release", "task", "(", "return", "to", "queue", ")", "with", "delay", "if", "specified" ]
python
train
zarr-developers/zarr
zarr/hierarchy.py
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/hierarchy.py#L368-L386
def group_keys(self): """Return an iterator over member names for groups only. Examples -------- >>> import zarr >>> g1 = zarr.group() >>> g2 = g1.create_group('foo') >>> g3 = g1.create_group('bar') >>> d1 = g1.create_dataset('baz', shape=100, chunks=10) >>> d2 = g1.create_dataset('quux', shape=200, chunks=20) >>> sorted(g1.group_keys()) ['bar', 'foo'] """ for key in sorted(listdir(self._store, self._path)): path = self._key_prefix + key if contains_group(self._store, path): yield key
[ "def", "group_keys", "(", "self", ")", ":", "for", "key", "in", "sorted", "(", "listdir", "(", "self", ".", "_store", ",", "self", ".", "_path", ")", ")", ":", "path", "=", "self", ".", "_key_prefix", "+", "key", "if", "contains_group", "(", "self", ...
Return an iterator over member names for groups only. Examples -------- >>> import zarr >>> g1 = zarr.group() >>> g2 = g1.create_group('foo') >>> g3 = g1.create_group('bar') >>> d1 = g1.create_dataset('baz', shape=100, chunks=10) >>> d2 = g1.create_dataset('quux', shape=200, chunks=20) >>> sorted(g1.group_keys()) ['bar', 'foo']
[ "Return", "an", "iterator", "over", "member", "names", "for", "groups", "only", "." ]
python
train
bcbio/bcbio-nextgen
bcbio/variation/prioritize.py
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/prioritize.py#L148-L161
def _calc_priority_filter(row, pops): """Calculate the priority filter based on external associated data. - Pass high/medium impact variants not found in population databases - Pass variants found in COSMIC or Clinvar provided they don't have two additional reasons to filter (found in multiple external populations) """ filters = [] passes = [] passes.extend(_find_known(row)) filters.extend(_known_populations(row, pops)) if len(filters) == 0 or (len(passes) > 0 and len(filters) < 2): passes.insert(0, "pass") return ",".join(passes + filters)
[ "def", "_calc_priority_filter", "(", "row", ",", "pops", ")", ":", "filters", "=", "[", "]", "passes", "=", "[", "]", "passes", ".", "extend", "(", "_find_known", "(", "row", ")", ")", "filters", ".", "extend", "(", "_known_populations", "(", "row", ",...
Calculate the priority filter based on external associated data. - Pass high/medium impact variants not found in population databases - Pass variants found in COSMIC or Clinvar provided they don't have two additional reasons to filter (found in multiple external populations)
[ "Calculate", "the", "priority", "filter", "based", "on", "external", "associated", "data", "." ]
python
train
JelteF/PyLaTeX
pylatex/table.py
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/table.py#L112-L129
def dumps(self): r"""Turn the Latex Object into a string in Latex format.""" string = "" if self.row_height is not None: row_height = Command('renewcommand', arguments=[ NoEscape(r'\arraystretch'), self.row_height]) string += row_height.dumps() + '%\n' if self.col_space is not None: col_space = Command('setlength', arguments=[ NoEscape(r'\tabcolsep'), self.col_space]) string += col_space.dumps() + '%\n' return string + super().dumps()
[ "def", "dumps", "(", "self", ")", ":", "string", "=", "\"\"", "if", "self", ".", "row_height", "is", "not", "None", ":", "row_height", "=", "Command", "(", "'renewcommand'", ",", "arguments", "=", "[", "NoEscape", "(", "r'\\arraystretch'", ")", ",", "sel...
r"""Turn the Latex Object into a string in Latex format.
[ "r", "Turn", "the", "Latex", "Object", "into", "a", "string", "in", "Latex", "format", "." ]
python
train
PMEAL/OpenPNM
openpnm/utils/Project.py
https://github.com/PMEAL/OpenPNM/blob/0547b5724ffedc0a593aae48639d36fe10e0baed/openpnm/utils/Project.py#L463-L478
def save_object(self, obj): r""" Saves the given object to a file Parameters ---------- obj : OpenPNM object The file to be saved. Depending on the object type, the file extension will be one of 'net', 'geo', 'phase', 'phys' or 'alg'. """ if not isinstance(obj, list): obj = [obj] for item in obj: filename = item.name + '.' + item.settings['prefix'] with open(filename, 'wb') as f: pickle.dump({item.name: item}, f)
[ "def", "save_object", "(", "self", ",", "obj", ")", ":", "if", "not", "isinstance", "(", "obj", ",", "list", ")", ":", "obj", "=", "[", "obj", "]", "for", "item", "in", "obj", ":", "filename", "=", "item", ".", "name", "+", "'.'", "+", "item", ...
r""" Saves the given object to a file Parameters ---------- obj : OpenPNM object The file to be saved. Depending on the object type, the file extension will be one of 'net', 'geo', 'phase', 'phys' or 'alg'.
[ "r", "Saves", "the", "given", "object", "to", "a", "file" ]
python
train
addisonlynch/iexfinance
iexfinance/stocks/base.py
https://github.com/addisonlynch/iexfinance/blob/40f0bdcc51b329031d06178020fd774494250456/iexfinance/stocks/base.py#L418-L441
def get_fund_ownership(self, **kwargs): """Fund Ownership Returns the top 10 fund holders, meaning any firm not defined as buy-side or sell-side such as mutual funds, pension funds, endowments, investment firms, and other large entities that manage funds on behalf of others. Reference: https://iexcloud.io/docs/api/#fund-ownership Data Weighting: ``10000`` per symbol per period Returns ------- list or pandas.DataFrame Stocks Fund Ownership endpoint data """ def fmt_p(out): out = {(symbol, owner["entityProperName"]): owner for symbol in out for owner in out[symbol]} return pd.DataFrame(out) return self._get_endpoint("fund-ownership", fmt_p=fmt_p, params=kwargs)
[ "def", "get_fund_ownership", "(", "self", ",", "*", "*", "kwargs", ")", ":", "def", "fmt_p", "(", "out", ")", ":", "out", "=", "{", "(", "symbol", ",", "owner", "[", "\"entityProperName\"", "]", ")", ":", "owner", "for", "symbol", "in", "out", "for",...
Fund Ownership Returns the top 10 fund holders, meaning any firm not defined as buy-side or sell-side such as mutual funds, pension funds, endowments, investment firms, and other large entities that manage funds on behalf of others. Reference: https://iexcloud.io/docs/api/#fund-ownership Data Weighting: ``10000`` per symbol per period Returns ------- list or pandas.DataFrame Stocks Fund Ownership endpoint data
[ "Fund", "Ownership", "Returns", "the", "top", "10", "fund", "holders", "meaning", "any", "firm", "not", "defined", "as", "buy", "-", "side", "or", "sell", "-", "side", "such", "as", "mutual", "funds", "pension", "funds", "endowments", "investment", "firms", ...
python
train
LCAV/pylocus
pylocus/opt_space.py
https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/opt_space.py#L222-L239
def getoptS(X, Y, M_E, E): ''' Find Sopt given X, Y ''' n, r = X.shape C = np.dot(np.dot(X.T, M_E), Y) C = C.flatten() A = np.zeros((r * r, r * r)) for i in range(r): for j in range(r): ind = j * r + i temp = np.dot( np.dot(X.T, np.dot(X[:, i, None], Y[:, j, None].T) * E), Y) A[:, ind] = temp.flatten() S = np.linalg.solve(A, C) return np.reshape(S, (r, r)).T
[ "def", "getoptS", "(", "X", ",", "Y", ",", "M_E", ",", "E", ")", ":", "n", ",", "r", "=", "X", ".", "shape", "C", "=", "np", ".", "dot", "(", "np", ".", "dot", "(", "X", ".", "T", ",", "M_E", ")", ",", "Y", ")", "C", "=", "C", ".", ...
Find Sopt given X, Y
[ "Find", "Sopt", "given", "X", "Y" ]
python
train
saltstack/salt
salt/modules/panos.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/panos.py#L724-L750
def get_jobs(state='all'): ''' List all jobs on the device. state The state of the jobs to display. Valid options are all, pending, or processed. Pending jobs are jobs that are currently in a running or waiting state. Processed jobs are jobs that have completed execution. CLI Example: .. code-block:: bash salt '*' panos.get_jobs salt '*' panos.get_jobs state=pending ''' if state.lower() == 'all': query = {'type': 'op', 'cmd': '<show><jobs><all></all></jobs></show>'} elif state.lower() == 'pending': query = {'type': 'op', 'cmd': '<show><jobs><pending></pending></jobs></show>'} elif state.lower() == 'processed': query = {'type': 'op', 'cmd': '<show><jobs><processed></processed></jobs></show>'} else: raise CommandExecutionError("The state parameter must be all, pending, or processed.") return __proxy__['panos.call'](query)
[ "def", "get_jobs", "(", "state", "=", "'all'", ")", ":", "if", "state", ".", "lower", "(", ")", "==", "'all'", ":", "query", "=", "{", "'type'", ":", "'op'", ",", "'cmd'", ":", "'<show><jobs><all></all></jobs></show>'", "}", "elif", "state", ".", "lower"...
List all jobs on the device. state The state of the jobs to display. Valid options are all, pending, or processed. Pending jobs are jobs that are currently in a running or waiting state. Processed jobs are jobs that have completed execution. CLI Example: .. code-block:: bash salt '*' panos.get_jobs salt '*' panos.get_jobs state=pending
[ "List", "all", "jobs", "on", "the", "device", "." ]
python
train
saltstack/salt
salt/states/glusterfs.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/glusterfs.py#L111-L222
def volume_present(name, bricks, stripe=False, replica=False, device_vg=False, transport='tcp', start=False, force=False, arbiter=False): ''' Ensure that the volume exists name name of the volume bricks list of brick paths replica replica count for volume arbiter use every third brick as arbiter (metadata only) .. versionadded:: 2019.2.0 start ensure that the volume is also started .. code-block:: yaml myvolume: glusterfs.volume_present: - bricks: - host1:/srv/gluster/drive1 - host2:/srv/gluster/drive2 Replicated Volume: glusterfs.volume_present: - name: volume2 - bricks: - host1:/srv/gluster/drive2 - host2:/srv/gluster/drive3 - replica: 2 - start: True Replicated Volume with arbiter brick: glusterfs.volume_present: - name: volume3 - bricks: - host1:/srv/gluster/drive2 - host2:/srv/gluster/drive3 - host3:/srv/gluster/drive4 - replica: 3 - arbiter: True - start: True ''' ret = {'name': name, 'changes': {}, 'comment': '', 'result': False} if suc.check_name(name, 'a-zA-Z0-9._-'): ret['comment'] = 'Invalid characters in volume name.' return ret volumes = __salt__['glusterfs.list_volumes']() if name not in volumes: if __opts__['test']: comment = 'Volume {0} will be created'.format(name) if start: comment += ' and started' ret['comment'] = comment ret['result'] = None return ret vol_created = __salt__['glusterfs.create_volume']( name, bricks, stripe, replica, device_vg, transport, start, force, arbiter) if not vol_created: ret['comment'] = 'Creation of volume {0} failed'.format(name) return ret old_volumes = volumes volumes = __salt__['glusterfs.list_volumes']() if name in volumes: ret['changes'] = {'new': volumes, 'old': old_volumes} ret['comment'] = 'Volume {0} is created'.format(name) else: ret['comment'] = 'Volume {0} already exists'.format(name) if start: if __opts__['test']: # volume already exists ret['comment'] = ret['comment'] + ' and will be started' ret['result'] = None return ret if int(__salt__['glusterfs.info']()[name]['status']) == 1: ret['result'] = True ret['comment'] = ret['comment'] + ' and is started' else: vol_started = __salt__['glusterfs.start_volume'](name) if vol_started: ret['result'] = True ret['comment'] = ret['comment'] + ' and is now started' if not ret['changes']: ret['changes'] = {'new': 'started', 'old': 'stopped'} else: ret['comment'] = ret['comment'] + ' but failed to start. Check logs for further information' return ret if __opts__['test']: ret['result'] = None else: ret['result'] = True return ret
[ "def", "volume_present", "(", "name", ",", "bricks", ",", "stripe", "=", "False", ",", "replica", "=", "False", ",", "device_vg", "=", "False", ",", "transport", "=", "'tcp'", ",", "start", "=", "False", ",", "force", "=", "False", ",", "arbiter", "=",...
Ensure that the volume exists name name of the volume bricks list of brick paths replica replica count for volume arbiter use every third brick as arbiter (metadata only) .. versionadded:: 2019.2.0 start ensure that the volume is also started .. code-block:: yaml myvolume: glusterfs.volume_present: - bricks: - host1:/srv/gluster/drive1 - host2:/srv/gluster/drive2 Replicated Volume: glusterfs.volume_present: - name: volume2 - bricks: - host1:/srv/gluster/drive2 - host2:/srv/gluster/drive3 - replica: 2 - start: True Replicated Volume with arbiter brick: glusterfs.volume_present: - name: volume3 - bricks: - host1:/srv/gluster/drive2 - host2:/srv/gluster/drive3 - host3:/srv/gluster/drive4 - replica: 3 - arbiter: True - start: True
[ "Ensure", "that", "the", "volume", "exists" ]
python
train
mitsei/dlkit
dlkit/json_/cataloging/managers.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/cataloging/managers.py#L384-L401
def get_catalog_hierarchy_design_session(self, proxy): """Gets the catalog hierarchy design session. arg: proxy (osid.proxy.Proxy): proxy return: (osid.cataloging.CatalogHierarchyDesignSession) - a ``CatalogHierarchyDesignSession`` raise: NullArgument - ``proxy`` is null raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_catalog_hierarchy_design()`` is ``false`` *compliance: optional -- This method must be implemented if ``supports_catalog_hierarchy_design()`` is ``true``.* """ if not self.supports_catalog_hierarchy_design(): raise errors.Unimplemented() # pylint: disable=no-member return sessions.CatalogHierarchyDesignSession(proxy=proxy, runtime=self._runtime)
[ "def", "get_catalog_hierarchy_design_session", "(", "self", ",", "proxy", ")", ":", "if", "not", "self", ".", "supports_catalog_hierarchy_design", "(", ")", ":", "raise", "errors", ".", "Unimplemented", "(", ")", "# pylint: disable=no-member", "return", "sessions", ...
Gets the catalog hierarchy design session. arg: proxy (osid.proxy.Proxy): proxy return: (osid.cataloging.CatalogHierarchyDesignSession) - a ``CatalogHierarchyDesignSession`` raise: NullArgument - ``proxy`` is null raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_catalog_hierarchy_design()`` is ``false`` *compliance: optional -- This method must be implemented if ``supports_catalog_hierarchy_design()`` is ``true``.*
[ "Gets", "the", "catalog", "hierarchy", "design", "session", "." ]
python
train
fake-name/ChromeController
ChromeController/Generator/Generated.py
https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/Generator/Generated.py#L3015-L3033
def DOMStorage_removeDOMStorageItem(self, storageId, key): """ Function path: DOMStorage.removeDOMStorageItem Domain: DOMStorage Method name: removeDOMStorageItem Parameters: Required arguments: 'storageId' (type: StorageId) -> No description 'key' (type: string) -> No description No return value. """ assert isinstance(key, (str,) ), "Argument 'key' must be of type '['str']'. Received type: '%s'" % type( key) subdom_funcs = self.synchronous_command('DOMStorage.removeDOMStorageItem', storageId=storageId, key=key) return subdom_funcs
[ "def", "DOMStorage_removeDOMStorageItem", "(", "self", ",", "storageId", ",", "key", ")", ":", "assert", "isinstance", "(", "key", ",", "(", "str", ",", ")", ")", ",", "\"Argument 'key' must be of type '['str']'. Received type: '%s'\"", "%", "type", "(", "key", ")...
Function path: DOMStorage.removeDOMStorageItem Domain: DOMStorage Method name: removeDOMStorageItem Parameters: Required arguments: 'storageId' (type: StorageId) -> No description 'key' (type: string) -> No description No return value.
[ "Function", "path", ":", "DOMStorage", ".", "removeDOMStorageItem", "Domain", ":", "DOMStorage", "Method", "name", ":", "removeDOMStorageItem", "Parameters", ":", "Required", "arguments", ":", "storageId", "(", "type", ":", "StorageId", ")", "-", ">", "No", "des...
python
train
erikrose/more-itertools
more_itertools/more.py
https://github.com/erikrose/more-itertools/blob/6a91b4e25c8e12fcf9fc2b53cf8ee0fba293e6f9/more_itertools/more.py#L1731-L1844
def islice_extended(iterable, *args): """An extension of :func:`itertools.islice` that supports negative values for *stop*, *start*, and *step*. >>> iterable = iter('abcdefgh') >>> list(islice_extended(iterable, -4, -1)) ['e', 'f', 'g'] Slices with negative values require some caching of *iterable*, but this function takes care to minimize the amount of memory required. For example, you can use a negative step with an infinite iterator: >>> from itertools import count >>> list(islice_extended(count(), 110, 99, -2)) [110, 108, 106, 104, 102, 100] """ s = slice(*args) start = s.start stop = s.stop if s.step == 0: raise ValueError('step argument must be a non-zero integer or None.') step = s.step or 1 it = iter(iterable) if step > 0: start = 0 if (start is None) else start if (start < 0): # Consume all but the last -start items cache = deque(enumerate(it, 1), maxlen=-start) len_iter = cache[-1][0] if cache else 0 # Adjust start to be positive i = max(len_iter + start, 0) # Adjust stop to be positive if stop is None: j = len_iter elif stop >= 0: j = min(stop, len_iter) else: j = max(len_iter + stop, 0) # Slice the cache n = j - i if n <= 0: return for index, item in islice(cache, 0, n, step): yield item elif (stop is not None) and (stop < 0): # Advance to the start position next(islice(it, start, start), None) # When stop is negative, we have to carry -stop items while # iterating cache = deque(islice(it, -stop), maxlen=-stop) for index, item in enumerate(it): cached_item = cache.popleft() if index % step == 0: yield cached_item cache.append(item) else: # When both start and stop are positive we have the normal case yield from islice(it, start, stop, step) else: start = -1 if (start is None) else start if (stop is not None) and (stop < 0): # Consume all but the last items n = -stop - 1 cache = deque(enumerate(it, 1), maxlen=n) len_iter = cache[-1][0] if cache else 0 # If start and stop are both negative they are comparable and # we can just slice. Otherwise we can adjust start to be negative # and then slice. if start < 0: i, j = start, stop else: i, j = min(start - len_iter, -1), None for index, item in list(cache)[i:j:step]: yield item else: # Advance to the stop position if stop is not None: m = stop + 1 next(islice(it, m, m), None) # stop is positive, so if start is negative they are not comparable # and we need the rest of the items. if start < 0: i = start n = None # stop is None and start is positive, so we just need items up to # the start index. elif stop is None: i = None n = start + 1 # Both stop and start are positive, so they are comparable. else: i = None n = start - stop if n <= 0: return cache = list(islice(it, n)) yield from cache[i::step]
[ "def", "islice_extended", "(", "iterable", ",", "*", "args", ")", ":", "s", "=", "slice", "(", "*", "args", ")", "start", "=", "s", ".", "start", "stop", "=", "s", ".", "stop", "if", "s", ".", "step", "==", "0", ":", "raise", "ValueError", "(", ...
An extension of :func:`itertools.islice` that supports negative values for *stop*, *start*, and *step*. >>> iterable = iter('abcdefgh') >>> list(islice_extended(iterable, -4, -1)) ['e', 'f', 'g'] Slices with negative values require some caching of *iterable*, but this function takes care to minimize the amount of memory required. For example, you can use a negative step with an infinite iterator: >>> from itertools import count >>> list(islice_extended(count(), 110, 99, -2)) [110, 108, 106, 104, 102, 100]
[ "An", "extension", "of", ":", "func", ":", "itertools", ".", "islice", "that", "supports", "negative", "values", "for", "*", "stop", "*", "*", "start", "*", "and", "*", "step", "*", "." ]
python
train
GoogleCloudPlatform/appengine-gcs-client
python/src/cloudstorage/cloudstorage_api.py
https://github.com/GoogleCloudPlatform/appengine-gcs-client/blob/d11078331ecd915d753c886e96a80133599f3f98/python/src/cloudstorage/cloudstorage_api.py#L47-L107
def open(filename, mode='r', content_type=None, options=None, read_buffer_size=storage_api.ReadBuffer.DEFAULT_BUFFER_SIZE, retry_params=None, _account_id=None, offset=0): """Opens a Google Cloud Storage file and returns it as a File-like object. Args: filename: A Google Cloud Storage filename of form '/bucket/filename'. mode: 'r' for reading mode. 'w' for writing mode. In reading mode, the file must exist. In writing mode, a file will be created or be overrode. content_type: The MIME type of the file. str. Only valid in writing mode. options: A str->basestring dict to specify additional headers to pass to GCS e.g. {'x-goog-acl': 'private', 'x-goog-meta-foo': 'foo'}. Supported options are x-goog-acl, x-goog-meta-, cache-control, content-disposition, and content-encoding. Only valid in writing mode. See https://developers.google.com/storage/docs/reference-headers for details. read_buffer_size: The buffer size for read. Read keeps a buffer and prefetches another one. To minimize blocking for large files, always read by buffer size. To minimize number of RPC requests for small files, set a large buffer size. Max is 30MB. retry_params: An instance of api_utils.RetryParams for subsequent calls to GCS from this file handle. If None, the default one is used. _account_id: Internal-use only. offset: Number of bytes to skip at the start of the file. If None, 0 is used. Returns: A reading or writing buffer that supports File-like interface. Buffer must be closed after operations are done. Raises: errors.AuthorizationError: if authorization failed. errors.NotFoundError: if an object that's expected to exist doesn't. ValueError: invalid open mode or if content_type or options are specified in reading mode. """ common.validate_file_path(filename) api = storage_api._get_storage_api(retry_params=retry_params, account_id=_account_id) filename = api_utils._quote_filename(filename) if mode == 'w': common.validate_options(options) return storage_api.StreamingBuffer(api, filename, content_type, options) elif mode == 'r': if content_type or options: raise ValueError('Options and content_type can only be specified ' 'for writing mode.') return storage_api.ReadBuffer(api, filename, buffer_size=read_buffer_size, offset=offset) else: raise ValueError('Invalid mode %s.' % mode)
[ "def", "open", "(", "filename", ",", "mode", "=", "'r'", ",", "content_type", "=", "None", ",", "options", "=", "None", ",", "read_buffer_size", "=", "storage_api", ".", "ReadBuffer", ".", "DEFAULT_BUFFER_SIZE", ",", "retry_params", "=", "None", ",", "_accou...
Opens a Google Cloud Storage file and returns it as a File-like object. Args: filename: A Google Cloud Storage filename of form '/bucket/filename'. mode: 'r' for reading mode. 'w' for writing mode. In reading mode, the file must exist. In writing mode, a file will be created or be overrode. content_type: The MIME type of the file. str. Only valid in writing mode. options: A str->basestring dict to specify additional headers to pass to GCS e.g. {'x-goog-acl': 'private', 'x-goog-meta-foo': 'foo'}. Supported options are x-goog-acl, x-goog-meta-, cache-control, content-disposition, and content-encoding. Only valid in writing mode. See https://developers.google.com/storage/docs/reference-headers for details. read_buffer_size: The buffer size for read. Read keeps a buffer and prefetches another one. To minimize blocking for large files, always read by buffer size. To minimize number of RPC requests for small files, set a large buffer size. Max is 30MB. retry_params: An instance of api_utils.RetryParams for subsequent calls to GCS from this file handle. If None, the default one is used. _account_id: Internal-use only. offset: Number of bytes to skip at the start of the file. If None, 0 is used. Returns: A reading or writing buffer that supports File-like interface. Buffer must be closed after operations are done. Raises: errors.AuthorizationError: if authorization failed. errors.NotFoundError: if an object that's expected to exist doesn't. ValueError: invalid open mode or if content_type or options are specified in reading mode.
[ "Opens", "a", "Google", "Cloud", "Storage", "file", "and", "returns", "it", "as", "a", "File", "-", "like", "object", "." ]
python
train
nickmilon/Hellas
Hellas/Sparta.py
https://github.com/nickmilon/Hellas/blob/542e4778692fbec90753942946f20100412ec9ee/Hellas/Sparta.py#L333-L340
def class_name_str(obj, skip_parent=False): """ return's object's class name as string """ rt = str(type(obj)).split(" ")[1][1:-2] if skip_parent: rt = rt.split(".")[-1] return rt
[ "def", "class_name_str", "(", "obj", ",", "skip_parent", "=", "False", ")", ":", "rt", "=", "str", "(", "type", "(", "obj", ")", ")", ".", "split", "(", "\" \"", ")", "[", "1", "]", "[", "1", ":", "-", "2", "]", "if", "skip_parent", ":", "rt", ...
return's object's class name as string
[ "return", "s", "object", "s", "class", "name", "as", "string" ]
python
train
martinpitt/python-dbusmock
dbusmock/mockobject.py
https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/mockobject.py#L197-L241
def AddObject(self, path, interface, properties, methods): '''Add a new D-Bus object to the mock path: D-Bus object path interface: Primary D-Bus interface name of this object (where properties and methods will be put on) properties: A property_name (string) → value map with initial properties on "interface" methods: An array of 4-tuples (name, in_sig, out_sig, code) describing methods to add to "interface"; see AddMethod() for details of the tuple values If this is a D-Bus ObjectManager instance, the InterfacesAdded signal will *not* be emitted for the object automatically; it must be emitted manually if desired. This is because AddInterface may be called after AddObject, but before the InterfacesAdded signal should be emitted. Example: dbus_proxy.AddObject('/com/example/Foo/Manager', 'com.example.Foo.Control', { 'state': dbus.String('online', variant_level=1), }, [ ('Start', '', '', ''), ('EchoInt', 'i', 'i', 'ret = args[0]'), ('GetClients', '', 'ao', 'ret = ["/com/example/Foo/Client1"]'), ]) ''' if path in objects: raise dbus.exceptions.DBusException( 'object %s already exists' % path, name='org.freedesktop.DBus.Mock.NameError') obj = DBusMockObject(self.bus_name, path, interface, properties) # make sure created objects inherit the log file stream obj.logfile = self.logfile obj.object_manager = self.object_manager obj.is_logfile_owner = False obj.AddMethods(interface, methods) objects[path] = obj
[ "def", "AddObject", "(", "self", ",", "path", ",", "interface", ",", "properties", ",", "methods", ")", ":", "if", "path", "in", "objects", ":", "raise", "dbus", ".", "exceptions", ".", "DBusException", "(", "'object %s already exists'", "%", "path", ",", ...
Add a new D-Bus object to the mock path: D-Bus object path interface: Primary D-Bus interface name of this object (where properties and methods will be put on) properties: A property_name (string) → value map with initial properties on "interface" methods: An array of 4-tuples (name, in_sig, out_sig, code) describing methods to add to "interface"; see AddMethod() for details of the tuple values If this is a D-Bus ObjectManager instance, the InterfacesAdded signal will *not* be emitted for the object automatically; it must be emitted manually if desired. This is because AddInterface may be called after AddObject, but before the InterfacesAdded signal should be emitted. Example: dbus_proxy.AddObject('/com/example/Foo/Manager', 'com.example.Foo.Control', { 'state': dbus.String('online', variant_level=1), }, [ ('Start', '', '', ''), ('EchoInt', 'i', 'i', 'ret = args[0]'), ('GetClients', '', 'ao', 'ret = ["/com/example/Foo/Client1"]'), ])
[ "Add", "a", "new", "D", "-", "Bus", "object", "to", "the", "mock" ]
python
train
RiotGames/cloud-inquisitor
plugins/public/cinq-collector-dns/cinq_collector_dns/__init__.py
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/plugins/public/cinq-collector-dns/cinq_collector_dns/__init__.py#L195-L230
def get_cloudflare_records(self, *, account): """Return a `list` of `dict`s containing the zones and their records, obtained from the CloudFlare API Returns: account (:obj:`CloudFlareAccount`): A CloudFlare Account object :obj:`list` of `dict` """ zones = [] for zobj in self.__cloudflare_list_zones(account=account): try: self.log.debug('Processing DNS zone CloudFlare/{}'.format(zobj['name'])) zone = { 'zone_id': get_resource_id('cfz', zobj['name']), 'name': zobj['name'], 'source': 'CloudFlare', 'comment': None, 'tags': {}, 'records': [] } for record in self.__cloudflare_list_zone_records(account=account, zoneID=zobj['id']): zone['records'].append({ 'id': get_resource_id('cfr', zobj['id'], ['{}={}'.format(k, v) for k, v in record.items()]), 'zone_id': zone['zone_id'], 'name': record['name'], 'value': record['value'], 'type': record['type'] }) if len(zone['records']) > 0: zones.append(zone) except CloudFlareError: self.log.exception('Failed getting records for CloudFlare zone {}'.format(zobj['name'])) return zones
[ "def", "get_cloudflare_records", "(", "self", ",", "*", ",", "account", ")", ":", "zones", "=", "[", "]", "for", "zobj", "in", "self", ".", "__cloudflare_list_zones", "(", "account", "=", "account", ")", ":", "try", ":", "self", ".", "log", ".", "debug...
Return a `list` of `dict`s containing the zones and their records, obtained from the CloudFlare API Returns: account (:obj:`CloudFlareAccount`): A CloudFlare Account object :obj:`list` of `dict`
[ "Return", "a", "list", "of", "dict", "s", "containing", "the", "zones", "and", "their", "records", "obtained", "from", "the", "CloudFlare", "API" ]
python
train
nyaruka/python-librato-bg
librato_bg/consumer.py
https://github.com/nyaruka/python-librato-bg/blob/e541092838694de31d256becea8391a9cfe086c7/librato_bg/consumer.py#L75-L82
def next_item(self): """Get a single item from the queue.""" queue = self.queue try: item = queue.get(block=True, timeout=5) return item except Exception: return None
[ "def", "next_item", "(", "self", ")", ":", "queue", "=", "self", ".", "queue", "try", ":", "item", "=", "queue", ".", "get", "(", "block", "=", "True", ",", "timeout", "=", "5", ")", "return", "item", "except", "Exception", ":", "return", "None" ]
Get a single item from the queue.
[ "Get", "a", "single", "item", "from", "the", "queue", "." ]
python
valid
gwastro/pycbc
pycbc/inference/models/__init__.py
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inference/models/__init__.py#L153-L174
def read_from_config(cp, **kwargs): """Initializes a model from the given config file. The section must have a ``name`` argument. The name argument corresponds to the name of the class to initialize. Parameters ---------- cp : WorkflowConfigParser Config file parser to read. \**kwargs : All other keyword arguments are passed to the ``from_config`` method of the class specified by the name argument. Returns ------- cls The initialized model. """ # use the name to get the distribution name = cp.get("model", "name") return models[name].from_config(cp, **kwargs)
[ "def", "read_from_config", "(", "cp", ",", "*", "*", "kwargs", ")", ":", "# use the name to get the distribution", "name", "=", "cp", ".", "get", "(", "\"model\"", ",", "\"name\"", ")", "return", "models", "[", "name", "]", ".", "from_config", "(", "cp", "...
Initializes a model from the given config file. The section must have a ``name`` argument. The name argument corresponds to the name of the class to initialize. Parameters ---------- cp : WorkflowConfigParser Config file parser to read. \**kwargs : All other keyword arguments are passed to the ``from_config`` method of the class specified by the name argument. Returns ------- cls The initialized model.
[ "Initializes", "a", "model", "from", "the", "given", "config", "file", "." ]
python
train
archman/beamline
beamline/mathutils.py
https://github.com/archman/beamline/blob/417bc5dc13e754bc89d246427984590fced64d07/beamline/mathutils.py#L350-L366
def setParams(self, bend_length, bend_field, drift_length, gamma): """ set chicane parameters :param bend_length: bend length, [m] :param bend_field: bend field, [T] :param drift_length: drift length, [m], list :param gamma: electron energy, gamma :return: None """ if None in (bend_length, bend_field, drift_length, gamma): print("warning: 'bend_length', 'bend_field', 'drift_length', 'gamma' should be positive float numbers.") self.mflag = False else: self._setDriftList(drift_length) self.gamma = gamma self.bend_length = bend_length self.bend_field = bend_field
[ "def", "setParams", "(", "self", ",", "bend_length", ",", "bend_field", ",", "drift_length", ",", "gamma", ")", ":", "if", "None", "in", "(", "bend_length", ",", "bend_field", ",", "drift_length", ",", "gamma", ")", ":", "print", "(", "\"warning: 'bend_lengt...
set chicane parameters :param bend_length: bend length, [m] :param bend_field: bend field, [T] :param drift_length: drift length, [m], list :param gamma: electron energy, gamma :return: None
[ "set", "chicane", "parameters" ]
python
train
oceanprotocol/squid-py
squid_py/ocean/ocean_conditions.py
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ocean/ocean_conditions.py#L42-L63
def release_reward(self, agreement_id, amount, account): """ Release reward condition. :param agreement_id: id of the agreement, hex str :param amount: Amount of tokens, int :param account: Account :return: """ agreement_values = self._keeper.agreement_manager.get_agreement(agreement_id) consumer, provider = self._keeper.escrow_access_secretstore_template.get_agreement_data( agreement_id) access_id, lock_id = agreement_values.condition_ids[:2] return self._keeper.escrow_reward_condition.fulfill( agreement_id, amount, provider, consumer, lock_id, access_id, account )
[ "def", "release_reward", "(", "self", ",", "agreement_id", ",", "amount", ",", "account", ")", ":", "agreement_values", "=", "self", ".", "_keeper", ".", "agreement_manager", ".", "get_agreement", "(", "agreement_id", ")", "consumer", ",", "provider", "=", "se...
Release reward condition. :param agreement_id: id of the agreement, hex str :param amount: Amount of tokens, int :param account: Account :return:
[ "Release", "reward", "condition", "." ]
python
train
ANTsX/ANTsPy
ants/core/ants_image.py
https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/core/ants_image.py#L302-L316
def astype(self, dtype): """ Cast & clone an ANTsImage to a given numpy datatype. Map: uint8 : unsigned char uint32 : unsigned int float32 : float float64 : double """ if dtype not in _supported_dtypes: raise ValueError('Datatype %s not supported. Supported types are %s' % (dtype, _supported_dtypes)) pixeltype = _npy_to_itk_map[dtype] return self.clone(pixeltype)
[ "def", "astype", "(", "self", ",", "dtype", ")", ":", "if", "dtype", "not", "in", "_supported_dtypes", ":", "raise", "ValueError", "(", "'Datatype %s not supported. Supported types are %s'", "%", "(", "dtype", ",", "_supported_dtypes", ")", ")", "pixeltype", "=", ...
Cast & clone an ANTsImage to a given numpy datatype. Map: uint8 : unsigned char uint32 : unsigned int float32 : float float64 : double
[ "Cast", "&", "clone", "an", "ANTsImage", "to", "a", "given", "numpy", "datatype", "." ]
python
train
happyleavesaoc/python-firetv
firetv/__main__.py
https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__main__.py#L50-L63
def is_valid_device_id(device_id): """ Check if device identifier is valid. A valid device identifier contains only ascii word characters or dashes. :param device_id: Device identifier :returns: Valid or not. """ valid = valid_device_id.match(device_id) if not valid: logging.error("A valid device identifier contains " "only ascii word characters or dashes. " "Device '%s' not added.", device_id) return valid
[ "def", "is_valid_device_id", "(", "device_id", ")", ":", "valid", "=", "valid_device_id", ".", "match", "(", "device_id", ")", "if", "not", "valid", ":", "logging", ".", "error", "(", "\"A valid device identifier contains \"", "\"only ascii word characters or dashes. \"...
Check if device identifier is valid. A valid device identifier contains only ascii word characters or dashes. :param device_id: Device identifier :returns: Valid or not.
[ "Check", "if", "device", "identifier", "is", "valid", "." ]
python
train
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/core/api/packages.py
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/api/packages.py#L205-L211
def get_package_format_names(predicate=None): """Get names for available package formats.""" return [ k for k, v in six.iteritems(get_package_formats()) if not predicate or predicate(k, v) ]
[ "def", "get_package_format_names", "(", "predicate", "=", "None", ")", ":", "return", "[", "k", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "get_package_formats", "(", ")", ")", "if", "not", "predicate", "or", "predicate", "(", "k", ",", ...
Get names for available package formats.
[ "Get", "names", "for", "available", "package", "formats", "." ]
python
train
googlefonts/ufo2ft
Lib/ufo2ft/featureWriters/__init__.py
https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/featureWriters/__init__.py#L62-L104
def loadFeatureWriters(ufo, ignoreErrors=True): """Check UFO lib for key "com.github.googlei18n.ufo2ft.featureWriters", containing a list of dicts, each having the following key/value pairs: For example: { "module": "myTools.featureWriters", # default: ufo2ft.featureWriters "class": "MyKernFeatureWriter", # required "options": {"doThis": False, "doThat": True}, } Import each feature writer class from the specified module (default is the built-in ufo2ft.featureWriters), and instantiate it with the given 'options' dict. Return the list of feature writer objects. If the 'featureWriters' key is missing from the UFO lib, return None. If an exception occurs and 'ignoreErrors' is True, the exception message is logged and the invalid writer is skipped, otrherwise it's propagated. """ if FEATURE_WRITERS_KEY not in ufo.lib: return None writers = [] for wdict in ufo.lib[FEATURE_WRITERS_KEY]: try: moduleName = wdict.get("module", __name__) className = wdict["class"] options = wdict.get("options", {}) if not isinstance(options, dict): raise TypeError(type(options)) module = importlib.import_module(moduleName) klass = getattr(module, className) if not isValidFeatureWriter(klass): raise TypeError(klass) writer = klass(**options) except Exception: if ignoreErrors: logger.exception("failed to load feature writer: %r", wdict) continue raise writers.append(writer) return writers
[ "def", "loadFeatureWriters", "(", "ufo", ",", "ignoreErrors", "=", "True", ")", ":", "if", "FEATURE_WRITERS_KEY", "not", "in", "ufo", ".", "lib", ":", "return", "None", "writers", "=", "[", "]", "for", "wdict", "in", "ufo", ".", "lib", "[", "FEATURE_WRIT...
Check UFO lib for key "com.github.googlei18n.ufo2ft.featureWriters", containing a list of dicts, each having the following key/value pairs: For example: { "module": "myTools.featureWriters", # default: ufo2ft.featureWriters "class": "MyKernFeatureWriter", # required "options": {"doThis": False, "doThat": True}, } Import each feature writer class from the specified module (default is the built-in ufo2ft.featureWriters), and instantiate it with the given 'options' dict. Return the list of feature writer objects. If the 'featureWriters' key is missing from the UFO lib, return None. If an exception occurs and 'ignoreErrors' is True, the exception message is logged and the invalid writer is skipped, otrherwise it's propagated.
[ "Check", "UFO", "lib", "for", "key", "com", ".", "github", ".", "googlei18n", ".", "ufo2ft", ".", "featureWriters", "containing", "a", "list", "of", "dicts", "each", "having", "the", "following", "key", "/", "value", "pairs", ":", "For", "example", ":" ]
python
train
Antidote1911/cryptoshop
cryptoshop/_cascade_engine.py
https://github.com/Antidote1911/cryptoshop/blob/0b7ff4a6848f2733f4737606957e8042a4d6ca0b/cryptoshop/_cascade_engine.py#L39-L104
def encry_decry_cascade(data, masterkey, bool_encry, assoc_data): """ When bool_encry is True, encrypt the data with master key. When it is False, the function extract the three nonce from the encrypted data (first 3*21 bytes), and decrypt the data. :param data: the data to encrypt or decrypt. :param masterkey: a 32 bytes key in bytes. :param bool_encry: if bool_encry is True, data is encrypted. Else, it will be decrypted. :param assoc_data: Additional data added to GCM authentication. :return: if bool_encry is True, corresponding nonce + encrypted data. Else, the decrypted data. """ engine1 = botan.cipher(algo="Serpent/GCM", encrypt=bool_encry) engine2 = botan.cipher(algo="AES-256/GCM", encrypt=bool_encry) engine3 = botan.cipher(algo="Twofish/GCM", encrypt=bool_encry) hash1 = botan.hash_function(algo="SHA-256") hash1.update(masterkey) hashed1 = hash1.final() hash2 = botan.hash_function(algo="SHA-256") hash2.update(hashed1) hashed2 = hash2.final() engine1.set_key(key=masterkey) engine1.set_assoc_data(assoc_data) engine2.set_key(key=hashed1) engine2.set_assoc_data(assoc_data) engine3.set_key(key=hashed2) engine3.set_assoc_data(assoc_data) if bool_encry is True: nonce1 = generate_nonce_timestamp() nonce2 = generate_nonce_timestamp() nonce3 = generate_nonce_timestamp() engine1.start(nonce=nonce1) engine2.start(nonce=nonce2) engine3.start(nonce=nonce3) cipher1 = engine1.finish(data) cipher2 = engine2.finish(cipher1) cipher3 = engine3.finish(cipher2) return nonce1 + nonce2 + nonce3 + cipher3 else: nonce1 = data[:__nonce_length__] nonce2 = data[__nonce_length__:__nonce_length__ * 2] nonce3 = data[__nonce_length__ * 2:__nonce_length__ * 3] encrypteddata = data[__nonce_length__ * 3:] engine1.start(nonce=nonce1) engine2.start(nonce=nonce2) engine3.start(nonce=nonce3) decrypteddata1 = engine3.finish(encrypteddata) if decrypteddata1 == b"": raise Exception("Integrity failure: Invalid passphrase or corrupted data") decrypteddata2 = engine2.finish(decrypteddata1) if decrypteddata2 == b"": raise Exception("Integrity failure: Invalid passphrase or corrupted data") decrypteddata3 = engine1.finish(decrypteddata2) if decrypteddata3 == b"": raise Exception("Integrity failure: Invalid passphrase or corrupted data") else: return decrypteddata3
[ "def", "encry_decry_cascade", "(", "data", ",", "masterkey", ",", "bool_encry", ",", "assoc_data", ")", ":", "engine1", "=", "botan", ".", "cipher", "(", "algo", "=", "\"Serpent/GCM\"", ",", "encrypt", "=", "bool_encry", ")", "engine2", "=", "botan", ".", ...
When bool_encry is True, encrypt the data with master key. When it is False, the function extract the three nonce from the encrypted data (first 3*21 bytes), and decrypt the data. :param data: the data to encrypt or decrypt. :param masterkey: a 32 bytes key in bytes. :param bool_encry: if bool_encry is True, data is encrypted. Else, it will be decrypted. :param assoc_data: Additional data added to GCM authentication. :return: if bool_encry is True, corresponding nonce + encrypted data. Else, the decrypted data.
[ "When", "bool_encry", "is", "True", "encrypt", "the", "data", "with", "master", "key", ".", "When", "it", "is", "False", "the", "function", "extract", "the", "three", "nonce", "from", "the", "encrypted", "data", "(", "first", "3", "*", "21", "bytes", ")"...
python
train
bitesofcode/projexui
projexui/xapplication.py
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/xapplication.py#L448-L473
def systemSettings(self): """ Returns the settings associated with this application for all users. :return <projexui.xsettings.XSettings> """ if not self._systemSettings: if self.isCompiled(): settings = QtCore.QSettings(XSettings.IniFormat, XSettings.SystemScope, self.organizationName(), self.applicationName()) rootpath = os.path.dirname(settings.fileName()) else: rootpath = os.path.abspath('.') name = self.applicationName() filename = os.path.join(rootpath, '{0}.yaml'.format(name)) self._systemSettings = XSettings(XSettings.YamlFormat, XSettings.SystemScope, self.organizationName(), self.applicationName(), filename=filename) return self._systemSettings
[ "def", "systemSettings", "(", "self", ")", ":", "if", "not", "self", ".", "_systemSettings", ":", "if", "self", ".", "isCompiled", "(", ")", ":", "settings", "=", "QtCore", ".", "QSettings", "(", "XSettings", ".", "IniFormat", ",", "XSettings", ".", "Sys...
Returns the settings associated with this application for all users. :return <projexui.xsettings.XSettings>
[ "Returns", "the", "settings", "associated", "with", "this", "application", "for", "all", "users", ".", ":", "return", "<projexui", ".", "xsettings", ".", "XSettings", ">" ]
python
train
feliphebueno/Rinzler
rinzler/__init__.py
https://github.com/feliphebueno/Rinzler/blob/7f6d5445b5662cba2e8938bb82c7f3ef94e5ded8/rinzler/__init__.py#L88-L99
def set_auth_service(self, auth_service: BaseAuthService): """ Sets the authentication service :param auth_service: BaseAuthService Authentication service :raises: TypeError If the auth_service object is not a subclass of rinzler.auth.BaseAuthService :rtype: Rinzler """ if issubclass(auth_service.__class__, BaseAuthService): self.auth_service = auth_service return self else: raise TypeError("Your auth service object must be a subclass of rinzler.auth.BaseAuthService.")
[ "def", "set_auth_service", "(", "self", ",", "auth_service", ":", "BaseAuthService", ")", ":", "if", "issubclass", "(", "auth_service", ".", "__class__", ",", "BaseAuthService", ")", ":", "self", ".", "auth_service", "=", "auth_service", "return", "self", "else"...
Sets the authentication service :param auth_service: BaseAuthService Authentication service :raises: TypeError If the auth_service object is not a subclass of rinzler.auth.BaseAuthService :rtype: Rinzler
[ "Sets", "the", "authentication", "service", ":", "param", "auth_service", ":", "BaseAuthService", "Authentication", "service", ":", "raises", ":", "TypeError", "If", "the", "auth_service", "object", "is", "not", "a", "subclass", "of", "rinzler", ".", "auth", "."...
python
train
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/matrixpilot.py
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/matrixpilot.py#L10671-L10696
def set_position_target_global_int_encode(self, time_boot_ms, target_system, target_component, coordinate_frame, type_mask, lat_int, lon_int, alt, vx, vy, vz, afx, afy, afz, yaw, yaw_rate): ''' Sets a desired vehicle position, velocity, and/or acceleration in a global coordinate system (WGS84). Used by an external controller to command the vehicle (manual controller or other system). time_boot_ms : Timestamp in milliseconds since system boot. The rationale for the timestamp in the setpoint is to allow the system to compensate for the transport delay of the setpoint. This allows the system to compensate processing latency. (uint32_t) target_system : System ID (uint8_t) target_component : Component ID (uint8_t) coordinate_frame : Valid options are: MAV_FRAME_GLOBAL_INT = 5, MAV_FRAME_GLOBAL_RELATIVE_ALT_INT = 6, MAV_FRAME_GLOBAL_TERRAIN_ALT_INT = 11 (uint8_t) type_mask : Bitmask to indicate which dimensions should be ignored by the vehicle: a value of 0b0000000000000000 or 0b0000001000000000 indicates that none of the setpoint dimensions should be ignored. If bit 10 is set the floats afx afy afz should be interpreted as force instead of acceleration. Mapping: bit 1: x, bit 2: y, bit 3: z, bit 4: vx, bit 5: vy, bit 6: vz, bit 7: ax, bit 8: ay, bit 9: az, bit 10: is force setpoint, bit 11: yaw, bit 12: yaw rate (uint16_t) lat_int : X Position in WGS84 frame in 1e7 * meters (int32_t) lon_int : Y Position in WGS84 frame in 1e7 * meters (int32_t) alt : Altitude in meters in AMSL altitude, not WGS84 if absolute or relative, above terrain if GLOBAL_TERRAIN_ALT_INT (float) vx : X velocity in NED frame in meter / s (float) vy : Y velocity in NED frame in meter / s (float) vz : Z velocity in NED frame in meter / s (float) afx : X acceleration or force (if bit 10 of type_mask is set) in NED frame in meter / s^2 or N (float) afy : Y acceleration or force (if bit 10 of type_mask is set) in NED frame in meter / s^2 or N (float) afz : Z acceleration or force (if bit 10 of type_mask is set) in NED frame in meter / s^2 or N (float) yaw : yaw setpoint in rad (float) yaw_rate : yaw rate setpoint in rad/s (float) ''' return MAVLink_set_position_target_global_int_message(time_boot_ms, target_system, target_component, coordinate_frame, type_mask, lat_int, lon_int, alt, vx, vy, vz, afx, afy, afz, yaw, yaw_rate)
[ "def", "set_position_target_global_int_encode", "(", "self", ",", "time_boot_ms", ",", "target_system", ",", "target_component", ",", "coordinate_frame", ",", "type_mask", ",", "lat_int", ",", "lon_int", ",", "alt", ",", "vx", ",", "vy", ",", "vz", ",", "afx", ...
Sets a desired vehicle position, velocity, and/or acceleration in a global coordinate system (WGS84). Used by an external controller to command the vehicle (manual controller or other system). time_boot_ms : Timestamp in milliseconds since system boot. The rationale for the timestamp in the setpoint is to allow the system to compensate for the transport delay of the setpoint. This allows the system to compensate processing latency. (uint32_t) target_system : System ID (uint8_t) target_component : Component ID (uint8_t) coordinate_frame : Valid options are: MAV_FRAME_GLOBAL_INT = 5, MAV_FRAME_GLOBAL_RELATIVE_ALT_INT = 6, MAV_FRAME_GLOBAL_TERRAIN_ALT_INT = 11 (uint8_t) type_mask : Bitmask to indicate which dimensions should be ignored by the vehicle: a value of 0b0000000000000000 or 0b0000001000000000 indicates that none of the setpoint dimensions should be ignored. If bit 10 is set the floats afx afy afz should be interpreted as force instead of acceleration. Mapping: bit 1: x, bit 2: y, bit 3: z, bit 4: vx, bit 5: vy, bit 6: vz, bit 7: ax, bit 8: ay, bit 9: az, bit 10: is force setpoint, bit 11: yaw, bit 12: yaw rate (uint16_t) lat_int : X Position in WGS84 frame in 1e7 * meters (int32_t) lon_int : Y Position in WGS84 frame in 1e7 * meters (int32_t) alt : Altitude in meters in AMSL altitude, not WGS84 if absolute or relative, above terrain if GLOBAL_TERRAIN_ALT_INT (float) vx : X velocity in NED frame in meter / s (float) vy : Y velocity in NED frame in meter / s (float) vz : Z velocity in NED frame in meter / s (float) afx : X acceleration or force (if bit 10 of type_mask is set) in NED frame in meter / s^2 or N (float) afy : Y acceleration or force (if bit 10 of type_mask is set) in NED frame in meter / s^2 or N (float) afz : Z acceleration or force (if bit 10 of type_mask is set) in NED frame in meter / s^2 or N (float) yaw : yaw setpoint in rad (float) yaw_rate : yaw rate setpoint in rad/s (float)
[ "Sets", "a", "desired", "vehicle", "position", "velocity", "and", "/", "or", "acceleration", "in", "a", "global", "coordinate", "system", "(", "WGS84", ")", ".", "Used", "by", "an", "external", "controller", "to", "command", "the", "vehicle", "(", "manual", ...
python
train
matrix-org/matrix-python-sdk
matrix_client/room.py
https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/room.py#L414-L427
def send_state_event(self, event_type, content, state_key=""): """Send a state event to the room. Args: event_type (str): The type of event that you are sending. content (): An object with the content of the message. state_key (str, optional): A unique key to identify the state. """ return self.client.api.send_state_event( self.room_id, event_type, content, state_key )
[ "def", "send_state_event", "(", "self", ",", "event_type", ",", "content", ",", "state_key", "=", "\"\"", ")", ":", "return", "self", ".", "client", ".", "api", ".", "send_state_event", "(", "self", ".", "room_id", ",", "event_type", ",", "content", ",", ...
Send a state event to the room. Args: event_type (str): The type of event that you are sending. content (): An object with the content of the message. state_key (str, optional): A unique key to identify the state.
[ "Send", "a", "state", "event", "to", "the", "room", "." ]
python
train