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
shoebot/shoebot
shoebot/data/img.py
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/data/img.py#L135-L140
def _get_center(self): '''Returns the center point of the path, disregarding transforms. ''' x = (self.x + self.width / 2) y = (self.y + self.height / 2) return (x, y)
[ "def", "_get_center", "(", "self", ")", ":", "x", "=", "(", "self", ".", "x", "+", "self", ".", "width", "/", "2", ")", "y", "=", "(", "self", ".", "y", "+", "self", ".", "height", "/", "2", ")", "return", "(", "x", ",", "y", ")" ]
Returns the center point of the path, disregarding transforms.
[ "Returns", "the", "center", "point", "of", "the", "path", "disregarding", "transforms", "." ]
python
valid
davisd50/sparc.common
sparc/common/cli.py
https://github.com/davisd50/sparc.common/blob/50fb47ff6f42042c363f27bd13cb3919a560e235/sparc/common/cli.py#L15-L70
def askQuestion(question, required = True, answers = dict(), tries = 3): """Ask a question to STDOUT and return answer from STDIN Args: question: A string question that will be printed to stdout Kwargs: required: True indicates the question must be answered answers: A sequence of dicts with key value pairs where the key will be a user-selectable choice menu item with the value as its related description. tries: Integer value of maximum amount of attempts users may exercise to select a valid answer Returns: A user specified string when required is False and answers was not provided. A user selected key from answers when required is True and answers was provided. None if required was false and user did not enter a answer. None if required was True and user reached reached maximum limit of tries. """ print question if not answers: # we get the user's answer via a named utility because direct calls to # raw_input() are hard to test (this way, tests can provide their own # implementation of ISelectedChoice without calls to raw_input()) answer = getUtility(ISelectedChoice, 'sparc.common.cli_selected_choice').selection() _attempts = 0 while True: if tries and _attempts > tries: print (u"Too many attempts") return None if not required or answer: return answer if answer else None print (u"Invalid input, please try again.") answer = getUtility(ISelectedChoice, 'sparc.common.cli_selected_choice').selection() _attempts += 1 for selection_pair in answers: for key, potential_answer in selection_pair.iteritems(): print "(" + key + ") " + potential_answer break # only process the first dict entry for the sequence _attempts = 0 while True: answer = getUtility(ISelectedChoice, 'sparc.common.cli_selected_choice').selection() if tries and _attempts > tries: print _(u"Too many attempts") return None if not answer and not required: return None for selection_pair in answers: if answer in selection_pair: return answer print (u"Invalid selection: {}, please try again.".format(answer)) answer = getUtility(ISelectedChoice, 'sparc.common.cli_selected_choice').selection() _attempts += 1
[ "def", "askQuestion", "(", "question", ",", "required", "=", "True", ",", "answers", "=", "dict", "(", ")", ",", "tries", "=", "3", ")", ":", "print", "question", "if", "not", "answers", ":", "# we get the user's answer via a named utility because direct calls to"...
Ask a question to STDOUT and return answer from STDIN Args: question: A string question that will be printed to stdout Kwargs: required: True indicates the question must be answered answers: A sequence of dicts with key value pairs where the key will be a user-selectable choice menu item with the value as its related description. tries: Integer value of maximum amount of attempts users may exercise to select a valid answer Returns: A user specified string when required is False and answers was not provided. A user selected key from answers when required is True and answers was provided. None if required was false and user did not enter a answer. None if required was True and user reached reached maximum limit of tries.
[ "Ask", "a", "question", "to", "STDOUT", "and", "return", "answer", "from", "STDIN", "Args", ":", "question", ":", "A", "string", "question", "that", "will", "be", "printed", "to", "stdout", "Kwargs", ":", "required", ":", "True", "indicates", "the", "quest...
python
test
genialis/resolwe
resolwe/flow/executors/manager_commands.py
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/executors/manager_commands.py#L44-L90
async def send_manager_command(cmd, expect_reply=True, extra_fields={}): """Send a properly formatted command to the manager. :param cmd: The command to send (:class:`str`). :param expect_reply: If ``True``, wait for the manager to reply with an acknowledgement packet. :param extra_fields: A dictionary of extra information that's merged into the packet body (i.e. not under an extra key). """ packet = { ExecutorProtocol.DATA_ID: DATA['id'], ExecutorProtocol.COMMAND: cmd, } packet.update(extra_fields) logger.debug("Sending command to listener: {}".format(json.dumps(packet))) # TODO what happens here if the push fails? we don't have any realistic recourse, # so just let it explode and stop processing queue_channel = EXECUTOR_SETTINGS['REDIS_CHANNEL_PAIR'][0] try: await redis_conn.rpush(queue_channel, json.dumps(packet)) except Exception: logger.error("Error sending command to manager:\n\n{}".format(traceback.format_exc())) raise if not expect_reply: return for _ in range(_REDIS_RETRIES): response = await redis_conn.blpop(QUEUE_RESPONSE_CHANNEL, timeout=1) if response: break else: # NOTE: If there's still no response after a few seconds, the system is broken # enough that it makes sense to give up; we're isolated here, so if the manager # doesn't respond, we can't really do much more than just crash raise RuntimeError("No response from the manager after {} retries.".format(_REDIS_RETRIES)) _, item = response result = json.loads(item.decode('utf-8'))[ExecutorProtocol.RESULT] assert result in [ExecutorProtocol.RESULT_OK, ExecutorProtocol.RESULT_ERROR] if result == ExecutorProtocol.RESULT_OK: return True return False
[ "async", "def", "send_manager_command", "(", "cmd", ",", "expect_reply", "=", "True", ",", "extra_fields", "=", "{", "}", ")", ":", "packet", "=", "{", "ExecutorProtocol", ".", "DATA_ID", ":", "DATA", "[", "'id'", "]", ",", "ExecutorProtocol", ".", "COMMAN...
Send a properly formatted command to the manager. :param cmd: The command to send (:class:`str`). :param expect_reply: If ``True``, wait for the manager to reply with an acknowledgement packet. :param extra_fields: A dictionary of extra information that's merged into the packet body (i.e. not under an extra key).
[ "Send", "a", "properly", "formatted", "command", "to", "the", "manager", "." ]
python
train
wbond/oscrypto
oscrypto/keys.py
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/keys.py#L613-L691
def _decrypt_encrypted_data(encryption_algorithm_info, encrypted_content, password): """ Decrypts encrypted ASN.1 data :param encryption_algorithm_info: An instance of asn1crypto.pkcs5.Pkcs5EncryptionAlgorithm :param encrypted_content: A byte string of the encrypted content :param password: A byte string of the encrypted content's password :return: A byte string of the decrypted plaintext """ decrypt_func = crypto_funcs[encryption_algorithm_info.encryption_cipher] # Modern, PKCS#5 PBES2-based encryption if encryption_algorithm_info.kdf == 'pbkdf2': if encryption_algorithm_info.encryption_cipher == 'rc5': raise ValueError(pretty_message( ''' PBES2 encryption scheme utilizing RC5 encryption is not supported ''' )) enc_key = pbkdf2( encryption_algorithm_info.kdf_hmac, password, encryption_algorithm_info.kdf_salt, encryption_algorithm_info.kdf_iterations, encryption_algorithm_info.key_length ) enc_iv = encryption_algorithm_info.encryption_iv plaintext = decrypt_func(enc_key, encrypted_content, enc_iv) elif encryption_algorithm_info.kdf == 'pbkdf1': derived_output = pbkdf1( encryption_algorithm_info.kdf_hmac, password, encryption_algorithm_info.kdf_salt, encryption_algorithm_info.kdf_iterations, encryption_algorithm_info.key_length + 8 ) enc_key = derived_output[0:8] enc_iv = derived_output[8:16] plaintext = decrypt_func(enc_key, encrypted_content, enc_iv) elif encryption_algorithm_info.kdf == 'pkcs12_kdf': enc_key = pkcs12_kdf( encryption_algorithm_info.kdf_hmac, password, encryption_algorithm_info.kdf_salt, encryption_algorithm_info.kdf_iterations, encryption_algorithm_info.key_length, 1 # ID 1 is for generating a key ) # Since RC4 is a stream cipher, we don't use an IV if encryption_algorithm_info.encryption_cipher == 'rc4': plaintext = decrypt_func(enc_key, encrypted_content) else: enc_iv = pkcs12_kdf( encryption_algorithm_info.kdf_hmac, password, encryption_algorithm_info.kdf_salt, encryption_algorithm_info.kdf_iterations, encryption_algorithm_info.encryption_block_size, 2 # ID 2 is for generating an IV ) plaintext = decrypt_func(enc_key, encrypted_content, enc_iv) return plaintext
[ "def", "_decrypt_encrypted_data", "(", "encryption_algorithm_info", ",", "encrypted_content", ",", "password", ")", ":", "decrypt_func", "=", "crypto_funcs", "[", "encryption_algorithm_info", ".", "encryption_cipher", "]", "# Modern, PKCS#5 PBES2-based encryption", "if", "enc...
Decrypts encrypted ASN.1 data :param encryption_algorithm_info: An instance of asn1crypto.pkcs5.Pkcs5EncryptionAlgorithm :param encrypted_content: A byte string of the encrypted content :param password: A byte string of the encrypted content's password :return: A byte string of the decrypted plaintext
[ "Decrypts", "encrypted", "ASN", ".", "1", "data" ]
python
valid
honeybadger-io/honeybadger-python
honeybadger/contrib/flask.py
https://github.com/honeybadger-io/honeybadger-python/blob/81519b40d3e446b62035f64e34900e08ff91938c/honeybadger/contrib/flask.py#L98-L127
def init_app(self, app, report_exceptions=False, reset_context_after_request=False): """ Initialize honeybadger and listen for errors. :param Flask app: the Flask application object. :param bool report_exceptions: whether to automatically report exceptions raised by Flask on requests (i.e. by calling abort) or not. :param bool reset_context_after_request: whether to reset honeybadger context after each request. """ from flask import request_tearing_down, got_request_exception self.app = app self.app.logger.info('Initializing Honeybadger') self.report_exceptions = report_exceptions self.reset_context_after_request = reset_context_after_request self._initialize_honeybadger(app.config) # Add hooks if self.report_exceptions: self._register_signal_handler('auto-reporting exceptions', got_request_exception, self._handle_exception) if self.reset_context_after_request: self._register_signal_handler('auto clear context on request end', request_tearing_down, self._reset_context) logger.info('Honeybadger helper installed')
[ "def", "init_app", "(", "self", ",", "app", ",", "report_exceptions", "=", "False", ",", "reset_context_after_request", "=", "False", ")", ":", "from", "flask", "import", "request_tearing_down", ",", "got_request_exception", "self", ".", "app", "=", "app", "self...
Initialize honeybadger and listen for errors. :param Flask app: the Flask application object. :param bool report_exceptions: whether to automatically report exceptions raised by Flask on requests (i.e. by calling abort) or not. :param bool reset_context_after_request: whether to reset honeybadger context after each request.
[ "Initialize", "honeybadger", "and", "listen", "for", "errors", ".", ":", "param", "Flask", "app", ":", "the", "Flask", "application", "object", ".", ":", "param", "bool", "report_exceptions", ":", "whether", "to", "automatically", "report", "exceptions", "raised...
python
train
ansible/molecule
molecule/command/init/role.py
https://github.com/ansible/molecule/blob/766dc35b0b0ce498cd5e3a62b40f828742d0d08c/molecule/command/init/role.py#L133-L160
def role(ctx, dependency_name, driver_name, lint_name, provisioner_name, role_name, verifier_name, template): # pragma: no cover """ Initialize a new role for use with Molecule. """ command_args = { 'dependency_name': dependency_name, 'driver_name': driver_name, 'lint_name': lint_name, 'provisioner_name': provisioner_name, 'role_name': role_name, 'scenario_name': command_base.MOLECULE_DEFAULT_SCENARIO_NAME, 'subcommand': __name__, 'verifier_name': verifier_name, } if verifier_name == 'inspec': command_args['verifier_lint_name'] = 'rubocop' if verifier_name == 'goss': command_args['verifier_lint_name'] = 'yamllint' if verifier_name == 'ansible': command_args['verifier_lint_name'] = 'ansible-lint' if template is not None: command_args['template'] = template r = Role(command_args) r.execute()
[ "def", "role", "(", "ctx", ",", "dependency_name", ",", "driver_name", ",", "lint_name", ",", "provisioner_name", ",", "role_name", ",", "verifier_name", ",", "template", ")", ":", "# pragma: no cover", "command_args", "=", "{", "'dependency_name'", ":", "dependen...
Initialize a new role for use with Molecule.
[ "Initialize", "a", "new", "role", "for", "use", "with", "Molecule", "." ]
python
train
saltstack/salt
salt/proxy/onyx.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/onyx.py#L87-L107
def init(opts=None): ''' Required. Can be used to initialize the server connection. ''' if opts is None: opts = __opts__ try: DETAILS[_worker_name()] = SSHConnection( host=opts['proxy']['host'], username=opts['proxy']['username'], password=opts['proxy']['password'], key_accept=opts['proxy'].get('key_accept', False), ssh_args=opts['proxy'].get('ssh_args', ''), prompt='{0}.*(#|>) '.format(opts['proxy']['prompt_name'])) DETAILS[_worker_name()].sendline('no cli session paging enable') except TerminalException as e: log.error(e) return False DETAILS['initialized'] = True
[ "def", "init", "(", "opts", "=", "None", ")", ":", "if", "opts", "is", "None", ":", "opts", "=", "__opts__", "try", ":", "DETAILS", "[", "_worker_name", "(", ")", "]", "=", "SSHConnection", "(", "host", "=", "opts", "[", "'proxy'", "]", "[", "'host...
Required. Can be used to initialize the server connection.
[ "Required", ".", "Can", "be", "used", "to", "initialize", "the", "server", "connection", "." ]
python
train
proversity-org/bibblio-api-python
bibbliothon/discovery.py
https://github.com/proversity-org/bibblio-api-python/blob/d619223ad80a4bcd32f90ba64d93370260601b60/bibbliothon/discovery.py#L14-L30
def content_recommendations(access_token, content_item_id): ''' Name: content_recommendations Parameters: access_token, content_item_id Return: dictionary ''' headers = {'Authorization': 'Bearer ' + str(access_token)} recommendations_url =\ construct_content_recommendations_url(enrichment_url, content_item_id) request = requests.get(recommendations_url, headers=headers) if request.status_code == 200: recommendations = request.json() return recommendations return {'status': request.status_code, "message": request.text}
[ "def", "content_recommendations", "(", "access_token", ",", "content_item_id", ")", ":", "headers", "=", "{", "'Authorization'", ":", "'Bearer '", "+", "str", "(", "access_token", ")", "}", "recommendations_url", "=", "construct_content_recommendations_url", "(", "enr...
Name: content_recommendations Parameters: access_token, content_item_id Return: dictionary
[ "Name", ":", "content_recommendations", "Parameters", ":", "access_token", "content_item_id", "Return", ":", "dictionary" ]
python
train
materialsproject/pymatgen
pymatgen/analysis/phase_diagram.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/analysis/phase_diagram.py#L624-L653
def get_transition_chempots(self, element): """ Get the critical chemical potentials for an element in the Phase Diagram. Args: element: An element. Has to be in the PD in the first place. Returns: A sorted sequence of critical chemical potentials, from less negative to more negative. """ if element not in self.elements: raise ValueError("get_transition_chempots can only be called with " "elements in the phase diagram.") critical_chempots = [] for facet in self.facets: chempots = self._get_facet_chempots(facet) critical_chempots.append(chempots[element]) clean_pots = [] for c in sorted(critical_chempots): if len(clean_pots) == 0: clean_pots.append(c) else: if abs(c - clean_pots[-1]) > PhaseDiagram.numerical_tol: clean_pots.append(c) clean_pots.reverse() return tuple(clean_pots)
[ "def", "get_transition_chempots", "(", "self", ",", "element", ")", ":", "if", "element", "not", "in", "self", ".", "elements", ":", "raise", "ValueError", "(", "\"get_transition_chempots can only be called with \"", "\"elements in the phase diagram.\"", ")", "critical_ch...
Get the critical chemical potentials for an element in the Phase Diagram. Args: element: An element. Has to be in the PD in the first place. Returns: A sorted sequence of critical chemical potentials, from less negative to more negative.
[ "Get", "the", "critical", "chemical", "potentials", "for", "an", "element", "in", "the", "Phase", "Diagram", "." ]
python
train
jopohl/urh
src/urh/plugins/PluginManager.py
https://github.com/jopohl/urh/blob/2eb33b125c8407964cd1092843cde5010eb88aae/src/urh/plugins/PluginManager.py#L18-L38
def load_installed_plugins(self): """ :rtype: list of Plugin """ result = [] plugin_dirs = [d for d in os.listdir(self.plugin_path) if os.path.isdir(os.path.join(self.plugin_path, d))] settings = constants.SETTINGS for d in plugin_dirs: if d == "__pycache__": continue try: class_module = self.load_plugin(d) plugin = class_module() plugin.plugin_path = os.path.join(self.plugin_path, plugin.name) plugin.load_description() plugin.enabled = settings.value(plugin.name, type=bool) if plugin.name in settings.allKeys() else False result.append(plugin) except ImportError as e: logger.warning("Could not load plugin {0} ({1})".format(d, e)) continue return result
[ "def", "load_installed_plugins", "(", "self", ")", ":", "result", "=", "[", "]", "plugin_dirs", "=", "[", "d", "for", "d", "in", "os", ".", "listdir", "(", "self", ".", "plugin_path", ")", "if", "os", ".", "path", ".", "isdir", "(", "os", ".", "pat...
:rtype: list of Plugin
[ ":", "rtype", ":", "list", "of", "Plugin" ]
python
train
buckhx/QuadKey
quadkey/__init__.py
https://github.com/buckhx/QuadKey/blob/546338f9b50b578ea765d3bf84b944db48dbec5b/quadkey/__init__.py#L33-L41
def is_ancestor(self, node): """ If node is ancestor of self Get the difference in level If not, None """ if self.level <= node.level or self.key[:len(node.key)] != node.key: return None return self.level - node.level
[ "def", "is_ancestor", "(", "self", ",", "node", ")", ":", "if", "self", ".", "level", "<=", "node", ".", "level", "or", "self", ".", "key", "[", ":", "len", "(", "node", ".", "key", ")", "]", "!=", "node", ".", "key", ":", "return", "None", "re...
If node is ancestor of self Get the difference in level If not, None
[ "If", "node", "is", "ancestor", "of", "self", "Get", "the", "difference", "in", "level", "If", "not", "None" ]
python
train
fhamborg/news-please
newsplease/helper_classes/url_extractor.py
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/helper_classes/url_extractor.py#L31-L42
def get_allowed_domain(url, allow_subdomains=True): """ Determines the url's domain. :param str url: the url to extract the allowed domain from :param bool allow_subdomains: determines wether to include subdomains :return str: subdomains.domain.topleveldomain or domain.topleveldomain """ if allow_subdomains: return re.sub(re_www, '', re.search(r'[^/]+\.[^/]+', url).group(0)) else: return re.search(re_domain, UrlExtractor.get_allowed_domain(url)).group(0)
[ "def", "get_allowed_domain", "(", "url", ",", "allow_subdomains", "=", "True", ")", ":", "if", "allow_subdomains", ":", "return", "re", ".", "sub", "(", "re_www", ",", "''", ",", "re", ".", "search", "(", "r'[^/]+\\.[^/]+'", ",", "url", ")", ".", "group"...
Determines the url's domain. :param str url: the url to extract the allowed domain from :param bool allow_subdomains: determines wether to include subdomains :return str: subdomains.domain.topleveldomain or domain.topleveldomain
[ "Determines", "the", "url", "s", "domain", "." ]
python
train
alvinwan/TexSoup
TexSoup/data.py
https://github.com/alvinwan/TexSoup/blob/63323ed71510fd2351102b8c36660a3b7703cead/TexSoup/data.py#L386-L411
def delete(self): r"""Delete this node from the parse tree. Where applicable, this will remove all descendants of this node from the parse tree. >>> from TexSoup import TexSoup >>> soup = TexSoup(r'''\textit{\color{blue}{Silly}}\textit{keep me!}''') >>> soup.textit.color.delete() >>> soup \textit{}\textit{keep me!} >>> soup.textit.delete() >>> soup \textit{keep me!} """ # TODO: needs better abstraction for supports contents parent = self.parent if parent.expr._supports_contents(): parent.remove(self) return # TODO: needs abstraction for removing from arg for arg in parent.args: if self.expr in arg.contents: arg.contents.remove(self.expr)
[ "def", "delete", "(", "self", ")", ":", "# TODO: needs better abstraction for supports contents", "parent", "=", "self", ".", "parent", "if", "parent", ".", "expr", ".", "_supports_contents", "(", ")", ":", "parent", ".", "remove", "(", "self", ")", "return", ...
r"""Delete this node from the parse tree. Where applicable, this will remove all descendants of this node from the parse tree. >>> from TexSoup import TexSoup >>> soup = TexSoup(r'''\textit{\color{blue}{Silly}}\textit{keep me!}''') >>> soup.textit.color.delete() >>> soup \textit{}\textit{keep me!} >>> soup.textit.delete() >>> soup \textit{keep me!}
[ "r", "Delete", "this", "node", "from", "the", "parse", "tree", "." ]
python
train
twilio/twilio-python
twilio/rest/sync/v1/service/sync_list/__init__.py
https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/sync/v1/service/sync_list/__init__.py#L102-L123
def page(self, page_token=values.unset, page_number=values.unset, page_size=values.unset): """ Retrieve a single page of SyncListInstance records from the API. Request is executed immediately :param str page_token: PageToken provided by the API :param int page_number: Page Number, this value is simply for client state :param int page_size: Number of records to return, defaults to 50 :returns: Page of SyncListInstance :rtype: twilio.rest.sync.v1.service.sync_list.SyncListPage """ params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) response = self._version.page( 'GET', self._uri, params=params, ) return SyncListPage(self._version, response, self._solution)
[ "def", "page", "(", "self", ",", "page_token", "=", "values", ".", "unset", ",", "page_number", "=", "values", ".", "unset", ",", "page_size", "=", "values", ".", "unset", ")", ":", "params", "=", "values", ".", "of", "(", "{", "'PageToken'", ":", "p...
Retrieve a single page of SyncListInstance records from the API. Request is executed immediately :param str page_token: PageToken provided by the API :param int page_number: Page Number, this value is simply for client state :param int page_size: Number of records to return, defaults to 50 :returns: Page of SyncListInstance :rtype: twilio.rest.sync.v1.service.sync_list.SyncListPage
[ "Retrieve", "a", "single", "page", "of", "SyncListInstance", "records", "from", "the", "API", ".", "Request", "is", "executed", "immediately" ]
python
train
briwilcox/Concurrent-Pandas
concurrentpandas.py
https://github.com/briwilcox/Concurrent-Pandas/blob/22cb392dacb712e1bdb5b60c6ba7015c38445c99/concurrentpandas.py#L259-L266
def set_source_google_finance(self): """ Set data source to Google Finance """ self.data_worker = data_worker self.worker_args = {"function": pandas.io.data.DataReader, "input": self.input_queue, "output": self.output_map, "source": 'google'} self.source_name = "Google Finance"
[ "def", "set_source_google_finance", "(", "self", ")", ":", "self", ".", "data_worker", "=", "data_worker", "self", ".", "worker_args", "=", "{", "\"function\"", ":", "pandas", ".", "io", ".", "data", ".", "DataReader", ",", "\"input\"", ":", "self", ".", "...
Set data source to Google Finance
[ "Set", "data", "source", "to", "Google", "Finance" ]
python
train
librosa/librosa
examples/estimate_tuning.py
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/examples/estimate_tuning.py#L15-L28
def estimate_tuning(input_file): '''Load an audio file and estimate tuning (in cents)''' print('Loading ', input_file) y, sr = librosa.load(input_file) print('Separating harmonic component ... ') y_harm = librosa.effects.harmonic(y) print('Estimating tuning ... ') # Just track the pitches associated with high magnitude tuning = librosa.estimate_tuning(y=y_harm, sr=sr) print('{:+0.2f} cents'.format(100 * tuning))
[ "def", "estimate_tuning", "(", "input_file", ")", ":", "print", "(", "'Loading '", ",", "input_file", ")", "y", ",", "sr", "=", "librosa", ".", "load", "(", "input_file", ")", "print", "(", "'Separating harmonic component ... '", ")", "y_harm", "=", "librosa",...
Load an audio file and estimate tuning (in cents)
[ "Load", "an", "audio", "file", "and", "estimate", "tuning", "(", "in", "cents", ")" ]
python
test
RudolfCardinal/pythonlib
cardinal_pythonlib/timing.py
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/timing.py#L81-L106
def start(self, name: str, increment_count: bool = True) -> None: """ Start a named timer. Args: name: name of the timer increment_count: increment the start count for this timer """ if not self._timing: return now = get_now_utc_pendulum() # If we were already timing something else, pause that. if self._stack: last = self._stack[-1] self._totaldurations[last] += now - self._starttimes[last] # Start timing our new thing if name not in self._starttimes: self._totaldurations[name] = datetime.timedelta() self._count[name] = 0 self._starttimes[name] = now if increment_count: self._count[name] += 1 self._stack.append(name)
[ "def", "start", "(", "self", ",", "name", ":", "str", ",", "increment_count", ":", "bool", "=", "True", ")", "->", "None", ":", "if", "not", "self", ".", "_timing", ":", "return", "now", "=", "get_now_utc_pendulum", "(", ")", "# If we were already timing s...
Start a named timer. Args: name: name of the timer increment_count: increment the start count for this timer
[ "Start", "a", "named", "timer", "." ]
python
train
sernst/cauldron
cauldron/session/reloading.py
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/reloading.py#L96-L143
def reload_module( module: typing.Union[str, types.ModuleType], recursive: bool, force: bool ) -> bool: """ Reloads the specified module, which can either be a module object or a string name of a module. Will not reload a module that has not been imported :param module: A module object or string module name that should be refreshed if its currently loaded version is out of date or the action is forced. :param recursive: When true, any imported sub-modules of this module will also be refreshed if they have been updated. :param force: When true, all modules will be refreshed even if it doesn't appear that they have been updated. :return: """ if isinstance(module, str): module = get_module(module) if module is None or not isinstance(module, types.ModuleType): return False try: step = session.project.get_internal_project().current_step modified = step.last_modified if step else None except AttributeError: modified = 0 if modified is None: # If the step has no modified time it hasn't been run yet and # a reload won't be needed return False newer_than = modified if not force and modified else 0 if recursive: children_reloaded = reload_children(module, newer_than) else: children_reloaded = False reloaded = do_reload(module, newer_than) return reloaded or children_reloaded
[ "def", "reload_module", "(", "module", ":", "typing", ".", "Union", "[", "str", ",", "types", ".", "ModuleType", "]", ",", "recursive", ":", "bool", ",", "force", ":", "bool", ")", "->", "bool", ":", "if", "isinstance", "(", "module", ",", "str", ")"...
Reloads the specified module, which can either be a module object or a string name of a module. Will not reload a module that has not been imported :param module: A module object or string module name that should be refreshed if its currently loaded version is out of date or the action is forced. :param recursive: When true, any imported sub-modules of this module will also be refreshed if they have been updated. :param force: When true, all modules will be refreshed even if it doesn't appear that they have been updated. :return:
[ "Reloads", "the", "specified", "module", "which", "can", "either", "be", "a", "module", "object", "or", "a", "string", "name", "of", "a", "module", ".", "Will", "not", "reload", "a", "module", "that", "has", "not", "been", "imported" ]
python
train
saltant-org/saltant-py
saltant/models/resource.py
https://github.com/saltant-org/saltant-py/blob/bf3bdbc4ec9c772c7f621f8bd6a76c5932af68be/saltant/models/resource.py#L131-L157
def get(self, id): """Get the model instance with a given id. Args: id (int or str): The primary identifier (e.g., pk or UUID) for the task instance to get. Returns: :class:`saltant.models.resource.Model`: A :class:`saltant.models.resource.Model` subclass instance representing the resource requested. """ # Get the object request_url = self._client.base_api_url + self.detail_url.format(id=id) response = self._client.session.get(request_url) # Validate that the request was successful self.validate_request_success( response_text=response.text, request_url=request_url, status_code=response.status_code, expected_status_code=HTTP_200_OK, ) # Return a model instance return self.response_data_to_model_instance(response.json())
[ "def", "get", "(", "self", ",", "id", ")", ":", "# Get the object", "request_url", "=", "self", ".", "_client", ".", "base_api_url", "+", "self", ".", "detail_url", ".", "format", "(", "id", "=", "id", ")", "response", "=", "self", ".", "_client", ".",...
Get the model instance with a given id. Args: id (int or str): The primary identifier (e.g., pk or UUID) for the task instance to get. Returns: :class:`saltant.models.resource.Model`: A :class:`saltant.models.resource.Model` subclass instance representing the resource requested.
[ "Get", "the", "model", "instance", "with", "a", "given", "id", "." ]
python
train
iterative/dvc
dvc/utils/compat.py
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/utils/compat.py#L68-L90
def _makedirs(name, mode=0o777, exist_ok=False): """Source: https://github.com/python/cpython/blob/ 3ce3dea60646d8a5a1c952469a2eb65f937875b3/Lib/os.py#L196-L226 """ head, tail = os.path.split(name) if not tail: head, tail = os.path.split(head) if head and tail and not os.path.exists(head): try: _makedirs(head, exist_ok=exist_ok) except OSError as e: if e.errno != errno.EEXIST: raise cdir = os.curdir if isinstance(tail, bytes): cdir = bytes(os.curdir, "ASCII") if tail == cdir: return try: os.mkdir(name, mode) except OSError: if not exist_ok or not os.path.isdir(name): raise
[ "def", "_makedirs", "(", "name", ",", "mode", "=", "0o777", ",", "exist_ok", "=", "False", ")", ":", "head", ",", "tail", "=", "os", ".", "path", ".", "split", "(", "name", ")", "if", "not", "tail", ":", "head", ",", "tail", "=", "os", ".", "pa...
Source: https://github.com/python/cpython/blob/ 3ce3dea60646d8a5a1c952469a2eb65f937875b3/Lib/os.py#L196-L226
[ "Source", ":", "https", ":", "//", "github", ".", "com", "/", "python", "/", "cpython", "/", "blob", "/", "3ce3dea60646d8a5a1c952469a2eb65f937875b3", "/", "Lib", "/", "os", ".", "py#L196", "-", "L226" ]
python
train
spacetelescope/stsci.tools
lib/stsci/tools/teal.py
https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/teal.py#L232-L237
def load(theTask, canExecute=True, strict=True, defaults=False): """ Shortcut to load TEAL .cfg files for non-GUI access where loadOnly=True. """ return teal(theTask, parent=None, loadOnly=True, returnAs="dict", canExecute=canExecute, strict=strict, errorsToTerm=True, defaults=defaults)
[ "def", "load", "(", "theTask", ",", "canExecute", "=", "True", ",", "strict", "=", "True", ",", "defaults", "=", "False", ")", ":", "return", "teal", "(", "theTask", ",", "parent", "=", "None", ",", "loadOnly", "=", "True", ",", "returnAs", "=", "\"d...
Shortcut to load TEAL .cfg files for non-GUI access where loadOnly=True.
[ "Shortcut", "to", "load", "TEAL", ".", "cfg", "files", "for", "non", "-", "GUI", "access", "where", "loadOnly", "=", "True", "." ]
python
train
stephen-bunn/file-config
src/file_config/handlers/msgpack.py
https://github.com/stephen-bunn/file-config/blob/93429360c949985202e1f2b9cd0340731819ba75/src/file_config/handlers/msgpack.py#L27-L37
def on_msgpack_loads(self, msgpack, config, content, **kwargs): """ The `msgpack <https://pypi.org/project/msgpack/>`_ loads method. :param module msgpack: The ``msgpack`` module :param class config: The loading config class :param dict content: The serialized content to deserialize :returns: The deserialized dictionary :rtype: dict """ return msgpack.loads(content, raw=False)
[ "def", "on_msgpack_loads", "(", "self", ",", "msgpack", ",", "config", ",", "content", ",", "*", "*", "kwargs", ")", ":", "return", "msgpack", ".", "loads", "(", "content", ",", "raw", "=", "False", ")" ]
The `msgpack <https://pypi.org/project/msgpack/>`_ loads method. :param module msgpack: The ``msgpack`` module :param class config: The loading config class :param dict content: The serialized content to deserialize :returns: The deserialized dictionary :rtype: dict
[ "The", "msgpack", "<https", ":", "//", "pypi", ".", "org", "/", "project", "/", "msgpack", "/", ">", "_", "loads", "method", "." ]
python
train
geertj/gruvi
vendor/txdbus/marshal.py
https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/vendor/txdbus/marshal.py#L783-L815
def unmarshal( compoundSignature, data, offset = 0, lendian = True ): """ Unmarshals DBus encoded data. @type compoundSignature: C{string} @param compoundSignature: DBus signature specifying the encoded value types @type data: C{string} @param data: Binary data @type offset: C{int} @param offset: Offset within data at which data for compoundSignature starts (used during recursion) @type lendian: C{bool} @param lendian: True if data is encoded in little-endian format @returns: (number_of_bytes_decoded, list_of_values) """ values = list() start_offset = offset for ct in genCompleteTypes( compoundSignature ): tcode = ct[0] offset += len(pad[tcode]( offset )) nbytes, value = unmarshallers[ tcode ]( ct, data, offset, lendian ) offset += nbytes values.append( value ) return offset - start_offset, values
[ "def", "unmarshal", "(", "compoundSignature", ",", "data", ",", "offset", "=", "0", ",", "lendian", "=", "True", ")", ":", "values", "=", "list", "(", ")", "start_offset", "=", "offset", "for", "ct", "in", "genCompleteTypes", "(", "compoundSignature", ")",...
Unmarshals DBus encoded data. @type compoundSignature: C{string} @param compoundSignature: DBus signature specifying the encoded value types @type data: C{string} @param data: Binary data @type offset: C{int} @param offset: Offset within data at which data for compoundSignature starts (used during recursion) @type lendian: C{bool} @param lendian: True if data is encoded in little-endian format @returns: (number_of_bytes_decoded, list_of_values)
[ "Unmarshals", "DBus", "encoded", "data", "." ]
python
train
funilrys/PyFunceble
PyFunceble/mining.py
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/mining.py#L243-L252
def _backup(self): """ Backup the mined informations. """ if PyFunceble.CONFIGURATION["mining"]: # The mining is activated. # We backup our mined informations. Dict(PyFunceble.INTERN["mined"]).to_json(self.file)
[ "def", "_backup", "(", "self", ")", ":", "if", "PyFunceble", ".", "CONFIGURATION", "[", "\"mining\"", "]", ":", "# The mining is activated.", "# We backup our mined informations.", "Dict", "(", "PyFunceble", ".", "INTERN", "[", "\"mined\"", "]", ")", ".", "to_json...
Backup the mined informations.
[ "Backup", "the", "mined", "informations", "." ]
python
test
EnigmaBridge/client.py
ebclient/eb_registration.py
https://github.com/EnigmaBridge/client.py/blob/0fafe3902da394da88e9f960751d695ca65bbabd/ebclient/eb_registration.py#L62-L92
def call(self, client_data=None, api_data=None, aux_data=None, *args, **kwargs): """ Calls the request with input data using given configuration (retry, timeout, ...). :param client_data: :param api_data: :param aux_data: :param args: :param kwargs: :return: """ self.build_request(client_data=client_data, api_data=api_data, aux_data=aux_data) self.caller = RequestCall(self.request) try: self.caller.call() self.response = self.caller.response if self.response is None: raise ValueError('Empty response') if self.response.response is None \ or 'response' not in self.response.response \ or self.response.response['response'] is None: raise ValueError('No result data') return self.response.response['response'] except Exception as e: logger.debug('Exception traceback: %s' % traceback.format_exc()) logger.info('Exception thrown %s' % e) raise pass
[ "def", "call", "(", "self", ",", "client_data", "=", "None", ",", "api_data", "=", "None", ",", "aux_data", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "build_request", "(", "client_data", "=", "client_data", ",", "...
Calls the request with input data using given configuration (retry, timeout, ...). :param client_data: :param api_data: :param aux_data: :param args: :param kwargs: :return:
[ "Calls", "the", "request", "with", "input", "data", "using", "given", "configuration", "(", "retry", "timeout", "...", ")", ".", ":", "param", "client_data", ":", ":", "param", "api_data", ":", ":", "param", "aux_data", ":", ":", "param", "args", ":", ":...
python
train
Azure/azure-sdk-for-python
azure-servicemanagement-legacy/azure/servicemanagement/servicebusmanagementservice.py
https://github.com/Azure/azure-sdk-for-python/blob/d7306fde32f60a293a7567678692bdad31e4b667/azure-servicemanagement-legacy/azure/servicemanagement/servicebusmanagementservice.py#L284-L303
def get_supported_metrics_notification_hub(self, name, hub_name): ''' Retrieves the list of supported metrics for this namespace and topic name: Name of the service bus namespace. hub_name: Name of the service bus notification hub in this namespace. ''' response = self._perform_get( self._get_get_supported_metrics_hub_path(name, hub_name), None) return _MinidomXmlToObject.convert_response_to_feeds( response, partial( _ServiceBusManagementXmlSerializer.xml_to_metrics, object_type=MetricProperties ) )
[ "def", "get_supported_metrics_notification_hub", "(", "self", ",", "name", ",", "hub_name", ")", ":", "response", "=", "self", ".", "_perform_get", "(", "self", ".", "_get_get_supported_metrics_hub_path", "(", "name", ",", "hub_name", ")", ",", "None", ")", "ret...
Retrieves the list of supported metrics for this namespace and topic name: Name of the service bus namespace. hub_name: Name of the service bus notification hub in this namespace.
[ "Retrieves", "the", "list", "of", "supported", "metrics", "for", "this", "namespace", "and", "topic" ]
python
test
pvlib/pvlib-python
pvlib/iotools/midc.py
https://github.com/pvlib/pvlib-python/blob/2e844a595b820b43d1170269781fa66bd0ccc8a3/pvlib/iotools/midc.py#L30-L64
def map_midc_to_pvlib(variable_map, field_name): """A mapper function to rename Dataframe columns to their pvlib counterparts. Parameters ---------- variable_map: Dictionary A dictionary for mapping MIDC field name to pvlib name. See VARIABLE_MAP for default value and description of how to construct this argument. field_name: string The Column to map. Returns ------- label: string The pvlib variable name associated with the MIDC field or the input if a mapping does not exist. Notes ----- Will fail if field_name to be mapped matches an entry in VARIABLE_MAP and does not contain brackets. This should not be an issue unless MIDC file headers are updated. """ new_field_name = field_name for midc_name, pvlib_name in variable_map.items(): if field_name.startswith(midc_name): # extract the instrument and units field and then remove units instrument_units = field_name[len(midc_name):] units_index = instrument_units.find('[') instrument = instrument_units[:units_index - 1] new_field_name = pvlib_name + instrument.replace(' ', '_') break return new_field_name
[ "def", "map_midc_to_pvlib", "(", "variable_map", ",", "field_name", ")", ":", "new_field_name", "=", "field_name", "for", "midc_name", ",", "pvlib_name", "in", "variable_map", ".", "items", "(", ")", ":", "if", "field_name", ".", "startswith", "(", "midc_name", ...
A mapper function to rename Dataframe columns to their pvlib counterparts. Parameters ---------- variable_map: Dictionary A dictionary for mapping MIDC field name to pvlib name. See VARIABLE_MAP for default value and description of how to construct this argument. field_name: string The Column to map. Returns ------- label: string The pvlib variable name associated with the MIDC field or the input if a mapping does not exist. Notes ----- Will fail if field_name to be mapped matches an entry in VARIABLE_MAP and does not contain brackets. This should not be an issue unless MIDC file headers are updated.
[ "A", "mapper", "function", "to", "rename", "Dataframe", "columns", "to", "their", "pvlib", "counterparts", "." ]
python
train
a1ezzz/wasp-general
wasp_general/network/clients/virtual_dir.py
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/clients/virtual_dir.py#L105-L111
def full_path(self): """ Return a full path to a current session directory. A result is made by joining a start path with current session directory :return: str """ return self.normalize_path(self.directory_sep().join((self.start_path(), self.session_path())))
[ "def", "full_path", "(", "self", ")", ":", "return", "self", ".", "normalize_path", "(", "self", ".", "directory_sep", "(", ")", ".", "join", "(", "(", "self", ".", "start_path", "(", ")", ",", "self", ".", "session_path", "(", ")", ")", ")", ")" ]
Return a full path to a current session directory. A result is made by joining a start path with current session directory :return: str
[ "Return", "a", "full", "path", "to", "a", "current", "session", "directory", ".", "A", "result", "is", "made", "by", "joining", "a", "start", "path", "with", "current", "session", "directory" ]
python
train
koalalorenzo/python-digitalocean
digitalocean/Volume.py
https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Volume.py#L21-L27
def get_object(cls, api_token, volume_id): """ Class method that will return an Volume object by ID. """ volume = cls(token=api_token, id=volume_id) volume.load() return volume
[ "def", "get_object", "(", "cls", ",", "api_token", ",", "volume_id", ")", ":", "volume", "=", "cls", "(", "token", "=", "api_token", ",", "id", "=", "volume_id", ")", "volume", ".", "load", "(", ")", "return", "volume" ]
Class method that will return an Volume object by ID.
[ "Class", "method", "that", "will", "return", "an", "Volume", "object", "by", "ID", "." ]
python
valid
aio-libs/aiohttp
aiohttp/web_middlewares.py
https://github.com/aio-libs/aiohttp/blob/9504fe2affaaff673fa4f3754c1c44221f8ba47d/aiohttp/web_middlewares.py#L42-L111
def normalize_path_middleware( *, append_slash: bool=True, remove_slash: bool=False, merge_slashes: bool=True, redirect_class: Type[HTTPMove]=HTTPMovedPermanently) -> _Middleware: """ Middleware factory which produces a middleware that normalizes the path of a request. By normalizing it means: - Add or remove a trailing slash to the path. - Double slashes are replaced by one. The middleware returns as soon as it finds a path that resolves correctly. The order if both merge and append/remove are enabled is 1) merge slashes 2) append/remove slash 3) both merge slashes and append/remove slash. If the path resolves with at least one of those conditions, it will redirect to the new path. Only one of `append_slash` and `remove_slash` can be enabled. If both are `True` the factory will raise an assertion error If `append_slash` is `True` the middleware will append a slash when needed. If a resource is defined with trailing slash and the request comes without it, it will append it automatically. If `remove_slash` is `True`, `append_slash` must be `False`. When enabled the middleware will remove trailing slashes and redirect if the resource is defined If merge_slashes is True, merge multiple consecutive slashes in the path into one. """ correct_configuration = not (append_slash and remove_slash) assert correct_configuration, "Cannot both remove and append slash" @middleware async def impl(request: Request, handler: _Handler) -> StreamResponse: if isinstance(request.match_info.route, SystemRoute): paths_to_check = [] if '?' in request.raw_path: path, query = request.raw_path.split('?', 1) query = '?' + query else: query = '' path = request.raw_path if merge_slashes: paths_to_check.append(re.sub('//+', '/', path)) if append_slash and not request.path.endswith('/'): paths_to_check.append(path + '/') if remove_slash and request.path.endswith('/'): paths_to_check.append(path[:-1]) if merge_slashes and append_slash: paths_to_check.append( re.sub('//+', '/', path + '/')) if merge_slashes and remove_slash and path.endswith('/'): merged_slashes = re.sub('//+', '/', path) paths_to_check.append(merged_slashes[:-1]) for path in paths_to_check: resolves, request = await _check_request_resolves( request, path) if resolves: raise redirect_class(request.raw_path + query) return await handler(request) return impl
[ "def", "normalize_path_middleware", "(", "*", ",", "append_slash", ":", "bool", "=", "True", ",", "remove_slash", ":", "bool", "=", "False", ",", "merge_slashes", ":", "bool", "=", "True", ",", "redirect_class", ":", "Type", "[", "HTTPMove", "]", "=", "HTT...
Middleware factory which produces a middleware that normalizes the path of a request. By normalizing it means: - Add or remove a trailing slash to the path. - Double slashes are replaced by one. The middleware returns as soon as it finds a path that resolves correctly. The order if both merge and append/remove are enabled is 1) merge slashes 2) append/remove slash 3) both merge slashes and append/remove slash. If the path resolves with at least one of those conditions, it will redirect to the new path. Only one of `append_slash` and `remove_slash` can be enabled. If both are `True` the factory will raise an assertion error If `append_slash` is `True` the middleware will append a slash when needed. If a resource is defined with trailing slash and the request comes without it, it will append it automatically. If `remove_slash` is `True`, `append_slash` must be `False`. When enabled the middleware will remove trailing slashes and redirect if the resource is defined If merge_slashes is True, merge multiple consecutive slashes in the path into one.
[ "Middleware", "factory", "which", "produces", "a", "middleware", "that", "normalizes", "the", "path", "of", "a", "request", ".", "By", "normalizing", "it", "means", ":" ]
python
train
TimBest/django-multi-form-view
multi_form_view/base.py
https://github.com/TimBest/django-multi-form-view/blob/d7f0a341881a5a36e4d567ca9bc29d233de01720/multi_form_view/base.py#L15-L22
def are_forms_valid(self, forms): """ Check if all forms defined in `form_classes` are valid. """ for form in six.itervalues(forms): if not form.is_valid(): return False return True
[ "def", "are_forms_valid", "(", "self", ",", "forms", ")", ":", "for", "form", "in", "six", ".", "itervalues", "(", "forms", ")", ":", "if", "not", "form", ".", "is_valid", "(", ")", ":", "return", "False", "return", "True" ]
Check if all forms defined in `form_classes` are valid.
[ "Check", "if", "all", "forms", "defined", "in", "form_classes", "are", "valid", "." ]
python
train
F5Networks/f5-common-python
f5/bigip/resource.py
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/resource.py#L475-L504
def _check_keys(self, rdict): """Call this from _local_update to validate response keys disallowed server-response json keys: 1. The string-literal '_meta_data' 2. strings that are not valid Python 2.7 identifiers 3. strings beginning with '__'. :param rdict: from response.json() :raises: DeviceProvidesIncompatibleKey :returns: checked response rdict """ if '_meta_data' in rdict: error_message = "Response contains key '_meta_data' which is "\ "incompatible with this API!!\n Response json: %r" % rdict raise DeviceProvidesIncompatibleKey(error_message) for x in rdict: if not re.match(tokenize.Name, x): error_message = "Device provided %r which is disallowed"\ " because it's not a valid Python 2.7 identifier." % x raise DeviceProvidesIncompatibleKey(error_message) elif keyword.iskeyword(x): # If attribute is keyword, append underscore to attribute name rdict[x + '_'] = rdict[x] rdict.pop(x) elif x.startswith('__'): error_message = "Device provided %r which is disallowed"\ ", it mangles into a Python non-public attribute." % x raise DeviceProvidesIncompatibleKey(error_message) return rdict
[ "def", "_check_keys", "(", "self", ",", "rdict", ")", ":", "if", "'_meta_data'", "in", "rdict", ":", "error_message", "=", "\"Response contains key '_meta_data' which is \"", "\"incompatible with this API!!\\n Response json: %r\"", "%", "rdict", "raise", "DeviceProvidesIncomp...
Call this from _local_update to validate response keys disallowed server-response json keys: 1. The string-literal '_meta_data' 2. strings that are not valid Python 2.7 identifiers 3. strings beginning with '__'. :param rdict: from response.json() :raises: DeviceProvidesIncompatibleKey :returns: checked response rdict
[ "Call", "this", "from", "_local_update", "to", "validate", "response", "keys" ]
python
train
albahnsen/CostSensitiveClassification
costcla/datasets/base.py
https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/datasets/base.py#L336-L415
def _creditscoring_costmat(income, debt, pi_1, cost_mat_parameters): """ Private function to calculate the cost matrix of credit scoring models. Parameters ---------- income : array of shape = [n_samples] Monthly income of each example debt : array of shape = [n_samples] Debt ratio each example pi_1 : float Percentage of positives in the training set References ---------- .. [1] A. Correa Bahnsen, D.Aouada, B, Ottersten, "Example-Dependent Cost-Sensitive Logistic Regression for Credit Scoring", in Proceedings of the International Conference on Machine Learning and Applications, , 2014. Returns ------- cost_mat : array-like of shape = [n_samples, 4] Cost matrix of the classification problem Where the columns represents the costs of: false positives, false negatives, true positives and true negatives, for each example. """ def calculate_a(cl_i, int_, n_term): """ Private function """ return cl_i * ((int_ * (1 + int_) ** n_term) / ((1 + int_) ** n_term - 1)) def calculate_pv(a, int_, n_term): """ Private function """ return a / int_ * (1 - 1 / (1 + int_) ** n_term) #Calculate credit line Cl def calculate_cl(k, inc_i, cl_max, debt_i, int_r, n_term): """ Private function """ cl_k = k * inc_i A = calculate_a(cl_k, int_r, n_term) Cl_debt = calculate_pv(inc_i * min(A / inc_i, 1 - debt_i), int_r, n_term) return min(cl_k, cl_max, Cl_debt) #calculate costs def calculate_cost_fn(cl_i, lgd): return cl_i * lgd def calculate_cost_fp(cl_i, int_r, n_term, int_cf, pi_1, lgd, cl_avg): a = calculate_a(cl_i, int_r, n_term) pv = calculate_pv(a, int_cf, n_term) r = pv - cl_i r_avg = calculate_pv(calculate_a(cl_avg, int_r, n_term), int_cf, n_term) - cl_avg cost_fp = r - (1 - pi_1) * r_avg + pi_1 * calculate_cost_fn(cl_avg, lgd) return max(0, cost_fp) v_calculate_cost_fp = np.vectorize(calculate_cost_fp) v_calculate_cost_fn = np.vectorize(calculate_cost_fn) v_calculate_cl = np.vectorize(calculate_cl) # Parameters k = cost_mat_parameters['k'] int_r = cost_mat_parameters['int_r'] n_term = cost_mat_parameters['n_term'] int_cf = cost_mat_parameters['int_cf'] lgd = cost_mat_parameters['lgd'] cl_max = cost_mat_parameters['cl_max'] cl = v_calculate_cl(k, income, cl_max, debt, int_r, n_term) cl_avg = cl.mean() n_samples = income.shape[0] cost_mat = np.zeros((n_samples, 4)) #cost_mat[FP,FN,TP,TN] cost_mat[:, 0] = v_calculate_cost_fp(cl, int_r, n_term, int_cf, pi_1, lgd, cl_avg) cost_mat[:, 1] = v_calculate_cost_fn(cl, lgd) cost_mat[:, 2] = 0.0 cost_mat[:, 3] = 0.0 return cost_mat
[ "def", "_creditscoring_costmat", "(", "income", ",", "debt", ",", "pi_1", ",", "cost_mat_parameters", ")", ":", "def", "calculate_a", "(", "cl_i", ",", "int_", ",", "n_term", ")", ":", "\"\"\" Private function \"\"\"", "return", "cl_i", "*", "(", "(", "int_", ...
Private function to calculate the cost matrix of credit scoring models. Parameters ---------- income : array of shape = [n_samples] Monthly income of each example debt : array of shape = [n_samples] Debt ratio each example pi_1 : float Percentage of positives in the training set References ---------- .. [1] A. Correa Bahnsen, D.Aouada, B, Ottersten, "Example-Dependent Cost-Sensitive Logistic Regression for Credit Scoring", in Proceedings of the International Conference on Machine Learning and Applications, , 2014. Returns ------- cost_mat : array-like of shape = [n_samples, 4] Cost matrix of the classification problem Where the columns represents the costs of: false positives, false negatives, true positives and true negatives, for each example.
[ "Private", "function", "to", "calculate", "the", "cost", "matrix", "of", "credit", "scoring", "models", "." ]
python
train
saltstack/salt
salt/crypt.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/crypt.py#L1428-L1464
def decrypt(self, data): ''' verify HMAC-SHA256 signature and decrypt data with AES-CBC ''' aes_key, hmac_key = self.keys sig = data[-self.SIG_SIZE:] data = data[:-self.SIG_SIZE] if six.PY3 and not isinstance(data, bytes): data = salt.utils.stringutils.to_bytes(data) mac_bytes = hmac.new(hmac_key, data, hashlib.sha256).digest() if len(mac_bytes) != len(sig): log.debug('Failed to authenticate message') raise AuthenticationError('message authentication failed') result = 0 if six.PY2: for zipped_x, zipped_y in zip(mac_bytes, sig): result |= ord(zipped_x) ^ ord(zipped_y) else: for zipped_x, zipped_y in zip(mac_bytes, sig): result |= zipped_x ^ zipped_y if result != 0: log.debug('Failed to authenticate message') raise AuthenticationError('message authentication failed') iv_bytes = data[:self.AES_BLOCK_SIZE] data = data[self.AES_BLOCK_SIZE:] if HAS_M2: cypher = EVP.Cipher(alg='aes_192_cbc', key=aes_key, iv=iv_bytes, op=0, padding=False) encr = cypher.update(data) data = encr + cypher.final() else: cypher = AES.new(aes_key, AES.MODE_CBC, iv_bytes) data = cypher.decrypt(data) if six.PY2: return data[:-ord(data[-1])] else: return data[:-data[-1]]
[ "def", "decrypt", "(", "self", ",", "data", ")", ":", "aes_key", ",", "hmac_key", "=", "self", ".", "keys", "sig", "=", "data", "[", "-", "self", ".", "SIG_SIZE", ":", "]", "data", "=", "data", "[", ":", "-", "self", ".", "SIG_SIZE", "]", "if", ...
verify HMAC-SHA256 signature and decrypt data with AES-CBC
[ "verify", "HMAC", "-", "SHA256", "signature", "and", "decrypt", "data", "with", "AES", "-", "CBC" ]
python
train
jay-johnson/spylunking
spylunking/send_to_splunk.py
https://github.com/jay-johnson/spylunking/blob/95cc86776f04ec5935cf04e291cf18798345d6cb/spylunking/send_to_splunk.py#L3-L33
def send_to_splunk( session=None, url=None, data=None, headers=None, verify=False, ssl_options=None, timeout=10.0): """send_to_splunk Send formatted msgs to Splunk. This will throw exceptions for any errors. It is decoupled from the publishers to make testing easier with mocks. :param session: requests.Session :param url: url for splunk logs :param data: data to send :param headers: headers for splunk :param verify: verify certs :param ssl_options: certs dictionary :param timeout: timeout in seconds """ r = session.post( url=url, data=data, headers=headers, verify=verify, timeout=timeout ) r.raise_for_status() # Throws exception for 4xx/5xx status return r
[ "def", "send_to_splunk", "(", "session", "=", "None", ",", "url", "=", "None", ",", "data", "=", "None", ",", "headers", "=", "None", ",", "verify", "=", "False", ",", "ssl_options", "=", "None", ",", "timeout", "=", "10.0", ")", ":", "r", "=", "se...
send_to_splunk Send formatted msgs to Splunk. This will throw exceptions for any errors. It is decoupled from the publishers to make testing easier with mocks. :param session: requests.Session :param url: url for splunk logs :param data: data to send :param headers: headers for splunk :param verify: verify certs :param ssl_options: certs dictionary :param timeout: timeout in seconds
[ "send_to_splunk" ]
python
train
django-danceschool/django-danceschool
danceschool/financial/models.py
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/financial/models.py#L874-L880
def relatedItems(self): ''' If this item is associated with a registration, then return all other items associated with the same registration. ''' if self.registration: return self.registration.revenueitem_set.exclude(pk=self.pk)
[ "def", "relatedItems", "(", "self", ")", ":", "if", "self", ".", "registration", ":", "return", "self", ".", "registration", ".", "revenueitem_set", ".", "exclude", "(", "pk", "=", "self", ".", "pk", ")" ]
If this item is associated with a registration, then return all other items associated with the same registration.
[ "If", "this", "item", "is", "associated", "with", "a", "registration", "then", "return", "all", "other", "items", "associated", "with", "the", "same", "registration", "." ]
python
train
jhuapl-boss/intern
intern/remote/boss/remote.py
https://github.com/jhuapl-boss/intern/blob/d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed/intern/remote/boss/remote.py#L127-L147
def _init_volume_service(self, version): """ Method to initialize the Volume Service from the config data Args: version (string): Version of Boss API to use. Returns: None Raises: (KeyError): if given invalid version. """ volume_cfg = self._load_config_section(CONFIG_VOLUME_SECTION) self._token_volume = volume_cfg[CONFIG_TOKEN] proto = volume_cfg[CONFIG_PROTOCOL] host = volume_cfg[CONFIG_HOST] self._volume = VolumeService(host, version) self._volume.base_protocol = proto self._volume.set_auth(self._token_volume)
[ "def", "_init_volume_service", "(", "self", ",", "version", ")", ":", "volume_cfg", "=", "self", ".", "_load_config_section", "(", "CONFIG_VOLUME_SECTION", ")", "self", ".", "_token_volume", "=", "volume_cfg", "[", "CONFIG_TOKEN", "]", "proto", "=", "volume_cfg", ...
Method to initialize the Volume Service from the config data Args: version (string): Version of Boss API to use. Returns: None Raises: (KeyError): if given invalid version.
[ "Method", "to", "initialize", "the", "Volume", "Service", "from", "the", "config", "data" ]
python
train
angr/angr
angr/engines/soot/statements/base.py
https://github.com/angr/angr/blob/4e2f97d56af5419ee73bdb30482c8dd8ff5f3e40/angr/engines/soot/statements/base.py#L41-L57
def _get_bb_addr_from_instr(self, instr): """ Returns the address of the methods basic block that contains the given instruction. :param instr: The index of the instruction (within the current method). :rtype: SootAddressDescriptor """ current_method = self.state.addr.method try: bb = current_method.block_by_label[instr] except KeyError: l.error("Possible jump to a non-existing bb %s --> %d", self.state.addr, instr) raise IncorrectLocationException() return SootAddressDescriptor(current_method, bb.idx, 0)
[ "def", "_get_bb_addr_from_instr", "(", "self", ",", "instr", ")", ":", "current_method", "=", "self", ".", "state", ".", "addr", ".", "method", "try", ":", "bb", "=", "current_method", ".", "block_by_label", "[", "instr", "]", "except", "KeyError", ":", "l...
Returns the address of the methods basic block that contains the given instruction. :param instr: The index of the instruction (within the current method). :rtype: SootAddressDescriptor
[ "Returns", "the", "address", "of", "the", "methods", "basic", "block", "that", "contains", "the", "given", "instruction", "." ]
python
train
tensorflow/tensor2tensor
tensor2tensor/models/research/glow_ops.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/glow_ops.py#L53-L82
def linear_interpolate_rank(tensor1, tensor2, coeffs, rank=1): """Linearly interpolate channel at "rank" between two tensors. The channels are ranked according to their L2 norm between tensor1[channel] and tensor2[channel]. Args: tensor1: 4-D Tensor, NHWC tensor2: 4-D Tensor, NHWC coeffs: list of floats. rank: integer. Returns: interp_latents: list of interpolated 4-D Tensors, shape=(NHWC) """ # sum across space, max across channels. _, _, _, num_channels = common_layers.shape_list(tensor1) diff_sq_sum = tf.reduce_sum((tensor1 - tensor2)**2, axis=(0, 1, 2)) _, feature_ranks = tf.math.top_k(diff_sq_sum, k=rank) feature_rank = feature_ranks[-1] channel_inds = tf.range(num_channels, dtype=tf.int32) channel_mask = tf.equal(channel_inds, feature_rank) ones_t = tf.ones(num_channels, dtype=tf.float32) zeros_t = tf.zeros(num_channels, dtype=tf.float32) interp_tensors = [] for coeff in coeffs: curr_coeff = tf.where(channel_mask, coeff * ones_t, zeros_t) interp_tensor = tensor1 + curr_coeff * (tensor2 - tensor1) interp_tensors.append(interp_tensor) return tf.concat(interp_tensors, axis=0)
[ "def", "linear_interpolate_rank", "(", "tensor1", ",", "tensor2", ",", "coeffs", ",", "rank", "=", "1", ")", ":", "# sum across space, max across channels.", "_", ",", "_", ",", "_", ",", "num_channels", "=", "common_layers", ".", "shape_list", "(", "tensor1", ...
Linearly interpolate channel at "rank" between two tensors. The channels are ranked according to their L2 norm between tensor1[channel] and tensor2[channel]. Args: tensor1: 4-D Tensor, NHWC tensor2: 4-D Tensor, NHWC coeffs: list of floats. rank: integer. Returns: interp_latents: list of interpolated 4-D Tensors, shape=(NHWC)
[ "Linearly", "interpolate", "channel", "at", "rank", "between", "two", "tensors", "." ]
python
train
pyviz/holoviews
holoviews/core/util.py
https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/core/util.py#L1984-L1990
def search_indices(values, source): """ Given a set of values returns the indices of each of those values in the source array. """ orig_indices = source.argsort() return orig_indices[np.searchsorted(source[orig_indices], values)]
[ "def", "search_indices", "(", "values", ",", "source", ")", ":", "orig_indices", "=", "source", ".", "argsort", "(", ")", "return", "orig_indices", "[", "np", ".", "searchsorted", "(", "source", "[", "orig_indices", "]", ",", "values", ")", "]" ]
Given a set of values returns the indices of each of those values in the source array.
[ "Given", "a", "set", "of", "values", "returns", "the", "indices", "of", "each", "of", "those", "values", "in", "the", "source", "array", "." ]
python
train
DeV1doR/aioethereum
aioethereum/management/eth.py
https://github.com/DeV1doR/aioethereum/blob/85eb46550d862b3ccc309914ea871ca1c7b42157/aioethereum/management/eth.py#L136-L149
def eth_getBlockTransactionCountByHash(self, bhash): """https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_getblocktransactioncountbyhash :param bhash: Block hash :type bhash: str :return: count :rtype: int or None """ response = yield from self.rpc_call('eth_getBlockTransactionCountByHash', [bhash]) if response: return hex_to_dec(response) return response
[ "def", "eth_getBlockTransactionCountByHash", "(", "self", ",", "bhash", ")", ":", "response", "=", "yield", "from", "self", ".", "rpc_call", "(", "'eth_getBlockTransactionCountByHash'", ",", "[", "bhash", "]", ")", "if", "response", ":", "return", "hex_to_dec", ...
https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_getblocktransactioncountbyhash :param bhash: Block hash :type bhash: str :return: count :rtype: int or None
[ "https", ":", "//", "github", ".", "com", "/", "ethereum", "/", "wiki", "/", "wiki", "/", "JSON", "-", "RPC#eth_getblocktransactioncountbyhash" ]
python
train
openego/eTraGo
etrago/tools/plot.py
https://github.com/openego/eTraGo/blob/2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9/etrago/tools/plot.py#L792-L827
def plot_residual_load(network): """ Plots residual load summed of all exisiting buses. Parameters ---------- network : PyPSA network containter """ renewables = network.generators[ network.generators.carrier.isin(['wind_onshore', 'wind_offshore', 'solar', 'run_of_river', 'wind'])] renewables_t = network.generators.p_nom[renewables.index] * \ network.generators_t.p_max_pu[renewables.index].mul( network.snapshot_weightings, axis=0) load = network.loads_t.p_set.mul(network.snapshot_weightings, axis=0).\ sum(axis=1) all_renew = renewables_t.sum(axis=1) residual_load = load - all_renew plot = residual_load.plot( title = 'Residual load', drawstyle='steps', lw=2, color='red', legend=False) plot.set_ylabel("MW") # sorted curve sorted_residual_load = residual_load.sort_values( ascending=False).reset_index() plot1 = sorted_residual_load.plot( title='Sorted residual load', drawstyle='steps', lw=2, color='red', legend=False) plot1.set_ylabel("MW")
[ "def", "plot_residual_load", "(", "network", ")", ":", "renewables", "=", "network", ".", "generators", "[", "network", ".", "generators", ".", "carrier", ".", "isin", "(", "[", "'wind_onshore'", ",", "'wind_offshore'", ",", "'solar'", ",", "'run_of_river'", "...
Plots residual load summed of all exisiting buses. Parameters ---------- network : PyPSA network containter
[ "Plots", "residual", "load", "summed", "of", "all", "exisiting", "buses", "." ]
python
train
biolink/ontobio
ontobio/assoc_factory.py
https://github.com/biolink/ontobio/blob/4e512a7831cfe6bc1b32f2c3be2ba41bc5cf7345/ontobio/assoc_factory.py#L88-L102
def create_from_tuples(self, tuples, **args): """ Creates from a list of (subj,subj_name,obj) tuples """ amap = {} subject_label_map = {} for a in tuples: subj = a[0] subject_label_map[subj] = a[1] if subj not in amap: amap[subj] = [] amap[subj].append(a[2]) aset = AssociationSet(subject_label_map=subject_label_map, association_map=amap, **args) return aset
[ "def", "create_from_tuples", "(", "self", ",", "tuples", ",", "*", "*", "args", ")", ":", "amap", "=", "{", "}", "subject_label_map", "=", "{", "}", "for", "a", "in", "tuples", ":", "subj", "=", "a", "[", "0", "]", "subject_label_map", "[", "subj", ...
Creates from a list of (subj,subj_name,obj) tuples
[ "Creates", "from", "a", "list", "of", "(", "subj", "subj_name", "obj", ")", "tuples" ]
python
train
alexras/pylsdj
pylsdj/filepack.py
https://github.com/alexras/pylsdj/blob/1c45a7919dd324e941f76b315558b9647892e4d5/pylsdj/filepack.py#L141-L201
def renumber_block_keys(blocks): """Renumber a block map's indices so that tehy match the blocks' block switch statements. :param blocks a block map to renumber :rtype: a renumbered copy of the block map """ # There is an implicit block switch to the 0th block at the start of the # file byte_switch_keys = [0] block_keys = list(blocks.keys()) # Scan the blocks, recording every block switch statement for block in list(blocks.values()): i = 0 while i < len(block.data) - 1: current_byte = block.data[i] next_byte = block.data[i + 1] if current_byte == RLE_BYTE: if next_byte == RLE_BYTE: i += 2 else: i += 3 elif current_byte == SPECIAL_BYTE: if next_byte in SPECIAL_DEFAULTS: i += 3 elif next_byte == SPECIAL_BYTE: i += 2 else: if next_byte != EOF_BYTE: byte_switch_keys.append(next_byte) break else: i += 1 byte_switch_keys.sort() block_keys.sort() assert len(byte_switch_keys) == len(block_keys), ( "Number of blocks that are target of block switches (%d) " % (len(byte_switch_keys)) + "does not equal number of blocks in the song (%d)" % (len(block_keys)) + "; possible corruption") if byte_switch_keys == block_keys: # No remapping necessary return blocks new_block_map = {} for block_key, byte_switch_key in zip( block_keys, byte_switch_keys): new_block_map[byte_switch_key] = blocks[block_key] return new_block_map
[ "def", "renumber_block_keys", "(", "blocks", ")", ":", "# There is an implicit block switch to the 0th block at the start of the", "# file", "byte_switch_keys", "=", "[", "0", "]", "block_keys", "=", "list", "(", "blocks", ".", "keys", "(", ")", ")", "# Scan the blocks,...
Renumber a block map's indices so that tehy match the blocks' block switch statements. :param blocks a block map to renumber :rtype: a renumbered copy of the block map
[ "Renumber", "a", "block", "map", "s", "indices", "so", "that", "tehy", "match", "the", "blocks", "block", "switch", "statements", "." ]
python
train
LonamiWebs/Telethon
telethon/tl/custom/message.py
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon/tl/custom/message.py#L686-L701
async def delete(self, *args, **kwargs): """ Deletes the message. You're responsible for checking whether you have the permission to do so, or to except the error otherwise. Shorthand for `telethon.client.messages.MessageMethods.delete_messages` with ``entity`` and ``message_ids`` already set. If you need to delete more than one message at once, don't use this `delete` method. Use a `telethon.client.telegramclient.TelegramClient` instance directly. """ return await self._client.delete_messages( await self.get_input_chat(), [self.id], *args, **kwargs )
[ "async", "def", "delete", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "await", "self", ".", "_client", ".", "delete_messages", "(", "await", "self", ".", "get_input_chat", "(", ")", ",", "[", "self", ".", "id", "]", ...
Deletes the message. You're responsible for checking whether you have the permission to do so, or to except the error otherwise. Shorthand for `telethon.client.messages.MessageMethods.delete_messages` with ``entity`` and ``message_ids`` already set. If you need to delete more than one message at once, don't use this `delete` method. Use a `telethon.client.telegramclient.TelegramClient` instance directly.
[ "Deletes", "the", "message", ".", "You", "re", "responsible", "for", "checking", "whether", "you", "have", "the", "permission", "to", "do", "so", "or", "to", "except", "the", "error", "otherwise", ".", "Shorthand", "for", "telethon", ".", "client", ".", "m...
python
train
spyder-ide/spyder
spyder/preferences/appearance.py
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/preferences/appearance.py#L334-L377
def create_new_scheme(self): """Creates a new color scheme with a custom name.""" names = self.get_option('names') custom_names = self.get_option('custom_names', []) # Get the available number this new color scheme counter = len(custom_names) - 1 custom_index = [int(n.split('-')[-1]) for n in custom_names] for i in range(len(custom_names)): if custom_index[i] != i: counter = i - 1 break custom_name = "custom-{0}".format(counter+1) # Add the config settings, based on the current one. custom_names.append(custom_name) self.set_option('custom_names', custom_names) for key in syntaxhighlighters.COLOR_SCHEME_KEYS: name = "{0}/{1}".format(custom_name, key) default_name = "{0}/{1}".format(self.current_scheme, key) option = self.get_option(default_name) self.set_option(name, option) self.set_option('{0}/name'.format(custom_name), custom_name) # Now they need to be loaded! how to make a partial load_from_conf? dlg = self.scheme_editor_dialog dlg.add_color_scheme_stack(custom_name, custom=True) dlg.set_scheme(custom_name) self.load_from_conf() if dlg.exec_(): # This is needed to have the custom name updated on the combobox name = dlg.get_scheme_name() self.set_option('{0}/name'.format(custom_name), name) # The +1 is needed because of the separator in the combobox index = (names + custom_names).index(custom_name) + 1 self.update_combobox() self.schemes_combobox.setCurrentIndex(index) else: # Delete the config .... custom_names.remove(custom_name) self.set_option('custom_names', custom_names) dlg.delete_color_scheme_stack(custom_name)
[ "def", "create_new_scheme", "(", "self", ")", ":", "names", "=", "self", ".", "get_option", "(", "'names'", ")", "custom_names", "=", "self", ".", "get_option", "(", "'custom_names'", ",", "[", "]", ")", "# Get the available number this new color scheme", "counter...
Creates a new color scheme with a custom name.
[ "Creates", "a", "new", "color", "scheme", "with", "a", "custom", "name", "." ]
python
train
dnanexus/dx-toolkit
src/python/dxpy/api.py
https://github.com/dnanexus/dx-toolkit/blob/74befb53ad90fcf902d8983ae6d74580f402d619/src/python/dxpy/api.py#L1092-L1098
def record_add_types(object_id, input_params={}, always_retry=True, **kwargs): """ Invokes the /record-xxxx/addTypes API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Types#API-method%3A-%2Fclass-xxxx%2FaddTypes """ return DXHTTPRequest('/%s/addTypes' % object_id, input_params, always_retry=always_retry, **kwargs)
[ "def", "record_add_types", "(", "object_id", ",", "input_params", "=", "{", "}", ",", "always_retry", "=", "True", ",", "*", "*", "kwargs", ")", ":", "return", "DXHTTPRequest", "(", "'/%s/addTypes'", "%", "object_id", ",", "input_params", ",", "always_retry", ...
Invokes the /record-xxxx/addTypes API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Types#API-method%3A-%2Fclass-xxxx%2FaddTypes
[ "Invokes", "the", "/", "record", "-", "xxxx", "/", "addTypes", "API", "method", "." ]
python
train
dschreij/python-mediadecoder
mediadecoder/soundrenderers/_base.py
https://github.com/dschreij/python-mediadecoder/blob/f01b02d790f2abc52d9792e43076cf4cb7d3ce51/mediadecoder/soundrenderers/_base.py#L22-L32
def queue(self, value): """ Sets the audioqueue. Parameters ---------- value : queue.Queue The buffer from which audioframes are received. """ if not isinstance(value, Queue): raise TypeError("queue is not a Queue object") self._queue = value
[ "def", "queue", "(", "self", ",", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "Queue", ")", ":", "raise", "TypeError", "(", "\"queue is not a Queue object\"", ")", "self", ".", "_queue", "=", "value" ]
Sets the audioqueue. Parameters ---------- value : queue.Queue The buffer from which audioframes are received.
[ "Sets", "the", "audioqueue", "." ]
python
train
scoutapp/scout_apm_python
src/scout_apm/core/socket.py
https://github.com/scoutapp/scout_apm_python/blob/e5539ee23b8129be9b75d5007c88b6158b51294f/src/scout_apm/core/socket.py#L95-L132
def run(self): """ Called by the threading system """ try: self._connect() self._register() while True: try: body = self.command_queue.get(block=True, timeout=1 * SECOND) except queue.Empty: body = None if body is not None: result = self._send(body) if result: self.command_queue.task_done() else: # Something was wrong with the socket. self._disconnect() self._connect() self._register() # Check for stop event after a read from the queue. This is to # allow you to open a socket, immediately send to it, and then # stop it. We do this in the Metadata send at application start # time if self._stop_event.is_set(): logger.debug("CoreAgentSocket thread stopping.") break except Exception: logger.debug("CoreAgentSocket thread exception.") finally: self._started_event.clear() self._stop_event.clear() self._stopped_event.set() logger.debug("CoreAgentSocket thread stopped.")
[ "def", "run", "(", "self", ")", ":", "try", ":", "self", ".", "_connect", "(", ")", "self", ".", "_register", "(", ")", "while", "True", ":", "try", ":", "body", "=", "self", ".", "command_queue", ".", "get", "(", "block", "=", "True", ",", "time...
Called by the threading system
[ "Called", "by", "the", "threading", "system" ]
python
train
catherinedevlin/ddl-generator
ddlgenerator/typehelpers.py
https://github.com/catherinedevlin/ddl-generator/blob/db6741216d1e9ad84b07d4ad281bfff021d344ea/ddlgenerator/typehelpers.py#L122-L132
def worst_decimal(d1, d2): """ Given two Decimals, return a 9-filled decimal representing both enough > 0 digits and enough < 0 digits (scale) to accomodate numbers like either. >>> worst_decimal(Decimal('762.1'), Decimal('-1.983')) Decimal('999.999') """ (d1b4, d1after) = _places_b4_and_after_decimal(d1) (d2b4, d2after) = _places_b4_and_after_decimal(d2) return Decimal('9' * max(d1b4, d2b4) + '.' + '9' * max(d1after, d2after))
[ "def", "worst_decimal", "(", "d1", ",", "d2", ")", ":", "(", "d1b4", ",", "d1after", ")", "=", "_places_b4_and_after_decimal", "(", "d1", ")", "(", "d2b4", ",", "d2after", ")", "=", "_places_b4_and_after_decimal", "(", "d2", ")", "return", "Decimal", "(", ...
Given two Decimals, return a 9-filled decimal representing both enough > 0 digits and enough < 0 digits (scale) to accomodate numbers like either. >>> worst_decimal(Decimal('762.1'), Decimal('-1.983')) Decimal('999.999')
[ "Given", "two", "Decimals", "return", "a", "9", "-", "filled", "decimal", "representing", "both", "enough", ">", "0", "digits", "and", "enough", "<", "0", "digits", "(", "scale", ")", "to", "accomodate", "numbers", "like", "either", "." ]
python
train
googleapis/google-cloud-python
api_core/google/api_core/timeout.py
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/timeout.py#L110-L140
def _exponential_timeout_generator(initial, maximum, multiplier, deadline): """A generator that yields exponential timeout values. Args: initial (float): The initial timeout. maximum (float): The maximum timeout. multiplier (float): The multiplier applied to the timeout. deadline (float): The overall deadline across all invocations. Yields: float: A timeout value. """ if deadline is not None: deadline_datetime = datetime_helpers.utcnow() + datetime.timedelta( seconds=deadline ) else: deadline_datetime = datetime.datetime.max timeout = initial while True: now = datetime_helpers.utcnow() yield min( # The calculated timeout based on invocations. timeout, # The set maximum timeout. maximum, # The remaining time before the deadline is reached. float((deadline_datetime - now).seconds), ) timeout = timeout * multiplier
[ "def", "_exponential_timeout_generator", "(", "initial", ",", "maximum", ",", "multiplier", ",", "deadline", ")", ":", "if", "deadline", "is", "not", "None", ":", "deadline_datetime", "=", "datetime_helpers", ".", "utcnow", "(", ")", "+", "datetime", ".", "tim...
A generator that yields exponential timeout values. Args: initial (float): The initial timeout. maximum (float): The maximum timeout. multiplier (float): The multiplier applied to the timeout. deadline (float): The overall deadline across all invocations. Yields: float: A timeout value.
[ "A", "generator", "that", "yields", "exponential", "timeout", "values", "." ]
python
train
apache/incubator-mxnet
python/mxnet/ndarray/ndarray.py
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/ndarray/ndarray.py#L3081-L3134
def minimum(lhs, rhs): """Returns element-wise minimum of the input arrays with broadcasting. Equivalent to ``mx.nd.broadcast_minimum(lhs, rhs)``. .. note:: If the corresponding dimensions of two arrays have the same size or one of them has size 1, then the arrays are broadcastable to a common shape. Parameters ---------- lhs : scalar or mxnet.ndarray.array First array to be compared. rhs : scalar or mxnet.ndarray.array Second array to be compared. If ``lhs.shape != rhs.shape``, they must be broadcastable to a common shape. Returns ------- NDArray The element-wise minimum of the input arrays. Examples -------- >>> x = mx.nd.ones((2,3)) >>> y = mx.nd.arange(2).reshape((2,1)) >>> z = mx.nd.arange(2).reshape((1,2)) >>> x.asnumpy() array([[ 1., 1., 1.], [ 1., 1., 1.]], dtype=float32) >>> y.asnumpy() array([[ 0.], [ 1.]], dtype=float32) >>> z.asnumpy() array([[ 0., 1.]], dtype=float32) >>> mx.nd.minimum(x, 2).asnumpy() array([[ 1., 1., 1.], [ 1., 1., 1.]], dtype=float32) >>> mx.nd.minimum(x, y).asnumpy() array([[ 0., 0., 0.], [ 1., 1., 1.]], dtype=float32) >>> mx.nd.minimum(z, y).asnumpy() array([[ 0., 0.], [ 0., 1.]], dtype=float32) """ # pylint: disable= no-member, protected-access return _ufunc_helper( lhs, rhs, op.broadcast_minimum, lambda x, y: x if x < y else y, _internal._minimum_scalar, None)
[ "def", "minimum", "(", "lhs", ",", "rhs", ")", ":", "# pylint: disable= no-member, protected-access", "return", "_ufunc_helper", "(", "lhs", ",", "rhs", ",", "op", ".", "broadcast_minimum", ",", "lambda", "x", ",", "y", ":", "x", "if", "x", "<", "y", "else...
Returns element-wise minimum of the input arrays with broadcasting. Equivalent to ``mx.nd.broadcast_minimum(lhs, rhs)``. .. note:: If the corresponding dimensions of two arrays have the same size or one of them has size 1, then the arrays are broadcastable to a common shape. Parameters ---------- lhs : scalar or mxnet.ndarray.array First array to be compared. rhs : scalar or mxnet.ndarray.array Second array to be compared. If ``lhs.shape != rhs.shape``, they must be broadcastable to a common shape. Returns ------- NDArray The element-wise minimum of the input arrays. Examples -------- >>> x = mx.nd.ones((2,3)) >>> y = mx.nd.arange(2).reshape((2,1)) >>> z = mx.nd.arange(2).reshape((1,2)) >>> x.asnumpy() array([[ 1., 1., 1.], [ 1., 1., 1.]], dtype=float32) >>> y.asnumpy() array([[ 0.], [ 1.]], dtype=float32) >>> z.asnumpy() array([[ 0., 1.]], dtype=float32) >>> mx.nd.minimum(x, 2).asnumpy() array([[ 1., 1., 1.], [ 1., 1., 1.]], dtype=float32) >>> mx.nd.minimum(x, y).asnumpy() array([[ 0., 0., 0.], [ 1., 1., 1.]], dtype=float32) >>> mx.nd.minimum(z, y).asnumpy() array([[ 0., 0.], [ 0., 1.]], dtype=float32)
[ "Returns", "element", "-", "wise", "minimum", "of", "the", "input", "arrays", "with", "broadcasting", "." ]
python
train
jmcgeheeiv/pyfakefs
pyfakefs/fake_filesystem.py
https://github.com/jmcgeheeiv/pyfakefs/blob/6c36fb8987108107fc861fc3013620d46c7d2f9c/pyfakefs/fake_filesystem.py#L1116-L1136
def set_disk_usage(self, total_size, path=None): """Changes the total size of the file system, preserving the used space. Example usage: set the size of an auto-mounted Windows drive. Args: total_size: The new total size of the filesystem in bytes. path: The disk space is changed for the file system device where `path` resides. Defaults to the root path (e.g. '/' on Unix systems). Raises: IOError: if the new space is smaller than the used size. """ if path is None: path = self.root.name mount_point = self._mount_point_for_path(path) if (mount_point['total_size'] is not None and mount_point['used_size'] > total_size): self.raise_io_error(errno.ENOSPC, path) mount_point['total_size'] = total_size
[ "def", "set_disk_usage", "(", "self", ",", "total_size", ",", "path", "=", "None", ")", ":", "if", "path", "is", "None", ":", "path", "=", "self", ".", "root", ".", "name", "mount_point", "=", "self", ".", "_mount_point_for_path", "(", "path", ")", "if...
Changes the total size of the file system, preserving the used space. Example usage: set the size of an auto-mounted Windows drive. Args: total_size: The new total size of the filesystem in bytes. path: The disk space is changed for the file system device where `path` resides. Defaults to the root path (e.g. '/' on Unix systems). Raises: IOError: if the new space is smaller than the used size.
[ "Changes", "the", "total", "size", "of", "the", "file", "system", "preserving", "the", "used", "space", ".", "Example", "usage", ":", "set", "the", "size", "of", "an", "auto", "-", "mounted", "Windows", "drive", "." ]
python
train
serge-sans-paille/pythran
pythran/analyses/aliases.py
https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/analyses/aliases.py#L317-L380
def visit_Call(self, node): ''' Resulting node alias to the return_alias of called function, if the function is already known by Pythran (i.e. it's an Intrinsic) or if Pythran already computed it's ``return_alias`` behavior. >>> from pythran import passmanager >>> pm = passmanager.PassManager('demo') >>> fun = """ ... def f(a): return a ... def foo(b): c = f(b)""" >>> module = ast.parse(fun) The ``f`` function create aliasing between the returned value and its first argument. >>> result = pm.gather(Aliases, module) >>> Aliases.dump(result, filter=ast.Call) f(b) => ['b'] This also works with intrinsics, e.g ``dict.setdefault`` which may create alias between its third argument and the return value. >>> fun = 'def foo(a, d): __builtin__.dict.setdefault(d, 0, a)' >>> module = ast.parse(fun) >>> result = pm.gather(Aliases, module) >>> Aliases.dump(result, filter=ast.Call) __builtin__.dict.setdefault(d, 0, a) => ['<unbound-value>', 'a'] Note that complex cases can arise, when one of the formal parameter is already known to alias to various values: >>> fun = """ ... def f(a, b): return a and b ... def foo(A, B, C, D): return f(A or B, C or D)""" >>> module = ast.parse(fun) >>> result = pm.gather(Aliases, module) >>> Aliases.dump(result, filter=ast.Call) f((A or B), (C or D)) => ['A', 'B', 'C', 'D'] ''' self.generic_visit(node) f = node.func # special handler for bind functions if isinstance(f, ast.Attribute) and f.attr == "partial": return self.add(node, {node}) else: return_alias = self.call_return_alias(node) # expand collected aliases all_aliases = set() for value in return_alias: # no translation if isinstance(value, (ContainerOf, ast.FunctionDef, Intrinsic)): all_aliases.add(value) elif value in self.result: all_aliases.update(self.result[value]) else: try: ap = Aliases.access_path(value) all_aliases.update(self.aliases.get(ap, ())) except NotImplementedError: # should we do something better here? all_aliases.add(value) return self.add(node, all_aliases)
[ "def", "visit_Call", "(", "self", ",", "node", ")", ":", "self", ".", "generic_visit", "(", "node", ")", "f", "=", "node", ".", "func", "# special handler for bind functions", "if", "isinstance", "(", "f", ",", "ast", ".", "Attribute", ")", "and", "f", "...
Resulting node alias to the return_alias of called function, if the function is already known by Pythran (i.e. it's an Intrinsic) or if Pythran already computed it's ``return_alias`` behavior. >>> from pythran import passmanager >>> pm = passmanager.PassManager('demo') >>> fun = """ ... def f(a): return a ... def foo(b): c = f(b)""" >>> module = ast.parse(fun) The ``f`` function create aliasing between the returned value and its first argument. >>> result = pm.gather(Aliases, module) >>> Aliases.dump(result, filter=ast.Call) f(b) => ['b'] This also works with intrinsics, e.g ``dict.setdefault`` which may create alias between its third argument and the return value. >>> fun = 'def foo(a, d): __builtin__.dict.setdefault(d, 0, a)' >>> module = ast.parse(fun) >>> result = pm.gather(Aliases, module) >>> Aliases.dump(result, filter=ast.Call) __builtin__.dict.setdefault(d, 0, a) => ['<unbound-value>', 'a'] Note that complex cases can arise, when one of the formal parameter is already known to alias to various values: >>> fun = """ ... def f(a, b): return a and b ... def foo(A, B, C, D): return f(A or B, C or D)""" >>> module = ast.parse(fun) >>> result = pm.gather(Aliases, module) >>> Aliases.dump(result, filter=ast.Call) f((A or B), (C or D)) => ['A', 'B', 'C', 'D']
[ "Resulting", "node", "alias", "to", "the", "return_alias", "of", "called", "function", "if", "the", "function", "is", "already", "known", "by", "Pythran", "(", "i", ".", "e", ".", "it", "s", "an", "Intrinsic", ")", "or", "if", "Pythran", "already", "comp...
python
train
caseman/noise
shader_noise.py
https://github.com/caseman/noise/blob/bb32991ab97e90882d0e46e578060717c5b90dc5/shader_noise.py#L46-L50
def load(self): """Load the noise texture data into the current texture unit""" glTexImage3D(GL_TEXTURE_3D, 0, GL_LUMINANCE16_ALPHA16, self.width, self.width, self.width, 0, GL_LUMINANCE_ALPHA, GL_UNSIGNED_SHORT, ctypes.byref(self.data))
[ "def", "load", "(", "self", ")", ":", "glTexImage3D", "(", "GL_TEXTURE_3D", ",", "0", ",", "GL_LUMINANCE16_ALPHA16", ",", "self", ".", "width", ",", "self", ".", "width", ",", "self", ".", "width", ",", "0", ",", "GL_LUMINANCE_ALPHA", ",", "GL_UNSIGNED_SHO...
Load the noise texture data into the current texture unit
[ "Load", "the", "noise", "texture", "data", "into", "the", "current", "texture", "unit" ]
python
train
opencast/pyCA
pyca/ui/jsonapi.py
https://github.com/opencast/pyCA/blob/c89b168d4780d157e1b3f7676628c1b131956a88/pyca/ui/jsonapi.py#L84-L106
def delete_event(uid): '''Delete a specific event identified by its uid. Note that only recorded events can be deleted. Events in the buffer for upcoming events are regularly replaced anyway and a manual removal could have unpredictable effects. Use ?hard=true parameter to delete the recorded files on disk as well. Returns 204 if the action was successful. Returns 404 if event does not exist ''' logger.info('deleting event %s via api', uid) db = get_session() events = db.query(RecordedEvent).filter(RecordedEvent.uid == uid) if not events.count(): return make_error_response('No event with specified uid', 404) hard_delete = request.args.get('hard', 'false') if hard_delete == 'true': logger.info('deleting recorded files at %s', events[0].directory()) shutil.rmtree(events[0].directory()) events.delete() db.commit() return make_response('', 204)
[ "def", "delete_event", "(", "uid", ")", ":", "logger", ".", "info", "(", "'deleting event %s via api'", ",", "uid", ")", "db", "=", "get_session", "(", ")", "events", "=", "db", ".", "query", "(", "RecordedEvent", ")", ".", "filter", "(", "RecordedEvent", ...
Delete a specific event identified by its uid. Note that only recorded events can be deleted. Events in the buffer for upcoming events are regularly replaced anyway and a manual removal could have unpredictable effects. Use ?hard=true parameter to delete the recorded files on disk as well. Returns 204 if the action was successful. Returns 404 if event does not exist
[ "Delete", "a", "specific", "event", "identified", "by", "its", "uid", ".", "Note", "that", "only", "recorded", "events", "can", "be", "deleted", ".", "Events", "in", "the", "buffer", "for", "upcoming", "events", "are", "regularly", "replaced", "anyway", "and...
python
test
diffeo/yakonfig
yakonfig/toplevel.py
https://github.com/diffeo/yakonfig/blob/412e195da29b4f4fc7b72967c192714a6f5eaeb5/yakonfig/toplevel.py#L303-L332
def create_config_tree(config, modules, prefix=''): '''Cause every possible configuration sub-dictionary to exist. This is intended to be called very early in the configuration sequence. For each module, it checks that the corresponding configuration item exists in `config` and creates it as an empty dictionary if required, and then recurses into child configs/modules. :param dict config: configuration to populate :param modules: modules or Configurable instances to use :type modules: iterable of :class:`~yakonfig.configurable.Configurable` :param str prefix: prefix name of the config :return: `config` :raises yakonfig.ConfigurationError: if an expected name is present in the provided config, but that name is not a dictionary ''' def work_in(parent_config, config_name, prefix, module): if config_name not in parent_config: # this is the usual, expected case parent_config[config_name] = {} elif not isinstance(parent_config[config_name], collections.Mapping): raise ConfigurationError( '{0} must be an object configuration'.format(prefix)) else: # config_name is a pre-existing dictionary in parent_config pass _recurse_config(config, modules, work_in)
[ "def", "create_config_tree", "(", "config", ",", "modules", ",", "prefix", "=", "''", ")", ":", "def", "work_in", "(", "parent_config", ",", "config_name", ",", "prefix", ",", "module", ")", ":", "if", "config_name", "not", "in", "parent_config", ":", "# t...
Cause every possible configuration sub-dictionary to exist. This is intended to be called very early in the configuration sequence. For each module, it checks that the corresponding configuration item exists in `config` and creates it as an empty dictionary if required, and then recurses into child configs/modules. :param dict config: configuration to populate :param modules: modules or Configurable instances to use :type modules: iterable of :class:`~yakonfig.configurable.Configurable` :param str prefix: prefix name of the config :return: `config` :raises yakonfig.ConfigurationError: if an expected name is present in the provided config, but that name is not a dictionary
[ "Cause", "every", "possible", "configuration", "sub", "-", "dictionary", "to", "exist", "." ]
python
train
StackStorm/pybind
pybind/slxos/v17r_1_01a/mpls_state/lsp/frr/__init__.py
https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17r_1_01a/mpls_state/lsp/frr/__init__.py#L691-L714
def _set_computation_mode(self, v, load=False): """ Setter method for computation_mode, mapped from YANG variable /mpls_state/lsp/frr/computation_mode (lsp-cspf-computation-mode) If this variable is read-only (config: false) in the source YANG file, then _set_computation_mode is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_computation_mode() directly. YANG Description: lsp frr computation mode """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'cspf-computation-mode-default': {'value': 1}, u'cspf-computation-mode-use-bypass-metric': {'value': 2}, u'cspf-computation-mode-use-igp-metric-global': {'value': 7}, u'cspf-computation-mode-use-igp-metric': {'value': 5}, u'cspf-computation-mode-use-te-metric': {'value': 4}, u'cspf-computation-mode-use-bypass-liberal': {'value': 3}, u'cspf-computation-mode-use-te-metric-global': {'value': 6}},), is_leaf=True, yang_name="computation-mode", rest_name="computation-mode", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='urn:brocade.com:mgmt:brocade-mpls-operational', defining_module='brocade-mpls-operational', yang_type='lsp-cspf-computation-mode', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """computation_mode must be of a type compatible with lsp-cspf-computation-mode""", 'defined-type': "brocade-mpls-operational:lsp-cspf-computation-mode", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'cspf-computation-mode-default': {'value': 1}, u'cspf-computation-mode-use-bypass-metric': {'value': 2}, u'cspf-computation-mode-use-igp-metric-global': {'value': 7}, u'cspf-computation-mode-use-igp-metric': {'value': 5}, u'cspf-computation-mode-use-te-metric': {'value': 4}, u'cspf-computation-mode-use-bypass-liberal': {'value': 3}, u'cspf-computation-mode-use-te-metric-global': {'value': 6}},), is_leaf=True, yang_name="computation-mode", rest_name="computation-mode", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='urn:brocade.com:mgmt:brocade-mpls-operational', defining_module='brocade-mpls-operational', yang_type='lsp-cspf-computation-mode', is_config=False)""", }) self.__computation_mode = t if hasattr(self, '_set'): self._set()
[ "def", "_set_computation_mode", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", ...
Setter method for computation_mode, mapped from YANG variable /mpls_state/lsp/frr/computation_mode (lsp-cspf-computation-mode) If this variable is read-only (config: false) in the source YANG file, then _set_computation_mode is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_computation_mode() directly. YANG Description: lsp frr computation mode
[ "Setter", "method", "for", "computation_mode", "mapped", "from", "YANG", "variable", "/", "mpls_state", "/", "lsp", "/", "frr", "/", "computation_mode", "(", "lsp", "-", "cspf", "-", "computation", "-", "mode", ")", "If", "this", "variable", "is", "read", ...
python
train
materialsproject/pymatgen
pymatgen/io/abinit/netcdf.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/abinit/netcdf.py#L233-L250
def read_keys(self, keys, dict_cls=AttrDict, path="/"): """ Read a list of variables/dimensions from file. If a key is not present the corresponding entry in the output dictionary is set to None. """ od = dict_cls() for k in keys: try: # Try to read a variable. od[k] = self.read_value(k, path=path) except self.Error: try: # Try to read a dimension. od[k] = self.read_dimvalue(k, path=path) except self.Error: od[k] = None return od
[ "def", "read_keys", "(", "self", ",", "keys", ",", "dict_cls", "=", "AttrDict", ",", "path", "=", "\"/\"", ")", ":", "od", "=", "dict_cls", "(", ")", "for", "k", "in", "keys", ":", "try", ":", "# Try to read a variable.", "od", "[", "k", "]", "=", ...
Read a list of variables/dimensions from file. If a key is not present the corresponding entry in the output dictionary is set to None.
[ "Read", "a", "list", "of", "variables", "/", "dimensions", "from", "file", ".", "If", "a", "key", "is", "not", "present", "the", "corresponding", "entry", "in", "the", "output", "dictionary", "is", "set", "to", "None", "." ]
python
train
StackStorm/pybind
pybind/slxos/v17s_1_02/overlay/access_list/type/vxlan/standard/seq/__init__.py
https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17s_1_02/overlay/access_list/type/vxlan/standard/seq/__init__.py#L272-L293
def _set_src_vtep_ip_any(self, v, load=False): """ Setter method for src_vtep_ip_any, mapped from YANG variable /overlay/access_list/type/vxlan/standard/seq/src_vtep_ip_any (empty) If this variable is read-only (config: false) in the source YANG file, then _set_src_vtep_ip_any is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_src_vtep_ip_any() directly. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=YANGBool, is_leaf=True, yang_name="src-vtep-ip-any", rest_name="src-vtep-ip-any", parent=self, choice=(u'choice-src-vtep-ip', u'case-src-vtep-ip-any'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'src vtep ip address: any', u'cli-incomplete-command': None, u'cli-suppress-no': None}}, namespace='urn:brocade.com:mgmt:brocade-vxlan-visibility', defining_module='brocade-vxlan-visibility', yang_type='empty', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """src_vtep_ip_any must be of a type compatible with empty""", 'defined-type': "empty", 'generated-type': """YANGDynClass(base=YANGBool, is_leaf=True, yang_name="src-vtep-ip-any", rest_name="src-vtep-ip-any", parent=self, choice=(u'choice-src-vtep-ip', u'case-src-vtep-ip-any'), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'src vtep ip address: any', u'cli-incomplete-command': None, u'cli-suppress-no': None}}, namespace='urn:brocade.com:mgmt:brocade-vxlan-visibility', defining_module='brocade-vxlan-visibility', yang_type='empty', is_config=True)""", }) self.__src_vtep_ip_any = t if hasattr(self, '_set'): self._set()
[ "def", "_set_src_vtep_ip_any", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", ...
Setter method for src_vtep_ip_any, mapped from YANG variable /overlay/access_list/type/vxlan/standard/seq/src_vtep_ip_any (empty) If this variable is read-only (config: false) in the source YANG file, then _set_src_vtep_ip_any is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_src_vtep_ip_any() directly.
[ "Setter", "method", "for", "src_vtep_ip_any", "mapped", "from", "YANG", "variable", "/", "overlay", "/", "access_list", "/", "type", "/", "vxlan", "/", "standard", "/", "seq", "/", "src_vtep_ip_any", "(", "empty", ")", "If", "this", "variable", "is", "read",...
python
train
lord63/tldr.py
tldr/cli.py
https://github.com/lord63/tldr.py/blob/73cf9f86254691b2476910ea6a743b6d8bd04963/tldr/cli.py#L175-L178
def locate(command, on): """Locate the command's man page.""" location = find_page_location(command, on) click.echo(location)
[ "def", "locate", "(", "command", ",", "on", ")", ":", "location", "=", "find_page_location", "(", "command", ",", "on", ")", "click", ".", "echo", "(", "location", ")" ]
Locate the command's man page.
[ "Locate", "the", "command", "s", "man", "page", "." ]
python
train
LuqueDaniel/pybooru
pybooru/api_danbooru.py
https://github.com/LuqueDaniel/pybooru/blob/60cd5254684d293b308f0b11b8f4ac2dce101479/pybooru/api_danbooru.py#L605-L612
def artist_undelete(self, artist_id): """Lets you undelete artist (Requires login) (UNTESTED) (Only Builder+). Parameters: artist_id (int): """ return self._get('artists/{0}/undelete.json'.format(artist_id), method='POST', auth=True)
[ "def", "artist_undelete", "(", "self", ",", "artist_id", ")", ":", "return", "self", ".", "_get", "(", "'artists/{0}/undelete.json'", ".", "format", "(", "artist_id", ")", ",", "method", "=", "'POST'", ",", "auth", "=", "True", ")" ]
Lets you undelete artist (Requires login) (UNTESTED) (Only Builder+). Parameters: artist_id (int):
[ "Lets", "you", "undelete", "artist", "(", "Requires", "login", ")", "(", "UNTESTED", ")", "(", "Only", "Builder", "+", ")", "." ]
python
train
rocky/python-uncompyle6
uncompyle6/parsers/parse3.py
https://github.com/rocky/python-uncompyle6/blob/c5d7944e657f0ad05a0e2edd34e1acb27001abc0/uncompyle6/parsers/parse3.py#L480-L515
def custom_classfunc_rule(self, opname, token, customize, next_token): """ call ::= expr {expr}^n CALL_FUNCTION_n call ::= expr {expr}^n CALL_FUNCTION_VAR_n call ::= expr {expr}^n CALL_FUNCTION_VAR_KW_n call ::= expr {expr}^n CALL_FUNCTION_KW_n classdefdeco2 ::= LOAD_BUILD_CLASS mkfunc {expr}^n-1 CALL_FUNCTION_n """ args_pos, args_kw = self.get_pos_kw(token) # Additional exprs for * and ** args: # 0 if neither # 1 for CALL_FUNCTION_VAR or CALL_FUNCTION_KW # 2 for * and ** args (CALL_FUNCTION_VAR_KW). # Yes, this computation based on instruction name is a little bit hoaky. nak = ( len(opname)-len('CALL_FUNCTION') ) // 3 token.kind = self.call_fn_name(token) uniq_param = args_kw + args_pos # Note: 3.5+ have subclassed this method; so we don't handle # 'CALL_FUNCTION_VAR' or 'CALL_FUNCTION_EX' here. rule = ('call ::= expr ' + ('pos_arg ' * args_pos) + ('kwarg ' * args_kw) + 'expr ' * nak + token.kind) self.add_unique_rule(rule, token.kind, uniq_param, customize) if 'LOAD_BUILD_CLASS' in self.seen_ops: if (next_token == 'CALL_FUNCTION' and next_token.attr == 1 and args_pos > 1): rule = ('classdefdeco2 ::= LOAD_BUILD_CLASS mkfunc %s%s_%d' % (('expr ' * (args_pos-1)), opname, args_pos)) self.add_unique_rule(rule, token.kind, uniq_param, customize)
[ "def", "custom_classfunc_rule", "(", "self", ",", "opname", ",", "token", ",", "customize", ",", "next_token", ")", ":", "args_pos", ",", "args_kw", "=", "self", ".", "get_pos_kw", "(", "token", ")", "# Additional exprs for * and ** args:", "# 0 if neither", "# ...
call ::= expr {expr}^n CALL_FUNCTION_n call ::= expr {expr}^n CALL_FUNCTION_VAR_n call ::= expr {expr}^n CALL_FUNCTION_VAR_KW_n call ::= expr {expr}^n CALL_FUNCTION_KW_n classdefdeco2 ::= LOAD_BUILD_CLASS mkfunc {expr}^n-1 CALL_FUNCTION_n
[ "call", "::", "=", "expr", "{", "expr", "}", "^n", "CALL_FUNCTION_n", "call", "::", "=", "expr", "{", "expr", "}", "^n", "CALL_FUNCTION_VAR_n", "call", "::", "=", "expr", "{", "expr", "}", "^n", "CALL_FUNCTION_VAR_KW_n", "call", "::", "=", "expr", "{", ...
python
train
bioasp/ingranalyze
src/bioquali.py
https://github.com/bioasp/ingranalyze/blob/60bdd679b6044a4d142abbca5bbe3cd5e9fd7596/src/bioquali.py#L46-L67
def readGraph(filename): p = graph_parser.Parser() """ input: string, name of a file containing a Bioquali-like graph description output: asp.TermSet, with atoms matching the contents of the input file Parses a Bioquali-like graph description, and returns a TermSet object. Written using original Bioquali """ accu = TermSet() file = open(filename,'r') s = file.readline() while s!="": try: accu = p.parse(s) except EOFError: break s = file.readline() return accu
[ "def", "readGraph", "(", "filename", ")", ":", "p", "=", "graph_parser", ".", "Parser", "(", ")", "accu", "=", "TermSet", "(", ")", "file", "=", "open", "(", "filename", ",", "'r'", ")", "s", "=", "file", ".", "readline", "(", ")", "while", "s", ...
input: string, name of a file containing a Bioquali-like graph description output: asp.TermSet, with atoms matching the contents of the input file Parses a Bioquali-like graph description, and returns a TermSet object. Written using original Bioquali
[ "input", ":", "string", "name", "of", "a", "file", "containing", "a", "Bioquali", "-", "like", "graph", "description", "output", ":", "asp", ".", "TermSet", "with", "atoms", "matching", "the", "contents", "of", "the", "input", "file" ]
python
train
timothycrosley/connectable
connectable/base.py
https://github.com/timothycrosley/connectable/blob/d5958d974c04b16f410c602786809d0e2a6665d2/connectable/base.py#L22-L57
def emit(self, signal, value=None, gather=False): """Emits a signal, causing all slot methods connected with the signal to be called (optionally w/ related value) signal: the name of the signal to emit, must be defined in the classes 'signals' list. value: the value to pass to all connected slot methods. gather: if set, causes emit to return a list of all slot results """ results = [] if gather else True if hasattr(self, 'connections') and signal in self.connections: for condition, values in self.connections[signal].items(): if condition is None or condition == value or (callable(condition) and condition(value)): for slot, transform in values.items(): if transform is not None: if callable(transform): used_value = transform(value) elif isinstance(transform, str): used_value = transform.format(value=value) else: used_value = transform else: used_value = value if used_value is not None: if(accept_arguments(slot, 1)): result = slot(used_value) elif(accept_arguments(slot, 0)): result = slot() else: result = '' else: result = slot() if gather: results.append(result) return results
[ "def", "emit", "(", "self", ",", "signal", ",", "value", "=", "None", ",", "gather", "=", "False", ")", ":", "results", "=", "[", "]", "if", "gather", "else", "True", "if", "hasattr", "(", "self", ",", "'connections'", ")", "and", "signal", "in", "...
Emits a signal, causing all slot methods connected with the signal to be called (optionally w/ related value) signal: the name of the signal to emit, must be defined in the classes 'signals' list. value: the value to pass to all connected slot methods. gather: if set, causes emit to return a list of all slot results
[ "Emits", "a", "signal", "causing", "all", "slot", "methods", "connected", "with", "the", "signal", "to", "be", "called", "(", "optionally", "w", "/", "related", "value", ")" ]
python
train
shaypal5/decore
decore/decore.py
https://github.com/shaypal5/decore/blob/460f22f8b9127e6a80b161a626d8827673343afb/decore/decore.py#L24-L30
def threadsafe_generator(generator_func): """A decorator that takes a generator function and makes it thread-safe. """ def decoration(*args, **keyword_args): """A thread-safe decoration for a generator function.""" return ThreadSafeIter(generator_func(*args, **keyword_args)) return decoration
[ "def", "threadsafe_generator", "(", "generator_func", ")", ":", "def", "decoration", "(", "*", "args", ",", "*", "*", "keyword_args", ")", ":", "\"\"\"A thread-safe decoration for a generator function.\"\"\"", "return", "ThreadSafeIter", "(", "generator_func", "(", "*",...
A decorator that takes a generator function and makes it thread-safe.
[ "A", "decorator", "that", "takes", "a", "generator", "function", "and", "makes", "it", "thread", "-", "safe", "." ]
python
train
AndrewAnnex/SpiceyPy
spiceypy/spiceypy.py
https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L280-L298
def axisar(axis, angle): """ Construct a rotation matrix that rotates vectors by a specified angle about a specified axis. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/axisar_c.html :param axis: Rotation axis. :type axis: 3 Element vector (list, tuple, numpy array) :param angle: Rotation angle, in radians. :type angle: float :return: Rotation matrix corresponding to axis and angle. :rtype: numpy array ((3, 3)) """ axis = stypes.toDoubleVector(axis) angle = ctypes.c_double(angle) r = stypes.emptyDoubleMatrix() libspice.axisar_c(axis, angle, r) return stypes.cMatrixToNumpy(r)
[ "def", "axisar", "(", "axis", ",", "angle", ")", ":", "axis", "=", "stypes", ".", "toDoubleVector", "(", "axis", ")", "angle", "=", "ctypes", ".", "c_double", "(", "angle", ")", "r", "=", "stypes", ".", "emptyDoubleMatrix", "(", ")", "libspice", ".", ...
Construct a rotation matrix that rotates vectors by a specified angle about a specified axis. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/axisar_c.html :param axis: Rotation axis. :type axis: 3 Element vector (list, tuple, numpy array) :param angle: Rotation angle, in radians. :type angle: float :return: Rotation matrix corresponding to axis and angle. :rtype: numpy array ((3, 3))
[ "Construct", "a", "rotation", "matrix", "that", "rotates", "vectors", "by", "a", "specified", "angle", "about", "a", "specified", "axis", "." ]
python
train
markovmodel/msmtools
msmtools/dtraj/api.py
https://github.com/markovmodel/msmtools/blob/54dc76dd2113a0e8f3d15d5316abab41402941be/msmtools/dtraj/api.py#L524-L561
def sample_indexes_by_distribution(indexes, distributions, nsample): """Samples trajectory/time indexes according to the given probability distributions Parameters ---------- indexes : list of ndarray( (N_i, 2) ) For each state, all trajectory and time indexes where this state occurs. Each matrix has a number of rows equal to the number of occurrences of the corresponding state, with rows consisting of a tuple (i, t), where i is the index of the trajectory and t is the time index within the trajectory. distributions : list or array of ndarray ( (n) ) m distributions over states. Each distribution must be of length n and must sum up to 1.0 nsample : int Number of samples per distribution. If replace = False, the number of returned samples per state could be smaller if less than nsample indexes are available for a state. Returns ------- indexes : length m list of ndarray( (nsample, 2) ) List of the sampled indices by distribution. Each element is an index array with a number of rows equal to nsample, with rows consisting of a tuple (i, t), where i is the index of the trajectory and t is the time index within the trajectory. """ # how many states in total? n = len(indexes) for dist in distributions: if len(dist) != n: raise ValueError('Size error: Distributions must all be of length n (number of states).') # list of states res = np.ndarray((len(distributions)), dtype=object) for i in range(len(distributions)): # sample states by distribution sequence = np.random.choice(n, size=nsample, p=distributions[i]) res[i] = sample_indexes_by_sequence(indexes, sequence) # return res
[ "def", "sample_indexes_by_distribution", "(", "indexes", ",", "distributions", ",", "nsample", ")", ":", "# how many states in total?", "n", "=", "len", "(", "indexes", ")", "for", "dist", "in", "distributions", ":", "if", "len", "(", "dist", ")", "!=", "n", ...
Samples trajectory/time indexes according to the given probability distributions Parameters ---------- indexes : list of ndarray( (N_i, 2) ) For each state, all trajectory and time indexes where this state occurs. Each matrix has a number of rows equal to the number of occurrences of the corresponding state, with rows consisting of a tuple (i, t), where i is the index of the trajectory and t is the time index within the trajectory. distributions : list or array of ndarray ( (n) ) m distributions over states. Each distribution must be of length n and must sum up to 1.0 nsample : int Number of samples per distribution. If replace = False, the number of returned samples per state could be smaller if less than nsample indexes are available for a state. Returns ------- indexes : length m list of ndarray( (nsample, 2) ) List of the sampled indices by distribution. Each element is an index array with a number of rows equal to nsample, with rows consisting of a tuple (i, t), where i is the index of the trajectory and t is the time index within the trajectory.
[ "Samples", "trajectory", "/", "time", "indexes", "according", "to", "the", "given", "probability", "distributions" ]
python
train
OLC-Bioinformatics/sipprverse
method.py
https://github.com/OLC-Bioinformatics/sipprverse/blob/d4f10cdf8e1a39dac0953db61c21c97efc6006de/method.py#L25-L44
def main(self): """ Run the analyses using the inputted values for forward and reverse read length. However, if not all strains pass the quality thresholds, continue to periodically run the analyses on these incomplete strains until either all strains are complete, or the sequencing run is finished """ logging.info('Starting {} analysis pipeline'.format(self.analysistype)) self.createobjects() # Run the genesipping analyses self.methods() # Determine if the analyses are complete self.complete() self.additionalsipping() # Update the report object self.reports = Reports(self) # Once all the analyses are complete, create reports for each sample Reports.methodreporter(self.reports) # Print the metadata printer = MetadataPrinter(self) printer.printmetadata()
[ "def", "main", "(", "self", ")", ":", "logging", ".", "info", "(", "'Starting {} analysis pipeline'", ".", "format", "(", "self", ".", "analysistype", ")", ")", "self", ".", "createobjects", "(", ")", "# Run the genesipping analyses", "self", ".", "methods", "...
Run the analyses using the inputted values for forward and reverse read length. However, if not all strains pass the quality thresholds, continue to periodically run the analyses on these incomplete strains until either all strains are complete, or the sequencing run is finished
[ "Run", "the", "analyses", "using", "the", "inputted", "values", "for", "forward", "and", "reverse", "read", "length", ".", "However", "if", "not", "all", "strains", "pass", "the", "quality", "thresholds", "continue", "to", "periodically", "run", "the", "analys...
python
train
QInfer/python-qinfer
src/qinfer/abstract_model.py
https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/abstract_model.py#L357-L374
def update_timestep(self, modelparams, expparams): r""" Returns a set of model parameter vectors that is the update of an input set of model parameter vectors, such that the new models are conditioned on a particular experiment having been performed. By default, this is the trivial function :math:`\vec{x}(t_{k+1}) = \vec{x}(t_k)`. :param np.ndarray modelparams: Set of model parameter vectors to be updated. :param np.ndarray expparams: An experiment parameter array describing the experiment that was just performed. :return np.ndarray: Array of shape ``(n_models, n_modelparams, n_experiments)`` describing the update of each model according to each experiment. """ return np.tile(modelparams, (expparams.shape[0],1,1)).transpose((1,2,0))
[ "def", "update_timestep", "(", "self", ",", "modelparams", ",", "expparams", ")", ":", "return", "np", ".", "tile", "(", "modelparams", ",", "(", "expparams", ".", "shape", "[", "0", "]", ",", "1", ",", "1", ")", ")", ".", "transpose", "(", "(", "1...
r""" Returns a set of model parameter vectors that is the update of an input set of model parameter vectors, such that the new models are conditioned on a particular experiment having been performed. By default, this is the trivial function :math:`\vec{x}(t_{k+1}) = \vec{x}(t_k)`. :param np.ndarray modelparams: Set of model parameter vectors to be updated. :param np.ndarray expparams: An experiment parameter array describing the experiment that was just performed. :return np.ndarray: Array of shape ``(n_models, n_modelparams, n_experiments)`` describing the update of each model according to each experiment.
[ "r", "Returns", "a", "set", "of", "model", "parameter", "vectors", "that", "is", "the", "update", "of", "an", "input", "set", "of", "model", "parameter", "vectors", "such", "that", "the", "new", "models", "are", "conditioned", "on", "a", "particular", "exp...
python
train
dwavesystems/dwave-cloud-client
dwave/cloud/utils.py
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/utils.py#L316-L320
def argshash(self, args, kwargs): "Hash mutable arguments' containers with immutable keys and values." a = repr(args) b = repr(sorted((repr(k), repr(v)) for k, v in kwargs.items())) return a + b
[ "def", "argshash", "(", "self", ",", "args", ",", "kwargs", ")", ":", "a", "=", "repr", "(", "args", ")", "b", "=", "repr", "(", "sorted", "(", "(", "repr", "(", "k", ")", ",", "repr", "(", "v", ")", ")", "for", "k", ",", "v", "in", "kwargs...
Hash mutable arguments' containers with immutable keys and values.
[ "Hash", "mutable", "arguments", "containers", "with", "immutable", "keys", "and", "values", "." ]
python
train
andrenarchy/krypy
krypy/utils.py
https://github.com/andrenarchy/krypy/blob/4883ec9a61d64ea56489e15c35cc40f0633ab2f1/krypy/utils.py#L1593-L1600
def strakos(n, l_min=0.1, l_max=100, rho=0.9): """Return the Strakoš matrix. See [Str92]_. """ d = [l_min + (i-1)*1./(n-1)*(l_max-l_min)*(rho**(n-i)) for i in range(1, n+1)] return numpy.diag(d)
[ "def", "strakos", "(", "n", ",", "l_min", "=", "0.1", ",", "l_max", "=", "100", ",", "rho", "=", "0.9", ")", ":", "d", "=", "[", "l_min", "+", "(", "i", "-", "1", ")", "*", "1.", "/", "(", "n", "-", "1", ")", "*", "(", "l_max", "-", "l_...
Return the Strakoš matrix. See [Str92]_.
[ "Return", "the", "Strakoš", "matrix", "." ]
python
train
saltstack/salt
salt/modules/riak.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/riak.py#L157-L179
def cluster_commit(): ''' Commit Cluster Changes .. versionchanged:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' riak.cluster_commit ''' ret = {'comment': '', 'success': False} cmd = __execute_cmd('riak-admin', 'cluster commit') if cmd['retcode'] != 0: ret['comment'] = cmd['stdout'] else: ret['comment'] = cmd['stdout'] ret['success'] = True return ret
[ "def", "cluster_commit", "(", ")", ":", "ret", "=", "{", "'comment'", ":", "''", ",", "'success'", ":", "False", "}", "cmd", "=", "__execute_cmd", "(", "'riak-admin'", ",", "'cluster commit'", ")", "if", "cmd", "[", "'retcode'", "]", "!=", "0", ":", "r...
Commit Cluster Changes .. versionchanged:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' riak.cluster_commit
[ "Commit", "Cluster", "Changes" ]
python
train
ph4r05/monero-serialize
monero_serialize/xmrrpc.py
https://github.com/ph4r05/monero-serialize/blob/cebb3ba2aaf2e9211b1dcc6db2bab02946d06e42/monero_serialize/xmrrpc.py#L372-L392
async def section(self, sec=None): """ Section / dict serialization :return: """ if self.writing: await dump_varint(self.iobj, len(sec)) for key in sec: await self.section_name(key) await self.storage_entry(sec[key]) else: sec = {} if sec is None else sec count = await load_varint(self.iobj) for idx in range(count): sec_name = await self.section_name() val = await self.storage_entry() sec[sec_name] = val return sec
[ "async", "def", "section", "(", "self", ",", "sec", "=", "None", ")", ":", "if", "self", ".", "writing", ":", "await", "dump_varint", "(", "self", ".", "iobj", ",", "len", "(", "sec", ")", ")", "for", "key", "in", "sec", ":", "await", "self", "."...
Section / dict serialization :return:
[ "Section", "/", "dict", "serialization", ":", "return", ":" ]
python
train
gwpy/gwpy
gwpy/io/cache.py
https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/io/cache.py#L155-L194
def read_cache(cachefile, coltype=LIGOTimeGPS, sort=None, segment=None): """Read a LAL- or FFL-format cache file as a list of file paths Parameters ---------- cachefile : `str`, `file` Input file or file path to read. coltype : `LIGOTimeGPS`, `int`, optional Type for GPS times. sort : `callable`, optional A callable key function by which to sort the output list of file paths segment : `gwpy.segments.Segment`, optional A GPS `[start, stop)` interval, if given only files overlapping this interval will be returned. Returns ------- paths : `list` of `str` A list of file paths as read from the cache file. """ # open file if not isinstance(cachefile, FILE_LIKE): with open(file_path(cachefile), 'r') as fobj: return read_cache(fobj, coltype=coltype, sort=sort, segment=segment) # read file cache = [x.path for x in _iter_cache(cachefile, gpstype=coltype)] # sieve and sort if segment: cache = sieve(cache, segment=segment) if sort: cache.sort(key=sort) # read simple paths return cache
[ "def", "read_cache", "(", "cachefile", ",", "coltype", "=", "LIGOTimeGPS", ",", "sort", "=", "None", ",", "segment", "=", "None", ")", ":", "# open file", "if", "not", "isinstance", "(", "cachefile", ",", "FILE_LIKE", ")", ":", "with", "open", "(", "file...
Read a LAL- or FFL-format cache file as a list of file paths Parameters ---------- cachefile : `str`, `file` Input file or file path to read. coltype : `LIGOTimeGPS`, `int`, optional Type for GPS times. sort : `callable`, optional A callable key function by which to sort the output list of file paths segment : `gwpy.segments.Segment`, optional A GPS `[start, stop)` interval, if given only files overlapping this interval will be returned. Returns ------- paths : `list` of `str` A list of file paths as read from the cache file.
[ "Read", "a", "LAL", "-", "or", "FFL", "-", "format", "cache", "file", "as", "a", "list", "of", "file", "paths" ]
python
train
edx/edx-enterprise
enterprise/api_client/discovery.py
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/discovery.py#L364-L416
def get_common_course_modes(self, course_run_ids): """ Find common course modes for a set of course runs. This function essentially returns an intersection of types of seats available for each course run. Arguments: course_run_ids(Iterable[str]): Target Course run IDs. Returns: set: course modes found in all given course runs Examples: # run1 has prof and audit, run 2 has the same get_common_course_modes(['course-v1:run1', 'course-v1:run2']) {'prof', 'audit'} # run1 has prof and audit, run 2 has only prof get_common_course_modes(['course-v1:run1', 'course-v1:run2']) {'prof'} # run1 has prof and audit, run 2 honor get_common_course_modes(['course-v1:run1', 'course-v1:run2']) {} # run1 has nothing, run2 has prof get_common_course_modes(['course-v1:run1', 'course-v1:run2']) {} # run1 has prof and audit, run 2 prof, run3 has audit get_common_course_modes(['course-v1:run1', 'course-v1:run2', 'course-v1:run3']) {} # run1 has nothing, run 2 prof, run3 has prof get_common_course_modes(['course-v1:run1', 'course-v1:run2', 'course-v1:run3']) {} """ available_course_modes = None for course_run_id in course_run_ids: course_run = self.get_course_run(course_run_id) or {} course_run_modes = {seat.get('type') for seat in course_run.get('seats', [])} if available_course_modes is None: available_course_modes = course_run_modes else: available_course_modes &= course_run_modes if not available_course_modes: return available_course_modes return available_course_modes
[ "def", "get_common_course_modes", "(", "self", ",", "course_run_ids", ")", ":", "available_course_modes", "=", "None", "for", "course_run_id", "in", "course_run_ids", ":", "course_run", "=", "self", ".", "get_course_run", "(", "course_run_id", ")", "or", "{", "}",...
Find common course modes for a set of course runs. This function essentially returns an intersection of types of seats available for each course run. Arguments: course_run_ids(Iterable[str]): Target Course run IDs. Returns: set: course modes found in all given course runs Examples: # run1 has prof and audit, run 2 has the same get_common_course_modes(['course-v1:run1', 'course-v1:run2']) {'prof', 'audit'} # run1 has prof and audit, run 2 has only prof get_common_course_modes(['course-v1:run1', 'course-v1:run2']) {'prof'} # run1 has prof and audit, run 2 honor get_common_course_modes(['course-v1:run1', 'course-v1:run2']) {} # run1 has nothing, run2 has prof get_common_course_modes(['course-v1:run1', 'course-v1:run2']) {} # run1 has prof and audit, run 2 prof, run3 has audit get_common_course_modes(['course-v1:run1', 'course-v1:run2', 'course-v1:run3']) {} # run1 has nothing, run 2 prof, run3 has prof get_common_course_modes(['course-v1:run1', 'course-v1:run2', 'course-v1:run3']) {}
[ "Find", "common", "course", "modes", "for", "a", "set", "of", "course", "runs", "." ]
python
valid
saltstack/salt
salt/cloud/clouds/nova.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/nova.py#L492-L500
def cloudnetwork(vm_): ''' Determine if we should use an extra network to bootstrap Either 'False' (default) or 'True'. ''' return config.get_cloud_config_value( 'cloudnetwork', vm_, __opts__, default=False, search_global=False )
[ "def", "cloudnetwork", "(", "vm_", ")", ":", "return", "config", ".", "get_cloud_config_value", "(", "'cloudnetwork'", ",", "vm_", ",", "__opts__", ",", "default", "=", "False", ",", "search_global", "=", "False", ")" ]
Determine if we should use an extra network to bootstrap Either 'False' (default) or 'True'.
[ "Determine", "if", "we", "should", "use", "an", "extra", "network", "to", "bootstrap", "Either", "False", "(", "default", ")", "or", "True", "." ]
python
train
Kaggle/kaggle-api
kaggle/api/kaggle_api.py
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api.py#L230-L250
def competitions_data_download_file(self, id, file_name, **kwargs): # noqa: E501 """Download competition data file # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.competitions_data_download_file(id, file_name, async_req=True) >>> result = thread.get() :param async_req bool :param str id: Competition name (required) :param str file_name: Competition name (required) :return: Result If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.competitions_data_download_file_with_http_info(id, file_name, **kwargs) # noqa: E501 else: (data) = self.competitions_data_download_file_with_http_info(id, file_name, **kwargs) # noqa: E501 return data
[ "def", "competitions_data_download_file", "(", "self", ",", "id", ",", "file_name", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "ret...
Download competition data file # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.competitions_data_download_file(id, file_name, async_req=True) >>> result = thread.get() :param async_req bool :param str id: Competition name (required) :param str file_name: Competition name (required) :return: Result If the method is called asynchronously, returns the request thread.
[ "Download", "competition", "data", "file", "#", "noqa", ":", "E501" ]
python
train
fvdsn/py-xml-escpos
xmlescpos/escpos.py
https://github.com/fvdsn/py-xml-escpos/blob/7f77e039c960d5773fb919aed02ba392dccbc360/xmlescpos/escpos.py#L169-L176
def to_escpos(self): """ converts the current style to an escpos command string """ cmd = '' ordered_cmds = self.cmds.keys() ordered_cmds.sort(lambda x,y: cmp(self.cmds[x]['_order'], self.cmds[y]['_order'])) for style in ordered_cmds: cmd += self.cmds[style][self.get(style)] return cmd
[ "def", "to_escpos", "(", "self", ")", ":", "cmd", "=", "''", "ordered_cmds", "=", "self", ".", "cmds", ".", "keys", "(", ")", "ordered_cmds", ".", "sort", "(", "lambda", "x", ",", "y", ":", "cmp", "(", "self", ".", "cmds", "[", "x", "]", "[", "...
converts the current style to an escpos command string
[ "converts", "the", "current", "style", "to", "an", "escpos", "command", "string" ]
python
train
cloudendpoints/endpoints-python
endpoints/util.py
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/util.py#L231-L259
def get_app_hostname(): """Return hostname of a running Endpoints service. Returns hostname of an running Endpoints API. It can be 1) "localhost:PORT" if running on development server, or 2) "app_id.appspot.com" if running on external app engine prod, or "app_id.googleplex.com" if running as Google first-party Endpoints API, or 4) None if not running on App Engine (e.g. Tornado Endpoints API). Returns: A string representing the hostname of the service. """ if not is_running_on_app_engine() or is_running_on_localhost(): return None app_id = app_identity.get_application_id() prefix = get_hostname_prefix() suffix = 'appspot.com' if ':' in app_id: tokens = app_id.split(':') api_name = tokens[1] if tokens[0] == 'google.com': suffix = 'googleplex.com' else: api_name = app_id return '{0}{1}.{2}'.format(prefix, api_name, suffix)
[ "def", "get_app_hostname", "(", ")", ":", "if", "not", "is_running_on_app_engine", "(", ")", "or", "is_running_on_localhost", "(", ")", ":", "return", "None", "app_id", "=", "app_identity", ".", "get_application_id", "(", ")", "prefix", "=", "get_hostname_prefix",...
Return hostname of a running Endpoints service. Returns hostname of an running Endpoints API. It can be 1) "localhost:PORT" if running on development server, or 2) "app_id.appspot.com" if running on external app engine prod, or "app_id.googleplex.com" if running as Google first-party Endpoints API, or 4) None if not running on App Engine (e.g. Tornado Endpoints API). Returns: A string representing the hostname of the service.
[ "Return", "hostname", "of", "a", "running", "Endpoints", "service", "." ]
python
train
mrcagney/gtfstk
gtfstk/miscellany.py
https://github.com/mrcagney/gtfstk/blob/c91494e6fefc02523889655a0dc92d1c0eee8d03/gtfstk/miscellany.py#L611-L617
def compute_convex_hull(feed: "Feed") -> Polygon: """ Return a Shapely Polygon representing the convex hull formed by the stops of the given Feed. """ m = sg.MultiPoint(feed.stops[["stop_lon", "stop_lat"]].values) return m.convex_hull
[ "def", "compute_convex_hull", "(", "feed", ":", "\"Feed\"", ")", "->", "Polygon", ":", "m", "=", "sg", ".", "MultiPoint", "(", "feed", ".", "stops", "[", "[", "\"stop_lon\"", ",", "\"stop_lat\"", "]", "]", ".", "values", ")", "return", "m", ".", "conve...
Return a Shapely Polygon representing the convex hull formed by the stops of the given Feed.
[ "Return", "a", "Shapely", "Polygon", "representing", "the", "convex", "hull", "formed", "by", "the", "stops", "of", "the", "given", "Feed", "." ]
python
train
twilio/twilio-python
twilio/rest/taskrouter/v1/workspace/worker/workers_cumulative_statistics.py
https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/taskrouter/v1/workspace/worker/workers_cumulative_statistics.py#L209-L222
def _proxy(self): """ Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: WorkersCumulativeStatisticsContext for this WorkersCumulativeStatisticsInstance :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics.WorkersCumulativeStatisticsContext """ if self._context is None: self._context = WorkersCumulativeStatisticsContext( self._version, workspace_sid=self._solution['workspace_sid'], ) return self._context
[ "def", "_proxy", "(", "self", ")", ":", "if", "self", ".", "_context", "is", "None", ":", "self", ".", "_context", "=", "WorkersCumulativeStatisticsContext", "(", "self", ".", "_version", ",", "workspace_sid", "=", "self", ".", "_solution", "[", "'workspace_...
Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: WorkersCumulativeStatisticsContext for this WorkersCumulativeStatisticsInstance :rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics.WorkersCumulativeStatisticsContext
[ "Generate", "an", "instance", "context", "for", "the", "instance", "the", "context", "is", "capable", "of", "performing", "various", "actions", ".", "All", "instance", "actions", "are", "proxied", "to", "the", "context" ]
python
train
PyCQA/pylint
pylint/utils/ast_walker.py
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/utils/ast_walker.py#L27-L55
def add_checker(self, checker): """walk to the checker's dir and collect visit and leave methods""" # XXX : should be possible to merge needed_checkers and add_checker vcids = set() lcids = set() visits = self.visit_events leaves = self.leave_events for member in dir(checker): cid = member[6:] if cid == "default": continue if member.startswith("visit_"): v_meth = getattr(checker, member) # don't use visit_methods with no activated message: if self._is_method_enabled(v_meth): visits[cid].append(v_meth) vcids.add(cid) elif member.startswith("leave_"): l_meth = getattr(checker, member) # don't use leave_methods with no activated message: if self._is_method_enabled(l_meth): leaves[cid].append(l_meth) lcids.add(cid) visit_default = getattr(checker, "visit_default", None) if visit_default: for cls in nodes.ALL_NODE_CLASSES: cid = cls.__name__.lower() if cid not in vcids: visits[cid].append(visit_default)
[ "def", "add_checker", "(", "self", ",", "checker", ")", ":", "# XXX : should be possible to merge needed_checkers and add_checker", "vcids", "=", "set", "(", ")", "lcids", "=", "set", "(", ")", "visits", "=", "self", ".", "visit_events", "leaves", "=", "self", "...
walk to the checker's dir and collect visit and leave methods
[ "walk", "to", "the", "checker", "s", "dir", "and", "collect", "visit", "and", "leave", "methods" ]
python
test
vaexio/vaex
packages/vaex-astro/vaex/astro/transformations.py
https://github.com/vaexio/vaex/blob/a45b672f8287afca2ada8e36b74b604b9b28dd85/packages/vaex-astro/vaex/astro/transformations.py#L206-L239
def add_virtual_columns_lbrvr_proper_motion2vcartesian(self, long_in="l", lat_in="b", distance="distance", pm_long="pm_l", pm_lat="pm_b", vr="vr", vx="vx", vy="vy", vz="vz", center_v=(0, 0, 0), propagate_uncertainties=False, radians=False): """Convert radial velocity and galactic proper motions (and positions) to cartesian velocities wrt the center_v Based on http://adsabs.harvard.edu/abs/1987AJ.....93..864J :param long_in: Name/expression for galactic longitude :param lat_in: Name/expression for galactic latitude :param distance: Name/expression for heliocentric distance :param pm_long: Name/expression for the galactic proper motion in latitude direction (pm_l*, so cosine(b) term should be included) :param pm_lat: Name/expression for the galactic proper motion in longitude direction :param vr: Name/expression for the radial velocity :param vx: Output name for the cartesian velocity x-component :param vy: Output name for the cartesian velocity y-component :param vz: Output name for the cartesian velocity z-component :param center_v: Extra motion that should be added, for instance lsr + motion of the sun wrt the galactic restframe :param radians: input and output in radians (True), or degrees (False) :return: """ k = 4.74057 a, d, distance = self._expr(long_in, lat_in, distance) pm_long, pm_lat, vr = self._expr(pm_long, pm_lat, vr) if not radians: a = a * np.pi/180 d = d * np.pi/180 A = [[np.cos(a)*np.cos(d), -np.sin(a), -np.cos(a)*np.sin(d)], [np.sin(a)*np.cos(d), np.cos(a), -np.sin(a)*np.sin(d)], [np.sin(d), d*0, np.cos(d)]] self.add_virtual_columns_matrix3d(vr, k * pm_long * distance, k * pm_lat * distance, vx, vy, vz, A, translation=center_v) if propagate_uncertainties: self.propagate_uncertainties([self[vx], self[vy], self[vz]])
[ "def", "add_virtual_columns_lbrvr_proper_motion2vcartesian", "(", "self", ",", "long_in", "=", "\"l\"", ",", "lat_in", "=", "\"b\"", ",", "distance", "=", "\"distance\"", ",", "pm_long", "=", "\"pm_l\"", ",", "pm_lat", "=", "\"pm_b\"", ",", "vr", "=", "\"vr\"", ...
Convert radial velocity and galactic proper motions (and positions) to cartesian velocities wrt the center_v Based on http://adsabs.harvard.edu/abs/1987AJ.....93..864J :param long_in: Name/expression for galactic longitude :param lat_in: Name/expression for galactic latitude :param distance: Name/expression for heliocentric distance :param pm_long: Name/expression for the galactic proper motion in latitude direction (pm_l*, so cosine(b) term should be included) :param pm_lat: Name/expression for the galactic proper motion in longitude direction :param vr: Name/expression for the radial velocity :param vx: Output name for the cartesian velocity x-component :param vy: Output name for the cartesian velocity y-component :param vz: Output name for the cartesian velocity z-component :param center_v: Extra motion that should be added, for instance lsr + motion of the sun wrt the galactic restframe :param radians: input and output in radians (True), or degrees (False) :return:
[ "Convert", "radial", "velocity", "and", "galactic", "proper", "motions", "(", "and", "positions", ")", "to", "cartesian", "velocities", "wrt", "the", "center_v" ]
python
test
belbio/bel
bel/lang/partialparse.py
https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/partialparse.py#L647-L736
def parsed_top_level_errors(parsed, errors, component_type: str = "") -> Errors: """Check full parse for errors Args: parsed: errors: component_type: Empty string or 'subject' or 'object' to indicate that we are parsing the subject or object field input """ # Error check fn_cnt = 0 rel_cnt = 0 nested_cnt = 0 for key in parsed: if parsed[key]["type"] == "Function": fn_cnt += 1 if parsed[key]["type"] == "Relation": rel_cnt += 1 if parsed[key]["type"] == "Nested": nested_cnt += 1 if not component_type: if nested_cnt > 1: errors.append( ( "Error", "Too many nested objects - can only have one per BEL Assertion", ) ) if nested_cnt: if rel_cnt > 2: errors.append( ( "Error", "Too many relations - can only have two in a nested BEL Assertion", ) ) elif fn_cnt > 4: errors.append(("Error", "Too many BEL subject and object candidates")) else: if rel_cnt > 1: errors.append( ( "Error", "Too many relations - can only have one in a BEL Assertion", ) ) elif fn_cnt > 2: errors.append(("Error", "Too many BEL subject and object candidates")) elif component_type == "subject": if rel_cnt > 0: errors.append( ("Error", "Too many relations - cannot have any in a BEL Subject") ) elif fn_cnt > 1: errors.append( ("Error", "Too many BEL subject candidates - can only have one") ) elif component_type == "object": if nested_cnt: if rel_cnt > 1: errors.append( ( "Error", "Too many relations - can only have one in a nested BEL object", ) ) elif fn_cnt > 2: errors.append( ( "Error", "Too many BEL subject and object candidates in a nested BEL object", ) ) else: if rel_cnt > 0: errors.append( ("Error", "Too many relations - cannot have any in a BEL Subject") ) elif fn_cnt > 1: errors.append( ("Error", "Too many BEL subject candidates - can only have one") ) return errors
[ "def", "parsed_top_level_errors", "(", "parsed", ",", "errors", ",", "component_type", ":", "str", "=", "\"\"", ")", "->", "Errors", ":", "# Error check", "fn_cnt", "=", "0", "rel_cnt", "=", "0", "nested_cnt", "=", "0", "for", "key", "in", "parsed", ":", ...
Check full parse for errors Args: parsed: errors: component_type: Empty string or 'subject' or 'object' to indicate that we are parsing the subject or object field input
[ "Check", "full", "parse", "for", "errors" ]
python
train
pyrogram/pyrogram
pyrogram/client/types/bots/callback_query.py
https://github.com/pyrogram/pyrogram/blob/e7258a341ba905cfa86264c22040654db732ec1c/pyrogram/client/types/bots/callback_query.py#L123-L165
def answer(self, text: str = None, show_alert: bool = None, url: str = None, cache_time: int = 0): """Bound method *answer* of :obj:`CallbackQuery <pyrogram.CallbackQuery>`. Use this method as a shortcut for: .. code-block:: python client.answer_callback_query( callback_query.id, text="Hello", show_alert=True ) Example: .. code-block:: python callback_query.answer("Hello", show_alert=True) Args: text (``str``): Text of the notification. If not specified, nothing will be shown to the user, 0-200 characters. show_alert (``bool``): If true, an alert will be shown by the client instead of a notification at the top of the chat screen. Defaults to False. url (``str``): URL that will be opened by the user's client. If you have created a Game and accepted the conditions via @Botfather, specify the URL that opens your game – note that this will only work if the query comes from a callback_game button. Otherwise, you may use links like t.me/your_bot?start=XXXX that open your bot with a parameter. cache_time (``int``): The maximum amount of time in seconds that the result of the callback query may be cached client-side. Telegram apps will support caching starting in version 3.14. Defaults to 0. """ return self._client.answer_callback_query( callback_query_id=self.id, text=text, show_alert=show_alert, url=url, cache_time=cache_time )
[ "def", "answer", "(", "self", ",", "text", ":", "str", "=", "None", ",", "show_alert", ":", "bool", "=", "None", ",", "url", ":", "str", "=", "None", ",", "cache_time", ":", "int", "=", "0", ")", ":", "return", "self", ".", "_client", ".", "answe...
Bound method *answer* of :obj:`CallbackQuery <pyrogram.CallbackQuery>`. Use this method as a shortcut for: .. code-block:: python client.answer_callback_query( callback_query.id, text="Hello", show_alert=True ) Example: .. code-block:: python callback_query.answer("Hello", show_alert=True) Args: text (``str``): Text of the notification. If not specified, nothing will be shown to the user, 0-200 characters. show_alert (``bool``): If true, an alert will be shown by the client instead of a notification at the top of the chat screen. Defaults to False. url (``str``): URL that will be opened by the user's client. If you have created a Game and accepted the conditions via @Botfather, specify the URL that opens your game – note that this will only work if the query comes from a callback_game button. Otherwise, you may use links like t.me/your_bot?start=XXXX that open your bot with a parameter. cache_time (``int``): The maximum amount of time in seconds that the result of the callback query may be cached client-side. Telegram apps will support caching starting in version 3.14. Defaults to 0.
[ "Bound", "method", "*", "answer", "*", "of", ":", "obj", ":", "CallbackQuery", "<pyrogram", ".", "CallbackQuery", ">", "." ]
python
train
fhcrc/taxtastic
taxtastic/taxtable.py
https://github.com/fhcrc/taxtastic/blob/4e874b7f2cc146178828bfba386314f8c342722b/taxtastic/taxtable.py#L199-L226
def write_taxtable(self, out_fp, **kwargs): """ Write a taxtable for this node and all descendants, including the lineage leading to this node. """ ranks_represented = frozenset(i.rank for i in self) | \ frozenset(i.rank for i in self.lineage()) ranks = [i for i in self.ranks if i in ranks_represented] assert len(ranks_represented) == len(ranks) def node_record(node): parent_id = node.parent.tax_id if node.parent else node.tax_id d = {'tax_id': node.tax_id, 'tax_name': node.name, 'parent_id': parent_id, 'rank': node.rank} L = {i.rank: i.tax_id for i in node.lineage()} d.update(L) return d header = ['tax_id', 'parent_id', 'rank', 'tax_name'] + ranks w = csv.DictWriter(out_fp, header, quoting=csv.QUOTE_NONNUMERIC, lineterminator='\n') w.writeheader() # All nodes leading to this one for i in self.lineage()[:-1]: w.writerow(node_record(i)) w.writerows(node_record(i) for i in self)
[ "def", "write_taxtable", "(", "self", ",", "out_fp", ",", "*", "*", "kwargs", ")", ":", "ranks_represented", "=", "frozenset", "(", "i", ".", "rank", "for", "i", "in", "self", ")", "|", "frozenset", "(", "i", ".", "rank", "for", "i", "in", "self", ...
Write a taxtable for this node and all descendants, including the lineage leading to this node.
[ "Write", "a", "taxtable", "for", "this", "node", "and", "all", "descendants", "including", "the", "lineage", "leading", "to", "this", "node", "." ]
python
train
Azure/azure-cli-extensions
src/express-route/azext_express_route/vendored_sdks/network_management_client.py
https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/express-route/azext_express_route/vendored_sdks/network_management_client.py#L327-L337
def available_delegations(self): """Instance depends on the API version: * 2018-08-01: :class:`AvailableDelegationsOperations<azure.mgmt.network.v2018_08_01.operations.AvailableDelegationsOperations>` """ api_version = self._get_api_version('available_delegations') if api_version == '2018-08-01': from .v2018_08_01.operations import AvailableDelegationsOperations as OperationClass else: raise NotImplementedError("APIVersion {} is not available".format(api_version)) return OperationClass(self._client, self.config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)))
[ "def", "available_delegations", "(", "self", ")", ":", "api_version", "=", "self", ".", "_get_api_version", "(", "'available_delegations'", ")", "if", "api_version", "==", "'2018-08-01'", ":", "from", ".", "v2018_08_01", ".", "operations", "import", "AvailableDelega...
Instance depends on the API version: * 2018-08-01: :class:`AvailableDelegationsOperations<azure.mgmt.network.v2018_08_01.operations.AvailableDelegationsOperations>`
[ "Instance", "depends", "on", "the", "API", "version", ":" ]
python
train
cloud-custodian/cloud-custodian
c7n/cwe.py
https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/cwe.py#L120-L147
def get_trail_ids(cls, event, mode): """extract resources ids from a cloud trail event.""" resource_ids = () event_name = event['detail']['eventName'] event_source = event['detail']['eventSource'] for e in mode.get('events', []): if not isinstance(e, dict): # Check if we have a short cut / alias info = CloudWatchEvents.match(event) if info: return info['ids'].search(event) continue if event_name != e.get('event'): continue if event_source != e.get('source'): continue id_query = e.get('ids') if not id_query: raise ValueError("No id query configured") evt = event # be forgiving for users specifying with details or without if not id_query.startswith('detail.'): evt = event.get('detail', {}) resource_ids = jmespath.search(id_query, evt) if resource_ids: break return resource_ids
[ "def", "get_trail_ids", "(", "cls", ",", "event", ",", "mode", ")", ":", "resource_ids", "=", "(", ")", "event_name", "=", "event", "[", "'detail'", "]", "[", "'eventName'", "]", "event_source", "=", "event", "[", "'detail'", "]", "[", "'eventSource'", "...
extract resources ids from a cloud trail event.
[ "extract", "resources", "ids", "from", "a", "cloud", "trail", "event", "." ]
python
train
noxdafox/vminspect
vminspect/vtscan.py
https://github.com/noxdafox/vminspect/blob/e685282564877e2d1950f1e09b292f4f4db1dbcd/vminspect/vtscan.py#L79-L108
def scan(self, filetypes=None): """Iterates over the content of the disk and queries VirusTotal to determine whether it's malicious or not. filetypes is a list containing regular expression patterns. If given, only the files which type will match with one or more of the given patterns will be queried against VirusTotal. For each file which is unknown by VT or positive to any of its engines, the method yields a namedtuple: VTReport(path -> C:\\Windows\\System32\\infected.dll hash -> ab231... detections) -> dictionary engine -> detection Files unknown by VirusTotal will contain the string 'unknown' in the detection field. """ self.logger.debug("Scanning FS content.") checksums = self.filetype_filter(self._filesystem.checksums('/'), filetypes=filetypes) self.logger.debug("Querying %d objects to VTotal.", len(checksums)) for files in chunks(checksums, size=self.batchsize): files = dict((reversed(e) for e in files)) response = vtquery(self._apikey, files.keys()) yield from self.parse_response(files, response)
[ "def", "scan", "(", "self", ",", "filetypes", "=", "None", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"Scanning FS content.\"", ")", "checksums", "=", "self", ".", "filetype_filter", "(", "self", ".", "_filesystem", ".", "checksums", "(", "'/'",...
Iterates over the content of the disk and queries VirusTotal to determine whether it's malicious or not. filetypes is a list containing regular expression patterns. If given, only the files which type will match with one or more of the given patterns will be queried against VirusTotal. For each file which is unknown by VT or positive to any of its engines, the method yields a namedtuple: VTReport(path -> C:\\Windows\\System32\\infected.dll hash -> ab231... detections) -> dictionary engine -> detection Files unknown by VirusTotal will contain the string 'unknown' in the detection field.
[ "Iterates", "over", "the", "content", "of", "the", "disk", "and", "queries", "VirusTotal", "to", "determine", "whether", "it", "s", "malicious", "or", "not", "." ]
python
train
sci-bots/dmf-device-ui
dmf_device_ui/canvas.py
https://github.com/sci-bots/dmf-device-ui/blob/05b480683c9fa43f91ce5a58de2fa90cdf363fc8/dmf_device_ui/canvas.py#L1236-L1245
def register_electrode_command(self, command, title=None, group=None): ''' Register electrode command. Add electrode plugin command to context menu. ''' commands = self.electrode_commands.setdefault(group, OrderedDict()) if title is None: title = (command[:1].upper() + command[1:]).replace('_', ' ') commands[command] = title
[ "def", "register_electrode_command", "(", "self", ",", "command", ",", "title", "=", "None", ",", "group", "=", "None", ")", ":", "commands", "=", "self", ".", "electrode_commands", ".", "setdefault", "(", "group", ",", "OrderedDict", "(", ")", ")", "if", ...
Register electrode command. Add electrode plugin command to context menu.
[ "Register", "electrode", "command", "." ]
python
train
Jaymon/endpoints
endpoints/http.py
https://github.com/Jaymon/endpoints/blob/2f1c4ae2c69a168e69447d3d8395ada7becaa5fb/endpoints/http.py#L816-L825
def accept_encoding(self): """The encoding the client requested the response to use""" # https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Charset ret = "" accept_encoding = self.get_header("Accept-Charset", "") if accept_encoding: bits = re.split(r"\s+", accept_encoding) bits = bits[0].split(";") ret = bits[0] return ret
[ "def", "accept_encoding", "(", "self", ")", ":", "# https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Charset", "ret", "=", "\"\"", "accept_encoding", "=", "self", ".", "get_header", "(", "\"Accept-Charset\"", ",", "\"\"", ")", "if", "accept_encoding", ":",...
The encoding the client requested the response to use
[ "The", "encoding", "the", "client", "requested", "the", "response", "to", "use" ]
python
train
alvations/pywsd
pywsd/similarity.py
https://github.com/alvations/pywsd/blob/4c12394c8adbcfed71dd912bdbef2e36370821bf/pywsd/similarity.py#L73-L90
def sim(sense1: "wn.Synset", sense2: "wn.Synset", option: str = "path") -> float: """ Calculates similarity based on user's choice. :param sense1: A synset. :param sense2: A synset. :param option: String, one of ('path', 'wup', 'lch', 'res', 'jcn', 'lin'). :return: A float, similarity measurement. """ option = option.lower() if option.lower() in ["path", "path_similarity", "wup", "wupa", "wu-palmer", "wu-palmer", 'lch', "leacock-chordorow"]: return similarity_by_path(sense1, sense2, option) elif option.lower() in ["res", "resnik", "jcn","jiang-conrath", "lin"]: return similarity_by_infocontent(sense1, sense2, option)
[ "def", "sim", "(", "sense1", ":", "\"wn.Synset\"", ",", "sense2", ":", "\"wn.Synset\"", ",", "option", ":", "str", "=", "\"path\"", ")", "->", "float", ":", "option", "=", "option", ".", "lower", "(", ")", "if", "option", ".", "lower", "(", ")", "in"...
Calculates similarity based on user's choice. :param sense1: A synset. :param sense2: A synset. :param option: String, one of ('path', 'wup', 'lch', 'res', 'jcn', 'lin'). :return: A float, similarity measurement.
[ "Calculates", "similarity", "based", "on", "user", "s", "choice", "." ]
python
train
bitesofcode/projexui
projexui/widgets/xtreewidget/xtreewidget.py
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xtreewidget/xtreewidget.py#L1007-L1012
def headerSortDescending( self ): """ Sorts the column at the current header index by descending order. """ self.setSortingEnabled(True) self.sortByColumn(self._headerIndex, QtCore.Qt.DescendingOrder)
[ "def", "headerSortDescending", "(", "self", ")", ":", "self", ".", "setSortingEnabled", "(", "True", ")", "self", ".", "sortByColumn", "(", "self", ".", "_headerIndex", ",", "QtCore", ".", "Qt", ".", "DescendingOrder", ")" ]
Sorts the column at the current header index by descending order.
[ "Sorts", "the", "column", "at", "the", "current", "header", "index", "by", "descending", "order", "." ]
python
train
cloud9ers/gurumate
environment/lib/python2.7/site-packages/IPython/parallel/util.py
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/util.py#L283-L294
def signal_children(children): """Relay interupt/term signals to children, for more solid process cleanup.""" def terminate_children(sig, frame): log = Application.instance().log log.critical("Got signal %i, terminating children..."%sig) for child in children: child.terminate() sys.exit(sig != SIGINT) # sys.exit(sig) for sig in (SIGINT, SIGABRT, SIGTERM): signal(sig, terminate_children)
[ "def", "signal_children", "(", "children", ")", ":", "def", "terminate_children", "(", "sig", ",", "frame", ")", ":", "log", "=", "Application", ".", "instance", "(", ")", ".", "log", "log", ".", "critical", "(", "\"Got signal %i, terminating children...\"", "...
Relay interupt/term signals to children, for more solid process cleanup.
[ "Relay", "interupt", "/", "term", "signals", "to", "children", "for", "more", "solid", "process", "cleanup", "." ]
python
test
spyder-ide/spyder
spyder/plugins/editor/utils/kill_ring.py
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/kill_ring.py#L55-L65
def rotate(self): """ Rotate the kill ring, then yank back the new top. Returns ------- A text string or None. """ self._index -= 1 if self._index >= 0: return self._ring[self._index] return None
[ "def", "rotate", "(", "self", ")", ":", "self", ".", "_index", "-=", "1", "if", "self", ".", "_index", ">=", "0", ":", "return", "self", ".", "_ring", "[", "self", ".", "_index", "]", "return", "None" ]
Rotate the kill ring, then yank back the new top. Returns ------- A text string or None.
[ "Rotate", "the", "kill", "ring", "then", "yank", "back", "the", "new", "top", "." ]
python
train
gmr/infoblox
infoblox/record.py
https://github.com/gmr/infoblox/blob/163dd9cff5f77c08751936c56aa8428acfd2d208/infoblox/record.py#L185-L200
def _build_search_values(self, kwargs): """Build the search criteria dictionary. It will first try and build the values from already set attributes on the object, falling back to the passed in kwargs. :param dict kwargs: Values to build the dict from :rtype: dict """ criteria = {} for key in self._search_by: if getattr(self, key, None): criteria[key] = getattr(self, key) elif key in kwargs and kwargs.get(key): criteria[key] = kwargs.get(key) return criteria
[ "def", "_build_search_values", "(", "self", ",", "kwargs", ")", ":", "criteria", "=", "{", "}", "for", "key", "in", "self", ".", "_search_by", ":", "if", "getattr", "(", "self", ",", "key", ",", "None", ")", ":", "criteria", "[", "key", "]", "=", "...
Build the search criteria dictionary. It will first try and build the values from already set attributes on the object, falling back to the passed in kwargs. :param dict kwargs: Values to build the dict from :rtype: dict
[ "Build", "the", "search", "criteria", "dictionary", ".", "It", "will", "first", "try", "and", "build", "the", "values", "from", "already", "set", "attributes", "on", "the", "object", "falling", "back", "to", "the", "passed", "in", "kwargs", "." ]
python
train
marcelnicolay/pycompressor
compressor/minifier/css.py
https://github.com/marcelnicolay/pycompressor/blob/ded6b16c58c9f2a7446014b171fd409a22b561e4/compressor/minifier/css.py#L40-L45
def minify(self, css): """Tries to minimize the length of CSS code passed as parameter. Returns string.""" css = css.replace("\r\n", "\n") # get rid of Windows line endings, if they exist for rule in _REPLACERS[self.level]: css = re.compile(rule[0], re.MULTILINE|re.UNICODE|re.DOTALL).sub(rule[1], css) return css
[ "def", "minify", "(", "self", ",", "css", ")", ":", "css", "=", "css", ".", "replace", "(", "\"\\r\\n\"", ",", "\"\\n\"", ")", "# get rid of Windows line endings, if they exist", "for", "rule", "in", "_REPLACERS", "[", "self", ".", "level", "]", ":", "css", ...
Tries to minimize the length of CSS code passed as parameter. Returns string.
[ "Tries", "to", "minimize", "the", "length", "of", "CSS", "code", "passed", "as", "parameter", ".", "Returns", "string", "." ]
python
valid
mushkevych/scheduler
launch.py
https://github.com/mushkevych/scheduler/blob/6740331360f49083c208085fb5a60ce80ebf418b/launch.py#L148-L155
def install_virtualenv(parser_args): """ Installs virtual environment """ python_version = '.'.join(str(v) for v in sys.version_info[:2]) sys.stdout.write('Installing Python {0} virtualenv into {1} \n'.format(python_version, VE_ROOT)) if sys.version_info < (3, 3): install_virtualenv_p2(VE_ROOT, python_version) else: install_virtualenv_p3(VE_ROOT, python_version)
[ "def", "install_virtualenv", "(", "parser_args", ")", ":", "python_version", "=", "'.'", ".", "join", "(", "str", "(", "v", ")", "for", "v", "in", "sys", ".", "version_info", "[", ":", "2", "]", ")", "sys", ".", "stdout", ".", "write", "(", "'Install...
Installs virtual environment
[ "Installs", "virtual", "environment" ]
python
train
etalab/cada
cada/commands.py
https://github.com/etalab/cada/blob/36e8b57514445c01ff7cd59a1c965180baf83d5e/cada/commands.py#L70-L73
def header(msg, *args, **kwargs): '''Display an header''' msg = ' '.join((yellow(HEADER), white(msg), yellow(HEADER))) echo(msg, *args, **kwargs)
[ "def", "header", "(", "msg", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "msg", "=", "' '", ".", "join", "(", "(", "yellow", "(", "HEADER", ")", ",", "white", "(", "msg", ")", ",", "yellow", "(", "HEADER", ")", ")", ")", "echo", "(",...
Display an header
[ "Display", "an", "header" ]
python
train