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
PythonCharmers/python-future
src/future/backports/xmlrpc/server.py
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/xmlrpc/server.py#L754-L797
def docroutine(self, object, name, mod=None, funcs={}, classes={}, methods={}, cl=None): """Produce HTML documentation for a function or method object.""" anchor = (cl and cl.__name__ or '') + '-' + name note = '' title = '<a name="%s"><strong>%s</strong></a>' % ( ...
[ "def", "docroutine", "(", "self", ",", "object", ",", "name", ",", "mod", "=", "None", ",", "funcs", "=", "{", "}", ",", "classes", "=", "{", "}", ",", "methods", "=", "{", "}", ",", "cl", "=", "None", ")", ":", "anchor", "=", "(", "cl", "and...
Produce HTML documentation for a function or method object.
[ "Produce", "HTML", "documentation", "for", "a", "function", "or", "method", "object", "." ]
python
train
cebel/pyuniprot
src/pyuniprot/manager/database.py
https://github.com/cebel/pyuniprot/blob/9462a6042c7c9295415a5eb589b77b27cb7c142b/src/pyuniprot/manager/database.py#L348-L365
def get_tissue_in_references(self, entry): """ get list of models.TissueInReference from XML node entry :param entry: XML node entry :return: list of :class:`pyuniprot.manager.models.TissueInReference` objects """ tissue_in_references = [] query = "./reference/so...
[ "def", "get_tissue_in_references", "(", "self", ",", "entry", ")", ":", "tissue_in_references", "=", "[", "]", "query", "=", "\"./reference/source/tissue\"", "tissues", "=", "{", "x", ".", "text", "for", "x", "in", "entry", ".", "iterfind", "(", "query", ")"...
get list of models.TissueInReference from XML node entry :param entry: XML node entry :return: list of :class:`pyuniprot.manager.models.TissueInReference` objects
[ "get", "list", "of", "models", ".", "TissueInReference", "from", "XML", "node", "entry" ]
python
train
fboender/ansible-cmdb
src/ansiblecmdb/ansible.py
https://github.com/fboender/ansible-cmdb/blob/ebd960ac10684e8c9ec2b12751bba2c4c9504ab7/src/ansiblecmdb/ansible.py#L191-L223
def _parse_hostvar_file(self, hostname, path): """ Parse a host var file and apply it to host `hostname`. """ # Check for ansible-vault files, because they're valid yaml for # some reason... (psst, the reason is that yaml sucks) first_line = open(path, 'r').readline() ...
[ "def", "_parse_hostvar_file", "(", "self", ",", "hostname", ",", "path", ")", ":", "# Check for ansible-vault files, because they're valid yaml for", "# some reason... (psst, the reason is that yaml sucks)", "first_line", "=", "open", "(", "path", ",", "'r'", ")", ".", "rea...
Parse a host var file and apply it to host `hostname`.
[ "Parse", "a", "host", "var", "file", "and", "apply", "it", "to", "host", "hostname", "." ]
python
train
bwohlberg/sporco
sporco/linalg.py
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/linalg.py#L614-L686
def solvemdbi_ism(ah, rho, b, axisM, axisK): r""" Solve a multiple diagonal block linear system with a scaled identity term by iterated application of the Sherman-Morrison equation. The computation is performed in a way that avoids explictly constructing the inverse operator, leading to an :math...
[ "def", "solvemdbi_ism", "(", "ah", ",", "rho", ",", "b", ",", "axisM", ",", "axisK", ")", ":", "if", "axisM", "<", "0", ":", "axisM", "+=", "ah", ".", "ndim", "if", "axisK", "<", "0", ":", "axisK", "+=", "ah", ".", "ndim", "K", "=", "ah", "."...
r""" Solve a multiple diagonal block linear system with a scaled identity term by iterated application of the Sherman-Morrison equation. The computation is performed in a way that avoids explictly constructing the inverse operator, leading to an :math:`O(K^2)` time cost. The solution is obtaine...
[ "r", "Solve", "a", "multiple", "diagonal", "block", "linear", "system", "with", "a", "scaled", "identity", "term", "by", "iterated", "application", "of", "the", "Sherman", "-", "Morrison", "equation", ".", "The", "computation", "is", "performed", "in", "a", ...
python
train
saltstack/salt
salt/modules/systemd_service.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/systemd_service.py#L696-L741
def mask(name, runtime=False, root=None): ''' .. versionadded:: 2015.5.0 .. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=205, `systemd-run(1)`_ is now used to isolate commands run by this function from the ``salt-minion`` daemon's control group. This is d...
[ "def", "mask", "(", "name", ",", "runtime", "=", "False", ",", "root", "=", "None", ")", ":", "_check_for_unit_changes", "(", "name", ")", "cmd", "=", "'mask --runtime'", "if", "runtime", "else", "'mask'", "out", "=", "__salt__", "[", "'cmd.run_all'", "]",...
.. versionadded:: 2015.5.0 .. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=205, `systemd-run(1)`_ is now used to isolate commands run by this function from the ``salt-minion`` daemon's control group. This is done to avoid a race condition in cases where t...
[ "..", "versionadded", "::", "2015", ".", "5", ".", "0", "..", "versionchanged", "::", "2015", ".", "8", ".", "12", "2016", ".", "3", ".", "3", "2016", ".", "11", ".", "0", "On", "minions", "running", "systemd", ">", "=", "205", "systemd", "-", "r...
python
train
dourvaris/nano-python
src/nano/rpc.py
https://github.com/dourvaris/nano-python/blob/f26b8bc895b997067780f925049a70e82c0c2479/src/nano/rpc.py#L2987-L3021
def work_set(self, wallet, account, work): """ Set **work** for **account** in **wallet** .. enable_control required .. version 8.0 required :param wallet: Wallet to set work for account for :type wallet: str :param account: Account to set work for :typ...
[ "def", "work_set", "(", "self", ",", "wallet", ",", "account", ",", "work", ")", ":", "wallet", "=", "self", ".", "_process_value", "(", "wallet", ",", "'wallet'", ")", "account", "=", "self", ".", "_process_value", "(", "account", ",", "'account'", ")",...
Set **work** for **account** in **wallet** .. enable_control required .. version 8.0 required :param wallet: Wallet to set work for account for :type wallet: str :param account: Account to set work for :type account: str :param work: Work to set for account in...
[ "Set", "**", "work", "**", "for", "**", "account", "**", "in", "**", "wallet", "**" ]
python
train
SeattleTestbed/seash
seash_modules.py
https://github.com/SeattleTestbed/seash/blob/40f9d2285662ff8b61e0468b4196acee089b273b/seash_modules.py#L74-L98
def import_all_modules(): """ <Purpose> Imports all modules within the modules folder. This should only be called once throughout the entire execution of seash. <Side Effects> Modules that don't have collisions will have their commanddicts and helptexts loaded and returned. <Excep...
[ "def", "import_all_modules", "(", ")", ":", "for", "module_folder", "in", "get_installed_modules", "(", ")", ":", "try", ":", "if", "module_folder", "in", "module_data", ":", "raise", "seash_exceptions", ".", "ModuleImportError", "(", "\"Module already imported\"", ...
<Purpose> Imports all modules within the modules folder. This should only be called once throughout the entire execution of seash. <Side Effects> Modules that don't have collisions will have their commanddicts and helptexts loaded and returned. <Exceptions> ImportError: There is a...
[ "<Purpose", ">", "Imports", "all", "modules", "within", "the", "modules", "folder", ".", "This", "should", "only", "be", "called", "once", "throughout", "the", "entire", "execution", "of", "seash", ".", "<Side", "Effects", ">", "Modules", "that", "don", "t",...
python
train
inveniosoftware-contrib/record-recommender
record_recommender/storage.py
https://github.com/inveniosoftware-contrib/record-recommender/blob/07f71e783369e6373218b5e6ba0bf15901e9251a/record_recommender/storage.py#L73-L94
def open(self, mode='read'): """Open the file.""" if self.file: self.close() raise 'Close file before opening.' if mode == 'write': self.file = open(self.path, 'w') elif mode == 'overwrite': # Delete file if exist. self.file = ...
[ "def", "open", "(", "self", ",", "mode", "=", "'read'", ")", ":", "if", "self", ".", "file", ":", "self", ".", "close", "(", ")", "raise", "'Close file before opening.'", "if", "mode", "==", "'write'", ":", "self", ".", "file", "=", "open", "(", "sel...
Open the file.
[ "Open", "the", "file", "." ]
python
train
kibitzr/kibitzr
kibitzr/fetcher/browser/fetcher.py
https://github.com/kibitzr/kibitzr/blob/749da312488f1dda1ed1093cf4c95aaac0a604f7/kibitzr/fetcher/browser/fetcher.py#L259-L279
def _find_element(self, selector, selector_type, check_displayed=False): """ Return first matching displayed element of non-zero size or None if nothing found """ if selector_type == 'css': elements = self.driver.find_elements_by_css_selector(selector) elif se...
[ "def", "_find_element", "(", "self", ",", "selector", ",", "selector_type", ",", "check_displayed", "=", "False", ")", ":", "if", "selector_type", "==", "'css'", ":", "elements", "=", "self", ".", "driver", ".", "find_elements_by_css_selector", "(", "selector", ...
Return first matching displayed element of non-zero size or None if nothing found
[ "Return", "first", "matching", "displayed", "element", "of", "non", "-", "zero", "size", "or", "None", "if", "nothing", "found" ]
python
train
datastax/python-driver
cassandra/metadata.py
https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/metadata.py#L901-L921
def as_cql_query(self, formatted=False): """ Returns a CQL query that can be used to recreate this aggregate. If `formatted` is set to :const:`True`, extra whitespace will be added to make the query more readable. """ sep = '\n ' if formatted else ' ' keyspace ...
[ "def", "as_cql_query", "(", "self", ",", "formatted", "=", "False", ")", ":", "sep", "=", "'\\n '", "if", "formatted", "else", "' '", "keyspace", "=", "protect_name", "(", "self", ".", "keyspace", ")", "name", "=", "protect_name", "(", "self", ".", "n...
Returns a CQL query that can be used to recreate this aggregate. If `formatted` is set to :const:`True`, extra whitespace will be added to make the query more readable.
[ "Returns", "a", "CQL", "query", "that", "can", "be", "used", "to", "recreate", "this", "aggregate", ".", "If", "formatted", "is", "set", "to", ":", "const", ":", "True", "extra", "whitespace", "will", "be", "added", "to", "make", "the", "query", "more", ...
python
train
dailymuse/oz
oz/bandit/__init__.py
https://github.com/dailymuse/oz/blob/4329f6a207dc9d2a8fbeb4d16d415dbe4570b5bd/oz/bandit/__init__.py#L298-L302
def get_experiments(redis, active=True): """Gets the full list of experiments""" key = ACTIVE_EXPERIMENTS_REDIS_KEY if active else ARCHIVED_EXPERIMENTS_REDIS_KEY return [Experiment(redis, escape.to_unicode(name)) for name in redis.smembers(key)]
[ "def", "get_experiments", "(", "redis", ",", "active", "=", "True", ")", ":", "key", "=", "ACTIVE_EXPERIMENTS_REDIS_KEY", "if", "active", "else", "ARCHIVED_EXPERIMENTS_REDIS_KEY", "return", "[", "Experiment", "(", "redis", ",", "escape", ".", "to_unicode", "(", ...
Gets the full list of experiments
[ "Gets", "the", "full", "list", "of", "experiments" ]
python
train
boundlessgeo/lib-qgis-commons
qgiscommons2/gui/__init__.py
https://github.com/boundlessgeo/lib-qgis-commons/blob/d25d13803db08c18632b55d12036e332f006d9ac/qgiscommons2/gui/__init__.py#L12-L29
def addHelpMenu(menuName, parentMenuFunction=None): ''' Adds a help menu to the plugin menu. This method should be called from the initGui() method of the plugin :param menuName: The name of the plugin menu in which the about menu is to be added. ''' parentMenuFunction = parentMenuFunction or ...
[ "def", "addHelpMenu", "(", "menuName", ",", "parentMenuFunction", "=", "None", ")", ":", "parentMenuFunction", "=", "parentMenuFunction", "or", "iface", ".", "addPluginToMenu", "namespace", "=", "_callerName", "(", ")", ".", "split", "(", "\".\"", ")", "[", "0...
Adds a help menu to the plugin menu. This method should be called from the initGui() method of the plugin :param menuName: The name of the plugin menu in which the about menu is to be added.
[ "Adds", "a", "help", "menu", "to", "the", "plugin", "menu", ".", "This", "method", "should", "be", "called", "from", "the", "initGui", "()", "method", "of", "the", "plugin" ]
python
train
3DLIRIOUS/MeshLabXML
meshlabxml/select.py
https://github.com/3DLIRIOUS/MeshLabXML/blob/177cce21e92baca500f56a932d66bd9a33257af8/meshlabxml/select.py#L425-L444
def cylindrical_vert(script, radius=1.0, inside=True): """Select all vertices within a cylindrical radius Args: radius (float): radius of the sphere center_pt (3 coordinate tuple or list): center point of the sphere Layer stack: No impacts MeshLab versions: 2016.12 ...
[ "def", "cylindrical_vert", "(", "script", ",", "radius", "=", "1.0", ",", "inside", "=", "True", ")", ":", "if", "inside", ":", "function", "=", "'sqrt(x^2+y^2)<={}'", ".", "format", "(", "radius", ")", "else", ":", "function", "=", "'sqrt(x^2+y^2)>={}'", ...
Select all vertices within a cylindrical radius Args: radius (float): radius of the sphere center_pt (3 coordinate tuple or list): center point of the sphere Layer stack: No impacts MeshLab versions: 2016.12 1.3.4BETA
[ "Select", "all", "vertices", "within", "a", "cylindrical", "radius" ]
python
test
chimera0/accel-brain-code
Reinforcement-Learning/demo/demo_maze_deep_q_network.py
https://github.com/chimera0/accel-brain-code/blob/03661f6f544bed656269fcd4b3c23c9061629daa/Reinforcement-Learning/demo/demo_maze_deep_q_network.py#L45-L79
def inference(self, state_arr, limit=1000): ''' Infernce. Args: state_arr: `np.ndarray` of state. limit: The number of inferencing. Returns: `list of `np.ndarray` of an optimal route. ''' agent_x, agent_y = n...
[ "def", "inference", "(", "self", ",", "state_arr", ",", "limit", "=", "1000", ")", ":", "agent_x", ",", "agent_y", "=", "np", ".", "where", "(", "state_arr", "[", "0", "]", "==", "1", ")", "agent_x", ",", "agent_y", "=", "agent_x", "[", "0", "]", ...
Infernce. Args: state_arr: `np.ndarray` of state. limit: The number of inferencing. Returns: `list of `np.ndarray` of an optimal route.
[ "Infernce", ".", "Args", ":", "state_arr", ":", "np", ".", "ndarray", "of", "state", ".", "limit", ":", "The", "number", "of", "inferencing", ".", "Returns", ":", "list", "of", "np", ".", "ndarray", "of", "an", "optimal", "route", "." ]
python
train
SandstoneHPC/sandstone-ide
sandstone/lib/filesystem/handlers.py
https://github.com/SandstoneHPC/sandstone-ide/blob/7a47947fb07281c3e3018042863dc67e7e56dc04/sandstone/lib/filesystem/handlers.py#L181-L189
def delete(self, filepath): """ Delete the specified file. """ try: self.fs.delete(filepath) self.write({'msg':'File deleted at {}'.format(filepath)}) except OSError: raise tornado.web.HTTPError(404)
[ "def", "delete", "(", "self", ",", "filepath", ")", ":", "try", ":", "self", ".", "fs", ".", "delete", "(", "filepath", ")", "self", ".", "write", "(", "{", "'msg'", ":", "'File deleted at {}'", ".", "format", "(", "filepath", ")", "}", ")", "except"...
Delete the specified file.
[ "Delete", "the", "specified", "file", "." ]
python
train
saltstack/salt
salt/modules/virt.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/virt.py#L2300-L2324
def get_nics(vm_, **kwargs): ''' Return info about the network interfaces of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versio...
[ "def", "get_nics", "(", "vm_", ",", "*", "*", "kwargs", ")", ":", "conn", "=", "__get_conn", "(", "*", "*", "kwargs", ")", "nics", "=", "_get_nics", "(", "_get_domain", "(", "conn", ",", "vm_", ")", ")", "conn", ".", "close", "(", ")", "return", ...
Return info about the network interfaces of a named vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param password: pa...
[ "Return", "info", "about", "the", "network", "interfaces", "of", "a", "named", "vm" ]
python
train
gmr/tredis
tredis/hashes.py
https://github.com/gmr/tredis/blob/2e91c6a58a35460be0525c51ac6a98fde3b506ad/tredis/hashes.py#L266-L289
def hsetnx(self, key, field, value): """ Sets `field` in the hash stored at `key` only if it does not exist. Sets `field` in the hash stored at `key` only if `field` does not yet exist. If `key` does not exist, a new key holding a hash is created. If `field` already exists, th...
[ "def", "hsetnx", "(", "self", ",", "key", ",", "field", ",", "value", ")", ":", "return", "self", ".", "_execute", "(", "[", "b'HSETNX'", ",", "key", ",", "field", ",", "value", "]", ")" ]
Sets `field` in the hash stored at `key` only if it does not exist. Sets `field` in the hash stored at `key` only if `field` does not yet exist. If `key` does not exist, a new key holding a hash is created. If `field` already exists, this operation has no effect. .. note:: ...
[ "Sets", "field", "in", "the", "hash", "stored", "at", "key", "only", "if", "it", "does", "not", "exist", "." ]
python
train
PyThaiNLP/pythainlp
pythainlp/util/thai.py
https://github.com/PyThaiNLP/pythainlp/blob/e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca/pythainlp/util/thai.py#L24-L39
def isthai(word: str, ignore_chars: str = ".") -> bool: """ Check if all character is Thai เป็นคำที่มีแต่อักษรไทยหรือไม่ :param str word: input text :param str ignore_chars: characters to be ignored (i.e. will be considered as Thai) :return: True or False """ if not ignore_chars: ...
[ "def", "isthai", "(", "word", ":", "str", ",", "ignore_chars", ":", "str", "=", "\".\"", ")", "->", "bool", ":", "if", "not", "ignore_chars", ":", "ignore_chars", "=", "\"\"", "for", "ch", "in", "word", ":", "if", "ch", "not", "in", "ignore_chars", "...
Check if all character is Thai เป็นคำที่มีแต่อักษรไทยหรือไม่ :param str word: input text :param str ignore_chars: characters to be ignored (i.e. will be considered as Thai) :return: True or False
[ "Check", "if", "all", "character", "is", "Thai", "เป็นคำที่มีแต่อักษรไทยหรือไม่" ]
python
train
KujiraProject/Flask-PAM
flask_pam/auth.py
https://github.com/KujiraProject/Flask-PAM/blob/d84f90ffd706c0f491af3539cd438e13771ada7e/flask_pam/auth.py#L179-L204
def group_required(self, group): """Decorator which checks if user is in group Decorator for Flask's view which blocks requests from not authenticated users or if user is not member of specified group :param group: group's name """ def decorator(view): @fun...
[ "def", "group_required", "(", "self", ",", "group", ")", ":", "def", "decorator", "(", "view", ")", ":", "@", "functools", ".", "wraps", "(", "view", ")", "def", "decorated", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "log", ".", "info", ...
Decorator which checks if user is in group Decorator for Flask's view which blocks requests from not authenticated users or if user is not member of specified group :param group: group's name
[ "Decorator", "which", "checks", "if", "user", "is", "in", "group" ]
python
train
log2timeline/dfvfs
dfvfs/credentials/manager.py
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/credentials/manager.py#L22-L37
def DeregisterCredentials(cls, credentials): """Deregisters a path specification credentials. Args: credentials (Credentials): credentials. Raises: KeyError: if credential object is not set for the corresponding type indicator. """ if credentials.type_indicator not in cls._cr...
[ "def", "DeregisterCredentials", "(", "cls", ",", "credentials", ")", ":", "if", "credentials", ".", "type_indicator", "not", "in", "cls", ".", "_credentials", ":", "raise", "KeyError", "(", "'Credential object not set for type indicator: {0:s}.'", ".", "format", "(", ...
Deregisters a path specification credentials. Args: credentials (Credentials): credentials. Raises: KeyError: if credential object is not set for the corresponding type indicator.
[ "Deregisters", "a", "path", "specification", "credentials", "." ]
python
train
fopina/tgbotplug
tgbot/botapi.py
https://github.com/fopina/tgbotplug/blob/c115733b03f2e23ddcdecfce588d1a6a1e5bde91/tgbot/botapi.py#L1304-L1330
def forward_message(chat_id, from_chat_id, message_id, **kwargs): """ Use this method to forward messages of any kind. :param chat_id: Unique identifier for the message recipient — User or GroupChat id :param from_chat_id: Unique identifier for the chat where the original message wa...
[ "def", "forward_message", "(", "chat_id", ",", "from_chat_id", ",", "message_id", ",", "*", "*", "kwargs", ")", ":", "# required args", "params", "=", "dict", "(", "chat_id", "=", "chat_id", ",", "from_chat_id", "=", "from_chat_id", ",", "message_id", "=", "...
Use this method to forward messages of any kind. :param chat_id: Unique identifier for the message recipient — User or GroupChat id :param from_chat_id: Unique identifier for the chat where the original message was sent — User or GroupChat id :param message_id: Unique message ident...
[ "Use", "this", "method", "to", "forward", "messages", "of", "any", "kind", "." ]
python
train
scidash/sciunit
sciunit/utils.py
https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/utils.py#L71-L78
def printd(*args, **kwargs): """Print if PRINT_DEBUG_STATE is True""" global settings if settings['PRINT_DEBUG_STATE']: print(*args, **kwargs) return True return False
[ "def", "printd", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "global", "settings", "if", "settings", "[", "'PRINT_DEBUG_STATE'", "]", ":", "print", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "True", "return", "False" ]
Print if PRINT_DEBUG_STATE is True
[ "Print", "if", "PRINT_DEBUG_STATE", "is", "True" ]
python
train
allenai/allennlp
allennlp/modules/similarity_functions/similarity_function.py
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/similarity_functions/similarity_function.py#L23-L30
def forward(self, tensor_1: torch.Tensor, tensor_2: torch.Tensor) -> torch.Tensor: # pylint: disable=arguments-differ """ Takes two tensors of the same shape, such as ``(batch_size, length_1, length_2, embedding_dim)``. Computes a (possibly parameterized) similarity on the final dimensi...
[ "def", "forward", "(", "self", ",", "tensor_1", ":", "torch", ".", "Tensor", ",", "tensor_2", ":", "torch", ".", "Tensor", ")", "->", "torch", ".", "Tensor", ":", "# pylint: disable=arguments-differ", "raise", "NotImplementedError" ]
Takes two tensors of the same shape, such as ``(batch_size, length_1, length_2, embedding_dim)``. Computes a (possibly parameterized) similarity on the final dimension and returns a tensor with one less dimension, such as ``(batch_size, length_1, length_2)``.
[ "Takes", "two", "tensors", "of", "the", "same", "shape", "such", "as", "(", "batch_size", "length_1", "length_2", "embedding_dim", ")", ".", "Computes", "a", "(", "possibly", "parameterized", ")", "similarity", "on", "the", "final", "dimension", "and", "return...
python
train
SavinaRoja/OpenAccess_EPUB
src/openaccess_epub/utils/images.py
https://github.com/SavinaRoja/OpenAccess_EPUB/blob/6b77ba30b7394fd003920e7a7957bca963a90656/src/openaccess_epub/utils/images.py#L76-L85
def image_cache(article_cache, img_dir): """ The method to be used by get_images() for copying images out of the cache. """ log.debug('Looking for image directory in the cache') if os.path.isdir(article_cache): log.info('Cached image directory found: {0}'.format(article_cache)) shuti...
[ "def", "image_cache", "(", "article_cache", ",", "img_dir", ")", ":", "log", ".", "debug", "(", "'Looking for image directory in the cache'", ")", "if", "os", ".", "path", ".", "isdir", "(", "article_cache", ")", ":", "log", ".", "info", "(", "'Cached image di...
The method to be used by get_images() for copying images out of the cache.
[ "The", "method", "to", "be", "used", "by", "get_images", "()", "for", "copying", "images", "out", "of", "the", "cache", "." ]
python
train
alaudet/hcsr04sensor
hcsr04sensor/sensor.py
https://github.com/alaudet/hcsr04sensor/blob/74caf5c825e3f700c9daa9985542c061ae04b002/hcsr04sensor/sensor.py#L36-L100
def raw_distance(self, sample_size=11, sample_wait=0.1): '''Return an error corrected unrounded distance, in cm, of an object adjusted for temperature in Celcius. The distance calculated is the median value of a sample of `sample_size` readings. Speed of readings is a result ...
[ "def", "raw_distance", "(", "self", ",", "sample_size", "=", "11", ",", "sample_wait", "=", "0.1", ")", ":", "if", "self", ".", "unit", "==", "'imperial'", ":", "self", ".", "temperature", "=", "(", "self", ".", "temperature", "-", "32", ")", "*", "0...
Return an error corrected unrounded distance, in cm, of an object adjusted for temperature in Celcius. The distance calculated is the median value of a sample of `sample_size` readings. Speed of readings is a result of two variables. The sample_size per reading and the sampl...
[ "Return", "an", "error", "corrected", "unrounded", "distance", "in", "cm", "of", "an", "object", "adjusted", "for", "temperature", "in", "Celcius", ".", "The", "distance", "calculated", "is", "the", "median", "value", "of", "a", "sample", "of", "sample_size", ...
python
train
StackStorm/pybind
pybind/slxos/v17s_1_02/brocade_mpls_rpc/__init__.py
https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17s_1_02/brocade_mpls_rpc/__init__.py#L2736-L2757
def _set_clear_mpls_ldp_neighbor(self, v, load=False): """ Setter method for clear_mpls_ldp_neighbor, mapped from YANG variable /brocade_mpls_rpc/clear_mpls_ldp_neighbor (rpc) If this variable is read-only (config: false) in the source YANG file, then _set_clear_mpls_ldp_neighbor is considered as a priv...
[ "def", "_set_clear_mpls_ldp_neighbor", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ...
Setter method for clear_mpls_ldp_neighbor, mapped from YANG variable /brocade_mpls_rpc/clear_mpls_ldp_neighbor (rpc) If this variable is read-only (config: false) in the source YANG file, then _set_clear_mpls_ldp_neighbor is considered as a private method. Backends looking to populate this variable should ...
[ "Setter", "method", "for", "clear_mpls_ldp_neighbor", "mapped", "from", "YANG", "variable", "/", "brocade_mpls_rpc", "/", "clear_mpls_ldp_neighbor", "(", "rpc", ")", "If", "this", "variable", "is", "read", "-", "only", "(", "config", ":", "false", ")", "in", "...
python
train
gwastro/pycbc-glue
pycbc_glue/datafind.py
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/datafind.py#L236-L278
def find_frame(self, framefile, urltype=None, on_missing="warn"): """Query the LDR host for a single framefile @returns: L{Cache<pycbc_glue.lal.Cache>} @param frametype: name of frametype to match @param urltype: file scheme to search for (e.g. 'file') @...
[ "def", "find_frame", "(", "self", ",", "framefile", ",", "urltype", "=", "None", ",", "on_missing", "=", "\"warn\"", ")", ":", "if", "on_missing", "not", "in", "(", "\"warn\"", ",", "\"error\"", ",", "\"ignore\"", ")", ":", "raise", "ValueError", "(", "\...
Query the LDR host for a single framefile @returns: L{Cache<pycbc_glue.lal.Cache>} @param frametype: name of frametype to match @param urltype: file scheme to search for (e.g. 'file') @param on_missing: what to do when the requested frame isn't found...
[ "Query", "the", "LDR", "host", "for", "a", "single", "framefile" ]
python
train
jreese/aiosqlite
aiosqlite/core.py
https://github.com/jreese/aiosqlite/blob/3f548b568b8db9a57022b6e2c9627f5cdefb983f/aiosqlite/core.py#L198-L202
async def close(self) -> None: """Complete queued queries/cursors and close the connection.""" await self._execute(self._conn.close) self._running = False self._connection = None
[ "async", "def", "close", "(", "self", ")", "->", "None", ":", "await", "self", ".", "_execute", "(", "self", ".", "_conn", ".", "close", ")", "self", ".", "_running", "=", "False", "self", ".", "_connection", "=", "None" ]
Complete queued queries/cursors and close the connection.
[ "Complete", "queued", "queries", "/", "cursors", "and", "close", "the", "connection", "." ]
python
train
assemblerflow/flowcraft
flowcraft/generator/recipe.py
https://github.com/assemblerflow/flowcraft/blob/fc3f4bddded1efc76006600016dc71a06dd908c0/flowcraft/generator/recipe.py#L237-L348
def define_pipeline_string(self, process_descriptions, tasks, check_upstream, check_downstream, count_forks, total_tasks, forks): """Builds the possible forks and connections between the provided processes ...
[ "def", "define_pipeline_string", "(", "self", ",", "process_descriptions", ",", "tasks", ",", "check_upstream", ",", "check_downstream", ",", "count_forks", ",", "total_tasks", ",", "forks", ")", ":", "tasks_array", "=", "tasks", ".", "split", "(", ")", "for", ...
Builds the possible forks and connections between the provided processes This method loops through all the provided tasks and builds the upstream and downstream pipeline if required. It then returns all possible forks than need to be merged à posteriori` Parameters ----...
[ "Builds", "the", "possible", "forks", "and", "connections", "between", "the", "provided", "processes" ]
python
test
tamasgal/km3pipe
km3pipe/io/aanet.py
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/io/aanet.py#L718-L741
def _record_app_data(self, data): """Parse raw metadata output for a single application The usual output is: ApplicationName RevisionNumber ApplicationName ROOT_Version ApplicationName KM3NET ApplicationName ./command/line --arguments --which --can contain ...
[ "def", "_record_app_data", "(", "self", ",", "data", ")", ":", "name", ",", "revision", "=", "data", "[", "0", "]", ".", "split", "(", ")", "root_version", "=", "data", "[", "1", "]", ".", "split", "(", ")", "[", "1", "]", "command", "=", "b'\\n'...
Parse raw metadata output for a single application The usual output is: ApplicationName RevisionNumber ApplicationName ROOT_Version ApplicationName KM3NET ApplicationName ./command/line --arguments --which --can contain also multiple lines and --a...
[ "Parse", "raw", "metadata", "output", "for", "a", "single", "application" ]
python
train
CEA-COSMIC/ModOpt
modopt/opt/gradient.py
https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/opt/gradient.py#L222-L241
def _get_grad_method(self, data): r"""Get the gradient This method calculates the gradient step from the input data Parameters ---------- data : np.ndarray Input data array Notes ----- Implements the following equation: .. math:: ...
[ "def", "_get_grad_method", "(", "self", ",", "data", ")", ":", "self", ".", "grad", "=", "self", ".", "trans_op", "(", "self", ".", "op", "(", "data", ")", "-", "self", ".", "obs_data", ")" ]
r"""Get the gradient This method calculates the gradient step from the input data Parameters ---------- data : np.ndarray Input data array Notes ----- Implements the following equation: .. math:: \nabla F(x) = \mathbf{H}^T(\math...
[ "r", "Get", "the", "gradient" ]
python
train
ClimateImpactLab/DataFS
datafs/core/data_file.py
https://github.com/ClimateImpactLab/DataFS/blob/0d32c2b4e18d300a11b748a552f6adbc3dd8f59d/datafs/core/data_file.py#L247-L327
def get_local_path( authority, cache, update, version_check, hasher, read_path, write_path=None, cache_on_write=False): ''' Context manager for retrieving a system path for I/O and updating on change Parameters ---------- authority : ...
[ "def", "get_local_path", "(", "authority", ",", "cache", ",", "update", ",", "version_check", ",", "hasher", ",", "read_path", ",", "write_path", "=", "None", ",", "cache_on_write", "=", "False", ")", ":", "if", "write_path", "is", "None", ":", "write_path",...
Context manager for retrieving a system path for I/O and updating on change Parameters ---------- authority : object :py:mod:`pyFilesystem` filesystem object to use as the authoritative, up-to-date source for the archive cache : object :py:mod:`pyFilesystem` filesystem objec...
[ "Context", "manager", "for", "retrieving", "a", "system", "path", "for", "I", "/", "O", "and", "updating", "on", "change" ]
python
train
Fantomas42/django-blog-zinnia
zinnia/feeds.py
https://github.com/Fantomas42/django-blog-zinnia/blob/b4949304b104a8e1a7a7a0773cbfd024313c3a15/zinnia/feeds.py#L428-L435
def get_object(self, request, year, month, day, slug): """ Retrieve the discussions by entry's slug. """ return get_object_or_404(Entry, slug=slug, publication_date__year=year, publication_date__month=month, ...
[ "def", "get_object", "(", "self", ",", "request", ",", "year", ",", "month", ",", "day", ",", "slug", ")", ":", "return", "get_object_or_404", "(", "Entry", ",", "slug", "=", "slug", ",", "publication_date__year", "=", "year", ",", "publication_date__month",...
Retrieve the discussions by entry's slug.
[ "Retrieve", "the", "discussions", "by", "entry", "s", "slug", "." ]
python
train
inasafe/inasafe
safe/plugin.py
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/plugin.py#L989-L1044
def layer_changed(self, layer): """Enable or disable keywords editor icon when active layer changes. :param layer: The layer that is now active. :type layer: QgsMapLayer """ if not layer: enable_keyword_wizard = False elif not hasattr(layer, 'providerType'): ...
[ "def", "layer_changed", "(", "self", ",", "layer", ")", ":", "if", "not", "layer", ":", "enable_keyword_wizard", "=", "False", "elif", "not", "hasattr", "(", "layer", ",", "'providerType'", ")", ":", "enable_keyword_wizard", "=", "False", "elif", "layer", "....
Enable or disable keywords editor icon when active layer changes. :param layer: The layer that is now active. :type layer: QgsMapLayer
[ "Enable", "or", "disable", "keywords", "editor", "icon", "when", "active", "layer", "changes", "." ]
python
train
bcbio/bcbio-nextgen
scripts/utils/hla_loh_comparison.py
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/scripts/utils/hla_loh_comparison.py#L247-L257
def prep_bam_inputs(out_dir, sample, call_file, bam_file): """Prepare expected input BAM files from pre-aligned. """ base = utils.splitext_plus(os.path.basename(bam_file))[0] with open(call_file) as in_handle: for cur_hla in (x.strip() for x in in_handle): out_file = os.path.join(uti...
[ "def", "prep_bam_inputs", "(", "out_dir", ",", "sample", ",", "call_file", ",", "bam_file", ")", ":", "base", "=", "utils", ".", "splitext_plus", "(", "os", ".", "path", ".", "basename", "(", "bam_file", ")", ")", "[", "0", "]", "with", "open", "(", ...
Prepare expected input BAM files from pre-aligned.
[ "Prepare", "expected", "input", "BAM", "files", "from", "pre", "-", "aligned", "." ]
python
train
morse-talk/morse-talk
morse_talk/utils.py
https://github.com/morse-talk/morse-talk/blob/71e09ace0aa554d28cada5ee658e43758305b8fa/morse_talk/utils.py#L357-L368
def _spoken_representation(message): """ Returns 2 lines of spoken representation of a message like: M O R S E C O D E (space) -- --- .-. ... . (space) -.-. --- -.. . """ lst_lst_char = _split_message(message) s = _spoken_representation_L1(lst_lst_char) ...
[ "def", "_spoken_representation", "(", "message", ")", ":", "lst_lst_char", "=", "_split_message", "(", "message", ")", "s", "=", "_spoken_representation_L1", "(", "lst_lst_char", ")", "s", "+=", "'\\n'", "+", "_spoken_representation_L2", "(", "lst_lst_char", ")", ...
Returns 2 lines of spoken representation of a message like: M O R S E C O D E (space) -- --- .-. ... . (space) -.-. --- -.. .
[ "Returns", "2", "lines", "of", "spoken", "representation", "of", "a", "message", "like", ":" ]
python
train
larryng/narwal
narwal/things.py
https://github.com/larryng/narwal/blob/58c409a475c8ed865579a61d7010162ed8cef597/narwal/things.py#L489-L496
def flair(self, name, text, css_class): """Sets flair for `user` in this subreddit (POST). Calls :meth:`narwal.Reddit.flairlist`. :param name: name of the user :param text: flair text to assign :param css_class: CSS class to assign to flair text """ return self....
[ "def", "flair", "(", "self", ",", "name", ",", "text", ",", "css_class", ")", ":", "return", "self", ".", "_reddit", ".", "flair", "(", "self", ".", "display_name", ",", "name", ",", "text", ",", "css_class", ")" ]
Sets flair for `user` in this subreddit (POST). Calls :meth:`narwal.Reddit.flairlist`. :param name: name of the user :param text: flair text to assign :param css_class: CSS class to assign to flair text
[ "Sets", "flair", "for", "user", "in", "this", "subreddit", "(", "POST", ")", ".", "Calls", ":", "meth", ":", "narwal", ".", "Reddit", ".", "flairlist", ".", ":", "param", "name", ":", "name", "of", "the", "user", ":", "param", "text", ":", "flair", ...
python
train
Rapptz/discord.py
discord/channel.py
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/channel.py#L406-L443
async def create_webhook(self, *, name, avatar=None, reason=None): """|coro| Creates a webhook for this channel. Requires :attr:`~.Permissions.manage_webhooks` permissions. .. versionchanged:: 1.1.0 Added the ``reason`` keyword-only parameter. Parameters -...
[ "async", "def", "create_webhook", "(", "self", ",", "*", ",", "name", ",", "avatar", "=", "None", ",", "reason", "=", "None", ")", ":", "if", "avatar", "is", "not", "None", ":", "avatar", "=", "utils", ".", "_bytes_to_base64_data", "(", "avatar", ")", ...
|coro| Creates a webhook for this channel. Requires :attr:`~.Permissions.manage_webhooks` permissions. .. versionchanged:: 1.1.0 Added the ``reason`` keyword-only parameter. Parameters ------------- name: :class:`str` The webhook's name. ...
[ "|coro|" ]
python
train
saltstack/salt
salt/log/setup.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/log/setup.py#L1172-L1197
def __remove_temp_logging_handler(): ''' This function will run once logging has been configured. It just removes the temporary stream Handler from the logging handlers. ''' if is_logging_configured(): # In this case, the temporary logging handler has been removed, return! return ...
[ "def", "__remove_temp_logging_handler", "(", ")", ":", "if", "is_logging_configured", "(", ")", ":", "# In this case, the temporary logging handler has been removed, return!", "return", "# This should already be done, but...", "__remove_null_logging_handler", "(", ")", "root_logger",...
This function will run once logging has been configured. It just removes the temporary stream Handler from the logging handlers.
[ "This", "function", "will", "run", "once", "logging", "has", "been", "configured", ".", "It", "just", "removes", "the", "temporary", "stream", "Handler", "from", "the", "logging", "handlers", "." ]
python
train
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/jwt.py
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/jwt.py#L284-L367
def unpack(self, token): """ Unpack a received signed or signed and encrypted Json Web Token :param token: The Json Web Token :return: If decryption and signature verification work the payload will be returned as a Message instance if possible. """ if not tok...
[ "def", "unpack", "(", "self", ",", "token", ")", ":", "if", "not", "token", ":", "raise", "KeyError", "_jwe_header", "=", "_jws_header", "=", "None", "# Check if it's an encrypted JWT", "darg", "=", "{", "}", "if", "self", ".", "allowed_enc_encs", ":", "darg...
Unpack a received signed or signed and encrypted Json Web Token :param token: The Json Web Token :return: If decryption and signature verification work the payload will be returned as a Message instance if possible.
[ "Unpack", "a", "received", "signed", "or", "signed", "and", "encrypted", "Json", "Web", "Token" ]
python
train
buildbot/buildbot
master/buildbot/util/__init__.py
https://github.com/buildbot/buildbot/blob/5df3cfae6d760557d99156633c32b1822a1e130c/master/buildbot/util/__init__.py#L454-L463
def dictionary_merge(a, b): """merges dictionary b into a Like dict.update, but recursive """ for key, value in b.items(): if key in a and isinstance(a[key], dict) and isinstance(value, dict): dictionary_merge(a[key], b[key]) continue a[key] = b[key] return...
[ "def", "dictionary_merge", "(", "a", ",", "b", ")", ":", "for", "key", ",", "value", "in", "b", ".", "items", "(", ")", ":", "if", "key", "in", "a", "and", "isinstance", "(", "a", "[", "key", "]", ",", "dict", ")", "and", "isinstance", "(", "va...
merges dictionary b into a Like dict.update, but recursive
[ "merges", "dictionary", "b", "into", "a", "Like", "dict", ".", "update", "but", "recursive" ]
python
train
roboogle/gtkmvc3
gtkmvco/gtkmvc3/support/decorators.py
https://github.com/roboogle/gtkmvc3/blob/63405fd8d2056be26af49103b13a8d5e57fe4dff/gtkmvco/gtkmvc3/support/decorators.py#L33-L47
def good_decorator(decorator): """This decorator makes decorators behave well wrt to decorated functions names, doc, etc.""" def new_decorator(f): g = decorator(f) g.__name__ = f.__name__ g.__doc__ = f.__doc__ g.__dict__.update(f.__dict__) return g new_d...
[ "def", "good_decorator", "(", "decorator", ")", ":", "def", "new_decorator", "(", "f", ")", ":", "g", "=", "decorator", "(", "f", ")", "g", ".", "__name__", "=", "f", ".", "__name__", "g", ".", "__doc__", "=", "f", ".", "__doc__", "g", ".", "__dict...
This decorator makes decorators behave well wrt to decorated functions names, doc, etc.
[ "This", "decorator", "makes", "decorators", "behave", "well", "wrt", "to", "decorated", "functions", "names", "doc", "etc", "." ]
python
train
materialsproject/pymatgen
pymatgen/io/lmto.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/lmto.py#L103-L152
def as_dict(self): """ Returns the CTRL as a dictionary. "SITE" and "CLASS" are of the form {'CATEGORY': {'TOKEN': value}}, the rest is of the form 'TOKEN'/'CATEGORY': value. It gets the conventional standard structure because primitive cells use the conventional a-lattic...
[ "def", "as_dict", "(", "self", ")", ":", "ctrl_dict", "=", "{", "\"@module\"", ":", "self", ".", "__class__", ".", "__module__", ",", "\"@class\"", ":", "self", ".", "__class__", ".", "__name__", "}", "if", "self", ".", "header", "is", "not", "None", "...
Returns the CTRL as a dictionary. "SITE" and "CLASS" are of the form {'CATEGORY': {'TOKEN': value}}, the rest is of the form 'TOKEN'/'CATEGORY': value. It gets the conventional standard structure because primitive cells use the conventional a-lattice parameter as the scaling factor and n...
[ "Returns", "the", "CTRL", "as", "a", "dictionary", ".", "SITE", "and", "CLASS", "are", "of", "the", "form", "{", "CATEGORY", ":", "{", "TOKEN", ":", "value", "}}", "the", "rest", "is", "of", "the", "form", "TOKEN", "/", "CATEGORY", ":", "value", ".",...
python
train
markovmodel/msmtools
msmtools/analysis/sparse/assessment.py
https://github.com/markovmodel/msmtools/blob/54dc76dd2113a0e8f3d15d5316abab41402941be/msmtools/analysis/sparse/assessment.py#L138-L160
def is_connected(T, directed=True): r"""Check connectivity of the transition matrix. Return true, if the input matrix is completely connected, effectively checking if the number of connected components equals one. Parameters ---------- T : scipy.sparse matrix Transition matrix dire...
[ "def", "is_connected", "(", "T", ",", "directed", "=", "True", ")", ":", "nc", "=", "connected_components", "(", "T", ",", "directed", "=", "directed", ",", "connection", "=", "'strong'", ",", "return_labels", "=", "False", ")", "return", "nc", "==", "1"...
r"""Check connectivity of the transition matrix. Return true, if the input matrix is completely connected, effectively checking if the number of connected components equals one. Parameters ---------- T : scipy.sparse matrix Transition matrix directed : bool, optional Whether to ...
[ "r", "Check", "connectivity", "of", "the", "transition", "matrix", "." ]
python
train
clinicedc/edc-notification
edc_notification/mailing_list_manager.py
https://github.com/clinicedc/edc-notification/blob/79e43a44261e37566c63a8780d80b0d8ece89cc9/edc_notification/mailing_list_manager.py#L73-L97
def subscribe(self, user, verbose=None): """Returns a response after attempting to subscribe a member to the list. """ if not self.email_enabled: raise EmailNotEnabledError("See settings.EMAIL_ENABLED") if not user.email: raise UserEmailError(f"User {user}...
[ "def", "subscribe", "(", "self", ",", "user", ",", "verbose", "=", "None", ")", ":", "if", "not", "self", ".", "email_enabled", ":", "raise", "EmailNotEnabledError", "(", "\"See settings.EMAIL_ENABLED\"", ")", "if", "not", "user", ".", "email", ":", "raise",...
Returns a response after attempting to subscribe a member to the list.
[ "Returns", "a", "response", "after", "attempting", "to", "subscribe", "a", "member", "to", "the", "list", "." ]
python
train
outini/python-pylls
pylls/cachet.py
https://github.com/outini/python-pylls/blob/f9fa220594bc1974469097d9bad690a42d0d0f0f/pylls/cachet.py#L479-L493
def create(self, email, verify=None, components=None): """Create a new subscriber :param str email: Email address to subscribe :param bool verify: Whether to send verification email :param list components: Components ID list, defaults to all :return: Created subscriber data (:cl...
[ "def", "create", "(", "self", ",", "email", ",", "verify", "=", "None", ",", "components", "=", "None", ")", ":", "data", "=", "ApiParams", "(", ")", "data", "[", "'email'", "]", "=", "email", "data", "[", "'verify'", "]", "=", "verify", "data", "[...
Create a new subscriber :param str email: Email address to subscribe :param bool verify: Whether to send verification email :param list components: Components ID list, defaults to all :return: Created subscriber data (:class:`dict`) .. seealso:: https://docs.cachethq.io/referen...
[ "Create", "a", "new", "subscriber" ]
python
train
sosreport/sos
sos/sosreport.py
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/sosreport.py#L988-L1003
def _collect_plugin(self, plugin): '''Wraps the collect_plugin() method so we can apply a timeout against the plugin as a whole''' with ThreadPoolExecutor(1) as pool: try: t = pool.submit(self.collect_plugin, plugin) # Re-type int 0 to NoneType, as oth...
[ "def", "_collect_plugin", "(", "self", ",", "plugin", ")", ":", "with", "ThreadPoolExecutor", "(", "1", ")", "as", "pool", ":", "try", ":", "t", "=", "pool", ".", "submit", "(", "self", ".", "collect_plugin", ",", "plugin", ")", "# Re-type int 0 to NoneTyp...
Wraps the collect_plugin() method so we can apply a timeout against the plugin as a whole
[ "Wraps", "the", "collect_plugin", "()", "method", "so", "we", "can", "apply", "a", "timeout", "against", "the", "plugin", "as", "a", "whole" ]
python
train
nicolargo/glances
glances/events.py
https://github.com/nicolargo/glances/blob/5bd4d587a736e0d2b03170b56926841d2a3eb7ee/glances/events.py#L102-L123
def add(self, event_state, event_type, event_value, proc_list=None, proc_desc="", peak_time=6): """Add a new item to the logs list. If 'event' is a 'new one', add it at the beginning of the list. If 'event' is not a 'new one', update the list . If event < peak_time then the ...
[ "def", "add", "(", "self", ",", "event_state", ",", "event_type", ",", "event_value", ",", "proc_list", "=", "None", ",", "proc_desc", "=", "\"\"", ",", "peak_time", "=", "6", ")", ":", "proc_list", "=", "proc_list", "or", "glances_processes", ".", "getlis...
Add a new item to the logs list. If 'event' is a 'new one', add it at the beginning of the list. If 'event' is not a 'new one', update the list . If event < peak_time then the alert is not set.
[ "Add", "a", "new", "item", "to", "the", "logs", "list", "." ]
python
train
mitsei/dlkit
dlkit/json_/repository/objects.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/repository/objects.py#L1197-L1209
def clear_published_date(self): """Removes the puiblished date. raise: NoAccess - ``Metadata.isRequired()`` is ``true`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid...
[ "def", "clear_published_date", "(", "self", ")", ":", "# Implemented from template for osid.assessment.AssessmentOfferedForm.clear_start_time_template", "if", "(", "self", ".", "get_published_date_metadata", "(", ")", ".", "is_read_only", "(", ")", "or", "self", ".", "get_p...
Removes the puiblished date. raise: NoAccess - ``Metadata.isRequired()`` is ``true`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.*
[ "Removes", "the", "puiblished", "date", "." ]
python
train
AtomHash/evernode
evernode/classes/translator.py
https://github.com/AtomHash/evernode/blob/b2fb91555fb937a3f3eba41db56dee26f9b034be/evernode/classes/translator.py#L38-L69
def trans(self, key) -> str: """ Root Example: Translator() Translator.trans('messages.hello') resources/lang/en/messages.lang will be opened and parsed for { 'hello': 'Some english text' } If language is fr, resources/lang/fr/messages.lang will be...
[ "def", "trans", "(", "self", ",", "key", ")", "->", "str", ":", "key_list", "=", "self", ".", "__list_key", "(", "key", ")", "try", ":", "current_selection", "=", "current_app", ".", "config", "[", "'LANGUAGE_PACKS'", "]", "[", "self", ".", "module_name"...
Root Example: Translator() Translator.trans('messages.hello') resources/lang/en/messages.lang will be opened and parsed for { 'hello': 'Some english text' } If language is fr, resources/lang/fr/messages.lang will be opened and parsed for { 'hello': 'Some fr...
[ "Root", "Example", ":", "Translator", "()", "Translator", ".", "trans", "(", "messages", ".", "hello", ")", "resources", "/", "lang", "/", "en", "/", "messages", ".", "lang", "will", "be", "opened", "and", "parsed", "for", "{", "hello", ":", "Some", "e...
python
train
iterative/dvc
dvc/command/metrics.py
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/command/metrics.py#L13-L33
def show_metrics(metrics, all_branches=False, all_tags=False): """ Args: metrics (list): Where each element is either a `list` if an xpath was specified, otherwise a `str` """ for branch, val in metrics.items(): if all_branches or all_tags: logger.info("{branch}:"...
[ "def", "show_metrics", "(", "metrics", ",", "all_branches", "=", "False", ",", "all_tags", "=", "False", ")", ":", "for", "branch", ",", "val", "in", "metrics", ".", "items", "(", ")", ":", "if", "all_branches", "or", "all_tags", ":", "logger", ".", "i...
Args: metrics (list): Where each element is either a `list` if an xpath was specified, otherwise a `str`
[ "Args", ":", "metrics", "(", "list", ")", ":", "Where", "each", "element", "is", "either", "a", "list", "if", "an", "xpath", "was", "specified", "otherwise", "a", "str" ]
python
train
YosaiProject/yosai
yosai/core/mgt/mgt.py
https://github.com/YosaiProject/yosai/blob/7f96aa6b837ceae9bf3d7387cd7e35f5ab032575/yosai/core/mgt/mgt.py#L429-L444
def check_permission(self, identifiers, permission_s, logical_operator): """ :type identifiers: SimpleIdentifierCollection :param permission_s: a collection of 1..N permissions :type permission_s: List of Permission objects or Strings :param logical_operator: indicates whether...
[ "def", "check_permission", "(", "self", ",", "identifiers", ",", "permission_s", ",", "logical_operator", ")", ":", "return", "self", ".", "authorizer", ".", "check_permission", "(", "identifiers", ",", "permission_s", ",", "logical_operator", ")" ]
:type identifiers: SimpleIdentifierCollection :param permission_s: a collection of 1..N permissions :type permission_s: List of Permission objects or Strings :param logical_operator: indicates whether all or at least one permission check is true (any) ...
[ ":", "type", "identifiers", ":", "SimpleIdentifierCollection" ]
python
train
flatangle/flatlib
flatlib/dignities/tables.py
https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/dignities/tables.py#L482-L495
def termLons(TERMS): """ Returns a list with the absolute longitude of all terms. """ res = [] for i, sign in enumerate(SIGN_LIST): termList = TERMS[sign] res.extend([ ID, sign, start + 30 * i, ] for (ID, start, end) in termList) ...
[ "def", "termLons", "(", "TERMS", ")", ":", "res", "=", "[", "]", "for", "i", ",", "sign", "in", "enumerate", "(", "SIGN_LIST", ")", ":", "termList", "=", "TERMS", "[", "sign", "]", "res", ".", "extend", "(", "[", "ID", ",", "sign", ",", "start", ...
Returns a list with the absolute longitude of all terms.
[ "Returns", "a", "list", "with", "the", "absolute", "longitude", "of", "all", "terms", "." ]
python
train
brian-rose/climlab
climlab/model/column.py
https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/model/column.py#L119-L141
def do_diagnostics(self): '''Set all the diagnostics from long and shortwave radiation.''' self.OLR = self.subprocess['LW'].flux_to_space self.LW_down_sfc = self.subprocess['LW'].flux_to_sfc self.LW_up_sfc = self.subprocess['LW'].flux_from_sfc self.LW_absorbed_sfc = self.LW_down_...
[ "def", "do_diagnostics", "(", "self", ")", ":", "self", ".", "OLR", "=", "self", ".", "subprocess", "[", "'LW'", "]", ".", "flux_to_space", "self", ".", "LW_down_sfc", "=", "self", ".", "subprocess", "[", "'LW'", "]", ".", "flux_to_sfc", "self", ".", "...
Set all the diagnostics from long and shortwave radiation.
[ "Set", "all", "the", "diagnostics", "from", "long", "and", "shortwave", "radiation", "." ]
python
train
botswana-harvard/edc-registration
edc_registration/model_mixins/registered_subject_model_mixin.py
https://github.com/botswana-harvard/edc-registration/blob/3daca624a496945fd4536488f6f80790bbecc081/edc_registration/model_mixins/registered_subject_model_mixin.py#L186-L193
def update_subject_identifier_on_save(self): """Overridden to not set the subject identifier on save. """ if not self.subject_identifier: self.subject_identifier = self.subject_identifier_as_pk.hex elif re.match(UUID_PATTERN, self.subject_identifier): pass ...
[ "def", "update_subject_identifier_on_save", "(", "self", ")", ":", "if", "not", "self", ".", "subject_identifier", ":", "self", ".", "subject_identifier", "=", "self", ".", "subject_identifier_as_pk", ".", "hex", "elif", "re", ".", "match", "(", "UUID_PATTERN", ...
Overridden to not set the subject identifier on save.
[ "Overridden", "to", "not", "set", "the", "subject", "identifier", "on", "save", "." ]
python
train
mpapi/lazylights
lazylights.py
https://github.com/mpapi/lazylights/blob/536dbd3ce75c28b3545cf66f25fc72589488063f/lazylights.py#L319-L339
def run(self): """ Process all outgoing packets, until `stop()` is called. Intended to run in its own thread. """ while True: to_send = self._queue.get() if to_send is _SHUTDOWN: break # If we get a gateway object, connect to i...
[ "def", "run", "(", "self", ")", ":", "while", "True", ":", "to_send", "=", "self", ".", "_queue", ".", "get", "(", ")", "if", "to_send", "is", "_SHUTDOWN", ":", "break", "# If we get a gateway object, connect to it. Otherwise, assume", "# it's a bytestring and send ...
Process all outgoing packets, until `stop()` is called. Intended to run in its own thread.
[ "Process", "all", "outgoing", "packets", "until", "stop", "()", "is", "called", ".", "Intended", "to", "run", "in", "its", "own", "thread", "." ]
python
train
tensorflow/probability
tensorflow_probability/python/optimizer/differential_evolution.py
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/optimizer/differential_evolution.py#L712-L768
def _get_mixing_indices(size, seed=None, name=None): """Generates an array of indices suitable for mutation operation. The mutation operation in differential evolution requires that for every element of the population, three distinct other elements be chosen to produce a trial candidate. This function generate...
[ "def", "_get_mixing_indices", "(", "size", ",", "seed", "=", "None", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "compat", ".", "v1", ".", "name_scope", "(", "name", ",", "default_name", "=", "'get_mixing_indices'", ",", "values", "=", "[", ...
Generates an array of indices suitable for mutation operation. The mutation operation in differential evolution requires that for every element of the population, three distinct other elements be chosen to produce a trial candidate. This function generates an array of shape [size, 3] satisfying the properties ...
[ "Generates", "an", "array", "of", "indices", "suitable", "for", "mutation", "operation", "." ]
python
test
python-diamond/Diamond
src/collectors/elasticsearch/elasticsearch.py
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/elasticsearch/elasticsearch.py#L107-L135
def _get(self, scheme, host, port, path, assert_key=None): """ Execute a ES API call. Convert response into JSON and optionally assert its structure. """ url = '%s://%s:%i/%s' % (scheme, host, port, path) try: request = urllib2.Request(url) if self...
[ "def", "_get", "(", "self", ",", "scheme", ",", "host", ",", "port", ",", "path", ",", "assert_key", "=", "None", ")", ":", "url", "=", "'%s://%s:%i/%s'", "%", "(", "scheme", ",", "host", ",", "port", ",", "path", ")", "try", ":", "request", "=", ...
Execute a ES API call. Convert response into JSON and optionally assert its structure.
[ "Execute", "a", "ES", "API", "call", ".", "Convert", "response", "into", "JSON", "and", "optionally", "assert", "its", "structure", "." ]
python
train
Netflix-Skunkworks/cloudaux
cloudaux/orchestration/aws/__init__.py
https://github.com/Netflix-Skunkworks/cloudaux/blob/c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea/cloudaux/orchestration/aws/__init__.py#L28-L45
def _get_name_from_structure(item, default): """ Given a possibly sparsely populated item dictionary, try to retrieve the item name. First try the default field. If that doesn't exist, try to parse the from the ARN. :param item: dict containing (at the very least) item_name and/or arn :return: item...
[ "def", "_get_name_from_structure", "(", "item", ",", "default", ")", ":", "if", "item", ".", "get", "(", "default", ")", ":", "return", "item", ".", "get", "(", "default", ")", "if", "item", ".", "get", "(", "'Arn'", ")", ":", "arn", "=", "item", "...
Given a possibly sparsely populated item dictionary, try to retrieve the item name. First try the default field. If that doesn't exist, try to parse the from the ARN. :param item: dict containing (at the very least) item_name and/or arn :return: item name
[ "Given", "a", "possibly", "sparsely", "populated", "item", "dictionary", "try", "to", "retrieve", "the", "item", "name", ".", "First", "try", "the", "default", "field", ".", "If", "that", "doesn", "t", "exist", "try", "to", "parse", "the", "from", "the", ...
python
valid
gwastro/pycbc
pycbc/events/stat.py
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/events/stat.py#L548-L567
def single(self, trigs): """ Calculate the single detector statistic. Parameters ---------- trigs: dict of numpy.ndarrays, h5py group (or similar dict-like object) Dictionary-like object holding single detector trigger information. 'snr', 'cont_chisq', 'cont_chis...
[ "def", "single", "(", "self", ",", "trigs", ")", ":", "chisq_newsnr", "=", "ranking", ".", "get_newsnr", "(", "trigs", ")", "rautochisq", "=", "trigs", "[", "'cont_chisq'", "]", "[", ":", "]", "/", "trigs", "[", "'cont_chisq_dof'", "]", "[", ":", "]", ...
Calculate the single detector statistic. Parameters ---------- trigs: dict of numpy.ndarrays, h5py group (or similar dict-like object) Dictionary-like object holding single detector trigger information. 'snr', 'cont_chisq', 'cont_chisq_dof', 'chisq_dof' and 'chisq' ...
[ "Calculate", "the", "single", "detector", "statistic", "." ]
python
train
kata198/indexedredis
IndexedRedis/__init__.py
https://github.com/kata198/indexedredis/blob/f9c85adcf5218dac25acb06eedc63fc2950816fa/IndexedRedis/__init__.py#L1851-L1913
def getMultipleOnlyFields(self, pks, fields, cascadeFetch=False): ''' getMultipleOnlyFields - Gets only certain fields from a list of primary keys. For working on entire filter set, see allOnlyFields @param pks list<str> - Primary Keys @param fields list<str> - List of fields @param cascadeFetch <boo...
[ "def", "getMultipleOnlyFields", "(", "self", ",", "pks", ",", "fields", ",", "cascadeFetch", "=", "False", ")", ":", "if", "type", "(", "pks", ")", "==", "set", ":", "pks", "=", "list", "(", "pks", ")", "if", "len", "(", "pks", ")", "==", "1", ":...
getMultipleOnlyFields - Gets only certain fields from a list of primary keys. For working on entire filter set, see allOnlyFields @param pks list<str> - Primary Keys @param fields list<str> - List of fields @param cascadeFetch <bool> Default False, If True, all Foreign objects associated with this model ...
[ "getMultipleOnlyFields", "-", "Gets", "only", "certain", "fields", "from", "a", "list", "of", "primary", "keys", ".", "For", "working", "on", "entire", "filter", "set", "see", "allOnlyFields" ]
python
valid
thespacedoctor/sherlock
sherlock/imports/ned_d.py
https://github.com/thespacedoctor/sherlock/blob/2c80fb6fa31b04e7820e6928e3d437a21e692dd3/sherlock/imports/ned_d.py#L325-L361
def _get_metadata_for_galaxies( self): """get metadata for galaxies .. todo :: - update key arguments values and definitions with defaults - update return values and definitions - update usage examples and text - update docstring text ...
[ "def", "_get_metadata_for_galaxies", "(", "self", ")", ":", "self", ".", "log", ".", "debug", "(", "'starting the ``_get_metadata_for_galaxies`` method'", ")", "total", ",", "batches", "=", "self", ".", "_count_galaxies_requiring_metadata", "(", ")", "print", "\"%(tot...
get metadata for galaxies .. todo :: - update key arguments values and definitions with defaults - update return values and definitions - update usage examples and text - update docstring text - check sublime snippet exists - clip any use...
[ "get", "metadata", "for", "galaxies" ]
python
train
raamana/pyradigm
pyradigm/pyradigm.py
https://github.com/raamana/pyradigm/blob/8ffb7958329c88b09417087b86887a3c92f438c2/pyradigm/pyradigm.py#L535-L574
def get_class(self, class_id): """ Returns a smaller dataset belonging to the requested classes. Parameters ---------- class_id : str or list identifier(s) of the class(es) to be returned. Returns ------- MLDataset With subset of ...
[ "def", "get_class", "(", "self", ",", "class_id", ")", ":", "if", "class_id", "in", "[", "None", ",", "''", "]", ":", "raise", "ValueError", "(", "\"class id can not be empty or None.\"", ")", "if", "isinstance", "(", "class_id", ",", "str", ")", ":", "cla...
Returns a smaller dataset belonging to the requested classes. Parameters ---------- class_id : str or list identifier(s) of the class(es) to be returned. Returns ------- MLDataset With subset of samples belonging to the given class(es). ...
[ "Returns", "a", "smaller", "dataset", "belonging", "to", "the", "requested", "classes", "." ]
python
train
pgmpy/pgmpy
pgmpy/models/FactorGraph.py
https://github.com/pgmpy/pgmpy/blob/9381a66aba3c3871d3ccd00672b148d17d63239e/pgmpy/models/FactorGraph.py#L285-L319
def to_markov_model(self): """ Converts the factor graph into markov model. A markov model contains nodes as random variables and edge between two nodes imply interaction between them. Examples -------- >>> from pgmpy.models import FactorGraph >>> from p...
[ "def", "to_markov_model", "(", "self", ")", ":", "mm", "=", "MarkovModel", "(", ")", "variable_nodes", "=", "self", ".", "get_variable_nodes", "(", ")", "if", "len", "(", "set", "(", "self", ".", "nodes", "(", ")", ")", "-", "set", "(", "variable_nodes...
Converts the factor graph into markov model. A markov model contains nodes as random variables and edge between two nodes imply interaction between them. Examples -------- >>> from pgmpy.models import FactorGraph >>> from pgmpy.factors.discrete import DiscreteFactor ...
[ "Converts", "the", "factor", "graph", "into", "markov", "model", "." ]
python
train
ajenhl/tacl
tacl/__main__.py
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/__main__.py#L257-L274
def generate_ngrams_subparser(subparsers): """Adds a sub-command parser to `subparsers` to add n-grams data to the data store.""" parser = subparsers.add_parser( 'ngrams', description=constants.NGRAMS_DESCRIPTION, epilog=constants.NGRAMS_EPILOG, formatter_class=ParagraphFormatter, he...
[ "def", "generate_ngrams_subparser", "(", "subparsers", ")", ":", "parser", "=", "subparsers", ".", "add_parser", "(", "'ngrams'", ",", "description", "=", "constants", ".", "NGRAMS_DESCRIPTION", ",", "epilog", "=", "constants", ".", "NGRAMS_EPILOG", ",", "formatte...
Adds a sub-command parser to `subparsers` to add n-grams data to the data store.
[ "Adds", "a", "sub", "-", "command", "parser", "to", "subparsers", "to", "add", "n", "-", "grams", "data", "to", "the", "data", "store", "." ]
python
train
yfpeng/bioc
bioc/encoder.py
https://github.com/yfpeng/bioc/blob/47ddaa010960d9ba673aefe068e7bbaf39f0fff4/bioc/encoder.py#L28-L32
def encode_annotation(obj): """Encode a single annotation.""" warnings.warn("deprecated. Please use bioc.biocxml.encoder.encode_annotation", DeprecationWarning) return bioc.biocxml.encoder.encode_annotation(obj)
[ "def", "encode_annotation", "(", "obj", ")", ":", "warnings", ".", "warn", "(", "\"deprecated. Please use bioc.biocxml.encoder.encode_annotation\"", ",", "DeprecationWarning", ")", "return", "bioc", ".", "biocxml", ".", "encoder", ".", "encode_annotation", "(", "obj", ...
Encode a single annotation.
[ "Encode", "a", "single", "annotation", "." ]
python
train
pybel/pybel
src/pybel/struct/mutation/induction/annotations.py
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/mutation/induction/annotations.py#L20-L36
def get_subgraph_by_annotations(graph, annotations, or_=None): """Induce a sub-graph given an annotations filter. :param graph: pybel.BELGraph graph: A BEL graph :param dict[str,iter[str]] annotations: Annotation filters (match all with :func:`pybel.utils.subdict_matches`) :param boolean or_: if True a...
[ "def", "get_subgraph_by_annotations", "(", "graph", ",", "annotations", ",", "or_", "=", "None", ")", ":", "edge_filter_builder", "=", "(", "build_annotation_dict_any_filter", "if", "(", "or_", "is", "None", "or", "or_", ")", "else", "build_annotation_dict_all_filte...
Induce a sub-graph given an annotations filter. :param graph: pybel.BELGraph graph: A BEL graph :param dict[str,iter[str]] annotations: Annotation filters (match all with :func:`pybel.utils.subdict_matches`) :param boolean or_: if True any annotation should be present, if False all annotations should be pr...
[ "Induce", "a", "sub", "-", "graph", "given", "an", "annotations", "filter", "." ]
python
train
openergy/oplus
oplus/weather_data/weather_data.py
https://github.com/openergy/oplus/blob/f095868d1990c1d126e906ada6acbab26348b3d3/oplus/weather_data/weather_data.py#L356-L369
def from_epw(cls, buffer_or_path): """ Parameters ---------- buffer_or_path: buffer or path containing epw format. Returns ------- WeatherData instance. """ from .epw_parse import parse_epw _, buffer = to_buffer(buffer_or_path) wit...
[ "def", "from_epw", "(", "cls", ",", "buffer_or_path", ")", ":", "from", ".", "epw_parse", "import", "parse_epw", "_", ",", "buffer", "=", "to_buffer", "(", "buffer_or_path", ")", "with", "buffer", "as", "f", ":", "return", "parse_epw", "(", "f", ")" ]
Parameters ---------- buffer_or_path: buffer or path containing epw format. Returns ------- WeatherData instance.
[ "Parameters", "----------", "buffer_or_path", ":", "buffer", "or", "path", "containing", "epw", "format", "." ]
python
test
h2oai/h2o-3
scripts/logscrapedaily.py
https://github.com/h2oai/h2o-3/blob/dd62aaa1e7f680a8b16ee14bc66b0fb5195c2ad8/scripts/logscrapedaily.py#L178-L208
def find_node_name(each_line,temp_func_list): """ Find the slave machine where a Jenkins job was executed on. It will save this information in g_failed_test_info_dict. In addition, it will delete this particular function handle off the temp_func_list as we do not need to perform this action again....
[ "def", "find_node_name", "(", "each_line", ",", "temp_func_list", ")", ":", "global", "g_node_name", "global", "g_failed_test_info_dict", "if", "g_node_name", "in", "each_line", ":", "temp_strings", "=", "each_line", ".", "split", "(", ")", "[", "start", ",", "f...
Find the slave machine where a Jenkins job was executed on. It will save this information in g_failed_test_info_dict. In addition, it will delete this particular function handle off the temp_func_list as we do not need to perform this action again. Parameters ---------- each_line : str ...
[ "Find", "the", "slave", "machine", "where", "a", "Jenkins", "job", "was", "executed", "on", ".", "It", "will", "save", "this", "information", "in", "g_failed_test_info_dict", ".", "In", "addition", "it", "will", "delete", "this", "particular", "function", "han...
python
test
scanny/python-pptx
pptx/shapes/shapetree.py
https://github.com/scanny/python-pptx/blob/d6ab8234f8b03953d2f831ff9394b1852db34130/pptx/shapes/shapetree.py#L668-L677
def get(self, ph_type, default=None): """ Return the first placeholder shape with type *ph_type* (e.g. 'body'), or *default* if no such placeholder shape is present in the collection. """ for placeholder in self: if placeholder.ph_type == ph_type: ...
[ "def", "get", "(", "self", ",", "ph_type", ",", "default", "=", "None", ")", ":", "for", "placeholder", "in", "self", ":", "if", "placeholder", ".", "ph_type", "==", "ph_type", ":", "return", "placeholder", "return", "default" ]
Return the first placeholder shape with type *ph_type* (e.g. 'body'), or *default* if no such placeholder shape is present in the collection.
[ "Return", "the", "first", "placeholder", "shape", "with", "type", "*", "ph_type", "*", "(", "e", ".", "g", ".", "body", ")", "or", "*", "default", "*", "if", "no", "such", "placeholder", "shape", "is", "present", "in", "the", "collection", "." ]
python
train
coleifer/wtf-peewee
wtfpeewee/orm.py
https://github.com/coleifer/wtf-peewee/blob/f062c59b05ce9ba74467514a272d353f803f37d1/wtfpeewee/orm.py#L224-L251
def model_form(model, base_class=Form, allow_pk=False, only=None, exclude=None, field_args=None, converter=None): """ Create a wtforms Form for a given Peewee model class:: from wtfpeewee.orm import model_form from myproject.myapp.models import User UserForm = model_form(...
[ "def", "model_form", "(", "model", ",", "base_class", "=", "Form", ",", "allow_pk", "=", "False", ",", "only", "=", "None", ",", "exclude", "=", "None", ",", "field_args", "=", "None", ",", "converter", "=", "None", ")", ":", "field_dict", "=", "model_...
Create a wtforms Form for a given Peewee model class:: from wtfpeewee.orm import model_form from myproject.myapp.models import User UserForm = model_form(User) :param model: A Peewee model class :param base_class: Base form class to extend from. Must be a ``wtforms.Form...
[ "Create", "a", "wtforms", "Form", "for", "a", "given", "Peewee", "model", "class", "::" ]
python
train
fprimex/zdesk
zdesk/zdesk_api.py
https://github.com/fprimex/zdesk/blob/851611c13b4d530e9df31390b3ec709baf0a0188/zdesk/zdesk_api.py#L1983-L1987
def help_center_user_segment_show(self, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/help_center/user_segments#show-user-segment" api_path = "/api/v2/help_center/user_segments/{id}.json" api_path = api_path.format(id=id) return self.call(api_path, **kwargs)
[ "def", "help_center_user_segment_show", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "api_path", "=", "\"/api/v2/help_center/user_segments/{id}.json\"", "api_path", "=", "api_path", ".", "format", "(", "id", "=", "id", ")", "return", "self", ".", ...
https://developer.zendesk.com/rest_api/docs/help_center/user_segments#show-user-segment
[ "https", ":", "//", "developer", ".", "zendesk", ".", "com", "/", "rest_api", "/", "docs", "/", "help_center", "/", "user_segments#show", "-", "user", "-", "segment" ]
python
train
farshidce/touchworks-python
touchworks/api/http.py
https://github.com/farshidce/touchworks-python/blob/ea8f93a0f4273de1317a318e945a571f5038ba62/touchworks/api/http.py#L178-L195
def _http_request(self, api, data, headers=None): """ internal method for handling request and response and raising an exception is http return status code is not success :rtype : response object from requests.post() """ if not headers: headers = {'Content-Ty...
[ "def", "_http_request", "(", "self", ",", "api", ",", "data", ",", "headers", "=", "None", ")", ":", "if", "not", "headers", ":", "headers", "=", "{", "'Content-Type'", ":", "'application/json'", "}", "if", "not", "self", ".", "_token_valid", ":", "self"...
internal method for handling request and response and raising an exception is http return status code is not success :rtype : response object from requests.post()
[ "internal", "method", "for", "handling", "request", "and", "response", "and", "raising", "an", "exception", "is", "http", "return", "status", "code", "is", "not", "success" ]
python
train
guma44/GEOparse
GEOparse/GEOparse.py
https://github.com/guma44/GEOparse/blob/7ee8d5b8678d780382a6bf884afa69d2033f5ca0/GEOparse/GEOparse.py#L31-L95
def get_GEO(geo=None, filepath=None, destdir="./", how='full', annotate_gpl=False, geotype=None, include_data=False, silent=False, aspera=False, partial=None): """Get the GEO entry. The GEO entry is taken directly from the GEO database or read it from SOFT file. Args: g...
[ "def", "get_GEO", "(", "geo", "=", "None", ",", "filepath", "=", "None", ",", "destdir", "=", "\"./\"", ",", "how", "=", "'full'", ",", "annotate_gpl", "=", "False", ",", "geotype", "=", "None", ",", "include_data", "=", "False", ",", "silent", "=", ...
Get the GEO entry. The GEO entry is taken directly from the GEO database or read it from SOFT file. Args: geo (:obj:`str`): GEO database identifier. filepath (:obj:`str`): Path to local SOFT file. Defaults to None. destdir (:obj:`str`, optional): Directory to download data. Default...
[ "Get", "the", "GEO", "entry", "." ]
python
train
eng-tools/sfsimodels
sfsimodels/models/soils.py
https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/models/soils.py#L1272-L1312
def discretize_soil_profile(sp, incs=None, target=1.0): """ Splits the soil profile into slices and stores as dictionary :param sp: SoilProfile :param incs: array_like, increments of depth to use for each layer :param target: target depth increment size :return: dict """ if incs is Non...
[ "def", "discretize_soil_profile", "(", "sp", ",", "incs", "=", "None", ",", "target", "=", "1.0", ")", ":", "if", "incs", "is", "None", ":", "incs", "=", "np", ".", "ones", "(", "sp", ".", "n_layers", ")", "*", "target", "dd", "=", "{", "}", "dd"...
Splits the soil profile into slices and stores as dictionary :param sp: SoilProfile :param incs: array_like, increments of depth to use for each layer :param target: target depth increment size :return: dict
[ "Splits", "the", "soil", "profile", "into", "slices", "and", "stores", "as", "dictionary" ]
python
train
uri-templates/uritemplate-py
uritemplate/__init__.py
https://github.com/uri-templates/uritemplate-py/blob/8e13d804ac8641f3b5948eb208c75465ad649da1/uritemplate/__init__.py#L192-L265
def expand(template, variables): """ Expand template as a URI Template using variables. """ def _sub(match): expression = match.group(1) operator = "" if expression[0] in OPERATOR: operator = expression[0] varlist = expression[1:] else: ...
[ "def", "expand", "(", "template", ",", "variables", ")", ":", "def", "_sub", "(", "match", ")", ":", "expression", "=", "match", ".", "group", "(", "1", ")", "operator", "=", "\"\"", "if", "expression", "[", "0", "]", "in", "OPERATOR", ":", "operator...
Expand template as a URI Template using variables.
[ "Expand", "template", "as", "a", "URI", "Template", "using", "variables", "." ]
python
train
materialsvirtuallab/monty
monty/bisect.py
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/bisect.py#L56-L60
def find_ge(a, x): """Find leftmost item greater than or equal to x.""" i = bs.bisect_left(a, x) if i != len(a): return i raise ValueError
[ "def", "find_ge", "(", "a", ",", "x", ")", ":", "i", "=", "bs", ".", "bisect_left", "(", "a", ",", "x", ")", "if", "i", "!=", "len", "(", "a", ")", ":", "return", "i", "raise", "ValueError" ]
Find leftmost item greater than or equal to x.
[ "Find", "leftmost", "item", "greater", "than", "or", "equal", "to", "x", "." ]
python
train
PetrochukM/PyTorch-NLP
torchnlp/utils.py
https://github.com/PetrochukM/PyTorch-NLP/blob/5f7320da5c8d781df072fab3f7e421c6347e5bfa/torchnlp/utils.py#L43-L59
def sampler_to_iterator(dataset, sampler): """ Given a batch sampler or sampler returns examples instead of indices Args: dataset (torch.utils.data.Dataset): Dataset to sample from. sampler (torch.utils.data.sampler.Sampler): Sampler over the dataset. Returns: generator over datase...
[ "def", "sampler_to_iterator", "(", "dataset", ",", "sampler", ")", ":", "for", "sample", "in", "sampler", ":", "if", "isinstance", "(", "sample", ",", "(", "list", ",", "tuple", ")", ")", ":", "# yield a batch", "yield", "[", "dataset", "[", "i", "]", ...
Given a batch sampler or sampler returns examples instead of indices Args: dataset (torch.utils.data.Dataset): Dataset to sample from. sampler (torch.utils.data.sampler.Sampler): Sampler over the dataset. Returns: generator over dataset examples
[ "Given", "a", "batch", "sampler", "or", "sampler", "returns", "examples", "instead", "of", "indices" ]
python
train
scanny/python-pptx
pptx/chart/xlsx.py
https://github.com/scanny/python-pptx/blob/d6ab8234f8b03953d2f831ff9394b1852db34130/pptx/chart/xlsx.py#L25-L33
def xlsx_blob(self): """ Return the byte stream of an Excel file formatted as chart data for the category chart specified in the chart data object. """ xlsx_file = BytesIO() with self._open_worksheet(xlsx_file) as (workbook, worksheet): self._populate_workshee...
[ "def", "xlsx_blob", "(", "self", ")", ":", "xlsx_file", "=", "BytesIO", "(", ")", "with", "self", ".", "_open_worksheet", "(", "xlsx_file", ")", "as", "(", "workbook", ",", "worksheet", ")", ":", "self", ".", "_populate_worksheet", "(", "workbook", ",", ...
Return the byte stream of an Excel file formatted as chart data for the category chart specified in the chart data object.
[ "Return", "the", "byte", "stream", "of", "an", "Excel", "file", "formatted", "as", "chart", "data", "for", "the", "category", "chart", "specified", "in", "the", "chart", "data", "object", "." ]
python
train
Yelp/kafka-utils
kafka_utils/kafka_cluster_manager/cluster_info/broker.py
https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_cluster_manager/cluster_info/broker.py#L142-L144
def count_partitions(self, topic): """Return count of partitions for given topic.""" return sum(1 for p in topic.partitions if p in self.partitions)
[ "def", "count_partitions", "(", "self", ",", "topic", ")", ":", "return", "sum", "(", "1", "for", "p", "in", "topic", ".", "partitions", "if", "p", "in", "self", ".", "partitions", ")" ]
Return count of partitions for given topic.
[ "Return", "count", "of", "partitions", "for", "given", "topic", "." ]
python
train
smarie/python-valid8
valid8/validation_lib/collections.py
https://github.com/smarie/python-valid8/blob/5e15d1de11602933c5114eb9f73277ad91d97800/valid8/validation_lib/collections.py#L134-L189
def length_between(min_len, max_len, open_left=False, # type: bool open_right=False # type: bool ): """ 'Is length between' validation_function generator. Returns a validation_function to check that `min_len <= len(x) <= max_len (...
[ "def", "length_between", "(", "min_len", ",", "max_len", ",", "open_left", "=", "False", ",", "# type: bool", "open_right", "=", "False", "# type: bool", ")", ":", "if", "open_left", "and", "open_right", ":", "def", "length_between_", "(", "x", ")", ":", "if...
'Is length between' validation_function generator. Returns a validation_function to check that `min_len <= len(x) <= max_len (default)`. `open_right` and `open_left` flags allow to transform each side into strict mode. For example setting `open_left=True` will enforce `min_len < len(x) <= max_len`. :pa...
[ "Is", "length", "between", "validation_function", "generator", ".", "Returns", "a", "validation_function", "to", "check", "that", "min_len", "<", "=", "len", "(", "x", ")", "<", "=", "max_len", "(", "default", ")", ".", "open_right", "and", "open_left", "fla...
python
train
tensorpack/tensorpack
tensorpack/utils/concurrency.py
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/concurrency.py#L152-L174
def ensure_proc_terminate(proc): """ Make sure processes terminate when main process exit. Args: proc (multiprocessing.Process or list) """ if isinstance(proc, list): for p in proc: ensure_proc_terminate(p) return def stop_proc_by_weak_ref(ref): proc...
[ "def", "ensure_proc_terminate", "(", "proc", ")", ":", "if", "isinstance", "(", "proc", ",", "list", ")", ":", "for", "p", "in", "proc", ":", "ensure_proc_terminate", "(", "p", ")", "return", "def", "stop_proc_by_weak_ref", "(", "ref", ")", ":", "proc", ...
Make sure processes terminate when main process exit. Args: proc (multiprocessing.Process or list)
[ "Make", "sure", "processes", "terminate", "when", "main", "process", "exit", "." ]
python
train
Rapptz/discord.py
discord/ext/commands/bot.py
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/bot.py#L584-L621
def load_extension(self, name): """Loads an extension. An extension is a python module that contains commands, cogs, or listeners. An extension must have a global function, ``setup`` defined as the entry point on what to do when the extension is loaded. This entry point...
[ "def", "load_extension", "(", "self", ",", "name", ")", ":", "if", "name", "in", "self", ".", "__extensions", ":", "raise", "errors", ".", "ExtensionAlreadyLoaded", "(", "name", ")", "try", ":", "lib", "=", "importlib", ".", "import_module", "(", "name", ...
Loads an extension. An extension is a python module that contains commands, cogs, or listeners. An extension must have a global function, ``setup`` defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the ``bot``. ...
[ "Loads", "an", "extension", "." ]
python
train
CodyKochmann/graphdb
graphdb/RamGraphDB.py
https://github.com/CodyKochmann/graphdb/blob/8c18830db4beda30204f5fd4450bc96eb39b0feb/graphdb/RamGraphDB.py#L355-L358
def _where(self, filter_fn): ''' use this to filter VLists, simply provide a filter function to filter the current found objects ''' assert callable(filter_fn), 'filter_fn needs to be callable' return VList(i for i in self if filter_fn(i()))
[ "def", "_where", "(", "self", ",", "filter_fn", ")", ":", "assert", "callable", "(", "filter_fn", ")", ",", "'filter_fn needs to be callable'", "return", "VList", "(", "i", "for", "i", "in", "self", "if", "filter_fn", "(", "i", "(", ")", ")", ")" ]
use this to filter VLists, simply provide a filter function to filter the current found objects
[ "use", "this", "to", "filter", "VLists", "simply", "provide", "a", "filter", "function", "to", "filter", "the", "current", "found", "objects" ]
python
train
selenol/selenol-python
selenol_python/connections.py
https://github.com/selenol/selenol-python/blob/53775fdfc95161f4aca350305cb3459e6f2f808d/selenol_python/connections.py#L47-L53
def recv(self): """Receive message from the backend or wait unilt next message.""" try: message = self.ws.recv() return json.loads(message) except websocket._exceptions.WebSocketConnectionClosedException as ex: raise SelenolWebSocketClosedException() from ex
[ "def", "recv", "(", "self", ")", ":", "try", ":", "message", "=", "self", ".", "ws", ".", "recv", "(", ")", "return", "json", ".", "loads", "(", "message", ")", "except", "websocket", ".", "_exceptions", ".", "WebSocketConnectionClosedException", "as", "...
Receive message from the backend or wait unilt next message.
[ "Receive", "message", "from", "the", "backend", "or", "wait", "unilt", "next", "message", "." ]
python
train
yandex/yandex-tank
yandextank/plugins/Autostop/cumulative_criterions.py
https://github.com/yandex/yandex-tank/blob/d71d63b6ab5de8b8a5ea2b728b6ab9ac0b1ba71b/yandextank/plugins/Autostop/cumulative_criterions.py#L205-L211
def get_level_str(self): ''' format level str ''' if self.is_relative: level_str = str(self.level) + "%" else: level_str = self.level return level_str
[ "def", "get_level_str", "(", "self", ")", ":", "if", "self", ".", "is_relative", ":", "level_str", "=", "str", "(", "self", ".", "level", ")", "+", "\"%\"", "else", ":", "level_str", "=", "self", ".", "level", "return", "level_str" ]
format level str
[ "format", "level", "str" ]
python
test
PGower/PyCanvas
pycanvas/apis/assignment_groups.py
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/assignment_groups.py#L160-L180
def edit_assignment_group(self, course_id, assignment_group_id): """ Edit an Assignment Group. Modify an existing Assignment Group. Accepts the same parameters as Assignment Group creation """ path = {} data = {} params = {} # REQUIRED...
[ "def", "edit_assignment_group", "(", "self", ",", "course_id", ",", "assignment_group_id", ")", ":", "path", "=", "{", "}", "data", "=", "{", "}", "params", "=", "{", "}", "# REQUIRED - PATH - course_id\r", "\"\"\"ID\"\"\"", "path", "[", "\"course_id\"", "]", ...
Edit an Assignment Group. Modify an existing Assignment Group. Accepts the same parameters as Assignment Group creation
[ "Edit", "an", "Assignment", "Group", ".", "Modify", "an", "existing", "Assignment", "Group", ".", "Accepts", "the", "same", "parameters", "as", "Assignment", "Group", "creation" ]
python
train
Fizzadar/pyinfra
pyinfra/api/connectors/ssh.py
https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/api/connectors/ssh.py#L150-L219
def connect(state, host, for_fact=None): ''' Connect to a single host. Returns the SSH client if succesful. Stateless by design so can be run in parallel. ''' kwargs = _make_paramiko_kwargs(state, host) logger.debug('Connecting to: {0} ({1})'.format(host.name, kwargs)) # Hostname can be pr...
[ "def", "connect", "(", "state", ",", "host", ",", "for_fact", "=", "None", ")", ":", "kwargs", "=", "_make_paramiko_kwargs", "(", "state", ",", "host", ")", "logger", ".", "debug", "(", "'Connecting to: {0} ({1})'", ".", "format", "(", "host", ".", "name",...
Connect to a single host. Returns the SSH client if succesful. Stateless by design so can be run in parallel.
[ "Connect", "to", "a", "single", "host", ".", "Returns", "the", "SSH", "client", "if", "succesful", ".", "Stateless", "by", "design", "so", "can", "be", "run", "in", "parallel", "." ]
python
train
saltstack/salt
salt/cli/cp.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cli/cp.py#L167-L286
def run_chunked(self): ''' Make the salt client call in the new fasion chunked multi-call way ''' files, empty_dirs = self._list_files() dest = self.opts['dest'] gzip = self.opts['gzip'] tgt = self.opts['tgt'] timeout = self.opts['timeout'] selecte...
[ "def", "run_chunked", "(", "self", ")", ":", "files", ",", "empty_dirs", "=", "self", ".", "_list_files", "(", ")", "dest", "=", "self", ".", "opts", "[", "'dest'", "]", "gzip", "=", "self", ".", "opts", "[", "'gzip'", "]", "tgt", "=", "self", ".",...
Make the salt client call in the new fasion chunked multi-call way
[ "Make", "the", "salt", "client", "call", "in", "the", "new", "fasion", "chunked", "multi", "-", "call", "way" ]
python
train
pavelsof/ipalint
ipalint/read.py
https://github.com/pavelsof/ipalint/blob/763e5979ede6980cbfc746b06fd007b379762eeb/ipalint/read.py#L116-L133
def _open(self, file_path=None): """ Opens the file specified by the given path. Raises ValueError if there is a problem with opening or reading the file. """ if file_path is None: file_path = self.file_path if not os.path.exists(file_path): raise ValueError('Could not find file: {}'.format(file_path...
[ "def", "_open", "(", "self", ",", "file_path", "=", "None", ")", ":", "if", "file_path", "is", "None", ":", "file_path", "=", "self", ".", "file_path", "if", "not", "os", ".", "path", ".", "exists", "(", "file_path", ")", ":", "raise", "ValueError", ...
Opens the file specified by the given path. Raises ValueError if there is a problem with opening or reading the file.
[ "Opens", "the", "file", "specified", "by", "the", "given", "path", ".", "Raises", "ValueError", "if", "there", "is", "a", "problem", "with", "opening", "or", "reading", "the", "file", "." ]
python
train
sosreport/sos
sos/plugins/ovirt.py
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/ovirt.py#L135-L226
def postproc(self): """ Obfuscate sensitive keys. """ self.do_file_sub( "/etc/ovirt-engine/engine-config/engine-config.properties", r"Password.type=(.*)", r"Password.type=********" ) self.do_file_sub( "/etc/rhevm/rhevm-confi...
[ "def", "postproc", "(", "self", ")", ":", "self", ".", "do_file_sub", "(", "\"/etc/ovirt-engine/engine-config/engine-config.properties\"", ",", "r\"Password.type=(.*)\"", ",", "r\"Password.type=********\"", ")", "self", ".", "do_file_sub", "(", "\"/etc/rhevm/rhevm-config/rhev...
Obfuscate sensitive keys.
[ "Obfuscate", "sensitive", "keys", "." ]
python
train
TechnicalBro/simple-python-plugins
simpleplugins/__init__.py
https://github.com/TechnicalBro/simple-python-plugins/blob/971f047c85c634bcbd28f247c8214dcf77a345f9/simpleplugins/__init__.py#L51-L78
def import_module_from_file(full_path_to_module): """ Import a module given the full path/filename of the .py file Python 3.4 """ if inspect.ismodule(full_path_to_module): return full_path_to_module module = None try: # Get module name and path from full path modul...
[ "def", "import_module_from_file", "(", "full_path_to_module", ")", ":", "if", "inspect", ".", "ismodule", "(", "full_path_to_module", ")", ":", "return", "full_path_to_module", "module", "=", "None", "try", ":", "# Get module name and path from full path", "module_dir", ...
Import a module given the full path/filename of the .py file Python 3.4
[ "Import", "a", "module", "given", "the", "full", "path", "/", "filename", "of", "the", ".", "py", "file", "Python", "3", ".", "4" ]
python
train
Equitable/trump
trump/converting/objects.py
https://github.com/Equitable/trump/blob/a2802692bc642fa32096374159eea7ceca2947b4/trump/converting/objects.py#L51-L63
def use_quandl_data(self, authtoken): """ Use quandl data to build conversion table """ dfs = {} st = self.start.strftime("%Y-%m-%d") at = authtoken for pair in self.pairs: symbol = "".join(pair) qsym = "CURRFX/{}".format(symbol) ...
[ "def", "use_quandl_data", "(", "self", ",", "authtoken", ")", ":", "dfs", "=", "{", "}", "st", "=", "self", ".", "start", ".", "strftime", "(", "\"%Y-%m-%d\"", ")", "at", "=", "authtoken", "for", "pair", "in", "self", ".", "pairs", ":", "symbol", "="...
Use quandl data to build conversion table
[ "Use", "quandl", "data", "to", "build", "conversion", "table" ]
python
train
odlgroup/odl
odl/contrib/theano/layer.py
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/contrib/theano/layer.py#L143-L166
def infer_shape(self, node, input_shapes): """Return a list of output shapes based on ``input_shapes``. This method is optional. It allows to compute the shape of the output without having to evaluate. Parameters ---------- node : `theano.gof.graph.Apply` Th...
[ "def", "infer_shape", "(", "self", ",", "node", ",", "input_shapes", ")", ":", "if", "isinstance", "(", "self", ".", "operator", ",", "Functional", ")", ":", "return", "[", "(", ")", "]", "else", ":", "# Need to convert to native to avoid error in Theano from", ...
Return a list of output shapes based on ``input_shapes``. This method is optional. It allows to compute the shape of the output without having to evaluate. Parameters ---------- node : `theano.gof.graph.Apply` The node of this Op in the computation graph. in...
[ "Return", "a", "list", "of", "output", "shapes", "based", "on", "input_shapes", "." ]
python
train
fastavro/fastavro
fastavro/_write_py.py
https://github.com/fastavro/fastavro/blob/bafe826293e19eb93e77bbb0f6adfa059c7884b2/fastavro/_write_py.py#L78-L85
def prepare_uuid(data, schema): """Converts uuid.UUID to string formatted UUID xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx """ if isinstance(data, uuid.UUID): return str(data) else: return data
[ "def", "prepare_uuid", "(", "data", ",", "schema", ")", ":", "if", "isinstance", "(", "data", ",", "uuid", ".", "UUID", ")", ":", "return", "str", "(", "data", ")", "else", ":", "return", "data" ]
Converts uuid.UUID to string formatted UUID xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
[ "Converts", "uuid", ".", "UUID", "to", "string", "formatted", "UUID", "xxxxxxxx", "-", "xxxx", "-", "xxxx", "-", "xxxx", "-", "xxxxxxxxxxxx" ]
python
train
jlesquembre/jlle
jlle/releaser/utils.py
https://github.com/jlesquembre/jlle/blob/3645d8f203708355853ef911f4b887ae4d794826/jlle/releaser/utils.py#L41-L87
def ask(question, default=True, exact=False): """Ask the question in y/n form and return True/False. If you don't want a default 'yes', set default to None (or to False if you want a default 'no'). With exact=True, we want to get a literal 'yes' or 'no', at least when it does not match the default...
[ "def", "ask", "(", "question", ",", "default", "=", "True", ",", "exact", "=", "False", ")", ":", "if", "AUTO_RESPONSE", ":", "if", "default", "is", "None", ":", "msg", "=", "(", "\"The question '%s' requires a manual answer, but \"", "+", "\"we're running in --...
Ask the question in y/n form and return True/False. If you don't want a default 'yes', set default to None (or to False if you want a default 'no'). With exact=True, we want to get a literal 'yes' or 'no', at least when it does not match the default.
[ "Ask", "the", "question", "in", "y", "/", "n", "form", "and", "return", "True", "/", "False", "." ]
python
train
fy0/slim
slim/base/sqlquery.py
https://github.com/fy0/slim/blob/9951a910750888dbe7dd3e98acae9c40efae0689/slim/base/sqlquery.py#L186-L208
def parse_order(text): """ :param text: order=id.desc, xxx.asc :return: [ [<column>, asc|desc|default], [<column2>, asc|desc|default], ] """ orders = [] for i in map(str.strip, text.split(',')): items = i.split('.', 2) ...
[ "def", "parse_order", "(", "text", ")", ":", "orders", "=", "[", "]", "for", "i", "in", "map", "(", "str", ".", "strip", ",", "text", ".", "split", "(", "','", ")", ")", ":", "items", "=", "i", ".", "split", "(", "'.'", ",", "2", ")", "if", ...
:param text: order=id.desc, xxx.asc :return: [ [<column>, asc|desc|default], [<column2>, asc|desc|default], ]
[ ":", "param", "text", ":", "order", "=", "id", ".", "desc", "xxx", ".", "asc", ":", "return", ":", "[", "[", "<column", ">", "asc|desc|default", "]", "[", "<column2", ">", "asc|desc|default", "]", "]" ]
python
valid
rackerlabs/rackspace-python-neutronclient
neutronclient/v2_0/client.py
https://github.com/rackerlabs/rackspace-python-neutronclient/blob/5a5009a8fe078e3aa1d582176669f1b28ab26bef/neutronclient/v2_0/client.py#L1722-L1724
def update_bgp_speaker(self, bgp_speaker_id, body=None): """Update a BGP speaker.""" return self.put(self.bgp_speaker_path % bgp_speaker_id, body=body)
[ "def", "update_bgp_speaker", "(", "self", ",", "bgp_speaker_id", ",", "body", "=", "None", ")", ":", "return", "self", ".", "put", "(", "self", ".", "bgp_speaker_path", "%", "bgp_speaker_id", ",", "body", "=", "body", ")" ]
Update a BGP speaker.
[ "Update", "a", "BGP", "speaker", "." ]
python
train
booktype/python-ooxml
ooxml/parse.py
https://github.com/booktype/python-ooxml/blob/b56990a5bee2e1bc46839cec5161ff3726dc4d87/ooxml/parse.py#L177-L190
def parse_drawing(document, container, elem): """Parse drawing element. We don't do much with drawing element. We can find embeded image but we don't do more than that. """ _blip = elem.xpath('.//a:blip', namespaces=NAMESPACES) if len(_blip) > 0: blip = _blip[0] _rid = blip.attrib...
[ "def", "parse_drawing", "(", "document", ",", "container", ",", "elem", ")", ":", "_blip", "=", "elem", ".", "xpath", "(", "'.//a:blip'", ",", "namespaces", "=", "NAMESPACES", ")", "if", "len", "(", "_blip", ")", ">", "0", ":", "blip", "=", "_blip", ...
Parse drawing element. We don't do much with drawing element. We can find embeded image but we don't do more than that.
[ "Parse", "drawing", "element", "." ]
python
train
Zaeb0s/epoll-socket-server
esockets/socket_server.py
https://github.com/Zaeb0s/epoll-socket-server/blob/0b8c8b3c368f8948777579ea1e89e75ab5899372/esockets/socket_server.py#L130-L144
def _subthread_handle_accepted(self, client): """Gets accepted clients from the queue object and sets up the client socket. The client can then be found in the clients dictionary with the socket object as the key. """ conn, addr = client if self.handle_incoming(conn, add...
[ "def", "_subthread_handle_accepted", "(", "self", ",", "client", ")", ":", "conn", ",", "addr", "=", "client", "if", "self", ".", "handle_incoming", "(", "conn", ",", "addr", ")", ":", "logging", ".", "info", "(", "'Accepted connection from client: {}'", ".", ...
Gets accepted clients from the queue object and sets up the client socket. The client can then be found in the clients dictionary with the socket object as the key.
[ "Gets", "accepted", "clients", "from", "the", "queue", "object", "and", "sets", "up", "the", "client", "socket", ".", "The", "client", "can", "then", "be", "found", "in", "the", "clients", "dictionary", "with", "the", "socket", "object", "as", "the", "key"...
python
train