repo
stringlengths
7
55
path
stringlengths
4
223
url
stringlengths
87
315
code
stringlengths
75
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
avg_line_len
float64
7.91
980
mardix/Mocha
mocha/core.py
https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/core.py#L224-L264
def page_attr(title=None, **kwargs): """ Page Attr allows you to add page meta data in the request `g` context :params **kwargs: meta keys we're expecting: title (str) description (str) url (str) (Will pick it up by itself if not set) image (str) site_name (str) ...
[ "def", "page_attr", "(", "title", "=", "None", ",", "*", "*", "kwargs", ")", ":", "default", "=", "dict", "(", "title", "=", "\"\"", ",", "description", "=", "\"\"", ",", "url", "=", "\"\"", ",", "image", "=", "\"\"", ",", "site_name", "=", "\"\"",...
Page Attr allows you to add page meta data in the request `g` context :params **kwargs: meta keys we're expecting: title (str) description (str) url (str) (Will pick it up by itself if not set) image (str) site_name (str) (but can pick it up from config file) obj...
[ "Page", "Attr", "allows", "you", "to", "add", "page", "meta", "data", "in", "the", "request", "g", "context", ":", "params", "**", "kwargs", ":" ]
python
train
24.02439
brocade/pynos
pynos/versions/ver_7/ver_7_1_0/yang/brocade_vcs.py
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_7/ver_7_1_0/yang/brocade_vcs.py#L764-L776
def vcs_virtual_ipv6_address_ipv6address(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") vcs = ET.SubElement(config, "vcs", xmlns="urn:brocade.com:mgmt:brocade-vcs") virtual = ET.SubElement(vcs, "virtual") ipv6 = ET.SubElement(virtual, "ipv6") ...
[ "def", "vcs_virtual_ipv6_address_ipv6address", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "vcs", "=", "ET", ".", "SubElement", "(", "config", ",", "\"vcs\"", ",", "xmlns", "=", "\"urn:brocad...
Auto Generated Code
[ "Auto", "Generated", "Code" ]
python
train
42.923077
dslackw/slpkg
slpkg/pkg/manager.py
https://github.com/dslackw/slpkg/blob/dd2e08a80e944d337d157b992167ba631a4343de/slpkg/pkg/manager.py#L270-L280
def _removepkg(self, package): """removepkg Slackware command """ try: subprocess.call("removepkg {0} {1}".format(self.flag, package), shell=True) if os.path.isfile(self.dep_path + package): os.remove(self.dep_path + package) #...
[ "def", "_removepkg", "(", "self", ",", "package", ")", ":", "try", ":", "subprocess", ".", "call", "(", "\"removepkg {0} {1}\"", ".", "format", "(", "self", ".", "flag", ",", "package", ")", ",", "shell", "=", "True", ")", "if", "os", ".", "path", "....
removepkg Slackware command
[ "removepkg", "Slackware", "command" ]
python
train
38.727273
kstaniek/condoor
condoor/actions.py
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/actions.py#L210-L214
def a_message_callback(ctx): """Message the captured pattern.""" message = ctx.ctrl.after.strip().splitlines()[-1] ctx.device.chain.connection.emit_message(message, log_level=logging.INFO) return True
[ "def", "a_message_callback", "(", "ctx", ")", ":", "message", "=", "ctx", ".", "ctrl", ".", "after", ".", "strip", "(", ")", ".", "splitlines", "(", ")", "[", "-", "1", "]", "ctx", ".", "device", ".", "chain", ".", "connection", ".", "emit_message", ...
Message the captured pattern.
[ "Message", "the", "captured", "pattern", "." ]
python
train
42.4
dagster-io/dagster
bin/publish.py
https://github.com/dagster-io/dagster/blob/4119f8c773089de64831b1dfb9e168e353d401dc/bin/publish.py#L50-L63
def construct_publish_comands(additional_steps=None, nightly=False): '''Get the shell commands we'll use to actually build and publish a package to PyPI.''' publish_commands = ( ['rm -rf dist'] + (additional_steps if additional_steps else []) + [ 'python setup.py sdist bdist_...
[ "def", "construct_publish_comands", "(", "additional_steps", "=", "None", ",", "nightly", "=", "False", ")", ":", "publish_commands", "=", "(", "[", "'rm -rf dist'", "]", "+", "(", "additional_steps", "if", "additional_steps", "else", "[", "]", ")", "+", "[", ...
Get the shell commands we'll use to actually build and publish a package to PyPI.
[ "Get", "the", "shell", "commands", "we", "ll", "use", "to", "actually", "build", "and", "publish", "a", "package", "to", "PyPI", "." ]
python
test
34.357143
log2timeline/plaso
plaso/cli/psteal_tool.py
https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/cli/psteal_tool.py#L340-L423
def ParseArguments(self): """Parses the command line arguments. Returns: bool: True if the arguments were successfully parsed. """ loggers.ConfigureLogging() argument_parser = argparse.ArgumentParser( description=self.DESCRIPTION, epilog=self.EPILOG, add_help=False, formatter...
[ "def", "ParseArguments", "(", "self", ")", ":", "loggers", ".", "ConfigureLogging", "(", ")", "argument_parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "self", ".", "DESCRIPTION", ",", "epilog", "=", "self", ".", "EPILOG", ",", "add...
Parses the command line arguments. Returns: bool: True if the arguments were successfully parsed.
[ "Parses", "the", "command", "line", "arguments", "." ]
python
train
33.642857
radjkarl/fancyTools
fancytools/math/blockshaped.py
https://github.com/radjkarl/fancyTools/blob/4c4d961003dc4ed6e46429a0c24f7e2bb52caa8b/fancytools/math/blockshaped.py#L12-L23
def blockshaped(arr, nrows, ncols): """ Return an new array of shape (n, nrows, ncols) where n * nrows * ncols = arr.size If arr is a 2D array, the returned array looks like n subblocks with each subblock preserving the "physical" layout of arr. """ h, w = arr.shape return (arr.reshape(...
[ "def", "blockshaped", "(", "arr", ",", "nrows", ",", "ncols", ")", ":", "h", ",", "w", "=", "arr", ".", "shape", "return", "(", "arr", ".", "reshape", "(", "h", "//", "nrows", ",", "nrows", ",", "-", "1", ",", "ncols", ")", ".", "swapaxes", "("...
Return an new array of shape (n, nrows, ncols) where n * nrows * ncols = arr.size If arr is a 2D array, the returned array looks like n subblocks with each subblock preserving the "physical" layout of arr.
[ "Return", "an", "new", "array", "of", "shape", "(", "n", "nrows", "ncols", ")", "where", "n", "*", "nrows", "*", "ncols", "=", "arr", ".", "size" ]
python
train
34.333333
androguard/androguard
androguard/core/bytecodes/axml/__init__.py
https://github.com/androguard/androguard/blob/984c0d981be2950cf0451e484f7b0d4d53bc4911/androguard/core/bytecodes/axml/__init__.py#L1826-L1840
def get_resolved_res_configs(self, rid, config=None): """ Return a list of resolved resource IDs with their corresponding configuration. It has a similar return type as :meth:`get_res_configs` but also handles complex entries and references. Also instead of returning :class:`ARSC...
[ "def", "get_resolved_res_configs", "(", "self", ",", "rid", ",", "config", "=", "None", ")", ":", "resolver", "=", "ARSCParser", ".", "ResourceResolver", "(", "self", ",", "config", ")", "return", "resolver", ".", "resolve", "(", "rid", ")" ]
Return a list of resolved resource IDs with their corresponding configuration. It has a similar return type as :meth:`get_res_configs` but also handles complex entries and references. Also instead of returning :class:`ARSCResTableEntry` in the tuple, the actual values are resolved. This...
[ "Return", "a", "list", "of", "resolved", "resource", "IDs", "with", "their", "corresponding", "configuration", ".", "It", "has", "a", "similar", "return", "type", "as", ":", "meth", ":", "get_res_configs", "but", "also", "handles", "complex", "entries", "and",...
python
train
51.333333
dossier/dossier.store
dossier/store/elastic.py
https://github.com/dossier/dossier.store/blob/b22ffe2470bba9fcc98a30cb55b437bfa1521e7f/dossier/store/elastic.py#L241-L253
def delete_all(self): '''Deletes all feature collections. This does not destroy the ES index, but instead only deletes all FCs with the configured document type (defaults to ``fc``). ''' try: self.conn.indices.delete_mapping( index=self.index,...
[ "def", "delete_all", "(", "self", ")", ":", "try", ":", "self", ".", "conn", ".", "indices", ".", "delete_mapping", "(", "index", "=", "self", ".", "index", ",", "doc_type", "=", "self", ".", "type", ")", "except", "TransportError", ":", "logger", ".",...
Deletes all feature collections. This does not destroy the ES index, but instead only deletes all FCs with the configured document type (defaults to ``fc``).
[ "Deletes", "all", "feature", "collections", "." ]
python
test
37.230769
BoGoEngine/bogo-python
bogo/core.py
https://github.com/BoGoEngine/bogo-python/blob/9b85329a408ded4cead3539cecba12984d5d7650/bogo/core.py#L365-L434
def _transform(comps, trans): """ Transform the given string with transform type trans """ logging.debug("== In _transform(%s, %s) ==", comps, trans) components = list(comps) action, parameter = _get_action(trans) if action == _Action.ADD_MARK and \ components[2] == "" and \ ...
[ "def", "_transform", "(", "comps", ",", "trans", ")", ":", "logging", ".", "debug", "(", "\"== In _transform(%s, %s) ==\"", ",", "comps", ",", "trans", ")", "components", "=", "list", "(", "comps", ")", "action", ",", "parameter", "=", "_get_action", "(", ...
Transform the given string with transform type trans
[ "Transform", "the", "given", "string", "with", "transform", "type", "trans" ]
python
train
48.971429
saltstack/salt
salt/states/git.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/git.py#L47-L63
def _revs_equal(rev1, rev2, rev_type): ''' Shorthand helper function for comparing SHA1s. If rev_type == 'sha1' then the comparison will be done using str.startwith() to allow short SHA1s to compare successfully. NOTE: This means that rev2 must be the short rev. ''' if (rev1 is None and rev...
[ "def", "_revs_equal", "(", "rev1", ",", "rev2", ",", "rev_type", ")", ":", "if", "(", "rev1", "is", "None", "and", "rev2", "is", "not", "None", ")", "or", "(", "rev2", "is", "None", "and", "rev1", "is", "not", "None", ")", ":", "return", "False", ...
Shorthand helper function for comparing SHA1s. If rev_type == 'sha1' then the comparison will be done using str.startwith() to allow short SHA1s to compare successfully. NOTE: This means that rev2 must be the short rev.
[ "Shorthand", "helper", "function", "for", "comparing", "SHA1s", ".", "If", "rev_type", "==", "sha1", "then", "the", "comparison", "will", "be", "done", "using", "str", ".", "startwith", "()", "to", "allow", "short", "SHA1s", "to", "compare", "successfully", ...
python
train
32.235294
rosenbrockc/ci
pyci/config.py
https://github.com/rosenbrockc/ci/blob/4d5a60291424a83124d1d962d17fb4c7718cde2b/pyci/config.py#L454-L460
def var_replace(self, text): """Replaces all instances of @VAR with their values in the specified text. """ result = text for var in self._vardict: result = result.replace("@{}".format(var), self._vardict[var]) return result
[ "def", "var_replace", "(", "self", ",", "text", ")", ":", "result", "=", "text", "for", "var", "in", "self", ".", "_vardict", ":", "result", "=", "result", ".", "replace", "(", "\"@{}\"", ".", "format", "(", "var", ")", ",", "self", ".", "_vardict", ...
Replaces all instances of @VAR with their values in the specified text.
[ "Replaces", "all", "instances", "of" ]
python
train
38.571429
drdoctr/doctr
doctr/travis.py
https://github.com/drdoctr/doctr/blob/0f19ff78c8239efcc98d417f36b0a31d9be01ba5/doctr/travis.py#L383-L400
def copy_to_tmp(source): """ Copies ``source`` to a temporary directory, and returns the copied location. If source is a file, the copied location is also a file. """ tmp_dir = tempfile.mkdtemp() # Use pathlib because os.path.basename is different depending on whether # the path ends in...
[ "def", "copy_to_tmp", "(", "source", ")", ":", "tmp_dir", "=", "tempfile", ".", "mkdtemp", "(", ")", "# Use pathlib because os.path.basename is different depending on whether", "# the path ends in a /", "p", "=", "pathlib", ".", "Path", "(", "source", ")", "dirname", ...
Copies ``source`` to a temporary directory, and returns the copied location. If source is a file, the copied location is also a file.
[ "Copies", "source", "to", "a", "temporary", "directory", "and", "returns", "the", "copied", "location", "." ]
python
train
30.555556
f3at/feat
src/feat/models/model.py
https://github.com/f3at/feat/blob/15da93fc9d6ec8154f52a9172824e25821195ef8/src/feat/models/model.py#L231-L250
def delete(name, *effects, **kwargs): """ Annotate a delete action to the model being defined. Should be delete(name, *effects, label=None, desc=None) but it is not supported by python < 3. @param name: item name unique for the model being defined. @type name: str or unicode @param effects: ...
[ "def", "delete", "(", "name", ",", "*", "effects", ",", "*", "*", "kwargs", ")", ":", "label", "=", "kwargs", ".", "pop", "(", "\"label\"", ",", "None", ")", "desc", "=", "kwargs", ".", "pop", "(", "\"desc\"", ",", "None", ")", "if", "kwargs", ":...
Annotate a delete action to the model being defined. Should be delete(name, *effects, label=None, desc=None) but it is not supported by python < 3. @param name: item name unique for the model being defined. @type name: str or unicode @param effects: @type effects: str or unicode @param label...
[ "Annotate", "a", "delete", "action", "to", "the", "model", "being", "defined", ".", "Should", "be", "delete", "(", "name", "*", "effects", "label", "=", "None", "desc", "=", "None", ")", "but", "it", "is", "not", "supported", "by", "python", "<", "3", ...
python
train
40.15
edoburu/django-template-analyzer
template_analyzer/djangoanalyzer.py
https://github.com/edoburu/django-template-analyzer/blob/912916dadf68e5fb6bd3dbaa8e5dcad69d3086d0/template_analyzer/djangoanalyzer.py#L100-L122
def _extend_nodelist(extends_node, context, instance_types): """ Returns a list of results found in the parent template(s) :type extends_node: ExtendsNode """ results = [] # Find all blocks in the complete inheritance chain blocks = extends_node.blocks.copy() # dict with all blocks in the ...
[ "def", "_extend_nodelist", "(", "extends_node", ",", "context", ",", "instance_types", ")", ":", "results", "=", "[", "]", "# Find all blocks in the complete inheritance chain", "blocks", "=", "extends_node", ".", "blocks", ".", "copy", "(", ")", "# dict with all bloc...
Returns a list of results found in the parent template(s) :type extends_node: ExtendsNode
[ "Returns", "a", "list", "of", "results", "found", "in", "the", "parent", "template", "(", "s", ")", ":", "type", "extends_node", ":", "ExtendsNode" ]
python
train
40.652174
pandas-dev/pandas
pandas/io/pytables.py
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/pytables.py#L1701-L1720
def validate_col(self, itemsize=None): """ validate this column: return the compared against itemsize """ # validate this column for string truncation (or reset to the max size) if _ensure_decoded(self.kind) == 'string': c = self.col if c is not None: if ...
[ "def", "validate_col", "(", "self", ",", "itemsize", "=", "None", ")", ":", "# validate this column for string truncation (or reset to the max size)", "if", "_ensure_decoded", "(", "self", ".", "kind", ")", "==", "'string'", ":", "c", "=", "self", ".", "col", "if"...
validate this column: return the compared against itemsize
[ "validate", "this", "column", ":", "return", "the", "compared", "against", "itemsize" ]
python
train
45.55
havardgulldahl/jottalib
src/jottalib/JFS.py
https://github.com/havardgulldahl/jottalib/blob/4d015e4309b1d9055e561ec757363fb2632b4eb7/src/jottalib/JFS.py#L334-L342
def rename(self, newpath): "Move folder to a new name, possibly a whole new path" # POST https://www.jottacloud.com/jfs/**USERNAME**/Jotta/Sync/Ny%20mappe?mvDir=/**USERNAME**/Jotta/Sync/testFolder #url = '%s?mvDir=/%s%s' % (self.path, self.jfs.username, newpath) params = {'mvDir':'/%s%s'...
[ "def", "rename", "(", "self", ",", "newpath", ")", ":", "# POST https://www.jottacloud.com/jfs/**USERNAME**/Jotta/Sync/Ny%20mappe?mvDir=/**USERNAME**/Jotta/Sync/testFolder", "#url = '%s?mvDir=/%s%s' % (self.path, self.jfs.username, newpath)", "params", "=", "{", "'mvDir'", ":", "'/%s%s...
Move folder to a new name, possibly a whole new path
[ "Move", "folder", "to", "a", "new", "name", "possibly", "a", "whole", "new", "path" ]
python
train
58.222222
AkihikoITOH/capybara
capybara/virtualenv/lib/python2.7/site-packages/setuptools/__init__.py
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/setuptools/__init__.py#L76-L82
def _all_dirs(base_path): """ Return all dirs in base_path, relative to base_path """ for root, dirs, files in os.walk(base_path, followlinks=True): for dir in dirs: yield os.path.relpath(os.path.join(root, dir), base_path)
[ "def", "_all_dirs", "(", "base_path", ")", ":", "for", "root", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "base_path", ",", "followlinks", "=", "True", ")", ":", "for", "dir", "in", "dirs", ":", "yield", "os", ".", "path", ".", "relpa...
Return all dirs in base_path, relative to base_path
[ "Return", "all", "dirs", "in", "base_path", "relative", "to", "base_path" ]
python
test
39.571429
urinieto/msaf
examples/compute_features.py
https://github.com/urinieto/msaf/blob/9dbb57d77a1310465a65cc40f1641d083ca74385/examples/compute_features.py#L37-L51
def process(in_path, out_file, n_jobs, framesync): """Computes the features for the selected dataset or file.""" if os.path.isfile(in_path): # Single file mode # Get (if they exitst) or compute features file_struct = msaf.io.FileStruct(in_path) file_struct.features_file = out_fil...
[ "def", "process", "(", "in_path", ",", "out_file", ",", "n_jobs", ",", "framesync", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "in_path", ")", ":", "# Single file mode", "# Get (if they exitst) or compute features", "file_struct", "=", "msaf", ".", ...
Computes the features for the selected dataset or file.
[ "Computes", "the", "features", "for", "the", "selected", "dataset", "or", "file", "." ]
python
test
41.4
streamlink/streamlink
src/streamlink/stream/segmented.py
https://github.com/streamlink/streamlink/blob/c8ed1daff14ac03195870238b9b900c1109dd5c1/src/streamlink/stream/segmented.py#L111-L122
def put(self, segment): """Adds a segment to the download pool and write queue.""" if self.closed: return if segment is not None: future = self.executor.submit(self.fetch, segment, retries=self.retries) else: ...
[ "def", "put", "(", "self", ",", "segment", ")", ":", "if", "self", ".", "closed", ":", "return", "if", "segment", "is", "not", "None", ":", "future", "=", "self", ".", "executor", ".", "submit", "(", "self", ".", "fetch", ",", "segment", ",", "retr...
Adds a segment to the download pool and write queue.
[ "Adds", "a", "segment", "to", "the", "download", "pool", "and", "write", "queue", "." ]
python
test
31.25
boriel/zxbasic
ast_/tree.py
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/ast_/tree.py#L154-L166
def makenode(clss, symbol, *nexts): """ Stores the symbol in an AST instance, and left and right to the given ones """ result = clss(symbol) for i in nexts: if i is None: continue if not isinstance(i, clss): raise NotAnAstEr...
[ "def", "makenode", "(", "clss", ",", "symbol", ",", "*", "nexts", ")", ":", "result", "=", "clss", "(", "symbol", ")", "for", "i", "in", "nexts", ":", "if", "i", "is", "None", ":", "continue", "if", "not", "isinstance", "(", "i", ",", "clss", ")"...
Stores the symbol in an AST instance, and left and right to the given ones
[ "Stores", "the", "symbol", "in", "an", "AST", "instance", "and", "left", "and", "right", "to", "the", "given", "ones" ]
python
train
28.538462
pgmpy/pgmpy
pgmpy/estimators/ExhaustiveSearch.py
https://github.com/pgmpy/pgmpy/blob/9381a66aba3c3871d3ccd00672b148d17d63239e/pgmpy/estimators/ExhaustiveSearch.py#L49-L99
def all_dags(self, nodes=None): """ Computes all possible directed acyclic graphs with a given set of nodes, sparse ones first. `2**(n*(n-1))` graphs need to be searched, given `n` nodes, so this is likely not feasible for n>6. This is a generator. Parameters ---------- ...
[ "def", "all_dags", "(", "self", ",", "nodes", "=", "None", ")", ":", "if", "nodes", "is", "None", ":", "nodes", "=", "sorted", "(", "self", ".", "state_names", ".", "keys", "(", ")", ")", "if", "len", "(", "nodes", ")", ">", "6", ":", "warn", "...
Computes all possible directed acyclic graphs with a given set of nodes, sparse ones first. `2**(n*(n-1))` graphs need to be searched, given `n` nodes, so this is likely not feasible for n>6. This is a generator. Parameters ---------- nodes: list of nodes for the DAGs (optional)...
[ "Computes", "all", "possible", "directed", "acyclic", "graphs", "with", "a", "given", "set", "of", "nodes", "sparse", "ones", "first", ".", "2", "**", "(", "n", "*", "(", "n", "-", "1", "))", "graphs", "need", "to", "be", "searched", "given", "n", "n...
python
train
43.176471
ray-project/ray
examples/resnet/resnet_model.py
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/examples/resnet/resnet_model.py#L49-L59
def build_graph(self): """Build a whole graph for the model.""" self.global_step = tf.Variable(0, trainable=False) self._build_model() if self.mode == "train": self._build_train_op() else: # Additional initialization for the test network. self....
[ "def", "build_graph", "(", "self", ")", ":", "self", ".", "global_step", "=", "tf", ".", "Variable", "(", "0", ",", "trainable", "=", "False", ")", "self", ".", "_build_model", "(", ")", "if", "self", ".", "mode", "==", "\"train\"", ":", "self", ".",...
Build a whole graph for the model.
[ "Build", "a", "whole", "graph", "for", "the", "model", "." ]
python
train
40.636364
Fantomas42/django-blog-zinnia
zinnia/templating.py
https://github.com/Fantomas42/django-blog-zinnia/blob/b4949304b104a8e1a7a7a0773cbfd024313c3a15/zinnia/templating.py#L7-L13
def append_position(path, position, separator=''): """ Concatenate a path and a position, between the filename and the extension. """ filename, extension = os.path.splitext(path) return ''.join([filename, separator, str(position), extension])
[ "def", "append_position", "(", "path", ",", "position", ",", "separator", "=", "''", ")", ":", "filename", ",", "extension", "=", "os", ".", "path", ".", "splitext", "(", "path", ")", "return", "''", ".", "join", "(", "[", "filename", ",", "separator",...
Concatenate a path and a position, between the filename and the extension.
[ "Concatenate", "a", "path", "and", "a", "position", "between", "the", "filename", "and", "the", "extension", "." ]
python
train
37.142857
pyGrowler/Growler
growler/http/response.py
https://github.com/pyGrowler/Growler/blob/90c923ff204f28b86a01d741224987a22f69540f/growler/http/response.py#L328-L345
def update(self, *args, **kwargs): """ Equivalent to the python dict update method. Update the dictionary with the key/value pairs from other, overwriting existing keys. Args: other (dict): The source of key value pairs to add to headers Keyword Args: ...
[ "def", "update", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "for", "next_dict", "in", "chain", "(", "args", ",", "(", "kwargs", ",", ")", ")", ":", "for", "k", ",", "v", "in", "next_dict", ".", "items", "(", ")", ":", "...
Equivalent to the python dict update method. Update the dictionary with the key/value pairs from other, overwriting existing keys. Args: other (dict): The source of key value pairs to add to headers Keyword Args: All keyword arguments are stored in header direct...
[ "Equivalent", "to", "the", "python", "dict", "update", "method", "." ]
python
train
29.333333
googledatalab/pydatalab
google/datalab/contrib/mlworkbench/_prediction_explainer.py
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/contrib/mlworkbench/_prediction_explainer.py#L334-L414
def probe_image(self, labels, instance, column_name=None, num_scaled_images=50, top_percent=10): """ Get pixel importance of the image. It performs pixel sensitivity analysis by showing only the most important pixels to a certain label in the image. It uses integrated gradie...
[ "def", "probe_image", "(", "self", ",", "labels", ",", "instance", ",", "column_name", "=", "None", ",", "num_scaled_images", "=", "50", ",", "top_percent", "=", "10", ")", ":", "if", "len", "(", "self", ".", "_image_columns", ")", ">", "1", "and", "no...
Get pixel importance of the image. It performs pixel sensitivity analysis by showing only the most important pixels to a certain label in the image. It uses integrated gradients to measure the importance of each pixel. Args: labels: labels to compute gradients from. ...
[ "Get", "pixel", "importance", "of", "the", "image", "." ]
python
train
47.481481
The-Politico/politico-civic-election-night
electionnight/serializers/election_day.py
https://github.com/The-Politico/politico-civic-election-night/blob/a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6/electionnight/serializers/election_day.py#L36-L42
def get_special_elections(self, obj): """States holding a special election on election day.""" return reverse( 'electionnight_api_special-election-list', request=self.context['request'], kwargs={'date': obj.date} )
[ "def", "get_special_elections", "(", "self", ",", "obj", ")", ":", "return", "reverse", "(", "'electionnight_api_special-election-list'", ",", "request", "=", "self", ".", "context", "[", "'request'", "]", ",", "kwargs", "=", "{", "'date'", ":", "obj", ".", ...
States holding a special election on election day.
[ "States", "holding", "a", "special", "election", "on", "election", "day", "." ]
python
train
38.285714
CityOfZion/neo-python
neo/Core/TX/Transaction.py
https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Core/TX/Transaction.py#L148-L162
def ToJson(self, index): """ Convert object members to a dictionary that can be parsed as JSON. Args: index (int): The index of the output in a transaction Returns: dict: """ return { 'n': index, 'asset': self.AssetId.To0x...
[ "def", "ToJson", "(", "self", ",", "index", ")", ":", "return", "{", "'n'", ":", "index", ",", "'asset'", ":", "self", ".", "AssetId", ".", "To0xString", "(", ")", ",", "'value'", ":", "self", ".", "Value", ".", "ToNeoJsonString", "(", ")", ",", "'...
Convert object members to a dictionary that can be parsed as JSON. Args: index (int): The index of the output in a transaction Returns: dict:
[ "Convert", "object", "members", "to", "a", "dictionary", "that", "can", "be", "parsed", "as", "JSON", ".", "Args", ":", "index", "(", "int", ")", ":", "The", "index", "of", "the", "output", "in", "a", "transaction" ]
python
train
27.466667
tornadoweb/tornado
tornado/netutil.py
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/netutil.py#L591-L614
def ssl_wrap_socket( socket: socket.socket, ssl_options: Union[Dict[str, Any], ssl.SSLContext], server_hostname: str = None, **kwargs: Any ) -> ssl.SSLSocket: """Returns an ``ssl.SSLSocket`` wrapping the given socket. ``ssl_options`` may be either an `ssl.SSLContext` object or a dictionary ...
[ "def", "ssl_wrap_socket", "(", "socket", ":", "socket", ".", "socket", ",", "ssl_options", ":", "Union", "[", "Dict", "[", "str", ",", "Any", "]", ",", "ssl", ".", "SSLContext", "]", ",", "server_hostname", ":", "str", "=", "None", ",", "*", "*", "kw...
Returns an ``ssl.SSLSocket`` wrapping the given socket. ``ssl_options`` may be either an `ssl.SSLContext` object or a dictionary (as accepted by `ssl_options_to_context`). Additional keyword arguments are passed to ``wrap_socket`` (either the `~ssl.SSLContext` method or the `ssl` module function as ...
[ "Returns", "an", "ssl", ".", "SSLSocket", "wrapping", "the", "given", "socket", "." ]
python
train
42.708333
pyupio/changelogs
changelogs/finder.py
https://github.com/pyupio/changelogs/blob/0cdb929ac4546c766cd7eef9ae4eb4baaa08f452/changelogs/finder.py#L23-L43
def validate_repo_url(url): """ Validates and formats `url` to be valid URL pointing to a repo on bitbucket.org or github.com :param url: str, URL :return: str, valid URL if valid repo, emptry string otherwise """ try: if "github.com" in url: return re.findall(r"https?://w?w?...
[ "def", "validate_repo_url", "(", "url", ")", ":", "try", ":", "if", "\"github.com\"", "in", "url", ":", "return", "re", ".", "findall", "(", "r\"https?://w?w?w?.?github.com/[\\w\\-]+/[\\w.-]+\"", ",", "url", ")", "[", "0", "]", "elif", "\"bitbucket.org\"", "in",...
Validates and formats `url` to be valid URL pointing to a repo on bitbucket.org or github.com :param url: str, URL :return: str, valid URL if valid repo, emptry string otherwise
[ "Validates", "and", "formats", "url", "to", "be", "valid", "URL", "pointing", "to", "a", "repo", "on", "bitbucket", ".", "org", "or", "github", ".", "com", ":", "param", "url", ":", "str", "URL", ":", "return", ":", "str", "valid", "URL", "if", "vali...
python
train
44.380952
jazzband/django-pipeline
pipeline/views.py
https://github.com/jazzband/django-pipeline/blob/3cd2f93bb47bf8d34447e13ff691f7027e7b07a2/pipeline/views.py#L11-L38
def serve_static(request, path, insecure=False, **kwargs): """Collect and serve static files. This view serves up static files, much like Django's :py:func:`~django.views.static.serve` view, with the addition that it collects static files first (if enabled). This allows images, fonts, and other ass...
[ "def", "serve_static", "(", "request", ",", "path", ",", "insecure", "=", "False", ",", "*", "*", "kwargs", ")", ":", "# Follow the same logic Django uses for determining access to the", "# static-serving view.", "if", "not", "django_settings", ".", "DEBUG", "and", "n...
Collect and serve static files. This view serves up static files, much like Django's :py:func:`~django.views.static.serve` view, with the addition that it collects static files first (if enabled). This allows images, fonts, and other assets to be served up without first loading a page using the ``{...
[ "Collect", "and", "serve", "static", "files", "." ]
python
train
50.178571
alfredodeza/notario
notario/engine.py
https://github.com/alfredodeza/notario/blob/d5dc2edfcb75d9291ced3f2551f368c35dd31475/notario/engine.py#L121-L129
def key_leaf(self, data, schema, tree): """ The deepest validation we can make in any given circumstance for a key. Does not recurse, it will just receive both values and the tree, passing them on to the :fun:`enforce` function. """ key, value = data schema_key, s...
[ "def", "key_leaf", "(", "self", ",", "data", ",", "schema", ",", "tree", ")", ":", "key", ",", "value", "=", "data", "schema_key", ",", "schema_value", "=", "schema", "enforce", "(", "key", ",", "schema_key", ",", "tree", ",", "'key'", ")" ]
The deepest validation we can make in any given circumstance for a key. Does not recurse, it will just receive both values and the tree, passing them on to the :fun:`enforce` function.
[ "The", "deepest", "validation", "we", "can", "make", "in", "any", "given", "circumstance", "for", "a", "key", ".", "Does", "not", "recurse", "it", "will", "just", "receive", "both", "values", "and", "the", "tree", "passing", "them", "on", "to", "the", ":...
python
train
42
esafak/mca
src/mca.py
https://github.com/esafak/mca/blob/f2b79ecbf37629902ccdbad2e1a556977c53d370/src/mca.py#L95-L119
def fs_r(self, percent=0.9, N=None): """Get the row factor scores (dimensionality-reduced representation), choosing how many factors to retain, directly or based on the explained variance. 'percent': The minimum variance that the retained factors are required to explain (default: 90% = 0.9) 'N': The ...
[ "def", "fs_r", "(", "self", ",", "percent", "=", "0.9", ",", "N", "=", "None", ")", ":", "if", "not", "0", "<=", "percent", "<=", "1", ":", "raise", "ValueError", "(", "\"Percent should be a real number between 0 and 1.\"", ")", "if", "N", ":", "if", "no...
Get the row factor scores (dimensionality-reduced representation), choosing how many factors to retain, directly or based on the explained variance. 'percent': The minimum variance that the retained factors are required to explain (default: 90% = 0.9) 'N': The number of factors to retain. Overrides 'pe...
[ "Get", "the", "row", "factor", "scores", "(", "dimensionality", "-", "reduced", "representation", ")", "choosing", "how", "many", "factors", "to", "retain", "directly", "or", "based", "on", "the", "explained", "variance", "." ]
python
train
42.72
edx/edx-enterprise
enterprise/management/commands/assign_enterprise_user_roles.py
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/management/commands/assign_enterprise_user_roles.py#L131-L171
def _assign_enterprise_role_to_users(self, _get_batch_method, options, is_feature_role=False): """ Assigns enterprise role to users. """ role_name = options['role'] batch_limit = options['batch_limit'] batch_sleep = options['batch_sleep'] batch_offset = options['b...
[ "def", "_assign_enterprise_role_to_users", "(", "self", ",", "_get_batch_method", ",", "options", ",", "is_feature_role", "=", "False", ")", ":", "role_name", "=", "options", "[", "'role'", "]", "batch_limit", "=", "options", "[", "'batch_limit'", "]", "batch_slee...
Assigns enterprise role to users.
[ "Assigns", "enterprise", "role", "to", "users", "." ]
python
valid
34.829268
orb-framework/orb
orb/core/model.py
https://github.com/orb-framework/orb/blob/575be2689cb269e65a0a2678232ff940acc19e5a/orb/core/model.py#L1011-L1024
def callbacks(cls, eventType=None): """ Returns a list of callback methods that can be invoked whenever an event is processed. :return: {subclass of <Event>: <list>, ..} """ key = '_{0}__callbacks'.format(cls.__name__) try: callbacks = getattr(cls, key) ...
[ "def", "callbacks", "(", "cls", ",", "eventType", "=", "None", ")", ":", "key", "=", "'_{0}__callbacks'", ".", "format", "(", "cls", ".", "__name__", ")", "try", ":", "callbacks", "=", "getattr", "(", "cls", ",", "key", ")", "except", "AttributeError", ...
Returns a list of callback methods that can be invoked whenever an event is processed. :return: {subclass of <Event>: <list>, ..}
[ "Returns", "a", "list", "of", "callback", "methods", "that", "can", "be", "invoked", "whenever", "an", "event", "is", "processed", "." ]
python
train
34.642857
chaoss/grimoirelab-sortinghat
sortinghat/db/api.py
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/db/api.py#L116-L133
def find_country(session, code): """Find a country. Find a country by its ISO-3166 `code` (i.e ES for Spain, US for United States of America) using the given `session. When the country does not exist the function will return `None`. :param session: database session :param code: ISO-3166 co...
[ "def", "find_country", "(", "session", ",", "code", ")", ":", "country", "=", "session", ".", "query", "(", "Country", ")", ".", "filter", "(", "Country", ".", "code", "==", "code", ")", ".", "first", "(", ")", "return", "country" ]
Find a country. Find a country by its ISO-3166 `code` (i.e ES for Spain, US for United States of America) using the given `session. When the country does not exist the function will return `None`. :param session: database session :param code: ISO-3166 code of the country to find :return: ...
[ "Find", "a", "country", "." ]
python
train
28.833333
ryanjdillon/pyotelem
pyotelem/plots/plotdives.py
https://github.com/ryanjdillon/pyotelem/blob/816563a9c3feb3fa416f1c2921c6b75db34111ad/pyotelem/plots/plotdives.py#L160-L203
def plot_triaxial_depths_speed(tag): '''Plot triaxial accelerometer data for whole deployment, descents, and ascents Only x and z axes are ploted since these are associated with stroking Args ---- tag: pandas.DataFrame Tag dataframe with acceleromter, depth, and propeller columns '...
[ "def", "plot_triaxial_depths_speed", "(", "tag", ")", ":", "import", "numpy", "from", ".", "import", "plotutils", "# TODO return to multiple inputs rather than dataframe", "fig", ",", "axes", "=", "plt", ".", "subplots", "(", "3", ",", "3", ",", "sharex", "=", "...
Plot triaxial accelerometer data for whole deployment, descents, and ascents Only x and z axes are ploted since these are associated with stroking Args ---- tag: pandas.DataFrame Tag dataframe with acceleromter, depth, and propeller columns
[ "Plot", "triaxial", "accelerometer", "data", "for", "whole", "deployment", "descents", "and", "ascents" ]
python
train
32.772727
jepegit/cellpy
cellpy/utils/batch_tools/dumpers.py
https://github.com/jepegit/cellpy/blob/9f4a84cdd11f72cfa02cda8c2d7b5174abbb7370/cellpy/utils/batch_tools/dumpers.py#L54-L75
def ram_dumper(**kwargs): """Dump data to 'memory' for later usage.""" logging.debug("trying to save stuff in memory") farms = kwargs["farms"] experiments = kwargs["experiments"] engine = kwargs["engine"] try: engine_name = engine.__name__ except AttributeError: engine_name ...
[ "def", "ram_dumper", "(", "*", "*", "kwargs", ")", ":", "logging", ".", "debug", "(", "\"trying to save stuff in memory\"", ")", "farms", "=", "kwargs", "[", "\"farms\"", "]", "experiments", "=", "kwargs", "[", "\"experiments\"", "]", "engine", "=", "kwargs", ...
Dump data to 'memory' for later usage.
[ "Dump", "data", "to", "memory", "for", "later", "usage", "." ]
python
train
36.636364
kensho-technologies/graphql-compiler
graphql_compiler/compiler/helpers.py
https://github.com/kensho-technologies/graphql-compiler/blob/f6079c6d10f64932f6b3af309b79bcea2123ca8f/graphql_compiler/compiler/helpers.py#L45-L53
def get_ast_field_name(ast): """Return the normalized field name for the given AST node.""" replacements = { # We always rewrite the following field names into their proper underlying counterparts. TYPENAME_META_FIELD_NAME: '@class' } base_field_name = ast.name.value normalized_name ...
[ "def", "get_ast_field_name", "(", "ast", ")", ":", "replacements", "=", "{", "# We always rewrite the following field names into their proper underlying counterparts.", "TYPENAME_META_FIELD_NAME", ":", "'@class'", "}", "base_field_name", "=", "ast", ".", "name", ".", "value",...
Return the normalized field name for the given AST node.
[ "Return", "the", "normalized", "field", "name", "for", "the", "given", "AST", "node", "." ]
python
train
43.444444
wbond/oscrypto
oscrypto/_osx/symmetric.py
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_osx/symmetric.py#L493-L531
def des_cbc_pkcs5_decrypt(key, data, iv): """ Decrypts DES ciphertext using a 56 bit key :param key: The encryption key - a byte string 8 bytes long (includes error correction bits) :param data: The ciphertext - a byte string :param iv: The initialization vector used for e...
[ "def", "des_cbc_pkcs5_decrypt", "(", "key", ",", "data", ",", "iv", ")", ":", "if", "len", "(", "key", ")", "!=", "8", ":", "raise", "ValueError", "(", "pretty_message", "(", "'''\n key must be 8 bytes (56 bits + 8 parity bits) long - is %s\n '''",...
Decrypts DES ciphertext using a 56 bit key :param key: The encryption key - a byte string 8 bytes long (includes error correction bits) :param data: The ciphertext - a byte string :param iv: The initialization vector used for encryption - a byte string :raises: ValueE...
[ "Decrypts", "DES", "ciphertext", "using", "a", "56", "bit", "key" ]
python
valid
27.153846
etingof/pysnmp
pysnmp/smi/instrum.py
https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/instrum.py#L375-L381
def _defaultErrorHandler(varBinds, **context): """Raise exception on any error if user callback is missing""" errors = context.get('errors') if errors: err = errors[-1] raise err['error']
[ "def", "_defaultErrorHandler", "(", "varBinds", ",", "*", "*", "context", ")", ":", "errors", "=", "context", ".", "get", "(", "'errors'", ")", "if", "errors", ":", "err", "=", "errors", "[", "-", "1", "]", "raise", "err", "[", "'error'", "]" ]
Raise exception on any error if user callback is missing
[ "Raise", "exception", "on", "any", "error", "if", "user", "callback", "is", "missing" ]
python
train
32.857143
guma44/GEOparse
GEOparse/GEOTypes.py
https://github.com/guma44/GEOparse/blob/7ee8d5b8678d780382a6bf884afa69d2033f5ca0/GEOparse/GEOTypes.py#L331-L367
def annotate(self, gpl, annotation_column, gpl_on="ID", gsm_on="ID_REF", in_place=False): """Annotate GSM with provided GPL Args: gpl (:obj:`pandas.DataFrame`): A Platform or DataFrame to annotate with annotation_column (str`): Column in a table for annotation ...
[ "def", "annotate", "(", "self", ",", "gpl", ",", "annotation_column", ",", "gpl_on", "=", "\"ID\"", ",", "gsm_on", "=", "\"ID_REF\"", ",", "in_place", "=", "False", ")", ":", "if", "isinstance", "(", "gpl", ",", "GPL", ")", ":", "annotation_table", "=", ...
Annotate GSM with provided GPL Args: gpl (:obj:`pandas.DataFrame`): A Platform or DataFrame to annotate with annotation_column (str`): Column in a table for annotation gpl_on (:obj:`str`): Use this column in GSM to merge. Defaults to "ID". gsm_on (:obj:`str`): Us...
[ "Annotate", "GSM", "with", "provided", "GPL" ]
python
train
36.324324
wonambi-python/wonambi
wonambi/widgets/notes.py
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/notes.py#L1577-L1596
def export(self, xformat='csv'): """action: export annotations to CSV.""" if self.annot is None: # remove if buttons are disabled self.parent.statusBar().showMessage('No score file loaded') return if xformat == 'csv': filename = splitext(self.annot.xml_file)...
[ "def", "export", "(", "self", ",", "xformat", "=", "'csv'", ")", ":", "if", "self", ".", "annot", "is", "None", ":", "# remove if buttons are disabled", "self", ".", "parent", ".", "statusBar", "(", ")", ".", "showMessage", "(", "'No score file loaded'", ")"...
action: export annotations to CSV.
[ "action", ":", "export", "annotations", "to", "CSV", "." ]
python
train
47.5
RPi-Distro/python-gpiozero
gpiozero/tools.py
https://github.com/RPi-Distro/python-gpiozero/blob/7b67374fd0c8c4fde5586d9bad9531f076db9c0c/gpiozero/tools.py#L652-L676
def cos_values(period=360): """ Provides an infinite source of values representing a cosine wave (from -1 to +1) which repeats every *period* values. For example, to produce a "siren" effect with a couple of LEDs that repeats once a second:: from gpiozero import PWMLED from gpiozero.too...
[ "def", "cos_values", "(", "period", "=", "360", ")", ":", "angles", "=", "(", "2", "*", "pi", "*", "i", "/", "period", "for", "i", "in", "range", "(", "period", ")", ")", "for", "a", "in", "cycle", "(", "angles", ")", ":", "yield", "cos", "(", ...
Provides an infinite source of values representing a cosine wave (from -1 to +1) which repeats every *period* values. For example, to produce a "siren" effect with a couple of LEDs that repeats once a second:: from gpiozero import PWMLED from gpiozero.tools import cos_values, scaled, inverted ...
[ "Provides", "an", "infinite", "source", "of", "values", "representing", "a", "cosine", "wave", "(", "from", "-", "1", "to", "+", "1", ")", "which", "repeats", "every", "*", "period", "*", "values", ".", "For", "example", "to", "produce", "a", "siren", ...
python
train
31.76
fastavro/fastavro
fastavro/_write_py.py
https://github.com/fastavro/fastavro/blob/bafe826293e19eb93e77bbb0f6adfa059c7884b2/fastavro/_write_py.py#L543-L633
def writer(fo, schema, records, codec='null', sync_interval=1000 * SYNC_SIZE, metadata=None, validator=None, sync_marker=None): """Write records to fo (stream) according to schema Parameters ---------- fo: file-like Ou...
[ "def", "writer", "(", "fo", ",", "schema", ",", "records", ",", "codec", "=", "'null'", ",", "sync_interval", "=", "1000", "*", "SYNC_SIZE", ",", "metadata", "=", "None", ",", "validator", "=", "None", ",", "sync_marker", "=", "None", ")", ":", "# Sani...
Write records to fo (stream) according to schema Parameters ---------- fo: file-like Output stream records: iterable Records to write. This is commonly a list of the dictionary representation of the records, but it can be any iterable codec: string, optional Compress...
[ "Write", "records", "to", "fo", "(", "stream", ")", "according", "to", "schema" ]
python
train
32.956044
chaoss/grimoirelab-manuscripts
manuscripts2/elasticsearch.py
https://github.com/chaoss/grimoirelab-manuscripts/blob/94a3ad4f11bfbcd6c5190e01cb5d3e47a5187cd9/manuscripts2/elasticsearch.py#L617-L645
def calculate_bmi(closed, submitted): """ BMI is the ratio of the number of closed items to the number of total items submitted in a particular period of analysis. The items can be issues, pull requests and such :param closed: dataframe returned from get_timeseries() containing closed items :pa...
[ "def", "calculate_bmi", "(", "closed", ",", "submitted", ")", ":", "if", "sorted", "(", "closed", ".", "keys", "(", ")", ")", "!=", "sorted", "(", "submitted", ".", "keys", "(", ")", ")", ":", "raise", "AttributeError", "(", "\"The buckets supplied are not...
BMI is the ratio of the number of closed items to the number of total items submitted in a particular period of analysis. The items can be issues, pull requests and such :param closed: dataframe returned from get_timeseries() containing closed items :param submitted: dataframe returned from get_timeser...
[ "BMI", "is", "the", "ratio", "of", "the", "number", "of", "closed", "items", "to", "the", "number", "of", "total", "items", "submitted", "in", "a", "particular", "period", "of", "analysis", ".", "The", "items", "can", "be", "issues", "pull", "requests", ...
python
train
40.068966
openstack/networking-cisco
networking_cisco/plugins/cisco/device_manager/rpc/devices_cfgagent_rpc_cb.py
https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/device_manager/rpc/devices_cfgagent_rpc_cb.py#L87-L104
def get_hosting_devices_for_agent(self, context, host): """Fetches routers that a Cisco cfg agent is managing. This function is supposed to be called when the agent has started, is ready to take on assignments and before any callbacks to fetch logical resources are issued. :par...
[ "def", "get_hosting_devices_for_agent", "(", "self", ",", "context", ",", "host", ")", ":", "agent_ids", "=", "self", ".", "_dmplugin", ".", "get_cfg_agents", "(", "context", ",", "active", "=", "None", ",", "filters", "=", "{", "'host'", ":", "[", "host",...
Fetches routers that a Cisco cfg agent is managing. This function is supposed to be called when the agent has started, is ready to take on assignments and before any callbacks to fetch logical resources are issued. :param context: contains user information :param host: originat...
[ "Fetches", "routers", "that", "a", "Cisco", "cfg", "agent", "is", "managing", "." ]
python
train
48.611111
neighbordog/deviantart
deviantart/api.py
https://github.com/neighbordog/deviantart/blob/5612f1d5e2139a48c9d793d7fd19cde7e162d7b1/deviantart/api.py#L520-L574
def get_collections(self, username="", calculate_size=False, ext_preload=False, offset=0, limit=10): """Fetch collection folders :param username: The user to list folders for, if omitted the authenticated user is used :param calculate_size: The option to include the content count per each coll...
[ "def", "get_collections", "(", "self", ",", "username", "=", "\"\"", ",", "calculate_size", "=", "False", ",", "ext_preload", "=", "False", ",", "offset", "=", "0", ",", "limit", "=", "10", ")", ":", "if", "not", "username", "and", "self", ".", "standa...
Fetch collection folders :param username: The user to list folders for, if omitted the authenticated user is used :param calculate_size: The option to include the content count per each collection folder :param ext_preload: Include first 5 deviations from the folder :param offset: the p...
[ "Fetch", "collection", "folders" ]
python
train
33.963636
bitesofcode/projexui
projexui/widgets/xtextedit.py
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xtextedit.py#L320-L379
def getText(cls, parent=None, windowTitle='Get Text', label='', text='', plain=True, wrapped=True): """ Prompts the user for a text entry using the text edit class. :param pare...
[ "def", "getText", "(", "cls", ",", "parent", "=", "None", ",", "windowTitle", "=", "'Get Text'", ",", "label", "=", "''", ",", "text", "=", "''", ",", "plain", "=", "True", ",", "wrapped", "=", "True", ")", ":", "# create the dialog\r", "dlg", "=", "...
Prompts the user for a text entry using the text edit class. :param parent | <QWidget> windowTitle | <str> label | <str> text | <str> plain | <bool> | return plain text or not ...
[ "Prompts", "the", "user", "for", "a", "text", "entry", "using", "the", "text", "edit", "class", ".", ":", "param", "parent", "|", "<QWidget", ">", "windowTitle", "|", "<str", ">", "label", "|", "<str", ">", "text", "|", "<str", ">", "plain", "|", "<b...
python
train
29.216667
Opentrons/opentrons
api/src/opentrons/drivers/smoothie_drivers/driver_3_0.py
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/drivers/smoothie_drivers/driver_3_0.py#L761-L778
def dwell_axes(self, axes): ''' Sets motors to low current, for when they are not moving. Dwell for XYZA axes is only called after HOMING Dwell for BC axes is called after both HOMING and MOVING axes: String containing the axes to set to low current (eg: 'XYZABC') ...
[ "def", "dwell_axes", "(", "self", ",", "axes", ")", ":", "axes", "=", "''", ".", "join", "(", "set", "(", "axes", ")", "&", "set", "(", "AXES", ")", "-", "set", "(", "DISABLE_AXES", ")", ")", "dwelling_currents", "=", "{", "ax", ":", "self", ".",...
Sets motors to low current, for when they are not moving. Dwell for XYZA axes is only called after HOMING Dwell for BC axes is called after both HOMING and MOVING axes: String containing the axes to set to low current (eg: 'XYZABC')
[ "Sets", "motors", "to", "low", "current", "for", "when", "they", "are", "not", "moving", "." ]
python
train
36.055556
Unidata/MetPy
metpy/calc/kinematics.py
https://github.com/Unidata/MetPy/blob/16f68a94919b9a82dcf9cada2169cf039129e67b/metpy/calc/kinematics.py#L337-L399
def frontogenesis(thta, u, v, dx, dy, dim_order='yx'): r"""Calculate the 2D kinematic frontogenesis of a temperature field. The implementation is a form of the Petterssen Frontogenesis and uses the formula outlined in [Bluestein1993]_ pg.248-253. .. math:: F=\frac{1}{2}\left|\nabla \theta\right|[D cos...
[ "def", "frontogenesis", "(", "thta", ",", "u", ",", "v", ",", "dx", ",", "dy", ",", "dim_order", "=", "'yx'", ")", ":", "# Get gradients of potential temperature in both x and y", "ddy_thta", "=", "first_derivative", "(", "thta", ",", "delta", "=", "dy", ",", ...
r"""Calculate the 2D kinematic frontogenesis of a temperature field. The implementation is a form of the Petterssen Frontogenesis and uses the formula outlined in [Bluestein1993]_ pg.248-253. .. math:: F=\frac{1}{2}\left|\nabla \theta\right|[D cos(2\beta)-\delta] * :math:`F` is 2D kinematic frontogen...
[ "r", "Calculate", "the", "2D", "kinematic", "frontogenesis", "of", "a", "temperature", "field", "." ]
python
train
38.857143
ejeschke/ginga
ginga/rv/plugins/Contents.py
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/Contents.py#L305-L320
def add_image_info_cb(self, viewer, channel, image_info): """Almost the same as add_image_cb(), except that the image may not be loaded in memory. """ chname = channel.name name = image_info.name self.logger.debug("name=%s" % (name)) # Updates of any extant infor...
[ "def", "add_image_info_cb", "(", "self", ",", "viewer", ",", "channel", ",", "image_info", ")", ":", "chname", "=", "channel", ".", "name", "name", "=", "image_info", ".", "name", "self", ".", "logger", ".", "debug", "(", "\"name=%s\"", "%", "(", "name",...
Almost the same as add_image_cb(), except that the image may not be loaded in memory.
[ "Almost", "the", "same", "as", "add_image_cb", "()", "except", "that", "the", "image", "may", "not", "be", "loaded", "in", "memory", "." ]
python
train
35.0625
adafruit/Adafruit_Python_PureIO
Adafruit_PureIO/smbus.py
https://github.com/adafruit/Adafruit_Python_PureIO/blob/6f4976d91c52d70b67b28bba75a429b5328a52c1/Adafruit_PureIO/smbus.py#L201-L216
def read_i2c_block_data(self, addr, cmd, length=32): """Perform a read from the specified cmd register of device. Length number of bytes (default of 32) will be read and returned as a bytearray. """ assert self._device is not None, 'Bus must be opened before operations are made against ...
[ "def", "read_i2c_block_data", "(", "self", ",", "addr", ",", "cmd", ",", "length", "=", "32", ")", ":", "assert", "self", ".", "_device", "is", "not", "None", ",", "'Bus must be opened before operations are made against it!'", "# Build ctypes values to marshall between ...
Perform a read from the specified cmd register of device. Length number of bytes (default of 32) will be read and returned as a bytearray.
[ "Perform", "a", "read", "from", "the", "specified", "cmd", "register", "of", "device", ".", "Length", "number", "of", "bytes", "(", "default", "of", "32", ")", "will", "be", "read", "and", "returned", "as", "a", "bytearray", "." ]
python
test
52
vilmibm/done
parsedatetime/parsedatetime_consts.py
https://github.com/vilmibm/done/blob/7e5b60d2900ceddefa49de352a19b794199b51a8/parsedatetime/parsedatetime_consts.py#L601-L707
def _initSymbols(ptc): """ Helper function to initialize the single character constants and other symbols needed. """ ptc.timeSep = [ u':' ] ptc.dateSep = [ u'/' ] ptc.meridian = [ u'AM', u'PM' ] ptc.usesMeridian = True ptc.uses24 = False if pyicu and ptc.usePyICU: ...
[ "def", "_initSymbols", "(", "ptc", ")", ":", "ptc", ".", "timeSep", "=", "[", "u':'", "]", "ptc", ".", "dateSep", "=", "[", "u'/'", "]", "ptc", ".", "meridian", "=", "[", "u'AM'", ",", "u'PM'", "]", "ptc", ".", "usesMeridian", "=", "True", "ptc", ...
Helper function to initialize the single character constants and other symbols needed.
[ "Helper", "function", "to", "initialize", "the", "single", "character", "constants", "and", "other", "symbols", "needed", "." ]
python
train
25.457944
gabstopper/smc-python
smc/routing/bgp.py
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/routing/bgp.py#L393-L420
def create(cls, name, port=179, external_distance=20, internal_distance=200, local_distance=200, subnet_distance=None): """ Create a custom BGP Profile :param str name: name of profile :param int port: port for BGP process :param int external_distance: external ad...
[ "def", "create", "(", "cls", ",", "name", ",", "port", "=", "179", ",", "external_distance", "=", "20", ",", "internal_distance", "=", "200", ",", "local_distance", "=", "200", ",", "subnet_distance", "=", "None", ")", ":", "json", "=", "{", "'name'", ...
Create a custom BGP Profile :param str name: name of profile :param int port: port for BGP process :param int external_distance: external administrative distance; (1-255) :param int internal_distance: internal administrative distance (1-255) :param int local_distance: local admi...
[ "Create", "a", "custom", "BGP", "Profile" ]
python
train
43.5
twisted/txacme
src/txacme/client.py
https://github.com/twisted/txacme/blob/9478381cc63c6d53d14bf8db8407c923f472989a/src/txacme/client.py#L807-L829
def _add_nonce(self, response): """ Store a nonce from a response we received. :param twisted.web.iweb.IResponse response: The HTTP response. :return: The response, unmodified. """ nonce = response.headers.getRawHeaders( REPLAY_NONCE_HEADER, [None])[0] ...
[ "def", "_add_nonce", "(", "self", ",", "response", ")", ":", "nonce", "=", "response", ".", "headers", ".", "getRawHeaders", "(", "REPLAY_NONCE_HEADER", ",", "[", "None", "]", ")", "[", "0", "]", "with", "LOG_JWS_ADD_NONCE", "(", "raw_nonce", "=", "nonce",...
Store a nonce from a response we received. :param twisted.web.iweb.IResponse response: The HTTP response. :return: The response, unmodified.
[ "Store", "a", "nonce", "from", "a", "response", "we", "received", "." ]
python
train
37.608696
explosion/spaCy
examples/training/train_textcat.py
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/examples/training/train_textcat.py#L120-L129
def load_data(limit=0, split=0.8): """Load data from the IMDB dataset.""" # Partition off part of the train data for evaluation train_data, _ = thinc.extra.datasets.imdb() random.shuffle(train_data) train_data = train_data[-limit:] texts, labels = zip(*train_data) cats = [{"POSITIVE": bool(y...
[ "def", "load_data", "(", "limit", "=", "0", ",", "split", "=", "0.8", ")", ":", "# Partition off part of the train data for evaluation", "train_data", ",", "_", "=", "thinc", ".", "extra", ".", "datasets", ".", "imdb", "(", ")", "random", ".", "shuffle", "("...
Load data from the IMDB dataset.
[ "Load", "data", "from", "the", "IMDB", "dataset", "." ]
python
train
46.8
log2timeline/dfvfs
dfvfs/vfs/file_entry.py
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/vfs/file_entry.py#L418-L426
def GetStat(self): """Retrieves information about the file entry. Returns: VFSStat: a stat object or None if not available. """ if self._stat_object is None: self._stat_object = self._GetStat() return self._stat_object
[ "def", "GetStat", "(", "self", ")", ":", "if", "self", ".", "_stat_object", "is", "None", ":", "self", ".", "_stat_object", "=", "self", ".", "_GetStat", "(", ")", "return", "self", ".", "_stat_object" ]
Retrieves information about the file entry. Returns: VFSStat: a stat object or None if not available.
[ "Retrieves", "information", "about", "the", "file", "entry", "." ]
python
train
27
fastai/fastai
docs_src/nbval/cover.py
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/docs_src/nbval/cover.py#L98-L106
def get_cov(config): """Returns the coverage object of pytest-cov.""" # Check with hasplugin to avoid getplugin exception in older pytest. if config.pluginmanager.hasplugin('_cov'): plugin = config.pluginmanager.getplugin('_cov') if plugin.cov_controller: return plugin.cov_contr...
[ "def", "get_cov", "(", "config", ")", ":", "# Check with hasplugin to avoid getplugin exception in older pytest.", "if", "config", ".", "pluginmanager", ".", "hasplugin", "(", "'_cov'", ")", ":", "plugin", "=", "config", ".", "pluginmanager", ".", "getplugin", "(", ...
Returns the coverage object of pytest-cov.
[ "Returns", "the", "coverage", "object", "of", "pytest", "-", "cov", "." ]
python
train
37.444444
trailofbits/manticore
manticore/ethereum/detectors.py
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/ethereum/detectors.py#L103-L108
def _get_location(self, state, hash_id): """ Get previously saved location A location is composed of: address, pc, finding, at_init, condition """ return state.context.setdefault('{:s}.locations'.format(self.name), {})[hash_id]
[ "def", "_get_location", "(", "self", ",", "state", ",", "hash_id", ")", ":", "return", "state", ".", "context", ".", "setdefault", "(", "'{:s}.locations'", ".", "format", "(", "self", ".", "name", ")", ",", "{", "}", ")", "[", "hash_id", "]" ]
Get previously saved location A location is composed of: address, pc, finding, at_init, condition
[ "Get", "previously", "saved", "location", "A", "location", "is", "composed", "of", ":", "address", "pc", "finding", "at_init", "condition" ]
python
valid
43.666667
kennedyshead/aioasuswrt
aioasuswrt/connection.py
https://github.com/kennedyshead/aioasuswrt/blob/0c4336433727abbb7b324ee29e4c5382be9aaa2b/aioasuswrt/connection.py#L120-L142
async def async_connect(self): """Connect to the ASUS-WRT Telnet server.""" self._reader, self._writer = await asyncio.open_connection( self._host, self._port) with (await self._io_lock): try: await asyncio.wait_for(self._reader.readuntil(b'login: '), 9) ...
[ "async", "def", "async_connect", "(", "self", ")", ":", "self", ".", "_reader", ",", "self", ".", "_writer", "=", "await", "asyncio", ".", "open_connection", "(", "self", ".", "_host", ",", "self", ".", "_port", ")", "with", "(", "await", "self", ".", ...
Connect to the ASUS-WRT Telnet server.
[ "Connect", "to", "the", "ASUS", "-", "WRT", "Telnet", "server", "." ]
python
train
40.695652
psd-tools/psd-tools
src/psd_tools/api/composer.py
https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/api/composer.py#L307-L332
def _generate_symbol(path, width, height, command='C'): """Sequence generator for SVG path.""" if len(path) == 0: return # Initial point. yield 'M' yield path[0].anchor[1] * width yield path[0].anchor[0] * height yield command # Closed path or open path points = (zip(path, ...
[ "def", "_generate_symbol", "(", "path", ",", "width", ",", "height", ",", "command", "=", "'C'", ")", ":", "if", "len", "(", "path", ")", "==", "0", ":", "return", "# Initial point.", "yield", "'M'", "yield", "path", "[", "0", "]", ".", "anchor", "["...
Sequence generator for SVG path.
[ "Sequence", "generator", "for", "SVG", "path", "." ]
python
train
26.692308
googleapis/google-cloud-python
storage/google/cloud/storage/batch.py
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/batch.py#L191-L218
def _prepare_batch_request(self): """Prepares headers and body for a batch request. :rtype: tuple (dict, str) :returns: The pair of headers and body of the batch request to be sent. :raises: :class:`ValueError` if no requests have been deferred. """ if len(self._requests...
[ "def", "_prepare_batch_request", "(", "self", ")", ":", "if", "len", "(", "self", ".", "_requests", ")", "==", "0", ":", "raise", "ValueError", "(", "\"No deferred requests\"", ")", "multi", "=", "MIMEMultipart", "(", ")", "for", "method", ",", "uri", ",",...
Prepares headers and body for a batch request. :rtype: tuple (dict, str) :returns: The pair of headers and body of the batch request to be sent. :raises: :class:`ValueError` if no requests have been deferred.
[ "Prepares", "headers", "and", "body", "for", "a", "batch", "request", "." ]
python
train
35.321429
mrstephenneal/mysql-toolkit
mysql/toolkit/commands/dump.py
https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/commands/dump.py#L42-L83
def dump_commands(commands, directory=None, sub_dir=None): """ Dump SQL commands to .sql files. :param commands: List of SQL commands :param directory: Directory to dump commands to :param sub_dir: Sub directory :return: Directory failed commands were dumped to """ print('\t' + str(len(...
[ "def", "dump_commands", "(", "commands", ",", "directory", "=", "None", ",", "sub_dir", "=", "None", ")", ":", "print", "(", "'\\t'", "+", "str", "(", "len", "(", "commands", ")", ")", ",", "'failed commands'", ")", "# Create dump_dir directory", "if", "di...
Dump SQL commands to .sql files. :param commands: List of SQL commands :param directory: Directory to dump commands to :param sub_dir: Sub directory :return: Directory failed commands were dumped to
[ "Dump", "SQL", "commands", "to", ".", "sql", "files", "." ]
python
train
39.809524
trailofbits/manticore
manticore/core/smtlib/visitors.py
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/smtlib/visitors.py#L580-L601
def to_constant(expression): """ Iff the expression can be simplified to a Constant get the actual concrete value. This discards/ignore any taint """ value = simplify(expression) if isinstance(value, Expression) and value.taint: raise ValueError("Can not simplify tainted values t...
[ "def", "to_constant", "(", "expression", ")", ":", "value", "=", "simplify", "(", "expression", ")", "if", "isinstance", "(", "value", ",", "Expression", ")", "and", "value", ".", "taint", ":", "raise", "ValueError", "(", "\"Can not simplify tainted values to co...
Iff the expression can be simplified to a Constant get the actual concrete value. This discards/ignore any taint
[ "Iff", "the", "expression", "can", "be", "simplified", "to", "a", "Constant", "get", "the", "actual", "concrete", "value", ".", "This", "discards", "/", "ignore", "any", "taint" ]
python
valid
35.681818
robotpy/pyfrc
lib/pyfrc/sim/field/user_renderer.py
https://github.com/robotpy/pyfrc/blob/7672ea3f17c8d4b702a9f18a7372d95feee7e37d/lib/pyfrc/sim/field/user_renderer.py#L41-L91
def draw_pathfinder_trajectory( self, trajectory, color="#ff0000", offset=None, scale=(1, 1), show_dt=False, dt_offset=0.0, **kwargs ): """ Special helper function for drawing trajectories generated by robotpy-pathfinder...
[ "def", "draw_pathfinder_trajectory", "(", "self", ",", "trajectory", ",", "color", "=", "\"#ff0000\"", ",", "offset", "=", "None", ",", "scale", "=", "(", "1", ",", "1", ")", ",", "show_dt", "=", "False", ",", "dt_offset", "=", "0.0", ",", "*", "*", ...
Special helper function for drawing trajectories generated by robotpy-pathfinder :param trajectory: A list of pathfinder segment objects :param offset: If specified, should be x/y tuple to add to the path relative to the robot coordinates ...
[ "Special", "helper", "function", "for", "drawing", "trajectories", "generated", "by", "robotpy", "-", "pathfinder", ":", "param", "trajectory", ":", "A", "list", "of", "pathfinder", "segment", "objects", ":", "param", "offset", ":", "If", "specified", "should", ...
python
train
35.745098
saltstack/salt
salt/modules/nspawn.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nspawn.py#L190-L208
def _bootstrap_fedora(name, **kwargs): ''' Bootstrap a Fedora container ''' dst = _make_container_root(name) if not kwargs.get('version', False): if __grains__['os'].lower() == 'fedora': version = __grains__['osrelease'] else: version = '21' else: ...
[ "def", "_bootstrap_fedora", "(", "name", ",", "*", "*", "kwargs", ")", ":", "dst", "=", "_make_container_root", "(", "name", ")", "if", "not", "kwargs", ".", "get", "(", "'version'", ",", "False", ")", ":", "if", "__grains__", "[", "'os'", "]", ".", ...
Bootstrap a Fedora container
[ "Bootstrap", "a", "Fedora", "container" ]
python
train
34.526316
gwastro/pycbc
pycbc/workflow/core.py
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/core.py#L1817-L1826
def parse_segdict_key(self, key): """ Return ifo and name from the segdict key. """ splt = key.split(':') if len(splt) == 2: return splt[0], splt[1] else: err_msg = "Key should be of the format 'ifo:name', got %s." %(key,) raise ValueEr...
[ "def", "parse_segdict_key", "(", "self", ",", "key", ")", ":", "splt", "=", "key", ".", "split", "(", "':'", ")", "if", "len", "(", "splt", ")", "==", "2", ":", "return", "splt", "[", "0", "]", ",", "splt", "[", "1", "]", "else", ":", "err_msg"...
Return ifo and name from the segdict key.
[ "Return", "ifo", "and", "name", "from", "the", "segdict", "key", "." ]
python
train
32.3
brocade/pynos
pynos/versions/ver_6/ver_6_0_1/yang/brocade_firmware_ext.py
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_firmware_ext.py#L25-L37
def show_firmware_version_output_show_firmware_version_switchid(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") show_firmware_version = ET.Element("show_firmware_version") config = show_firmware_version output = ET.SubElement(show_firmware_versio...
[ "def", "show_firmware_version_output_show_firmware_version_switchid", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "show_firmware_version", "=", "ET", ".", "Element", "(", "\"show_firmware_version\"", "...
Auto Generated Code
[ "Auto", "Generated", "Code" ]
python
train
46.538462
inveniosoftware/invenio-access
invenio_access/factory.py
https://github.com/inveniosoftware/invenio-access/blob/3b033a4bdc110eb2f7e9f08f0744a780884bfc80/invenio_access/factory.py#L20-L30
def action_factory(name, parameter=False): """Factory method for creating new actions (w/wo parameters). :param name: Name of the action (prefix with your module name). :param parameter: Determines if action should take parameters or not. Default is ``False``. """ if parameter: retu...
[ "def", "action_factory", "(", "name", ",", "parameter", "=", "False", ")", ":", "if", "parameter", ":", "return", "partial", "(", "ParameterizedActionNeed", ",", "name", ")", "else", ":", "return", "ActionNeed", "(", "name", ")" ]
Factory method for creating new actions (w/wo parameters). :param name: Name of the action (prefix with your module name). :param parameter: Determines if action should take parameters or not. Default is ``False``.
[ "Factory", "method", "for", "creating", "new", "actions", "(", "w", "/", "wo", "parameters", ")", "." ]
python
train
35.727273
rbit/pydtls
dtls/__init__.py
https://github.com/rbit/pydtls/blob/41a71fccd990347d0de5f42418fea1e4e733359c/dtls/__init__.py#L37-L59
def _prep_bins(): """ Support for running straight out of a cloned source directory instead of an installed distribution """ from os import path from sys import platform, maxsize from shutil import copy bit_suffix = "-x86_64" if maxsize > 2**32 else "-x86" package_root = path.abspat...
[ "def", "_prep_bins", "(", ")", ":", "from", "os", "import", "path", "from", "sys", "import", "platform", ",", "maxsize", "from", "shutil", "import", "copy", "bit_suffix", "=", "\"-x86_64\"", "if", "maxsize", ">", "2", "**", "32", "else", "\"-x86\"", "packa...
Support for running straight out of a cloned source directory instead of an installed distribution
[ "Support", "for", "running", "straight", "out", "of", "a", "cloned", "source", "directory", "instead", "of", "an", "installed", "distribution" ]
python
train
36.956522
peepall/FancyLogger
FancyLogger/__init__.py
https://github.com/peepall/FancyLogger/blob/7f13f1397e76ed768fb6b6358194118831fafc6d/FancyLogger/__init__.py#L277-L286
def set_level(self, level, console_only=False): """ Defines the logging level (from standard logging module) for log messages. :param level: Level of logging for the file logger. :param console_only: [Optional] If True then the file logger...
[ "def", "set_level", "(", "self", ",", "level", ",", "console_only", "=", "False", ")", ":", "self", ".", "queue", ".", "put", "(", "dill", ".", "dumps", "(", "SetLevelCommand", "(", "level", "=", "level", ",", "console_only", "=", "console_only", ")", ...
Defines the logging level (from standard logging module) for log messages. :param level: Level of logging for the file logger. :param console_only: [Optional] If True then the file logger will not be affected.
[ "Defines", "the", "logging", "level", "(", "from", "standard", "logging", "module", ")", "for", "log", "messages", ".", ":", "param", "level", ":", "Level", "of", "logging", "for", "the", "file", "logger", ".", ":", "param", "console_only", ":", "[", "Op...
python
train
48.7
apple/turicreate
deps/src/libxml2-2.9.1/python/libxml2.py
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L3160-L3166
def copyNodeList(self): """Do a recursive copy of the node list. Use xmlDocCopyNodeList() if possible to ensure string interning. """ ret = libxml2mod.xmlCopyNodeList(self._o) if ret is None:raise treeError('xmlCopyNodeList() failed') __tmp = xmlNode(_obj=ret) return __...
[ "def", "copyNodeList", "(", "self", ")", ":", "ret", "=", "libxml2mod", ".", "xmlCopyNodeList", "(", "self", ".", "_o", ")", "if", "ret", "is", "None", ":", "raise", "treeError", "(", "'xmlCopyNodeList() failed'", ")", "__tmp", "=", "xmlNode", "(", "_obj",...
Do a recursive copy of the node list. Use xmlDocCopyNodeList() if possible to ensure string interning.
[ "Do", "a", "recursive", "copy", "of", "the", "node", "list", ".", "Use", "xmlDocCopyNodeList", "()", "if", "possible", "to", "ensure", "string", "interning", "." ]
python
train
45.285714
pmacosta/pcsv
pcsv/csv_file.py
https://github.com/pmacosta/pcsv/blob/cd1588c19b0cd58c38bc672e396db940f88ffbd7/pcsv/csv_file.py#L596-L643
def dsort(self, order): r""" Sort rows. :param order: Sort order :type order: :ref:`CsvColFilter` .. [[[cog cog.out(exobj.get_sphinx_autodoc()) ]]] .. Auto-generated exceptions documentation for .. pcsv.csv_file.CsvFile.dsort :raises: * Runtim...
[ "def", "dsort", "(", "self", ",", "order", ")", ":", "# Make order conforming to a list of dictionaries", "order", "=", "order", "if", "isinstance", "(", "order", ",", "list", ")", "else", "[", "order", "]", "norder", "=", "[", "{", "item", ":", "\"A\"", "...
r""" Sort rows. :param order: Sort order :type order: :ref:`CsvColFilter` .. [[[cog cog.out(exobj.get_sphinx_autodoc()) ]]] .. Auto-generated exceptions documentation for .. pcsv.csv_file.CsvFile.dsort :raises: * RuntimeError (Argument \`order\` is no...
[ "r", "Sort", "rows", "." ]
python
train
37.958333
wummel/linkchecker
third_party/dnspython/dns/name.py
https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/third_party/dnspython/dns/name.py#L90-L102
def _escapify(label): """Escape the characters in label which need it. @returns: the escaped string @rtype: string""" text = '' for c in label: if c in _escaped: text += '\\' + c elif ord(c) > 0x20 and ord(c) < 0x7F: text += c else: text +=...
[ "def", "_escapify", "(", "label", ")", ":", "text", "=", "''", "for", "c", "in", "label", ":", "if", "c", "in", "_escaped", ":", "text", "+=", "'\\\\'", "+", "c", "elif", "ord", "(", "c", ")", ">", "0x20", "and", "ord", "(", "c", ")", "<", "0...
Escape the characters in label which need it. @returns: the escaped string @rtype: string
[ "Escape", "the", "characters", "in", "label", "which", "need", "it", "." ]
python
train
26.307692
RudolfCardinal/pythonlib
cardinal_pythonlib/tools/remove_duplicate_files.py
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/tools/remove_duplicate_files.py#L53-L186
def deduplicate(directories: List[str], recursive: bool, dummy_run: bool) -> None: """ De-duplicate files within one or more directories. Remove files that are identical to ones already considered. Args: directories: list of directories to process recursive: process subd...
[ "def", "deduplicate", "(", "directories", ":", "List", "[", "str", "]", ",", "recursive", ":", "bool", ",", "dummy_run", ":", "bool", ")", "->", "None", ":", "# -------------------------------------------------------------------------", "# Catalogue files by their size", ...
De-duplicate files within one or more directories. Remove files that are identical to ones already considered. Args: directories: list of directories to process recursive: process subdirectories (recursively)? dummy_run: say what it'll do, but don't do it
[ "De", "-", "duplicate", "files", "within", "one", "or", "more", "directories", ".", "Remove", "files", "that", "are", "identical", "to", "ones", "already", "considered", "." ]
python
train
40.179104
pinterest/pymemcache
pymemcache/client/base.py
https://github.com/pinterest/pymemcache/blob/f3a348f4ce2248cce8b398e93e08d984fb9100e5/pymemcache/client/base.py#L361-L380
def replace(self, key, value, expire=0, noreply=None): """ The memcached "replace" command. Args: key: str, see class docs for details. value: str, see class docs for details. expire: optional int, number of seconds until the item is expired from ...
[ "def", "replace", "(", "self", ",", "key", ",", "value", ",", "expire", "=", "0", ",", "noreply", "=", "None", ")", ":", "if", "noreply", "is", "None", ":", "noreply", "=", "self", ".", "default_noreply", "return", "self", ".", "_store_cmd", "(", "b'...
The memcached "replace" command. Args: key: str, see class docs for details. value: str, see class docs for details. expire: optional int, number of seconds until the item is expired from the cache, or zero for no expiry (the default). noreply: optional...
[ "The", "memcached", "replace", "command", "." ]
python
train
41.45
Unidata/MetPy
metpy/plots/ctables.py
https://github.com/Unidata/MetPy/blob/16f68a94919b9a82dcf9cada2169cf039129e67b/metpy/plots/ctables.py#L167-L179
def add_colortable(self, fobj, name): r"""Add a color table from a file to the registry. Parameters ---------- fobj : file-like object The file to read the color table from name : str The name under which the color table will be stored """ ...
[ "def", "add_colortable", "(", "self", ",", "fobj", ",", "name", ")", ":", "self", "[", "name", "]", "=", "read_colortable", "(", "fobj", ")", "self", "[", "name", "+", "'_r'", "]", "=", "self", "[", "name", "]", "[", ":", ":", "-", "1", "]" ]
r"""Add a color table from a file to the registry. Parameters ---------- fobj : file-like object The file to read the color table from name : str The name under which the color table will be stored
[ "r", "Add", "a", "color", "table", "from", "a", "file", "to", "the", "registry", "." ]
python
train
29.923077
jsvine/spectra
spectra/core.py
https://github.com/jsvine/spectra/blob/2269a0ae9b5923154b15bd661fb81179608f7ec2/spectra/core.py#L223-L238
def range(self, count): """ Create a list of colors evenly spaced along this scale's domain. :param int count: The number of colors to return. :rtype: list :returns: A list of spectra.Color objects. """ if count <= 1: raise ValueError("Range size mus...
[ "def", "range", "(", "self", ",", "count", ")", ":", "if", "count", "<=", "1", ":", "raise", "ValueError", "(", "\"Range size must be greater than 1.\"", ")", "dom", "=", "self", ".", "_domain", "distance", "=", "dom", "[", "-", "1", "]", "-", "dom", "...
Create a list of colors evenly spaced along this scale's domain. :param int count: The number of colors to return. :rtype: list :returns: A list of spectra.Color objects.
[ "Create", "a", "list", "of", "colors", "evenly", "spaced", "along", "this", "scale", "s", "domain", "." ]
python
train
31.875
hazelcast/hazelcast-python-client
hazelcast/config.py
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/config.py#L354-L363
def set_custom_serializer(self, _type, serializer): """ Assign a serializer for the type. :param _type: (Type), the target type of the serializer :param serializer: (Serializer), Custom Serializer constructor function """ validate_type(_type) validate_serializer(...
[ "def", "set_custom_serializer", "(", "self", ",", "_type", ",", "serializer", ")", ":", "validate_type", "(", "_type", ")", "validate_serializer", "(", "serializer", ",", "StreamSerializer", ")", "self", ".", "_custom_serializers", "[", "_type", "]", "=", "seria...
Assign a serializer for the type. :param _type: (Type), the target type of the serializer :param serializer: (Serializer), Custom Serializer constructor function
[ "Assign", "a", "serializer", "for", "the", "type", "." ]
python
train
39.3
stevearc/dynamo3
dynamo3/connection.py
https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/connection.py#L751-L779
def batch_write(self, tablename, return_capacity=None, return_item_collection_metrics=NONE): """ Perform a batch write on a table Parameters ---------- tablename : str Name of the table to write to return_capacity : {NONE, INDEXES, TOTAL},...
[ "def", "batch_write", "(", "self", ",", "tablename", ",", "return_capacity", "=", "None", ",", "return_item_collection_metrics", "=", "NONE", ")", ":", "return_capacity", "=", "self", ".", "_default_capacity", "(", "return_capacity", ")", "return", "BatchWriter", ...
Perform a batch write on a table Parameters ---------- tablename : str Name of the table to write to return_capacity : {NONE, INDEXES, TOTAL}, optional INDEXES will return the consumed capacity for indexes, TOTAL will return the consumed capacity for ...
[ "Perform", "a", "batch", "write", "on", "a", "table" ]
python
train
38.344828
HazyResearch/fonduer
src/fonduer/utils/data_model_utils/tabular.py
https://github.com/HazyResearch/fonduer/blob/4520f86a716f03dcca458a9f4bddac75b4e7068f/src/fonduer/utils/data_model_utils/tabular.py#L152-L174
def get_sentence_ngrams(mention, attrib="words", n_min=1, n_max=1, lower=True): """Get the ngrams that are in the Sentence of the given Mention, not including itself. Note that if a candidate is passed in, all of its Mentions will be searched. :param mention: The Mention whose Sentence is being search...
[ "def", "get_sentence_ngrams", "(", "mention", ",", "attrib", "=", "\"words\"", ",", "n_min", "=", "1", ",", "n_max", "=", "1", ",", "lower", "=", "True", ")", ":", "spans", "=", "_to_spans", "(", "mention", ")", "for", "span", "in", "spans", ":", "fo...
Get the ngrams that are in the Sentence of the given Mention, not including itself. Note that if a candidate is passed in, all of its Mentions will be searched. :param mention: The Mention whose Sentence is being searched :param attrib: The token attribute type (e.g. words, lemmas, poses) :param n...
[ "Get", "the", "ngrams", "that", "are", "in", "the", "Sentence", "of", "the", "given", "Mention", "not", "including", "itself", "." ]
python
train
43.130435
proycon/clam
clam/common/data.py
https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L1637-L1660
def fromxml(node): """Static method returning an MetaField instance (any subclass of AbstractMetaField) from the given XML description. Node can be a string or an etree._Element.""" if not isinstance(node,ElementTree._Element): #pylint: disable=protected-access node = parsexmlstring(node) ...
[ "def", "fromxml", "(", "node", ")", ":", "if", "not", "isinstance", "(", "node", ",", "ElementTree", ".", "_Element", ")", ":", "#pylint: disable=protected-access", "node", "=", "parsexmlstring", "(", "node", ")", "if", "node", ".", "tag", ".", "lower", "(...
Static method returning an MetaField instance (any subclass of AbstractMetaField) from the given XML description. Node can be a string or an etree._Element.
[ "Static", "method", "returning", "an", "MetaField", "instance", "(", "any", "subclass", "of", "AbstractMetaField", ")", "from", "the", "given", "XML", "description", ".", "Node", "can", "be", "a", "string", "or", "an", "etree", ".", "_Element", "." ]
python
train
39.541667
kensho-technologies/graphql-compiler
graphql_compiler/compiler/expressions.py
https://github.com/kensho-technologies/graphql-compiler/blob/f6079c6d10f64932f6b3af309b79bcea2123ca8f/graphql_compiler/compiler/expressions.py#L185-L204
def to_match(self): """Return a unicode object with the MATCH representation of this Variable.""" self.validate() # We don't want the dollar sign as part of the variable name. variable_with_no_dollar_sign = self.variable_name[1:] match_variable_name = '{%s}' % (six.text_type(va...
[ "def", "to_match", "(", "self", ")", ":", "self", ".", "validate", "(", ")", "# We don't want the dollar sign as part of the variable name.", "variable_with_no_dollar_sign", "=", "self", ".", "variable_name", "[", "1", ":", "]", "match_variable_name", "=", "'{%s}'", "...
Return a unicode object with the MATCH representation of this Variable.
[ "Return", "a", "unicode", "object", "with", "the", "MATCH", "representation", "of", "this", "Variable", "." ]
python
train
53.1
blockstack/blockstack-core
blockstack/blockstackd.py
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/blockstackd.py#L1207-L1229
def rpc_get_historic_names_by_address(self, address, offset, count, **con_info): """ Get the list of names owned by an address throughout history Return {'status': True, 'names': [{'name': ..., 'block_id': ..., 'vtxindex': ...}]} on success Return {'error': ...} on error """ ...
[ "def", "rpc_get_historic_names_by_address", "(", "self", ",", "address", ",", "offset", ",", "count", ",", "*", "*", "con_info", ")", ":", "if", "not", "check_address", "(", "address", ")", ":", "return", "{", "'error'", ":", "'Invalid address'", ",", "'http...
Get the list of names owned by an address throughout history Return {'status': True, 'names': [{'name': ..., 'block_id': ..., 'vtxindex': ...}]} on success Return {'error': ...} on error
[ "Get", "the", "list", "of", "names", "owned", "by", "an", "address", "throughout", "history", "Return", "{", "status", ":", "True", "names", ":", "[", "{", "name", ":", "...", "block_id", ":", "...", "vtxindex", ":", "...", "}", "]", "}", "on", "succ...
python
train
37.217391
Opentrons/opentrons
api/src/opentrons/system/udev.py
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/system/udev.py#L7-L35
def setup_rules_file(): """ Copy the udev rules file for Opentrons Modules to opentrons_data directory and trigger the new rules. This rules file in opentrons_data is symlinked into udev rules directory TODO: Move this file to resources and move the symlink to point to /data/system/ """ ...
[ "def", "setup_rules_file", "(", ")", ":", "import", "shutil", "import", "subprocess", "rules_file", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ")", ",", "...
Copy the udev rules file for Opentrons Modules to opentrons_data directory and trigger the new rules. This rules file in opentrons_data is symlinked into udev rules directory TODO: Move this file to resources and move the symlink to point to /data/system/
[ "Copy", "the", "udev", "rules", "file", "for", "Opentrons", "Modules", "to", "opentrons_data", "directory", "and", "trigger", "the", "new", "rules", ".", "This", "rules", "file", "in", "opentrons_data", "is", "symlinked", "into", "udev", "rules", "directory" ]
python
train
32.586207
cogniteev/docido-python-sdk
docido_sdk/core.py
https://github.com/cogniteev/docido-python-sdk/blob/58ecb6c6f5757fd40c0601657ab18368da7ddf33/docido_sdk/core.py#L206-L210
def is_enabled(self, cls): """Return whether the given component class is enabled.""" if cls not in self.enabled: self.enabled[cls] = self.is_component_enabled(cls) return self.enabled[cls]
[ "def", "is_enabled", "(", "self", ",", "cls", ")", ":", "if", "cls", "not", "in", "self", ".", "enabled", ":", "self", ".", "enabled", "[", "cls", "]", "=", "self", ".", "is_component_enabled", "(", "cls", ")", "return", "self", ".", "enabled", "[", ...
Return whether the given component class is enabled.
[ "Return", "whether", "the", "given", "component", "class", "is", "enabled", "." ]
python
train
44.2
astropy/photutils
photutils/aperture/core.py
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/aperture/core.py#L674-L761
def _prepare_photometry_input(data, error, mask, wcs, unit): """ Parse the inputs to `aperture_photometry`. `aperture_photometry` accepts a wide range of inputs, e.g. ``data`` could be a numpy array, a Quantity array, or a fits HDU. This requires some parsing and validation to ensure that all inpu...
[ "def", "_prepare_photometry_input", "(", "data", ",", "error", ",", "mask", ",", "wcs", ",", "unit", ")", ":", "if", "isinstance", "(", "data", ",", "fits", ".", "HDUList", ")", ":", "for", "i", "in", "range", "(", "len", "(", "data", ")", ")", ":"...
Parse the inputs to `aperture_photometry`. `aperture_photometry` accepts a wide range of inputs, e.g. ``data`` could be a numpy array, a Quantity array, or a fits HDU. This requires some parsing and validation to ensure that all inputs are complete and consistent. For example, the data could carry a ...
[ "Parse", "the", "inputs", "to", "aperture_photometry", "." ]
python
train
36.852273
nyrkovalex/httpsrv
httpsrv/httpsrv.py
https://github.com/nyrkovalex/httpsrv/blob/0acc3298be56856f73bda1ed10c9ab5153894b01/httpsrv/httpsrv.py#L188-L212
def always(self, method, path=None, headers=None, text=None, json=None): ''' Sends response every time matching parameters are found util :func:`Server.reset` is called :type method: str :param method: request method: ``'GET'``, ``'POST'``, etc. can be some custom string :type ...
[ "def", "always", "(", "self", ",", "method", ",", "path", "=", "None", ",", "headers", "=", "None", ",", "text", "=", "None", ",", "json", "=", "None", ")", ":", "rule", "=", "Rule", "(", "method", ",", "path", ",", "headers", ",", "text", ",", ...
Sends response every time matching parameters are found util :func:`Server.reset` is called :type method: str :param method: request method: ``'GET'``, ``'POST'``, etc. can be some custom string :type path: str :param path: request path including query parameters :type headers...
[ "Sends", "response", "every", "time", "matching", "parameters", "are", "found", "util", ":", "func", ":", "Server", ".", "reset", "is", "called" ]
python
train
37.36
fitnr/convertdate
convertdate/persian.py
https://github.com/fitnr/convertdate/blob/e920f168a87f99183b0aa7290d6c3af222582d43/convertdate/persian.py#L33-L48
def to_jd(year, month, day): '''Determine Julian day from Persian date''' if year >= 0: y = 474 else: y = 473 epbase = year - y epyear = 474 + (epbase % 2820) if month <= 7: m = (month - 1) * 31 else: m = (month - 1) * 30 + 6 return day + m + trunc(((ep...
[ "def", "to_jd", "(", "year", ",", "month", ",", "day", ")", ":", "if", "year", ">=", "0", ":", "y", "=", "474", "else", ":", "y", "=", "473", "epbase", "=", "year", "-", "y", "epyear", "=", "474", "+", "(", "epbase", "%", "2820", ")", "if", ...
Determine Julian day from Persian date
[ "Determine", "Julian", "day", "from", "Persian", "date" ]
python
train
24.9375
saltstack/salt
salt/netapi/rest_cherrypy/app.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/app.py#L921-L933
def hypermedia_out(): ''' Determine the best handler for the requested content type Wrap the normal handler and transform the output from that handler into the requested content type ''' request = cherrypy.serving.request request._hypermedia_inner_handler = request.handler # If handler...
[ "def", "hypermedia_out", "(", ")", ":", "request", "=", "cherrypy", ".", "serving", ".", "request", "request", ".", "_hypermedia_inner_handler", "=", "request", ".", "handler", "# If handler has been explicitly set to None, don't override.", "if", "request", ".", "handl...
Determine the best handler for the requested content type Wrap the normal handler and transform the output from that handler into the requested content type
[ "Determine", "the", "best", "handler", "for", "the", "requested", "content", "type" ]
python
train
33.692308
carta/ldap_tools
src/ldap_tools/audit.py
https://github.com/carta/ldap_tools/blob/7c039304a5abaf836c7afc35cf068b4471306264/src/ldap_tools/audit.py#L100-L105
def raw(config): # pragma: no cover """Dump the contents of LDAP to console in raw format.""" client = Client() client.prepare_connection() audit_api = API(client) print(audit_api.raw())
[ "def", "raw", "(", "config", ")", ":", "# pragma: no cover", "client", "=", "Client", "(", ")", "client", ".", "prepare_connection", "(", ")", "audit_api", "=", "API", "(", "client", ")", "print", "(", "audit_api", ".", "raw", "(", ")", ")" ]
Dump the contents of LDAP to console in raw format.
[ "Dump", "the", "contents", "of", "LDAP", "to", "console", "in", "raw", "format", "." ]
python
train
37
MainRo/cyclotron-py
cyclotron/router.py
https://github.com/MainRo/cyclotron-py/blob/4530f65173aa4b9e27c3d4a2f5d33900fc19f754/cyclotron/router.py#L5-L59
def make_crossroad_router(source, drain=False): ''' legacy crossroad implementation. deprecated ''' sink_observer = None def on_sink_subscribe(observer): nonlocal sink_observer sink_observer = observer def dispose(): nonlocal sink_observer sink_observer ...
[ "def", "make_crossroad_router", "(", "source", ",", "drain", "=", "False", ")", ":", "sink_observer", "=", "None", "def", "on_sink_subscribe", "(", "observer", ")", ":", "nonlocal", "sink_observer", "sink_observer", "=", "observer", "def", "dispose", "(", ")", ...
legacy crossroad implementation. deprecated
[ "legacy", "crossroad", "implementation", ".", "deprecated" ]
python
train
30.072727
click-contrib/click-repl
click_repl/__init__.py
https://github.com/click-contrib/click-repl/blob/2d78dc520eb0bb5b813bad3b72344edbd22a7f4e/click_repl/__init__.py#L146-L165
def bootstrap_prompt(prompt_kwargs, group): """ Bootstrap prompt_toolkit kwargs or use user defined values. :param prompt_kwargs: The user specified prompt kwargs. """ prompt_kwargs = prompt_kwargs or {} defaults = { "history": InMemoryHistory(), "completer": ClickCompleter(gro...
[ "def", "bootstrap_prompt", "(", "prompt_kwargs", ",", "group", ")", ":", "prompt_kwargs", "=", "prompt_kwargs", "or", "{", "}", "defaults", "=", "{", "\"history\"", ":", "InMemoryHistory", "(", ")", ",", "\"completer\"", ":", "ClickCompleter", "(", "group", ")...
Bootstrap prompt_toolkit kwargs or use user defined values. :param prompt_kwargs: The user specified prompt kwargs.
[ "Bootstrap", "prompt_toolkit", "kwargs", "or", "use", "user", "defined", "values", "." ]
python
train
25.55
user-cont/conu
conu/utils/__init__.py
https://github.com/user-cont/conu/blob/08caae7bb6bdd265b55bb106c3da6a7946a5a352/conu/utils/__init__.py#L389-L399
def get_oc_api_token(): """ Get token of user logged in OpenShift cluster :return: str, API token """ oc_command_exists() try: return run_cmd(["oc", "whoami", "-t"], return_output=True).rstrip() # remove '\n' except subprocess.CalledProcessError as ex: raise ConuException("...
[ "def", "get_oc_api_token", "(", ")", ":", "oc_command_exists", "(", ")", "try", ":", "return", "run_cmd", "(", "[", "\"oc\"", ",", "\"whoami\"", ",", "\"-t\"", "]", ",", "return_output", "=", "True", ")", ".", "rstrip", "(", ")", "# remove '\\n'", "except"...
Get token of user logged in OpenShift cluster :return: str, API token
[ "Get", "token", "of", "user", "logged", "in", "OpenShift", "cluster", ":", "return", ":", "str", "API", "token" ]
python
train
30.909091
openstack/horizon
openstack_dashboard/api/neutron.py
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/neutron.py#L615-L640
def allocate(self, pool, tenant_id=None, **params): """Allocates a floating IP to the tenant. You must provide a pool name or id for which you would like to allocate a floating IP. :returns: FloatingIp object corresponding to an allocated floating IP """ if not tenant_i...
[ "def", "allocate", "(", "self", ",", "pool", ",", "tenant_id", "=", "None", ",", "*", "*", "params", ")", ":", "if", "not", "tenant_id", ":", "tenant_id", "=", "self", ".", "request", ".", "user", ".", "project_id", "create_dict", "=", "{", "'floating_...
Allocates a floating IP to the tenant. You must provide a pool name or id for which you would like to allocate a floating IP. :returns: FloatingIp object corresponding to an allocated floating IP
[ "Allocates", "a", "floating", "IP", "to", "the", "tenant", "." ]
python
train
43.153846
ayust/kitnirc
kitnirc/client.py
https://github.com/ayust/kitnirc/blob/cf19fe39219da75f053e1a3976bf21331b6fefea/kitnirc/client.py#L332-L341
def send(self, *args): """Sends a single raw message to the IRC server. Arguments are automatically joined by spaces. No newlines are allowed. """ msg = " ".join(a.nick if isinstance(a, User) else str(a) for a in args) if "\n" in msg: raise ValueError("Cannot send() ...
[ "def", "send", "(", "self", ",", "*", "args", ")", ":", "msg", "=", "\" \"", ".", "join", "(", "a", ".", "nick", "if", "isinstance", "(", "a", ",", "User", ")", "else", "str", "(", "a", ")", "for", "a", "in", "args", ")", "if", "\"\\n\"", "in...
Sends a single raw message to the IRC server. Arguments are automatically joined by spaces. No newlines are allowed.
[ "Sends", "a", "single", "raw", "message", "to", "the", "IRC", "server", "." ]
python
train
43.9
pycontribs/python-crowd
crowd.py
https://github.com/pycontribs/python-crowd/blob/a075e45774dd5baecf0217843cda747084268e32/crowd.py#L483-L505
def remove_user_from_group(self, username, groupname, raise_on_error=False): """Remove a user from a group Attempts to remove a user from a group Args username: The username to remove from the group. groupname: The group name to be removed from the user. Returns: ...
[ "def", "remove_user_from_group", "(", "self", ",", "username", ",", "groupname", ",", "raise_on_error", "=", "False", ")", ":", "response", "=", "self", ".", "_delete", "(", "self", ".", "rest_url", "+", "\"/group/user/direct\"", ",", "params", "=", "{", "\"...
Remove a user from a group Attempts to remove a user from a group Args username: The username to remove from the group. groupname: The group name to be removed from the user. Returns: True: Succeeded False: If unsuccessful
[ "Remove", "a", "user", "from", "a", "group" ]
python
train
28.782609
nickjj/ansigenome
ansigenome/utils.py
https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/utils.py#L303-L309
def exit_if_no_roles(roles_count, roles_path): """ Exit if there were no roles found. """ if roles_count == 0: ui.warn(c.MESSAGES["empty_roles_path"], roles_path) sys.exit()
[ "def", "exit_if_no_roles", "(", "roles_count", ",", "roles_path", ")", ":", "if", "roles_count", "==", "0", ":", "ui", ".", "warn", "(", "c", ".", "MESSAGES", "[", "\"empty_roles_path\"", "]", ",", "roles_path", ")", "sys", ".", "exit", "(", ")" ]
Exit if there were no roles found.
[ "Exit", "if", "there", "were", "no", "roles", "found", "." ]
python
train
28.428571
molmod/molmod
molmod/graphs.py
https://github.com/molmod/molmod/blob/a7b5b4364ed514ad4c465856c05b5eda1cb561e0/molmod/graphs.py#L1248-L1257
def get_new_edges(self, level): """Get new edges from the pattern graph for the graph search algorithm The level argument denotes the distance of the new edges from the starting vertex in the pattern graph. """ return ( self.level_edges.get(level, []), ...
[ "def", "get_new_edges", "(", "self", ",", "level", ")", ":", "return", "(", "self", ".", "level_edges", ".", "get", "(", "level", ",", "[", "]", ")", ",", "self", ".", "level_constraints", ".", "get", "(", "level", ",", "[", "]", ")", ")" ]
Get new edges from the pattern graph for the graph search algorithm The level argument denotes the distance of the new edges from the starting vertex in the pattern graph.
[ "Get", "new", "edges", "from", "the", "pattern", "graph", "for", "the", "graph", "search", "algorithm" ]
python
train
36.2