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
BD2KGenomics/toil-scripts
src/toil_scripts/exome_variant_pipeline/exome_variant_pipeline.py
https://github.com/BD2KGenomics/toil-scripts/blob/f878d863defcdccaabb7fe06f991451b7a198fb7/src/toil_scripts/exome_variant_pipeline/exome_variant_pipeline.py#L85-L96
def index_bams(job, config): """ Convenience job for handling bam indexing to make the workflow declaration cleaner :param JobFunctionWrappingJob job: passed automatically by Toil :param Namespace config: Argparse Namespace object containing argument inputs """ job.fileStore.logToMaster('Indexe...
[ "def", "index_bams", "(", "job", ",", "config", ")", ":", "job", ".", "fileStore", ".", "logToMaster", "(", "'Indexed sample BAMS: '", "+", "config", ".", "uuid", ")", "disk", "=", "'1G'", "if", "config", ".", "ci_test", "else", "'20G'", "config", ".", "...
Convenience job for handling bam indexing to make the workflow declaration cleaner :param JobFunctionWrappingJob job: passed automatically by Toil :param Namespace config: Argparse Namespace object containing argument inputs
[ "Convenience", "job", "for", "handling", "bam", "indexing", "to", "make", "the", "workflow", "declaration", "cleaner" ]
python
train
lesscpy/lesscpy
lesscpy/lessc/parser.py
https://github.com/lesscpy/lesscpy/blob/51e392fb4a3cd4ccfb6175e0e42ce7d2f6b78126/lesscpy/lessc/parser.py#L226-L271
def p_statement_import(self, p): """ import_statement : css_import t_ws string t_semicolon | css_import t_ws css_string t_semicolon | css_import t_ws css_string media_query_list t_semicolon | css_import t_ws f...
[ "def", "p_statement_import", "(", "self", ",", "p", ")", ":", "#import pdb; pdb.set_trace()", "if", "self", ".", "importlvl", ">", "8", ":", "raise", "ImportError", "(", "'Recrusive import level too deep > 8 (circular import ?)'", ")", "if", "isinstance", "(", "p", ...
import_statement : css_import t_ws string t_semicolon | css_import t_ws css_string t_semicolon | css_import t_ws css_string media_query_list t_semicolon | css_import t_ws fcall t_semicolon ...
[ "import_statement", ":", "css_import", "t_ws", "string", "t_semicolon", "|", "css_import", "t_ws", "css_string", "t_semicolon", "|", "css_import", "t_ws", "css_string", "media_query_list", "t_semicolon", "|", "css_import", "t_ws", "fcall", "t_semicolon", "|", "css_impor...
python
valid
apache/incubator-heron
heron/tools/tracker/src/python/topology.py
https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/topology.py#L95-L102
def unregister_watch(self, uid): """ Unregister the watch with the given UUID. """ # Do not raise an error if UUID is # not present in the watches. Log.info("Unregister a watch with uid: " + str(uid)) self.watches.pop(uid, None)
[ "def", "unregister_watch", "(", "self", ",", "uid", ")", ":", "# Do not raise an error if UUID is", "# not present in the watches.", "Log", ".", "info", "(", "\"Unregister a watch with uid: \"", "+", "str", "(", "uid", ")", ")", "self", ".", "watches", ".", "pop", ...
Unregister the watch with the given UUID.
[ "Unregister", "the", "watch", "with", "the", "given", "UUID", "." ]
python
valid
nerdvegas/rez
src/build_utils/virtualenv/virtualenv.py
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/build_utils/virtualenv/virtualenv.py#L1569-L1591
def resolve_interpreter(exe): """ If the executable given isn't an absolute path, search $PATH for the interpreter """ # If the "executable" is a version number, get the installed executable for # that version python_versions = get_installed_pythons() if exe in python_versions: exe =...
[ "def", "resolve_interpreter", "(", "exe", ")", ":", "# If the \"executable\" is a version number, get the installed executable for", "# that version", "python_versions", "=", "get_installed_pythons", "(", ")", "if", "exe", "in", "python_versions", ":", "exe", "=", "python_ver...
If the executable given isn't an absolute path, search $PATH for the interpreter
[ "If", "the", "executable", "given", "isn", "t", "an", "absolute", "path", "search", "$PATH", "for", "the", "interpreter" ]
python
train
bdcht/grandalf
grandalf/layouts.py
https://github.com/bdcht/grandalf/blob/b0a604afa79e5201eebe5feb56ae5ec7afc07b95/grandalf/layouts.py#L378-L404
def init_all(self,roots=None,inverted_edges=None,optimize=False): """initializes the layout algorithm by computing roots (unless provided), inverted edges (unless provided), vertices ranks and creates all dummy vertices and layers. Parameters: ro...
[ "def", "init_all", "(", "self", ",", "roots", "=", "None", ",", "inverted_edges", "=", "None", ",", "optimize", "=", "False", ")", ":", "if", "self", ".", "initdone", ":", "return", "# For layered sugiyama algorithm, the input graph must be acyclic,", "# so we must ...
initializes the layout algorithm by computing roots (unless provided), inverted edges (unless provided), vertices ranks and creates all dummy vertices and layers. Parameters: roots (list[Vertex]): set *root* vertices (layer 0) inverted_ed...
[ "initializes", "the", "layout", "algorithm", "by", "computing", "roots", "(", "unless", "provided", ")", "inverted", "edges", "(", "unless", "provided", ")", "vertices", "ranks", "and", "creates", "all", "dummy", "vertices", "and", "layers", ".", "Parameters", ...
python
train
wtsi-hgi/consul-lock
consullock/managers.py
https://github.com/wtsi-hgi/consul-lock/blob/deb07ab41dabbb49f4d0bbc062bc3b4b6e5d71b2/consullock/managers.py#L296-L305
def release_all(self, keys: Sequence[str]) -> Set[str]: """ Releases all of the given keys. :param keys: the keys to release :return: the names of the keys that were released """ released: List[str] = [] for key in keys: released.append(self.release(ke...
[ "def", "release_all", "(", "self", ",", "keys", ":", "Sequence", "[", "str", "]", ")", "->", "Set", "[", "str", "]", ":", "released", ":", "List", "[", "str", "]", "=", "[", "]", "for", "key", "in", "keys", ":", "released", ".", "append", "(", ...
Releases all of the given keys. :param keys: the keys to release :return: the names of the keys that were released
[ "Releases", "all", "of", "the", "given", "keys", ".", ":", "param", "keys", ":", "the", "keys", "to", "release", ":", "return", ":", "the", "names", "of", "the", "keys", "that", "were", "released" ]
python
train
saltstack/salt
salt/modules/status.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/status.py#L444-L604
def meminfo(): ''' Return the memory info for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.meminfo ''' def linux_meminfo(): '''...
[ "def", "meminfo", "(", ")", ":", "def", "linux_meminfo", "(", ")", ":", "'''\n linux specific implementation of meminfo\n '''", "ret", "=", "{", "}", "try", ":", "with", "salt", ".", "utils", ".", "files", ".", "fopen", "(", "'/proc/meminfo'", ",",...
Return the memory info for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.meminfo
[ "Return", "the", "memory", "info", "for", "this", "minion" ]
python
train
mushkevych/scheduler
synergy/scheduler/state_machine_recomputing.py
https://github.com/mushkevych/scheduler/blob/6740331360f49083c208085fb5a60ce80ebf418b/synergy/scheduler/state_machine_recomputing.py#L65-L75
def _compute_and_transfer_to_final_run(self, process_name, start_timeperiod, end_timeperiod, job_record): """ method computes new unit_of_work and transfers the job to STATE_FINAL_RUN it also shares _fuzzy_ DuplicateKeyError logic from _compute_and_transfer_to_progress method""" source_collectio...
[ "def", "_compute_and_transfer_to_final_run", "(", "self", ",", "process_name", ",", "start_timeperiod", ",", "end_timeperiod", ",", "job_record", ")", ":", "source_collection_name", "=", "context", ".", "process_context", "[", "process_name", "]", ".", "source", "star...
method computes new unit_of_work and transfers the job to STATE_FINAL_RUN it also shares _fuzzy_ DuplicateKeyError logic from _compute_and_transfer_to_progress method
[ "method", "computes", "new", "unit_of_work", "and", "transfers", "the", "job", "to", "STATE_FINAL_RUN", "it", "also", "shares", "_fuzzy_", "DuplicateKeyError", "logic", "from", "_compute_and_transfer_to_progress", "method" ]
python
train
globocom/GloboNetworkAPI-client-python
networkapiclient/Ip.py
https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/Ip.py#L241-L273
def check_vip_ip(self, ip, id_evip): """ Get a Ipv4 or Ipv6 for Vip request :param ip: IPv4 or Ipv6. 'xxx.xxx.xxx.xxx or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx' :return: Dictionary with the following structure: :: {'ip': {'ip': < ip - octs for ipv4, blocks for ip...
[ "def", "check_vip_ip", "(", "self", ",", "ip", ",", "id_evip", ")", ":", "ip_map", "=", "dict", "(", ")", "ip_map", "[", "'ip'", "]", "=", "ip", "ip_map", "[", "'id_evip'", "]", "=", "id_evip", "url", "=", "\"ip/checkvipip/\"", "code", ",", "xml", "=...
Get a Ipv4 or Ipv6 for Vip request :param ip: IPv4 or Ipv6. 'xxx.xxx.xxx.xxx or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx' :return: Dictionary with the following structure: :: {'ip': {'ip': < ip - octs for ipv4, blocks for ipv6 - >, 'id': <id>, 'network4 or ...
[ "Get", "a", "Ipv4", "or", "Ipv6", "for", "Vip", "request" ]
python
train
ulfalizer/Kconfiglib
examples/print_config_tree.py
https://github.com/ulfalizer/Kconfiglib/blob/9fe13c03de16c341cd7ed40167216207b821ea50/examples/print_config_tree.py#L104-L154
def node_str(node): """ Returns the complete menu entry text for a menu node, or "" for invisible menu nodes. Invisible menu nodes are those that lack a prompt or that do not have a satisfied prompt condition. Example return value: "[*] Bool symbol (BOOL)" The symbol name is printed in parenth...
[ "def", "node_str", "(", "node", ")", ":", "if", "not", "node", ".", "prompt", ":", "return", "\"\"", "# Even for menu nodes for symbols and choices, it's wrong to check", "# Symbol.visibility / Choice.visibility here. The reason is that a symbol", "# (and a choice, in theory) can be ...
Returns the complete menu entry text for a menu node, or "" for invisible menu nodes. Invisible menu nodes are those that lack a prompt or that do not have a satisfied prompt condition. Example return value: "[*] Bool symbol (BOOL)" The symbol name is printed in parentheses to the right of the prompt.
[ "Returns", "the", "complete", "menu", "entry", "text", "for", "a", "menu", "node", "or", "for", "invisible", "menu", "nodes", ".", "Invisible", "menu", "nodes", "are", "those", "that", "lack", "a", "prompt", "or", "that", "do", "not", "have", "a", "satis...
python
train
rndusr/torf
torf/_torrent.py
https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_torrent.py#L966-L988
def read(cls, filepath, validate=True): """ Read torrent metainfo from file :param filepath: Path of the torrent file :param bool validate: Whether to run :meth:`validate` on the new Torrent object :raises ReadError: if reading from `filepath` fails :raises ...
[ "def", "read", "(", "cls", ",", "filepath", ",", "validate", "=", "True", ")", ":", "try", ":", "with", "open", "(", "filepath", ",", "'rb'", ")", "as", "fh", ":", "return", "cls", ".", "read_stream", "(", "fh", ")", "except", "(", "OSError", ",", ...
Read torrent metainfo from file :param filepath: Path of the torrent file :param bool validate: Whether to run :meth:`validate` on the new Torrent object :raises ReadError: if reading from `filepath` fails :raises ParseError: if `filepath` does not contain a valid bencoded ...
[ "Read", "torrent", "metainfo", "from", "file" ]
python
train
BernardFW/bernard
src/bernard/platforms/telegram/platform.py
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/telegram/platform.py#L591-L599
async def _deferred_init(self): """ Register the web hook onto which Telegram should send its messages. """ hook_path = self.make_hook_path() url = urljoin(settings.BERNARD_BASE_URL, hook_path) await self.call('setWebhook', url=url) logger.info('Setting Telegram ...
[ "async", "def", "_deferred_init", "(", "self", ")", ":", "hook_path", "=", "self", ".", "make_hook_path", "(", ")", "url", "=", "urljoin", "(", "settings", ".", "BERNARD_BASE_URL", ",", "hook_path", ")", "await", "self", ".", "call", "(", "'setWebhook'", "...
Register the web hook onto which Telegram should send its messages.
[ "Register", "the", "web", "hook", "onto", "which", "Telegram", "should", "send", "its", "messages", "." ]
python
train
chrislim2888/IP2Location-Python
IP2Location.py
https://github.com/chrislim2888/IP2Location-Python/blob/6b2a7d3a5e61c9f8efda5ae96c7064f9a7714621/IP2Location.py#L342-L359
def _parse_addr(self, addr): ''' Parses address and returns IP version. Raises exception on invalid argument ''' ipv = 0 try: socket.inet_pton(socket.AF_INET6, addr) # Convert ::FFFF:x.y.z.y to IPv4 if addr.lower().startswith('::ffff:'): try: ...
[ "def", "_parse_addr", "(", "self", ",", "addr", ")", ":", "ipv", "=", "0", "try", ":", "socket", ".", "inet_pton", "(", "socket", ".", "AF_INET6", ",", "addr", ")", "# Convert ::FFFF:x.y.z.y to IPv4", "if", "addr", ".", "lower", "(", ")", ".", "startswit...
Parses address and returns IP version. Raises exception on invalid argument
[ "Parses", "address", "and", "returns", "IP", "version", ".", "Raises", "exception", "on", "invalid", "argument" ]
python
train
knipknap/exscript
Exscript/stdlib/connection.py
https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/stdlib/connection.py#L278-L288
def set_timeout(scope, timeout): """ Defines the time after which Exscript fails if it does not receive a prompt from the remote host. :type timeout: int :param timeout: The timeout in seconds. """ conn = scope.get('__connection__') conn.set_timeout(int(timeout[0])) return True
[ "def", "set_timeout", "(", "scope", ",", "timeout", ")", ":", "conn", "=", "scope", ".", "get", "(", "'__connection__'", ")", "conn", ".", "set_timeout", "(", "int", "(", "timeout", "[", "0", "]", ")", ")", "return", "True" ]
Defines the time after which Exscript fails if it does not receive a prompt from the remote host. :type timeout: int :param timeout: The timeout in seconds.
[ "Defines", "the", "time", "after", "which", "Exscript", "fails", "if", "it", "does", "not", "receive", "a", "prompt", "from", "the", "remote", "host", "." ]
python
train
saltstack/salt
salt/utils/cloud.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/cloud.py#L301-L344
def minion_config(opts, vm_): ''' Return a minion's configuration for the provided options and VM ''' # Don't start with a copy of the default minion opts; they're not always # what we need. Some default options are Null, let's set a reasonable default minion = { 'master': 'salt', ...
[ "def", "minion_config", "(", "opts", ",", "vm_", ")", ":", "# Don't start with a copy of the default minion opts; they're not always", "# what we need. Some default options are Null, let's set a reasonable default", "minion", "=", "{", "'master'", ":", "'salt'", ",", "'log_level'",...
Return a minion's configuration for the provided options and VM
[ "Return", "a", "minion", "s", "configuration", "for", "the", "provided", "options", "and", "VM" ]
python
train
pyqg/pyqg
pyqg/diagnostic_tools.py
https://github.com/pyqg/pyqg/blob/4f41584a12bcbf8657785b8cb310fa5065ecabd1/pyqg/diagnostic_tools.py#L53-L86
def calc_ispec(model, ph): """Compute isotropic spectrum `phr` of `ph` from 2D spectrum. Parameters ---------- model : pyqg.Model instance The model object from which `ph` originates ph : complex array The field on which to compute the variance Returns ------- kr : arra...
[ "def", "calc_ispec", "(", "model", ",", "ph", ")", ":", "if", "model", ".", "kk", ".", "max", "(", ")", ">", "model", ".", "ll", ".", "max", "(", ")", ":", "kmax", "=", "model", ".", "ll", ".", "max", "(", ")", "else", ":", "kmax", "=", "mo...
Compute isotropic spectrum `phr` of `ph` from 2D spectrum. Parameters ---------- model : pyqg.Model instance The model object from which `ph` originates ph : complex array The field on which to compute the variance Returns ------- kr : array isotropic wavenumber ...
[ "Compute", "isotropic", "spectrum", "phr", "of", "ph", "from", "2D", "spectrum", "." ]
python
train
googledatalab/pydatalab
google/datalab/stackdriver/commands/_monitoring.py
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/stackdriver/commands/_monitoring.py#L102-L108
def _monitoring_groups_list(args, _): """Lists the groups in the project.""" project_id = args['project'] pattern = args['name'] or '*' groups = gcm.Groups(context=_make_context(project_id)) dataframe = groups.as_dataframe(pattern=pattern) return _render_dataframe(dataframe)
[ "def", "_monitoring_groups_list", "(", "args", ",", "_", ")", ":", "project_id", "=", "args", "[", "'project'", "]", "pattern", "=", "args", "[", "'name'", "]", "or", "'*'", "groups", "=", "gcm", ".", "Groups", "(", "context", "=", "_make_context", "(", ...
Lists the groups in the project.
[ "Lists", "the", "groups", "in", "the", "project", "." ]
python
train
shoppimon/figcan
figcan/figcan.py
https://github.com/shoppimon/figcan/blob/bdfa59ceed33277c060fc009fbf44c41b9852681/figcan/figcan.py#L109-L130
def _recursive_merge(dct, merge_dct, raise_on_missing): # type: (Dict[str, Any], Dict[str, Any], bool) -> Dict[str, Any] """Recursive dict merge This modifies `dct` in place. Use `copy.deepcopy` if this behavior is not desired. """ for k, v in merge_dct.items(): if k in dct: if ...
[ "def", "_recursive_merge", "(", "dct", ",", "merge_dct", ",", "raise_on_missing", ")", ":", "# type: (Dict[str, Any], Dict[str, Any], bool) -> Dict[str, Any]", "for", "k", ",", "v", "in", "merge_dct", ".", "items", "(", ")", ":", "if", "k", "in", "dct", ":", "if...
Recursive dict merge This modifies `dct` in place. Use `copy.deepcopy` if this behavior is not desired.
[ "Recursive", "dict", "merge" ]
python
train
Rapptz/discord.py
discord/guild.py
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/guild.py#L379-L385
def system_channel(self): """Optional[:class:`TextChannel`]: Returns the guild's channel used for system messages. Currently this is only for new member joins. If no channel is set, then this returns ``None``. """ channel_id = self._system_channel_id return channel_id and self._...
[ "def", "system_channel", "(", "self", ")", ":", "channel_id", "=", "self", ".", "_system_channel_id", "return", "channel_id", "and", "self", ".", "_channels", ".", "get", "(", "channel_id", ")" ]
Optional[:class:`TextChannel`]: Returns the guild's channel used for system messages. Currently this is only for new member joins. If no channel is set, then this returns ``None``.
[ "Optional", "[", ":", "class", ":", "TextChannel", "]", ":", "Returns", "the", "guild", "s", "channel", "used", "for", "system", "messages", "." ]
python
train
Arvedui/picuplib
picuplib/upload.py
https://github.com/Arvedui/picuplib/blob/c8a5d1542dbd421e84afd5ee81fe76efec89fb95/picuplib/upload.py#L183-L223
def upload(apikey, picture, resize=None, rotation='00', noexif=False, callback=None): """ prepares post for regular upload :param str apikey: Apikey needed for Autentication on picflash. :param str/tuple/list picture: Path to picture as str or picture data. \ If data a tuple or list ...
[ "def", "upload", "(", "apikey", ",", "picture", ",", "resize", "=", "None", ",", "rotation", "=", "'00'", ",", "noexif", "=", "False", ",", "callback", "=", "None", ")", ":", "if", "isinstance", "(", "picture", ",", "str", ")", ":", "with", "open", ...
prepares post for regular upload :param str apikey: Apikey needed for Autentication on picflash. :param str/tuple/list picture: Path to picture as str or picture data. \ If data a tuple or list with the file name as str \ and data as byte object in that order. :param str resize: Aresolution...
[ "prepares", "post", "for", "regular", "upload" ]
python
train
SylvanasSun/FishFishJump
fish_searcher/views/search.py
https://github.com/SylvanasSun/FishFishJump/blob/696212d242d8d572f3f1b43925f3d8ab8acc6a2d/fish_searcher/views/search.py#L131-L147
def generate_key(url, page_number): """ >>> url_a = 'http://localhost:5009/search?keywords=a' >>> generate_key(url_a, 10) 'http://localhost:5009/search?keywords=a&page=10' >>> url_b = 'http://localhost:5009/search?keywords=b&page=1' >>> generate_key(url_b, 10) 'http://localhost:5009/search?k...
[ "def", "generate_key", "(", "url", ",", "page_number", ")", ":", "index", "=", "url", ".", "rfind", "(", "'page'", ")", "if", "index", "!=", "-", "1", ":", "result", "=", "url", "[", "0", ":", "index", "]", "result", "+=", "'page=%s'", "%", "page_n...
>>> url_a = 'http://localhost:5009/search?keywords=a' >>> generate_key(url_a, 10) 'http://localhost:5009/search?keywords=a&page=10' >>> url_b = 'http://localhost:5009/search?keywords=b&page=1' >>> generate_key(url_b, 10) 'http://localhost:5009/search?keywords=b&page=10'
[ ">>>", "url_a", "=", "http", ":", "//", "localhost", ":", "5009", "/", "search?keywords", "=", "a", ">>>", "generate_key", "(", "url_a", "10", ")", "http", ":", "//", "localhost", ":", "5009", "/", "search?keywords", "=", "a&page", "=", "10", ">>>", "u...
python
train
gitpython-developers/GitPython
git/index/fun.py
https://github.com/gitpython-developers/GitPython/blob/1f66e25c25cde2423917ee18c4704fff83b837d1/git/index/fun.py#L111-L156
def write_cache(entries, stream, extension_data=None, ShaStreamCls=IndexFileSHA1Writer): """Write the cache represented by entries to a stream :param entries: **sorted** list of entries :param stream: stream to wrap into the AdapterStreamCls - it is used for final output. :param ShaStreamCls: ...
[ "def", "write_cache", "(", "entries", ",", "stream", ",", "extension_data", "=", "None", ",", "ShaStreamCls", "=", "IndexFileSHA1Writer", ")", ":", "# wrap the stream into a compatible writer", "stream", "=", "ShaStreamCls", "(", "stream", ")", "tell", "=", "stream"...
Write the cache represented by entries to a stream :param entries: **sorted** list of entries :param stream: stream to wrap into the AdapterStreamCls - it is used for final output. :param ShaStreamCls: Type to use when writing to the stream. It produces a sha while writing to it, before th...
[ "Write", "the", "cache", "represented", "by", "entries", "to", "a", "stream" ]
python
train
pytest-dev/pytest-xdist
xdist/scheduler/loadscope.py
https://github.com/pytest-dev/pytest-xdist/blob/9fcf8fa636bc69ee6cac9348a6ec20c87f2bb5e4/xdist/scheduler/loadscope.py#L322-L380
def schedule(self): """Initiate distribution of the test collection. Initiate scheduling of the items across the nodes. If this gets called again later it behaves the same as calling ``._reschedule()`` on all nodes so that newly added nodes will start to be used. If ``.collect...
[ "def", "schedule", "(", "self", ")", ":", "assert", "self", ".", "collection_is_completed", "# Initial distribution already happened, reschedule on all nodes", "if", "self", ".", "collection", "is", "not", "None", ":", "for", "node", "in", "self", ".", "nodes", ":",...
Initiate distribution of the test collection. Initiate scheduling of the items across the nodes. If this gets called again later it behaves the same as calling ``._reschedule()`` on all nodes so that newly added nodes will start to be used. If ``.collection_is_completed`` is True, thi...
[ "Initiate", "distribution", "of", "the", "test", "collection", "." ]
python
train
saltstack/salt
salt/modules/network.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/network.py#L270-L283
def _ppid(): ''' Return a dict of pid to ppid mappings ''' ret = {} if __grains__['kernel'] == 'SunOS': cmd = 'ps -a -o pid,ppid | tail +2' else: cmd = 'ps -ax -o pid,ppid | tail -n+2' out = __salt__['cmd.run'](cmd, python_shell=True) for line in out.splitlines(): ...
[ "def", "_ppid", "(", ")", ":", "ret", "=", "{", "}", "if", "__grains__", "[", "'kernel'", "]", "==", "'SunOS'", ":", "cmd", "=", "'ps -a -o pid,ppid | tail +2'", "else", ":", "cmd", "=", "'ps -ax -o pid,ppid | tail -n+2'", "out", "=", "__salt__", "[", "'cmd....
Return a dict of pid to ppid mappings
[ "Return", "a", "dict", "of", "pid", "to", "ppid", "mappings" ]
python
train
odlgroup/odl
odl/space/pspace.py
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/space/pspace.py#L372-L388
def dtype(self): """The data type of this space. This is only well defined if all subspaces have the same dtype. Raises ------ AttributeError If any of the subspaces does not implement `dtype` or if the dtype of the subspaces does not match. """ ...
[ "def", "dtype", "(", "self", ")", ":", "dtypes", "=", "[", "space", ".", "dtype", "for", "space", "in", "self", ".", "spaces", "]", "if", "all", "(", "dtype", "==", "dtypes", "[", "0", "]", "for", "dtype", "in", "dtypes", ")", ":", "return", "dty...
The data type of this space. This is only well defined if all subspaces have the same dtype. Raises ------ AttributeError If any of the subspaces does not implement `dtype` or if the dtype of the subspaces does not match.
[ "The", "data", "type", "of", "this", "space", "." ]
python
train
automl/HpBandSter
hpbandster/examples/plot_example_7_interactive_plot.py
https://github.com/automl/HpBandSter/blob/841db4b827f342e5eb7f725723ea6461ac52d45a/hpbandster/examples/plot_example_7_interactive_plot.py#L39-L51
def realtime_learning_curves(runs): """ example how to extract a different kind of learning curve. The x values are now the time the runs finished, not the budget anymore. We no longer plot the validation loss on the y axis, but now the test accuracy. This is just to show how to get different information into ...
[ "def", "realtime_learning_curves", "(", "runs", ")", ":", "sr", "=", "sorted", "(", "runs", ",", "key", "=", "lambda", "r", ":", "r", ".", "budget", ")", "lc", "=", "list", "(", "filter", "(", "lambda", "t", ":", "not", "t", "[", "1", "]", "is", ...
example how to extract a different kind of learning curve. The x values are now the time the runs finished, not the budget anymore. We no longer plot the validation loss on the y axis, but now the test accuracy. This is just to show how to get different information into the interactive plot.
[ "example", "how", "to", "extract", "a", "different", "kind", "of", "learning", "curve", ".", "The", "x", "values", "are", "now", "the", "time", "the", "runs", "finished", "not", "the", "budget", "anymore", ".", "We", "no", "longer", "plot", "the", "valid...
python
train
Cymmetria/honeycomb
honeycomb/utils/config_utils.py
https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/utils/config_utils.py#L30-L38
def validate_config(config_json, fields): """Validate a JSON file configuration against list of :obj:`honeycomb.defs.ConfigField`.""" for field_name, validator_obj in six.iteritems(fields): field_value = config_json.get(field_name, None) if field_value is None: raise exceptions.Confi...
[ "def", "validate_config", "(", "config_json", ",", "fields", ")", ":", "for", "field_name", ",", "validator_obj", "in", "six", ".", "iteritems", "(", "fields", ")", ":", "field_value", "=", "config_json", ".", "get", "(", "field_name", ",", "None", ")", "i...
Validate a JSON file configuration against list of :obj:`honeycomb.defs.ConfigField`.
[ "Validate", "a", "JSON", "file", "configuration", "against", "list", "of", ":", "obj", ":", "honeycomb", ".", "defs", ".", "ConfigField", "." ]
python
train
ArangoDB-Community/pyArango
pyArango/graph.py
https://github.com/ArangoDB-Community/pyArango/blob/dd72e5f6c540e5e148943d615ddf7553bb78ce0b/pyArango/graph.py#L142-L170
def createEdge(self, collectionName, _fromId, _toId, edgeAttributes, waitForSync = False) : """creates an edge between two documents""" if not _fromId : raise ValueError("Invalid _fromId: %s" % _fromId) if not _toId : raise ValueError("Invalid _toId: %s" % _toId) ...
[ "def", "createEdge", "(", "self", ",", "collectionName", ",", "_fromId", ",", "_toId", ",", "edgeAttributes", ",", "waitForSync", "=", "False", ")", ":", "if", "not", "_fromId", ":", "raise", "ValueError", "(", "\"Invalid _fromId: %s\"", "%", "_fromId", ")", ...
creates an edge between two documents
[ "creates", "an", "edge", "between", "two", "documents" ]
python
train
reingart/pyafipws
utils.py
https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/utils.py#L228-L304
def Conectar(self, cache=None, wsdl=None, proxy="", wrapper=None, cacert=None, timeout=30, soap_server=None): "Conectar cliente soap del web service" try: # analizar transporte y servidor proxy: if wrapper: Http = set_http_wrapper(wrapper) self.Ver...
[ "def", "Conectar", "(", "self", ",", "cache", "=", "None", ",", "wsdl", "=", "None", ",", "proxy", "=", "\"\"", ",", "wrapper", "=", "None", ",", "cacert", "=", "None", ",", "timeout", "=", "30", ",", "soap_server", "=", "None", ")", ":", "try", ...
Conectar cliente soap del web service
[ "Conectar", "cliente", "soap", "del", "web", "service" ]
python
train
Shoobx/xmldiff
xmldiff/main.py
https://github.com/Shoobx/xmldiff/blob/ec7835bce9ba69ff4ce03ab6c11397183b6f8411/xmldiff/main.py#L129-L143
def patch_file(actions, tree): """Takes two filenames or streams, one with XML the other a diff""" tree = etree.parse(tree) if isinstance(actions, six.string_types): # It's a string, so it's a filename with open(actions) as f: actions = f.read() else: # We assume it'...
[ "def", "patch_file", "(", "actions", ",", "tree", ")", ":", "tree", "=", "etree", ".", "parse", "(", "tree", ")", "if", "isinstance", "(", "actions", ",", "six", ".", "string_types", ")", ":", "# It's a string, so it's a filename", "with", "open", "(", "ac...
Takes two filenames or streams, one with XML the other a diff
[ "Takes", "two", "filenames", "or", "streams", "one", "with", "XML", "the", "other", "a", "diff" ]
python
train
etcher-be/elib_miz
elib_miz/mission.py
https://github.com/etcher-be/elib_miz/blob/f28db58fadb2cd9341e0ae4d65101c0cc7d8f3d7/elib_miz/mission.py#L597-L614
def get_country_by_id(self, country_id) -> 'Country': """ Gets a country in this coalition by its ID Args: country_id: country Id Returns: Country """ VALID_POSITIVE_INT.validate(country_id, 'get_country_by_id', exc=ValueError) if country_id not in s...
[ "def", "get_country_by_id", "(", "self", ",", "country_id", ")", "->", "'Country'", ":", "VALID_POSITIVE_INT", ".", "validate", "(", "country_id", ",", "'get_country_by_id'", ",", "exc", "=", "ValueError", ")", "if", "country_id", "not", "in", "self", ".", "_c...
Gets a country in this coalition by its ID Args: country_id: country Id Returns: Country
[ "Gets", "a", "country", "in", "this", "coalition", "by", "its", "ID" ]
python
train
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/matrixpilot.py
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/matrixpilot.py#L8392-L8409
def serial_udb_extra_f14_send(self, sue_WIND_ESTIMATION, sue_GPS_TYPE, sue_DR, sue_BOARD_TYPE, sue_AIRFRAME, sue_RCON, sue_TRAP_FLAGS, sue_TRAP_SOURCE, sue_osc_fail_count, sue_CLOCK_CONFIG, sue_FLIGHT_PLAN_TYPE, force_mavlink1=False): ''' Backwards compatible version of SERIAL_UDB_EXTRA ...
[ "def", "serial_udb_extra_f14_send", "(", "self", ",", "sue_WIND_ESTIMATION", ",", "sue_GPS_TYPE", ",", "sue_DR", ",", "sue_BOARD_TYPE", ",", "sue_AIRFRAME", ",", "sue_RCON", ",", "sue_TRAP_FLAGS", ",", "sue_TRAP_SOURCE", ",", "sue_osc_fail_count", ",", "sue_CLOCK_CONFIG...
Backwards compatible version of SERIAL_UDB_EXTRA F14: format sue_WIND_ESTIMATION : Serial UDB Extra Wind Estimation Enabled (uint8_t) sue_GPS_TYPE : Serial UDB Extra Type of GPS Unit (uint8_t) sue_DR : Serial UDB Extra Dead Reckonin...
[ "Backwards", "compatible", "version", "of", "SERIAL_UDB_EXTRA", "F14", ":", "format" ]
python
train
apple/turicreate
src/unity/python/turicreate/meta/decompiler/disassemble.py
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/meta/decompiler/disassemble.py#L29-L92
def print_code(co, lasti= -1, level=0): """Disassemble a code object.""" code = co.co_code for constant in co.co_consts: print( '| |' * level, end=' ') print( 'constant:', constant) labels = findlabels(code) linestarts = dict(findlinestarts(co)) n = len...
[ "def", "print_code", "(", "co", ",", "lasti", "=", "-", "1", ",", "level", "=", "0", ")", ":", "code", "=", "co", ".", "co_code", "for", "constant", "in", "co", ".", "co_consts", ":", "print", "(", "'| |'", "*", "level", ",", "end", "=...
Disassemble a code object.
[ "Disassemble", "a", "code", "object", "." ]
python
train
F5Networks/f5-common-python
f5/bigip/mixins.py
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/mixins.py#L243-L263
def _exec_cmd(self, command, **kwargs): """Create a new method as command has specific requirements. There is a handful of the TMSH global commands supported, so this method requires them as a parameter. :raises: InvalidCommand """ kwargs['command'] = command s...
[ "def", "_exec_cmd", "(", "self", ",", "command", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'command'", "]", "=", "command", "self", ".", "_check_exclusive_parameters", "(", "*", "*", "kwargs", ")", "requests_params", "=", "self", ".", "_handle_req...
Create a new method as command has specific requirements. There is a handful of the TMSH global commands supported, so this method requires them as a parameter. :raises: InvalidCommand
[ "Create", "a", "new", "method", "as", "command", "has", "specific", "requirements", "." ]
python
train
Capitains/MyCapytain
MyCapytain/common/metadata.py
https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/common/metadata.py#L72-L87
def add(self, key, value, lang=None): """ Add a triple to the graph related to this node :param key: Predicate of the triple :param value: Object of the triple :param lang: Language of the triple if applicable """ if not isinstance(value, Literal) and lang is not None: ...
[ "def", "add", "(", "self", ",", "key", ",", "value", ",", "lang", "=", "None", ")", ":", "if", "not", "isinstance", "(", "value", ",", "Literal", ")", "and", "lang", "is", "not", "None", ":", "value", "=", "Literal", "(", "value", ",", "lang", "=...
Add a triple to the graph related to this node :param key: Predicate of the triple :param value: Object of the triple :param lang: Language of the triple if applicable
[ "Add", "a", "triple", "to", "the", "graph", "related", "to", "this", "node" ]
python
train
odlgroup/odl
odl/phantom/geometric.py
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/phantom/geometric.py#L706-L764
def smooth_cuboid(space, min_pt=None, max_pt=None, axis=0): """Cuboid with smooth variations. Parameters ---------- space : `DiscreteLp` Discretized space in which the phantom is supposed to be created. min_pt : array-like of shape ``(space.ndim,)``, optional Lower left corner of th...
[ "def", "smooth_cuboid", "(", "space", ",", "min_pt", "=", "None", ",", "max_pt", "=", "None", ",", "axis", "=", "0", ")", ":", "dom_min_pt", "=", "space", ".", "domain", ".", "min", "(", ")", "dom_max_pt", "=", "space", ".", "domain", ".", "max", "...
Cuboid with smooth variations. Parameters ---------- space : `DiscreteLp` Discretized space in which the phantom is supposed to be created. min_pt : array-like of shape ``(space.ndim,)``, optional Lower left corner of the cuboid. If ``None`` is given, a quarter of the extent fro...
[ "Cuboid", "with", "smooth", "variations", "." ]
python
train
O365/python-o365
O365/excel.py
https://github.com/O365/python-o365/blob/02a71cf3775cc6a3c042e003365d6a07c8c75a73/O365/excel.py#L1613-L1634
def add_named_range(self, name, reference, comment='', is_formula=False): """ Adds a new name to the collection of the given scope using the user's locale for the formula :param str name: the name of this range :param str reference: the reference for this range or formula :param ...
[ "def", "add_named_range", "(", "self", ",", "name", ",", "reference", ",", "comment", "=", "''", ",", "is_formula", "=", "False", ")", ":", "if", "is_formula", ":", "url", "=", "self", ".", "build_url", "(", "self", ".", "_endpoints", ".", "get", "(", ...
Adds a new name to the collection of the given scope using the user's locale for the formula :param str name: the name of this range :param str reference: the reference for this range or formula :param str comment: a comment to describe this named range :param bool is_formula: True if th...
[ "Adds", "a", "new", "name", "to", "the", "collection", "of", "the", "given", "scope", "using", "the", "user", "s", "locale", "for", "the", "formula", ":", "param", "str", "name", ":", "the", "name", "of", "this", "range", ":", "param", "str", "referenc...
python
train
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/matrixpilot.py
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/matrixpilot.py#L12161-L12174
def terrain_report_encode(self, lat, lon, spacing, terrain_height, current_height, pending, loaded): ''' Response from a TERRAIN_CHECK request lat : Latitude (degrees *10^7) (int32_t) lon : Longitude (degrees *1...
[ "def", "terrain_report_encode", "(", "self", ",", "lat", ",", "lon", ",", "spacing", ",", "terrain_height", ",", "current_height", ",", "pending", ",", "loaded", ")", ":", "return", "MAVLink_terrain_report_message", "(", "lat", ",", "lon", ",", "spacing", ",",...
Response from a TERRAIN_CHECK request lat : Latitude (degrees *10^7) (int32_t) lon : Longitude (degrees *10^7) (int32_t) spacing : grid spacing (zero if terrain at this location unavailable) (uint16_t) ...
[ "Response", "from", "a", "TERRAIN_CHECK", "request" ]
python
train
markuskiller/textblob-de
textblob_de/ext/_pattern/text/search.py
https://github.com/markuskiller/textblob-de/blob/1b427b2cdd7e5e9fd3697677a98358fae4aa6ad1/textblob_de/ext/_pattern/text/search.py#L487-L546
def fromstring(cls, s, **kwargs): """ Returns a new Constraint from the given string. Uppercase words indicate either a tag ("NN", "JJ", "VP") or a taxonomy term (e.g., "PRODUCT", "PERSON"). Syntax: ( defines an optional constraint, e.g., "(JJ)". [ def...
[ "def", "fromstring", "(", "cls", ",", "s", ",", "*", "*", "kwargs", ")", ":", "C", "=", "cls", "(", "*", "*", "kwargs", ")", "s", "=", "s", ".", "strip", "(", ")", "s", "=", "s", ".", "strip", "(", "\"{}\"", ")", "s", "=", "s", ".", "stri...
Returns a new Constraint from the given string. Uppercase words indicate either a tag ("NN", "JJ", "VP") or a taxonomy term (e.g., "PRODUCT", "PERSON"). Syntax: ( defines an optional constraint, e.g., "(JJ)". [ defines a constraint with spaces, e.g., "[Mac OS ...
[ "Returns", "a", "new", "Constraint", "from", "the", "given", "string", ".", "Uppercase", "words", "indicate", "either", "a", "tag", "(", "NN", "JJ", "VP", ")", "or", "a", "taxonomy", "term", "(", "e", ".", "g", ".", "PRODUCT", "PERSON", ")", ".", "Sy...
python
train
python-cmd2/cmd2
cmd2/cmd2.py
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L2037-L2069
def onecmd(self, statement: Union[Statement, str]) -> bool: """ This executes the actual do_* method for a command. If the command provided doesn't exist, then it executes default() instead. :param statement: intended to be a Statement instance parsed command from the input stream, alternative...
[ "def", "onecmd", "(", "self", ",", "statement", ":", "Union", "[", "Statement", ",", "str", "]", ")", "->", "bool", ":", "# For backwards compatibility with cmd, allow a str to be passed in", "if", "not", "isinstance", "(", "statement", ",", "Statement", ")", ":",...
This executes the actual do_* method for a command. If the command provided doesn't exist, then it executes default() instead. :param statement: intended to be a Statement instance parsed command from the input stream, alternative acceptance of a str is present only for backw...
[ "This", "executes", "the", "actual", "do_", "*", "method", "for", "a", "command", "." ]
python
train
sorgerlab/indra
indra/sources/trips/processor.py
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/trips/processor.py#L1710-L1721
def _stmt_location_to_agents(stmt, location): """Apply an event location to the Agents in the corresponding Statement. If a Statement is in a given location we represent that by requiring all Agents in the Statement to be in that location. """ if location is None: return agents = stmt.a...
[ "def", "_stmt_location_to_agents", "(", "stmt", ",", "location", ")", ":", "if", "location", "is", "None", ":", "return", "agents", "=", "stmt", ".", "agent_list", "(", ")", "for", "a", "in", "agents", ":", "if", "a", "is", "not", "None", ":", "a", "...
Apply an event location to the Agents in the corresponding Statement. If a Statement is in a given location we represent that by requiring all Agents in the Statement to be in that location.
[ "Apply", "an", "event", "location", "to", "the", "Agents", "in", "the", "corresponding", "Statement", "." ]
python
train
horazont/aioxmpp
aioxmpp/stringprep.py
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/stringprep.py#L107-L117
def check_prohibited_output(chars, bad_tables): """ Check against prohibited output, by checking whether any of the characters from `chars` are in any of the `bad_tables`. Operates in-place on a list of code points from `chars`. """ violator = check_against_tables(chars, bad_tables) if viol...
[ "def", "check_prohibited_output", "(", "chars", ",", "bad_tables", ")", ":", "violator", "=", "check_against_tables", "(", "chars", ",", "bad_tables", ")", "if", "violator", "is", "not", "None", ":", "raise", "ValueError", "(", "\"Input contains invalid unicode code...
Check against prohibited output, by checking whether any of the characters from `chars` are in any of the `bad_tables`. Operates in-place on a list of code points from `chars`.
[ "Check", "against", "prohibited", "output", "by", "checking", "whether", "any", "of", "the", "characters", "from", "chars", "are", "in", "any", "of", "the", "bad_tables", "." ]
python
train
inasafe/inasafe
safe/defaults.py
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/defaults.py#L18-L28
def default_provenance(): """The provenance for the default values. :return: default provenance. :rtype: str """ field = TextParameter() field.name = tr('Provenance') field.description = tr('The provenance of minimum needs') field.value = 'The minimum needs are based on BNPB Perka 7/200...
[ "def", "default_provenance", "(", ")", ":", "field", "=", "TextParameter", "(", ")", "field", ".", "name", "=", "tr", "(", "'Provenance'", ")", "field", ".", "description", "=", "tr", "(", "'The provenance of minimum needs'", ")", "field", ".", "value", "=",...
The provenance for the default values. :return: default provenance. :rtype: str
[ "The", "provenance", "for", "the", "default", "values", "." ]
python
train
knagra/farnsworth
events/ajax.py
https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/events/ajax.py#L12-L37
def build_ajax_rsvps(event, user_profile): """Return link and list strings for a given event.""" if user_profile in event.rsvps.all(): link_string = True else: link_string = False if not event.rsvps.all().count(): list_string = 'No RSVPs.' else: list_string = 'RSVPs:...
[ "def", "build_ajax_rsvps", "(", "event", ",", "user_profile", ")", ":", "if", "user_profile", "in", "event", ".", "rsvps", ".", "all", "(", ")", ":", "link_string", "=", "True", "else", ":", "link_string", "=", "False", "if", "not", "event", ".", "rsvps"...
Return link and list strings for a given event.
[ "Return", "link", "and", "list", "strings", "for", "a", "given", "event", "." ]
python
train
tensorpack/tensorpack
tensorpack/train/base.py
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/train/base.py#L142-L165
def _register_callback(self, cb): """ Register callbacks to the trainer. It can only be called before :meth:`Trainer.train()`. Args: cb (Callback or [Callback]): a callback or a list of callbacks Returns: succeed or not """ if isinstance(...
[ "def", "_register_callback", "(", "self", ",", "cb", ")", ":", "if", "isinstance", "(", "cb", ",", "(", "list", ",", "tuple", ")", ")", ":", "for", "x", "in", "cb", ":", "self", ".", "_register_callback", "(", "x", ")", "return", "assert", "isinstanc...
Register callbacks to the trainer. It can only be called before :meth:`Trainer.train()`. Args: cb (Callback or [Callback]): a callback or a list of callbacks Returns: succeed or not
[ "Register", "callbacks", "to", "the", "trainer", ".", "It", "can", "only", "be", "called", "before", ":", "meth", ":", "Trainer", ".", "train", "()", "." ]
python
train
crate/crate-python
src/crate/client/http.py
https://github.com/crate/crate-python/blob/68e39c95f5bbe88b74bbfa26de4347fc644636a8/src/crate/client/http.py#L369-L378
def blob_get(self, table, digest, chunk_size=1024 * 128): """ Returns a file like object representing the contents of the blob with the given digest. """ response = self._request('GET', _blob_path(table, digest), stream=True) if response.status == 404: raise D...
[ "def", "blob_get", "(", "self", ",", "table", ",", "digest", ",", "chunk_size", "=", "1024", "*", "128", ")", ":", "response", "=", "self", ".", "_request", "(", "'GET'", ",", "_blob_path", "(", "table", ",", "digest", ")", ",", "stream", "=", "True"...
Returns a file like object representing the contents of the blob with the given digest.
[ "Returns", "a", "file", "like", "object", "representing", "the", "contents", "of", "the", "blob", "with", "the", "given", "digest", "." ]
python
train
junzis/pyModeS
pyModeS/decoder/bds/bds40.py
https://github.com/junzis/pyModeS/blob/8cd5655a04b08171a9ad5f1ffd232b7e0178ea53/pyModeS/decoder/bds/bds40.py#L25-L65
def is40(msg): """Check if a message is likely to be BDS code 4,0 Args: msg (String): 28 bytes hexadecimal message string Returns: bool: True or False """ if allzeros(msg): return False d = hex2bin(data(msg)) # status bit 1, 14, and 27 if wrongstatus(d, 1, 2...
[ "def", "is40", "(", "msg", ")", ":", "if", "allzeros", "(", "msg", ")", ":", "return", "False", "d", "=", "hex2bin", "(", "data", "(", "msg", ")", ")", "# status bit 1, 14, and 27", "if", "wrongstatus", "(", "d", ",", "1", ",", "2", ",", "13", ")",...
Check if a message is likely to be BDS code 4,0 Args: msg (String): 28 bytes hexadecimal message string Returns: bool: True or False
[ "Check", "if", "a", "message", "is", "likely", "to", "be", "BDS", "code", "4", "0" ]
python
train
patrickfuller/imolecule
imolecule/json_formatter.py
https://github.com/patrickfuller/imolecule/blob/07e91600c805123935a78782871414754bd3696d/imolecule/json_formatter.py#L37-L45
def default(self, obj): """Fired when an unserializable object is hit.""" if hasattr(obj, '__dict__'): return obj.__dict__.copy() elif HAS_NUMPY and isinstance(obj, np.ndarray): return obj.copy().tolist() else: raise TypeError(("Object of type {:s} wit...
[ "def", "default", "(", "self", ",", "obj", ")", ":", "if", "hasattr", "(", "obj", ",", "'__dict__'", ")", ":", "return", "obj", ".", "__dict__", ".", "copy", "(", ")", "elif", "HAS_NUMPY", "and", "isinstance", "(", "obj", ",", "np", ".", "ndarray", ...
Fired when an unserializable object is hit.
[ "Fired", "when", "an", "unserializable", "object", "is", "hit", "." ]
python
train
zakdoek/django-simple-resizer
simple_resizer/__init__.py
https://github.com/zakdoek/django-simple-resizer/blob/5614eb1717948c65d179c3d1567439a8c90a4d44/simple_resizer/__init__.py#L60-L144
def _resize(image, width, height, crop): """ Resize the image with respect to the aspect ratio """ ext = os.path.splitext(image.name)[1].strip(".") with Image(file=image, format=ext) as b_image: # Account for orientation if ORIENTATION_TYPES.index(b_image.orientation) > 4: ...
[ "def", "_resize", "(", "image", ",", "width", ",", "height", ",", "crop", ")", ":", "ext", "=", "os", ".", "path", ".", "splitext", "(", "image", ".", "name", ")", "[", "1", "]", ".", "strip", "(", "\".\"", ")", "with", "Image", "(", "file", "=...
Resize the image with respect to the aspect ratio
[ "Resize", "the", "image", "with", "respect", "to", "the", "aspect", "ratio" ]
python
train
FPGAwars/apio
apio/managers/scons.py
https://github.com/FPGAwars/apio/blob/5c6310f11a061a760764c6b5847bfb431dc3d0bc/apio/managers/scons.py#L301-L326
def run(self, command, variables=[], board=None, packages=[]): """Executes scons for building""" # -- Check for the SConstruct file if not isfile(util.safe_join(util.get_project_dir(), 'SConstruct')): variables += ['-f'] variables += [util.safe_join( util...
[ "def", "run", "(", "self", ",", "command", ",", "variables", "=", "[", "]", ",", "board", "=", "None", ",", "packages", "=", "[", "]", ")", ":", "# -- Check for the SConstruct file", "if", "not", "isfile", "(", "util", ".", "safe_join", "(", "util", "....
Executes scons for building
[ "Executes", "scons", "for", "building" ]
python
train
pypa/pipenv
pipenv/vendor/toml/encoder.py
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/toml/encoder.py#L11-L29
def dump(o, f): """Writes out dict as toml to a file Args: o: Object to dump into toml f: File descriptor where the toml should be stored Returns: String containing the toml corresponding to dictionary Raises: TypeError: When anything other than file descriptor is pass...
[ "def", "dump", "(", "o", ",", "f", ")", ":", "if", "not", "f", ".", "write", ":", "raise", "TypeError", "(", "\"You can only dump an object to a file descriptor\"", ")", "d", "=", "dumps", "(", "o", ")", "f", ".", "write", "(", "d", ")", "return", "d" ...
Writes out dict as toml to a file Args: o: Object to dump into toml f: File descriptor where the toml should be stored Returns: String containing the toml corresponding to dictionary Raises: TypeError: When anything other than file descriptor is passed
[ "Writes", "out", "dict", "as", "toml", "to", "a", "file" ]
python
train
wangwenpei/fantasy
fantasy/utils.py
https://github.com/wangwenpei/fantasy/blob/0fe92059bd868f14da84235beb05b217b1d46e4a/fantasy/utils.py#L29-L38
def config_value(key, app=None, default=None, prefix='hive_'): """Get a Flask-Security configuration value. :param key: The configuration key without the prefix `SECURITY_` :param app: An optional specific application to inspect. Defaults to Flask's `current_app` :param default: An opti...
[ "def", "config_value", "(", "key", ",", "app", "=", "None", ",", "default", "=", "None", ",", "prefix", "=", "'hive_'", ")", ":", "app", "=", "app", "or", "current_app", "return", "get_config", "(", "app", ",", "prefix", "=", "prefix", ")", ".", "get...
Get a Flask-Security configuration value. :param key: The configuration key without the prefix `SECURITY_` :param app: An optional specific application to inspect. Defaults to Flask's `current_app` :param default: An optional default value if the value is not set
[ "Get", "a", "Flask", "-", "Security", "configuration", "value", "." ]
python
test
theosysbio/means
src/means/io/sbml.py
https://github.com/theosysbio/means/blob/fe164916a1d84ab2a4fa039871d38ccdf638b1db/src/means/io/sbml.py#L55-L125
def read_sbml(filename): """ Read the model from a SBML file. :param filename: SBML filename to read the model from :return: A tuple, consisting of :class:`~means.core.model.Model` instance, set of parameter values, and set of initial conditions variables. """ import libsbml i...
[ "def", "read_sbml", "(", "filename", ")", ":", "import", "libsbml", "if", "not", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "raise", "IOError", "(", "'File {0!r} does not exist'", ".", "format", "(", "filename", ")", ")", "reader", "=", ...
Read the model from a SBML file. :param filename: SBML filename to read the model from :return: A tuple, consisting of :class:`~means.core.model.Model` instance, set of parameter values, and set of initial conditions variables.
[ "Read", "the", "model", "from", "a", "SBML", "file", "." ]
python
train
pszafer/epson_projector
epson_projector/main.py
https://github.com/pszafer/epson_projector/blob/b8a10ace56e0a5cf858546041819c0e7ebca208f/epson_projector/main.py#L52-L56
def __initLock(self): """Init lock for sending request to projector when it is busy.""" self._isLocked = False self._timer = 0 self._operation = False
[ "def", "__initLock", "(", "self", ")", ":", "self", ".", "_isLocked", "=", "False", "self", ".", "_timer", "=", "0", "self", ".", "_operation", "=", "False" ]
Init lock for sending request to projector when it is busy.
[ "Init", "lock", "for", "sending", "request", "to", "projector", "when", "it", "is", "busy", "." ]
python
train
DLR-RM/RAFCON
source/rafcon/gui/mygaphas/items/line.py
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/items/line.py#L309-L316
def _head_length(self, port): """Distance from the center of the port to the perpendicular waypoint""" if not port: return 0. parent_state_v = self.get_parent_state_v() if parent_state_v is port.parent: # port of connection's parent state return port.port_size[1]...
[ "def", "_head_length", "(", "self", ",", "port", ")", ":", "if", "not", "port", ":", "return", "0.", "parent_state_v", "=", "self", ".", "get_parent_state_v", "(", ")", "if", "parent_state_v", "is", "port", ".", "parent", ":", "# port of connection's parent st...
Distance from the center of the port to the perpendicular waypoint
[ "Distance", "from", "the", "center", "of", "the", "port", "to", "the", "perpendicular", "waypoint" ]
python
train
JonathanRaiman/ciseau
ciseau/word_tokenizer.py
https://github.com/JonathanRaiman/ciseau/blob/f72d1c82d85eeb3d3ac9fac17690041725402175/ciseau/word_tokenizer.py#L185-L260
def tokenize(text, normalize_ascii=True): """ Convert a single string into a list of substrings split along punctuation and word boundaries. Keep whitespace intact by always attaching it to the previous token. Arguments: ---------- text : str normalize_ascii : bool, perform ...
[ "def", "tokenize", "(", "text", ",", "normalize_ascii", "=", "True", ")", ":", "# 1. If there's no punctuation, return immediately", "if", "no_punctuation", ".", "match", "(", "text", ")", ":", "return", "[", "text", "]", "# 2. let's standardize the input text to ascii ...
Convert a single string into a list of substrings split along punctuation and word boundaries. Keep whitespace intact by always attaching it to the previous token. Arguments: ---------- text : str normalize_ascii : bool, perform some replacements on non-ascii characters ...
[ "Convert", "a", "single", "string", "into", "a", "list", "of", "substrings", "split", "along", "punctuation", "and", "word", "boundaries", ".", "Keep", "whitespace", "intact", "by", "always", "attaching", "it", "to", "the", "previous", "token", "." ]
python
test
Azure/azure-storage-python
azure-storage-queue/azure/storage/queue/queueservice.py
https://github.com/Azure/azure-storage-python/blob/52327354b192cbcf6b7905118ec6b5d57fa46275/azure-storage-queue/azure/storage/queue/queueservice.py#L414-L450
def list_queues(self, prefix=None, num_results=None, include_metadata=False, marker=None, timeout=None): ''' Returns a generator to list the queues. The generator will lazily follow the continuation tokens returned by the service and stop when all queues have been r...
[ "def", "list_queues", "(", "self", ",", "prefix", "=", "None", ",", "num_results", "=", "None", ",", "include_metadata", "=", "False", ",", "marker", "=", "None", ",", "timeout", "=", "None", ")", ":", "include", "=", "'metadata'", "if", "include_metadata"...
Returns a generator to list the queues. The generator will lazily follow the continuation tokens returned by the service and stop when all queues have been returned or num_results is reached. If num_results is specified and the account has more than that number of queues, the generat...
[ "Returns", "a", "generator", "to", "list", "the", "queues", ".", "The", "generator", "will", "lazily", "follow", "the", "continuation", "tokens", "returned", "by", "the", "service", "and", "stop", "when", "all", "queues", "have", "been", "returned", "or", "n...
python
train
sorgerlab/indra
indra/sources/tees/processor.py
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/tees/processor.py#L188-L199
def get_related_node(self, node, relation): """Looks for an edge from node to some other node, such that the edge is annotated with the given relation. If there exists such an edge, returns the name of the node it points to. Otherwise, returns None.""" G = self.G for edge in G.ed...
[ "def", "get_related_node", "(", "self", ",", "node", ",", "relation", ")", ":", "G", "=", "self", ".", "G", "for", "edge", "in", "G", ".", "edges", "(", "node", ")", ":", "to", "=", "edge", "[", "1", "]", "to_relation", "=", "G", ".", "edges", ...
Looks for an edge from node to some other node, such that the edge is annotated with the given relation. If there exists such an edge, returns the name of the node it points to. Otherwise, returns None.
[ "Looks", "for", "an", "edge", "from", "node", "to", "some", "other", "node", "such", "that", "the", "edge", "is", "annotated", "with", "the", "given", "relation", ".", "If", "there", "exists", "such", "an", "edge", "returns", "the", "name", "of", "the", ...
python
train
rigetti/quantumflow
quantumflow/visualization.py
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/visualization.py#L308-L327
def circuit_to_image(circ: Circuit, qubits: Qubits = None) -> PIL.Image: # pragma: no cover """Create an image of a quantum circuit. A convenience function that calls circuit_to_latex() and render_latex(). Args: circ: A quantum Circuit qubits: Optional qubi...
[ "def", "circuit_to_image", "(", "circ", ":", "Circuit", ",", "qubits", ":", "Qubits", "=", "None", ")", "->", "PIL", ".", "Image", ":", "# pragma: no cover", "latex", "=", "circuit_to_latex", "(", "circ", ",", "qubits", ")", "img", "=", "render_latex", "("...
Create an image of a quantum circuit. A convenience function that calls circuit_to_latex() and render_latex(). Args: circ: A quantum Circuit qubits: Optional qubit list to specify qubit order Returns: Returns: A PIL Image (Use img.show() to display) Raises: ...
[ "Create", "an", "image", "of", "a", "quantum", "circuit", "." ]
python
train
Robpol86/flake8-pydocstyle
flake8_pydocstyle.py
https://github.com/Robpol86/flake8-pydocstyle/blob/657425541e1d868a6a5241a83c3a16a9a715d6b5/flake8_pydocstyle.py#L20-L43
def load_file(filename): """Read file to memory. For stdin sourced files, this function does something super duper incredibly hacky and shameful. So so shameful. I'm obtaining the original source code of the target module from the only instance of pycodestyle.Checker through the Python garbage collecto...
[ "def", "load_file", "(", "filename", ")", ":", "if", "filename", "in", "(", "'stdin'", ",", "'-'", ",", "None", ")", ":", "instances", "=", "[", "i", "for", "i", "in", "gc", ".", "get_objects", "(", ")", "if", "isinstance", "(", "i", ",", "pycodest...
Read file to memory. For stdin sourced files, this function does something super duper incredibly hacky and shameful. So so shameful. I'm obtaining the original source code of the target module from the only instance of pycodestyle.Checker through the Python garbage collector. Flake8's API doesn't give me ...
[ "Read", "file", "to", "memory", "." ]
python
train
JelteF/PyLaTeX
pylatex/tikz.py
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/tikz.py#L230-L247
def dumps(self): """Return string representation of the node.""" ret_str = [] ret_str.append(Command('node', options=self.options).dumps()) if self.handle is not None: ret_str.append('({})'.format(self.handle)) if self._node_position is not None: ret_st...
[ "def", "dumps", "(", "self", ")", ":", "ret_str", "=", "[", "]", "ret_str", ".", "append", "(", "Command", "(", "'node'", ",", "options", "=", "self", ".", "options", ")", ".", "dumps", "(", ")", ")", "if", "self", ".", "handle", "is", "not", "No...
Return string representation of the node.
[ "Return", "string", "representation", "of", "the", "node", "." ]
python
train
pandas-dev/pandas
pandas/plotting/_core.py
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/plotting/_core.py#L3248-L3293
def hist(self, by=None, bins=10, **kwds): """ Draw one histogram of the DataFrame's columns. A histogram is a representation of the distribution of data. This function groups the values of all given Series in the DataFrame into bins and draws all bins in one :class:`matplotlib.a...
[ "def", "hist", "(", "self", ",", "by", "=", "None", ",", "bins", "=", "10", ",", "*", "*", "kwds", ")", ":", "return", "self", "(", "kind", "=", "'hist'", ",", "by", "=", "by", ",", "bins", "=", "bins", ",", "*", "*", "kwds", ")" ]
Draw one histogram of the DataFrame's columns. A histogram is a representation of the distribution of data. This function groups the values of all given Series in the DataFrame into bins and draws all bins in one :class:`matplotlib.axes.Axes`. This is useful when the DataFrame's Series ...
[ "Draw", "one", "histogram", "of", "the", "DataFrame", "s", "columns", "." ]
python
train
jaraco/keyring
keyring/backends/SecretService.py
https://github.com/jaraco/keyring/blob/71c798378e365286b7cc03c06e4d7d24c7de8fc4/keyring/backends/SecretService.py#L61-L72
def get_password(self, service, username): """Get password of the username for the service """ collection = self.get_preferred_collection() items = collection.search_items( {"username": username, "service": service}) for item in items: if hasattr(item, 'un...
[ "def", "get_password", "(", "self", ",", "service", ",", "username", ")", ":", "collection", "=", "self", ".", "get_preferred_collection", "(", ")", "items", "=", "collection", ".", "search_items", "(", "{", "\"username\"", ":", "username", ",", "\"service\"",...
Get password of the username for the service
[ "Get", "password", "of", "the", "username", "for", "the", "service" ]
python
valid
alecthomas/voluptuous
voluptuous/schema_builder.py
https://github.com/alecthomas/voluptuous/blob/36c8c11e2b7eb402c24866fa558473661ede9403/voluptuous/schema_builder.py#L598-L653
def _compile_sequence(self, schema, seq_type): """Validate a sequence type. This is a sequence of valid values or validators tried in order. >>> validator = Schema(['one', 'two', int]) >>> validator(['one']) ['one'] >>> with raises(er.MultipleInvalid, 'expected int @ da...
[ "def", "_compile_sequence", "(", "self", ",", "schema", ",", "seq_type", ")", ":", "_compiled", "=", "[", "self", ".", "_compile", "(", "s", ")", "for", "s", "in", "schema", "]", "seq_type_name", "=", "seq_type", ".", "__name__", "def", "validate_sequence"...
Validate a sequence type. This is a sequence of valid values or validators tried in order. >>> validator = Schema(['one', 'two', int]) >>> validator(['one']) ['one'] >>> with raises(er.MultipleInvalid, 'expected int @ data[0]'): ... validator([3.5]) >>> valida...
[ "Validate", "a", "sequence", "type", "." ]
python
train
saltstack/salt
salt/utils/virtualbox.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/virtualbox.py#L436-L475
def vb_start_vm(name=None, timeout=10000, **kwargs): ''' Tells Virtualbox to start up a VM. Blocking function! @param name: @type name: str @param timeout: Maximum time in milliseconds to wait or -1 to wait indefinitely @type timeout: int @return untreated dict of started VM ''' ...
[ "def", "vb_start_vm", "(", "name", "=", "None", ",", "timeout", "=", "10000", ",", "*", "*", "kwargs", ")", ":", "# Time tracking", "start_time", "=", "time", ".", "time", "(", ")", "timeout_in_seconds", "=", "timeout", "/", "1000", "max_time", "=", "sta...
Tells Virtualbox to start up a VM. Blocking function! @param name: @type name: str @param timeout: Maximum time in milliseconds to wait or -1 to wait indefinitely @type timeout: int @return untreated dict of started VM
[ "Tells", "Virtualbox", "to", "start", "up", "a", "VM", ".", "Blocking", "function!" ]
python
train
saltstack/salt
salt/states/netsnmp.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/netsnmp.py#L133-L141
def _str_elem(config, key): ''' Re-adds the value of a specific key in the dict, only in case of valid str value. ''' _value = config.pop(key, '') if _valid_str(_value): config[key] = _value
[ "def", "_str_elem", "(", "config", ",", "key", ")", ":", "_value", "=", "config", ".", "pop", "(", "key", ",", "''", ")", "if", "_valid_str", "(", "_value", ")", ":", "config", "[", "key", "]", "=", "_value" ]
Re-adds the value of a specific key in the dict, only in case of valid str value.
[ "Re", "-", "adds", "the", "value", "of", "a", "specific", "key", "in", "the", "dict", "only", "in", "case", "of", "valid", "str", "value", "." ]
python
train
CitrineInformatics/python-citrination-client
citrination_client/base/base_client.py
https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/base/base_client.py#L96-L110
def _post(self, route, data, headers=None, failure_message=None): """ Execute a post request and return the result :param data: :param headers: :return: """ headers = self._get_headers(headers) response_lambda = ( lambda: requests.post( ...
[ "def", "_post", "(", "self", ",", "route", ",", "data", ",", "headers", "=", "None", ",", "failure_message", "=", "None", ")", ":", "headers", "=", "self", ".", "_get_headers", "(", "headers", ")", "response_lambda", "=", "(", "lambda", ":", "requests", ...
Execute a post request and return the result :param data: :param headers: :return:
[ "Execute", "a", "post", "request", "and", "return", "the", "result", ":", "param", "data", ":", ":", "param", "headers", ":", ":", "return", ":" ]
python
valid
bhmm/bhmm
bhmm/estimators/maximum_likelihood.py
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/estimators/maximum_likelihood.py#L332-L352
def compute_viterbi_paths(self): """ Computes the viterbi paths using the current HMM model """ # get parameters K = len(self._observations) A = self._hmm.transition_matrix pi = self._hmm.initial_distribution # compute viterbi path for each trajectory ...
[ "def", "compute_viterbi_paths", "(", "self", ")", ":", "# get parameters", "K", "=", "len", "(", "self", ".", "_observations", ")", "A", "=", "self", ".", "_hmm", ".", "transition_matrix", "pi", "=", "self", ".", "_hmm", ".", "initial_distribution", "# compu...
Computes the viterbi paths using the current HMM model
[ "Computes", "the", "viterbi", "paths", "using", "the", "current", "HMM", "model" ]
python
train
seleniumbase/SeleniumBase
seleniumbase/fixtures/base_case.py
https://github.com/seleniumbase/SeleniumBase/blob/62e5b43ee1f90a9ed923841bdd53b1b38358f43a/seleniumbase/fixtures/base_case.py#L906-L965
def create_shepherd_tour(self, name=None, theme=None): """ Creates a Shepherd JS website tour. @Params name - If creating multiple tours at the same time, use this to select the tour you wish to add steps to. theme - Sets the default theme for the tour. ...
[ "def", "create_shepherd_tour", "(", "self", ",", "name", "=", "None", ",", "theme", "=", "None", ")", ":", "shepherd_theme", "=", "\"shepherd-theme-arrows\"", "if", "theme", ":", "if", "theme", ".", "lower", "(", ")", "==", "\"default\"", ":", "shepherd_them...
Creates a Shepherd JS website tour. @Params name - If creating multiple tours at the same time, use this to select the tour you wish to add steps to. theme - Sets the default theme for the tour. Choose from "light"/"arrows", "dark", "default", "...
[ "Creates", "a", "Shepherd", "JS", "website", "tour", "." ]
python
train
paulovn/sparql-kernel
sparqlkernel/connection.py
https://github.com/paulovn/sparql-kernel/blob/1d2d155ff5da72070cb2a98fae33ea8113fac782/sparqlkernel/connection.py#L181-L190
def lang_match_xml(row, accepted_languages): '''Find if the XML row contains acceptable language data''' if not accepted_languages: return True column_languages = set() for elem in row: lang = elem[0].attrib.get(XML_LANG, None) if lang: column_languages.add(lang) ...
[ "def", "lang_match_xml", "(", "row", ",", "accepted_languages", ")", ":", "if", "not", "accepted_languages", ":", "return", "True", "column_languages", "=", "set", "(", ")", "for", "elem", "in", "row", ":", "lang", "=", "elem", "[", "0", "]", ".", "attri...
Find if the XML row contains acceptable language data
[ "Find", "if", "the", "XML", "row", "contains", "acceptable", "language", "data" ]
python
train
secdev/scapy
scapy/layers/l2.py
https://github.com/secdev/scapy/blob/3ffe757c184017dd46464593a8f80f85abc1e79a/scapy/layers/l2.py#L736-L785
def arpleak(target, plen=255, hwlen=255, **kargs): """Exploit ARP leak flaws, like NetBSD-SA2017-002. https://ftp.netbsd.org/pub/NetBSD/security/advisories/NetBSD-SA2017-002.txt.asc """ # We want explicit packets pkts_iface = {} for pkt in ARP(pdst=target): # We have to do some of Scapy's ...
[ "def", "arpleak", "(", "target", ",", "plen", "=", "255", ",", "hwlen", "=", "255", ",", "*", "*", "kargs", ")", ":", "# We want explicit packets", "pkts_iface", "=", "{", "}", "for", "pkt", "in", "ARP", "(", "pdst", "=", "target", ")", ":", "# We ha...
Exploit ARP leak flaws, like NetBSD-SA2017-002. https://ftp.netbsd.org/pub/NetBSD/security/advisories/NetBSD-SA2017-002.txt.asc
[ "Exploit", "ARP", "leak", "flaws", "like", "NetBSD", "-", "SA2017", "-", "002", "." ]
python
train
thelabnyc/wagtail_blog
blog/management/commands/wordpress_to_wagtail.py
https://github.com/thelabnyc/wagtail_blog/blob/7e092c02d10ec427c9a2c4b5dcbe910d88c628cf/blog/management/commands/wordpress_to_wagtail.py#L64-L99
def handle(self, *args, **options): """gets data from WordPress site""" # TODO: refactor these with .get if 'username' in options: self.username = options['username'] else: self.username = None if 'password' in options: self.password = options[...
[ "def", "handle", "(", "self", ",", "*", "args", ",", "*", "*", "options", ")", ":", "# TODO: refactor these with .get", "if", "'username'", "in", "options", ":", "self", ".", "username", "=", "options", "[", "'username'", "]", "else", ":", "self", ".", "...
gets data from WordPress site
[ "gets", "data", "from", "WordPress", "site" ]
python
train
pyrogram/pyrogram
pyrogram/client/client.py
https://github.com/pyrogram/pyrogram/blob/e7258a341ba905cfa86264c22040654db732ec1c/pyrogram/client/client.py#L1315-L1386
def resolve_peer(self, peer_id: Union[int, str]): """Use this method to get the InputPeer of a known peer_id. This is a utility method intended to be used **only** when working with Raw Functions (i.e: a Telegram API method you wish to use which is not available yet in the ...
[ "def", "resolve_peer", "(", "self", ",", "peer_id", ":", "Union", "[", "int", ",", "str", "]", ")", ":", "try", ":", "return", "self", ".", "peers_by_id", "[", "peer_id", "]", "except", "KeyError", ":", "if", "type", "(", "peer_id", ")", "is", "str",...
Use this method to get the InputPeer of a known peer_id. This is a utility method intended to be used **only** when working with Raw Functions (i.e: a Telegram API method you wish to use which is not available yet in the Client class as an easy-to-use method), whenever an InputPeer type is requ...
[ "Use", "this", "method", "to", "get", "the", "InputPeer", "of", "a", "known", "peer_id", "." ]
python
train
dslackw/slpkg
slpkg/pkg/manager.py
https://github.com/dslackw/slpkg/blob/dd2e08a80e944d337d157b992167ba631a4343de/slpkg/pkg/manager.py#L524-L539
def list_lib(self, repo): """Return package lists """ packages = "" if repo == "sbo": if (os.path.isfile( self.meta.lib_path + "{0}_repo/SLACKBUILDS.TXT".format( repo))): packages = Utils().read_file(self.meta.lib_pa...
[ "def", "list_lib", "(", "self", ",", "repo", ")", ":", "packages", "=", "\"\"", "if", "repo", "==", "\"sbo\"", ":", "if", "(", "os", ".", "path", ".", "isfile", "(", "self", ".", "meta", ".", "lib_path", "+", "\"{0}_repo/SLACKBUILDS.TXT\"", ".", "forma...
Return package lists
[ "Return", "package", "lists" ]
python
train
ChristopherRabotin/bungiesearch
bungiesearch/__init__.py
https://github.com/ChristopherRabotin/bungiesearch/blob/13768342bc2698b214eb0003c2d113b6e273c30d/bungiesearch/__init__.py#L132-L141
def get_models(cls, index, as_class=False): ''' Returns the list of models defined for this index. :param index: index name. :param as_class: set to True to return the model as a model object instead of as a string. ''' try: return cls._index_to_model[index] i...
[ "def", "get_models", "(", "cls", ",", "index", ",", "as_class", "=", "False", ")", ":", "try", ":", "return", "cls", ".", "_index_to_model", "[", "index", "]", "if", "as_class", "else", "cls", ".", "_idx_name_to_mdl_to_mdlidx", "[", "index", "]", ".", "k...
Returns the list of models defined for this index. :param index: index name. :param as_class: set to True to return the model as a model object instead of as a string.
[ "Returns", "the", "list", "of", "models", "defined", "for", "this", "index", ".", ":", "param", "index", ":", "index", "name", ".", ":", "param", "as_class", ":", "set", "to", "True", "to", "return", "the", "model", "as", "a", "model", "object", "inste...
python
train
chrissimpkins/crypto
lib/crypto/library/package.py
https://github.com/chrissimpkins/crypto/blob/6b95fa81b26312e46f02557dca0b5f5c898a76fd/lib/crypto/library/package.py#L28-L32
def remove_tar_files(file_list): """Public function that removes temporary tar archive files in a local directory""" for f in file_list: if file_exists(f) and f.endswith('.tar'): os.remove(f)
[ "def", "remove_tar_files", "(", "file_list", ")", ":", "for", "f", "in", "file_list", ":", "if", "file_exists", "(", "f", ")", "and", "f", ".", "endswith", "(", "'.tar'", ")", ":", "os", ".", "remove", "(", "f", ")" ]
Public function that removes temporary tar archive files in a local directory
[ "Public", "function", "that", "removes", "temporary", "tar", "archive", "files", "in", "a", "local", "directory" ]
python
train
thunder-project/thunder
thunder/blocks/blocks.py
https://github.com/thunder-project/thunder/blob/967ff8f3e7c2fabe1705743d95eb2746d4329786/thunder/blocks/blocks.py#L89-L102
def toseries(self): """ Converts blocks to series. """ from thunder.series.series import Series if self.mode == 'spark': values = self.values.values_to_keys(tuple(range(1, len(self.shape)))).unchunk() if self.mode == 'local': values = self.values...
[ "def", "toseries", "(", "self", ")", ":", "from", "thunder", ".", "series", ".", "series", "import", "Series", "if", "self", ".", "mode", "==", "'spark'", ":", "values", "=", "self", ".", "values", ".", "values_to_keys", "(", "tuple", "(", "range", "("...
Converts blocks to series.
[ "Converts", "blocks", "to", "series", "." ]
python
train
bcbio/bcbio-nextgen
bcbio/ngsalign/alignprep.py
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/ngsalign/alignprep.py#L64-L101
def _set_align_split_size(data): """Set useful align_split_size, generating an estimate if it doesn't exist. We try to split on larger inputs and avoid too many pieces, aiming for size chunks of 5Gb or at most 50 maximum splits. The size estimate used in calculations is 20 million reads for ~5Gb. ...
[ "def", "_set_align_split_size", "(", "data", ")", ":", "if", "cwlutils", ".", "is_cwl_run", "(", "data", ")", ":", "target_size", "=", "20", "# Gb", "target_size_reads", "=", "80", "# million reads", "else", ":", "target_size", "=", "5", "# Gb", "target_size_r...
Set useful align_split_size, generating an estimate if it doesn't exist. We try to split on larger inputs and avoid too many pieces, aiming for size chunks of 5Gb or at most 50 maximum splits. The size estimate used in calculations is 20 million reads for ~5Gb. For UMI calculations we skip splitting ...
[ "Set", "useful", "align_split_size", "generating", "an", "estimate", "if", "it", "doesn", "t", "exist", "." ]
python
train
KarchinLab/probabilistic2020
prob2020/python/permutation.py
https://github.com/KarchinLab/probabilistic2020/blob/5d70583b0a7c07cfe32e95f3a70e05df412acb84/prob2020/python/permutation.py#L210-L357
def hotmaps_permutation(obs_stat, context_counts, context_to_mut, seq_context, gene_seq, window, num_permutations=10000, stop_criteria=100, ...
[ "def", "hotmaps_permutation", "(", "obs_stat", ",", "context_counts", ",", "context_to_mut", ",", "seq_context", ",", "gene_seq", ",", "window", ",", "num_permutations", "=", "10000", ",", "stop_criteria", "=", "100", ",", "max_batch", "=", "25000", ",", "null_s...
Performs null-permutations for position-based mutation statistics in a single gene. Parameters ---------- obs_stat : dict dictionary mapping codons to the sum of mutations in a window context_counts : pd.Series number of mutations for each context context_to_mut : dict d...
[ "Performs", "null", "-", "permutations", "for", "position", "-", "based", "mutation", "statistics", "in", "a", "single", "gene", "." ]
python
train
markovmodel/PyEMMA
pyemma/coordinates/data/util/traj_info_backends.py
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/coordinates/data/util/traj_info_backends.py#L234-L257
def _database_from_key(self, key): """ gets the database name for the given key. Should ensure a uniform spread of keys over the databases in order to minimize waiting times. Since the database has to be locked for updates and multiple processes want to write, each process has to...
[ "def", "_database_from_key", "(", "self", ",", "key", ")", ":", "if", "not", "self", ".", "filename", ":", "return", "None", "from", "pyemma", ".", "util", ".", "files", "import", "mkdir_p", "hash_value_long", "=", "int", "(", "key", ",", "16", ")", "#...
gets the database name for the given key. Should ensure a uniform spread of keys over the databases in order to minimize waiting times. Since the database has to be locked for updates and multiple processes want to write, each process has to wait until the lock has been released. By def...
[ "gets", "the", "database", "name", "for", "the", "given", "key", ".", "Should", "ensure", "a", "uniform", "spread", "of", "keys", "over", "the", "databases", "in", "order", "to", "minimize", "waiting", "times", ".", "Since", "the", "database", "has", "to",...
python
train
jwodder/doapi
doapi/doapi.py
https://github.com/jwodder/doapi/blob/b1306de86a01d8ae7b9c1fe2699765bb82e4f310/doapi/doapi.py#L955-L1025
def _wait(self, objects, attr, value, wait_interval=None, wait_time=None): r""" Calls the ``fetch`` method of each object in ``objects`` periodically until the ``attr`` attribute of each one equals ``value``, yielding the final state of each object as soon as it satisfies the condition. ...
[ "def", "_wait", "(", "self", ",", "objects", ",", "attr", ",", "value", ",", "wait_interval", "=", "None", ",", "wait_time", "=", "None", ")", ":", "objects", "=", "list", "(", "objects", ")", "if", "not", "objects", ":", "return", "if", "wait_interval...
r""" Calls the ``fetch`` method of each object in ``objects`` periodically until the ``attr`` attribute of each one equals ``value``, yielding the final state of each object as soon as it satisfies the condition. If ``wait_time`` is exceeded, a `WaitTimeoutError` (containing any ...
[ "r", "Calls", "the", "fetch", "method", "of", "each", "object", "in", "objects", "periodically", "until", "the", "attr", "attribute", "of", "each", "one", "equals", "value", "yielding", "the", "final", "state", "of", "each", "object", "as", "soon", "as", "...
python
train
borntyping/python-riemann-client
riemann_client/command.py
https://github.com/borntyping/python-riemann-client/blob/3e181d90bdf685afd21c1ec5ee20e6840b011ea5/riemann_client/command.py#L57-L81
def main(ctx, host, port, transport_type, timeout, ca_certs): """Connects to a Riemann server to send events or query the index By default, will attempt to contact Riemann on localhost:5555 over TCP. The RIEMANN_HOST and RIEMANN_PORT environment variables can be used to configure the host and port used...
[ "def", "main", "(", "ctx", ",", "host", ",", "port", ",", "transport_type", ",", "timeout", ",", "ca_certs", ")", ":", "if", "transport_type", "==", "'udp'", ":", "if", "timeout", "is", "not", "None", ":", "ctx", ".", "fail", "(", "'--timeout cannot be u...
Connects to a Riemann server to send events or query the index By default, will attempt to contact Riemann on localhost:5555 over TCP. The RIEMANN_HOST and RIEMANN_PORT environment variables can be used to configure the host and port used. Command line parameters will override the environment variables...
[ "Connects", "to", "a", "Riemann", "server", "to", "send", "events", "or", "query", "the", "index" ]
python
train
ktdreyer/txkoji
txkoji/connection.py
https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/connection.py#L393-L406
def listChannels(self, **kwargs): """ Get information about all Koji channels. :param **kwargs: keyword args to pass through to listChannels RPC. :returns: deferred that when fired returns a list of Channel objects. """ data = yield self.call('listChannels', **kwargs) ...
[ "def", "listChannels", "(", "self", ",", "*", "*", "kwargs", ")", ":", "data", "=", "yield", "self", ".", "call", "(", "'listChannels'", ",", "*", "*", "kwargs", ")", "channels", "=", "[", "]", "for", "cdata", "in", "data", ":", "channel", "=", "Ch...
Get information about all Koji channels. :param **kwargs: keyword args to pass through to listChannels RPC. :returns: deferred that when fired returns a list of Channel objects.
[ "Get", "information", "about", "all", "Koji", "channels", "." ]
python
train
marcocamma/datastorage
datastorage/datastorage.py
https://github.com/marcocamma/datastorage/blob/d88cdc08414c1c99d34d62e65fcbf807c3088a37/datastorage/datastorage.py#L233-L254
def save(fname, d, link_copy=True,raiseError=False): """ link_copy is used by hdf5 saving only, it allows to creat link of identical arrays (saving space) """ # make sure the object is dict (recursively) this allows reading it # without the DataStorage module fname = pathlib.Path(fname) d = toDict(d...
[ "def", "save", "(", "fname", ",", "d", ",", "link_copy", "=", "True", ",", "raiseError", "=", "False", ")", ":", "# make sure the object is dict (recursively) this allows reading it", "# without the DataStorage module", "fname", "=", "pathlib", ".", "Path", "(", "fnam...
link_copy is used by hdf5 saving only, it allows to creat link of identical arrays (saving space)
[ "link_copy", "is", "used", "by", "hdf5", "saving", "only", "it", "allows", "to", "creat", "link", "of", "identical", "arrays", "(", "saving", "space", ")" ]
python
train
roclark/sportsreference
sportsreference/nba/roster.py
https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/nba/roster.py#L442-L468
def _parse_contract(self, player_info): """ Parse the player's contract. Depending on the player's contract status, a contract table is located at the bottom of the stats page and includes player wages by season. If found, create a dictionary housing the wages by season. ...
[ "def", "_parse_contract", "(", "self", ",", "player_info", ")", ":", "tables", "=", "player_info", "(", "'table'", ")", ".", "items", "(", ")", "for", "table", "in", "tables", ":", "id_attr", "=", "table", ".", "attr", "(", "'id'", ")", "if", "id_attr"...
Parse the player's contract. Depending on the player's contract status, a contract table is located at the bottom of the stats page and includes player wages by season. If found, create a dictionary housing the wages by season. Parameters ---------- player_info : PyQuer...
[ "Parse", "the", "player", "s", "contract", "." ]
python
train
fabioz/PyDev.Debugger
pydevd.py
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd.py#L1172-L1231
def set_suspend(self, thread, stop_reason, suspend_other_threads=False, is_pause=False): ''' :param thread: The thread which should be suspended. :param stop_reason: Reason why the thread was suspended. :param suspend_other_threads: Whether to force ...
[ "def", "set_suspend", "(", "self", ",", "thread", ",", "stop_reason", ",", "suspend_other_threads", "=", "False", ",", "is_pause", "=", "False", ")", ":", "self", ".", "_threads_suspended_single_notification", ".", "increment_suspend_time", "(", ")", "if", "is_pau...
:param thread: The thread which should be suspended. :param stop_reason: Reason why the thread was suspended. :param suspend_other_threads: Whether to force other threads to be suspended (i.e.: when hitting a breakpoint with a suspend all threads policy)...
[ ":", "param", "thread", ":", "The", "thread", "which", "should", "be", "suspended", "." ]
python
train
getsentry/raven-python
raven/contrib/django/client.py
https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/contrib/django/client.py#L104-L142
def install_sql_hook(): """If installed this causes Django's queries to be captured.""" try: from django.db.backends.utils import CursorWrapper except ImportError: from django.db.backends.util import CursorWrapper try: real_execute = CursorWrapper.execute real_executeman...
[ "def", "install_sql_hook", "(", ")", ":", "try", ":", "from", "django", ".", "db", ".", "backends", ".", "utils", "import", "CursorWrapper", "except", "ImportError", ":", "from", "django", ".", "db", ".", "backends", ".", "util", "import", "CursorWrapper", ...
If installed this causes Django's queries to be captured.
[ "If", "installed", "this", "causes", "Django", "s", "queries", "to", "be", "captured", "." ]
python
train
nccgroup/Scout2
AWSScout2/services/iam.py
https://github.com/nccgroup/Scout2/blob/5d86d46d7ed91a92000496189e9cfa6b98243937/AWSScout2/services/iam.py#L244-L270
def parse_users(self, user, params): """ Parse a single IAM user and fetch additional data """ if user['UserName'] in self.users: return api_client = params['api_client'] # Ensure consistent attribute names across resource types user['id'] = user.pop('...
[ "def", "parse_users", "(", "self", ",", "user", ",", "params", ")", ":", "if", "user", "[", "'UserName'", "]", "in", "self", ".", "users", ":", "return", "api_client", "=", "params", "[", "'api_client'", "]", "# Ensure consistent attribute names across resource ...
Parse a single IAM user and fetch additional data
[ "Parse", "a", "single", "IAM", "user", "and", "fetch", "additional", "data" ]
python
train
bkeating/python-payflowpro
payflowpro/client.py
https://github.com/bkeating/python-payflowpro/blob/e74fc85135f171caa28277196fdcf7c7481ff298/payflowpro/client.py#L133-L174
def _parse_parmlist(self, parmlist): """ Parses a PARMLIST string into a dictionary of name and value pairs. The parsing is complicated by the following: - parameter keynames may or may not include a length specification - delimiter characters (=, &) may a...
[ "def", "_parse_parmlist", "(", "self", ",", "parmlist", ")", ":", "parmlist", "=", "\"&\"", "+", "parmlist", "name_re", "=", "re", ".", "compile", "(", "r'\\&([A-Z0-9_]+)(\\[\\d+\\])?='", ")", "results", "=", "{", "}", "offset", "=", "0", "match", "=", "na...
Parses a PARMLIST string into a dictionary of name and value pairs. The parsing is complicated by the following: - parameter keynames may or may not include a length specification - delimiter characters (=, &) may appear inside parameter values, provided the pa...
[ "Parses", "a", "PARMLIST", "string", "into", "a", "dictionary", "of", "name", "and", "value", "pairs", ".", "The", "parsing", "is", "complicated", "by", "the", "following", ":", "-", "parameter", "keynames", "may", "or", "may", "not", "include", "a", "leng...
python
train
ChristianKuehnel/btlewrap
btlewrap/gatttool.py
https://github.com/ChristianKuehnel/btlewrap/blob/1b7aec934529dcf03f5ecdccd0b09c25c389974f/btlewrap/gatttool.py#L19-L27
def wrap_exception(func: Callable) -> Callable: """Wrap all IOErrors to BluetoothBackendException""" def _func_wrapper(*args, **kwargs): try: return func(*args, **kwargs) except IOError as exception: raise BluetoothBackendException() from exception return _func_wrapp...
[ "def", "wrap_exception", "(", "func", ":", "Callable", ")", "->", "Callable", ":", "def", "_func_wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", ...
Wrap all IOErrors to BluetoothBackendException
[ "Wrap", "all", "IOErrors", "to", "BluetoothBackendException" ]
python
train
codelv/enaml-native
src/enamlnative/android/android_view.py
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/android/android_view.py#L330-L359
def set_layout(self, layout): """ Sets the LayoutParams of this widget. Since the available properties that may be set for the layout params depends on the parent, actual creation of the params is delegated to the parent Parameters ---------- ...
[ "def", "set_layout", "(", "self", ",", "layout", ")", ":", "# Update the layout with the widget defaults", "update", "=", "self", ".", "layout_params", "is", "not", "None", "params", "=", "self", ".", "default_layout", ".", "copy", "(", ")", "params", ".", "up...
Sets the LayoutParams of this widget. Since the available properties that may be set for the layout params depends on the parent, actual creation of the params is delegated to the parent Parameters ---------- layout: Dict A dict of layo...
[ "Sets", "the", "LayoutParams", "of", "this", "widget", ".", "Since", "the", "available", "properties", "that", "may", "be", "set", "for", "the", "layout", "params", "depends", "on", "the", "parent", "actual", "creation", "of", "the", "params", "is", "delegat...
python
train
intel-analytics/BigDL
pyspark/bigdl/optim/optimizer.py
https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/optim/optimizer.py#L1009-L1023
def set_validation(self, batch_size, X_val, Y_val, trigger, val_method=None): """ Configure validation settings. :param batch_size: validation batch size :param X_val: features of validation dataset :param Y_val: label of validation dataset :param trigger: validation int...
[ "def", "set_validation", "(", "self", ",", "batch_size", ",", "X_val", ",", "Y_val", ",", "trigger", ",", "val_method", "=", "None", ")", ":", "if", "val_method", "is", "None", ":", "val_method", "=", "[", "Top1Accuracy", "(", ")", "]", "callBigDlFunc", ...
Configure validation settings. :param batch_size: validation batch size :param X_val: features of validation dataset :param Y_val: label of validation dataset :param trigger: validation interval :param val_method: the ValidationMethod to use,e.g. "Top1Accuracy", "Top5Accuracy", ...
[ "Configure", "validation", "settings", "." ]
python
test
aholkner/bacon
native/Vendor/FreeType/src/tools/glnames.py
https://github.com/aholkner/bacon/blob/edf3810dcb211942d392a8637945871399b0650d/native/Vendor/FreeType/src/tools/glnames.py#L5171-L5183
def filter_glyph_names( alist, filter ): """filter `alist' by taking _out_ all glyph names that are in `filter'""" count = 0 extras = [] for name in alist: try: filtered_index = filter.index( name ) except: extras.append( name ) return extras
[ "def", "filter_glyph_names", "(", "alist", ",", "filter", ")", ":", "count", "=", "0", "extras", "=", "[", "]", "for", "name", "in", "alist", ":", "try", ":", "filtered_index", "=", "filter", ".", "index", "(", "name", ")", "except", ":", "extras", "...
filter `alist' by taking _out_ all glyph names that are in `filter
[ "filter", "alist", "by", "taking", "_out_", "all", "glyph", "names", "that", "are", "in", "filter" ]
python
test
ZeitOnline/briefkasten
application/briefkasten/dropbox.py
https://github.com/ZeitOnline/briefkasten/blob/ce6b6eeb89196014fe21d68614c20059d02daa11/application/briefkasten/dropbox.py#L376-L382
def replies(self): """ returns a list of strings """ fs_reply_path = join(self.fs_replies_path, 'message_001.txt') if exists(fs_reply_path): return [load(open(fs_reply_path, 'r'))] else: return []
[ "def", "replies", "(", "self", ")", ":", "fs_reply_path", "=", "join", "(", "self", ".", "fs_replies_path", ",", "'message_001.txt'", ")", "if", "exists", "(", "fs_reply_path", ")", ":", "return", "[", "load", "(", "open", "(", "fs_reply_path", ",", "'r'",...
returns a list of strings
[ "returns", "a", "list", "of", "strings" ]
python
valid
mixmastamyk/console
console/detection.py
https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/detection.py#L336-L344
def is_a_tty(stream=sys.stdout): ''' Detect terminal or something else, such as output redirection. Returns: Boolean, None: is tty or None if not found. ''' result = stream.isatty() if hasattr(stream, 'isatty') else None log.debug(result) return result
[ "def", "is_a_tty", "(", "stream", "=", "sys", ".", "stdout", ")", ":", "result", "=", "stream", ".", "isatty", "(", ")", "if", "hasattr", "(", "stream", ",", "'isatty'", ")", "else", "None", "log", ".", "debug", "(", "result", ")", "return", "result"...
Detect terminal or something else, such as output redirection. Returns: Boolean, None: is tty or None if not found.
[ "Detect", "terminal", "or", "something", "else", "such", "as", "output", "redirection", "." ]
python
train
IdentityPython/oidcendpoint
src/oidcendpoint/userinfo.py
https://github.com/IdentityPython/oidcendpoint/blob/6c1d729d51bfb6332816117fe476073df7a1d823/src/oidcendpoint/userinfo.py#L164-L188
def userinfo_in_id_token_claims(endpoint_context, session, def_itc=None): """ Collect user info claims that are to be placed in the id token. :param endpoint_context: Endpoint context :param session: Session information :param def_itc: Default ID Token claims :return: User information or None ...
[ "def", "userinfo_in_id_token_claims", "(", "endpoint_context", ",", "session", ",", "def_itc", "=", "None", ")", ":", "if", "def_itc", ":", "itc", "=", "def_itc", "else", ":", "itc", "=", "{", "}", "itc", ".", "update", "(", "id_token_claims", "(", "sessio...
Collect user info claims that are to be placed in the id token. :param endpoint_context: Endpoint context :param session: Session information :param def_itc: Default ID Token claims :return: User information or None
[ "Collect", "user", "info", "claims", "that", "are", "to", "be", "placed", "in", "the", "id", "token", "." ]
python
train
scopus-api/scopus
scopus/utils/get_content.py
https://github.com/scopus-api/scopus/blob/27ce02dd3095bfdab9d3e8475543d7c17767d1ab/scopus/utils/get_content.py#L12-L49
def detect_id_type(sid): """Method that tries to infer the type of abstract ID. Parameters ---------- sid : str The ID of an abstract on Scopus. Raises ------ ValueError If the ID type cannot be inferred. Notes ----- PII usually has 17 chars, but in Scopus ther...
[ "def", "detect_id_type", "(", "sid", ")", ":", "sid", "=", "str", "(", "sid", ")", "if", "not", "sid", ".", "isnumeric", "(", ")", ":", "if", "sid", ".", "startswith", "(", "'2-s2.0-'", ")", ":", "id_type", "=", "'eid'", "elif", "'/'", "in", "sid",...
Method that tries to infer the type of abstract ID. Parameters ---------- sid : str The ID of an abstract on Scopus. Raises ------ ValueError If the ID type cannot be inferred. Notes ----- PII usually has 17 chars, but in Scopus there are valid cases with only ...
[ "Method", "that", "tries", "to", "infer", "the", "type", "of", "abstract", "ID", "." ]
python
train
JelleAalbers/multihist
multihist.py
https://github.com/JelleAalbers/multihist/blob/072288277f807e7e388fdf424c3921c80576f3ab/multihist.py#L167-L171
def density(self): """Gives emprical PDF, like np.histogram(...., density=True)""" h = self.histogram.astype(np.float) bindifs = np.array(np.diff(self.bin_edges), float) return h / (bindifs * self.n)
[ "def", "density", "(", "self", ")", ":", "h", "=", "self", ".", "histogram", ".", "astype", "(", "np", ".", "float", ")", "bindifs", "=", "np", ".", "array", "(", "np", ".", "diff", "(", "self", ".", "bin_edges", ")", ",", "float", ")", "return",...
Gives emprical PDF, like np.histogram(...., density=True)
[ "Gives", "emprical", "PDF", "like", "np", ".", "histogram", "(", "....", "density", "=", "True", ")" ]
python
train
gem/oq-engine
openquake/hazardlib/geo/surface/base.py
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/surface/base.py#L342-L375
def get_resampled_top_edge(self, angle_var=0.1): """ This methods computes a simplified representation of a fault top edge by removing the points that are not describing a change of direction, provided a certain tolerance angle. :param float angle_var: Number represe...
[ "def", "get_resampled_top_edge", "(", "self", ",", "angle_var", "=", "0.1", ")", ":", "mesh", "=", "self", ".", "mesh", "top_edge", "=", "[", "Point", "(", "mesh", ".", "lons", "[", "0", "]", "[", "0", "]", ",", "mesh", ".", "lats", "[", "0", "]"...
This methods computes a simplified representation of a fault top edge by removing the points that are not describing a change of direction, provided a certain tolerance angle. :param float angle_var: Number representing the maximum deviation (in degrees) admitted without...
[ "This", "methods", "computes", "a", "simplified", "representation", "of", "a", "fault", "top", "edge", "by", "removing", "the", "points", "that", "are", "not", "describing", "a", "change", "of", "direction", "provided", "a", "certain", "tolerance", "angle", "....
python
train
nvbn/thefuck
thefuck/specific/sudo.py
https://github.com/nvbn/thefuck/blob/40ab4eb62db57627bff10cf029d29c94704086a2/thefuck/specific/sudo.py#L6-L18
def sudo_support(fn, command): """Removes sudo before calling fn and adds it after.""" if not command.script.startswith('sudo '): return fn(command) result = fn(command.update(script=command.script[5:])) if result and isinstance(result, six.string_types): return u'sudo {}'.format(resul...
[ "def", "sudo_support", "(", "fn", ",", "command", ")", ":", "if", "not", "command", ".", "script", ".", "startswith", "(", "'sudo '", ")", ":", "return", "fn", "(", "command", ")", "result", "=", "fn", "(", "command", ".", "update", "(", "script", "=...
Removes sudo before calling fn and adds it after.
[ "Removes", "sudo", "before", "calling", "fn", "and", "adds", "it", "after", "." ]
python
train