repo
stringlengths
7
54
path
stringlengths
4
192
url
stringlengths
87
284
code
stringlengths
78
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
junzis/pyModeS
pyModeS/decoder/bds/bds60.py
https://github.com/junzis/pyModeS/blob/8cd5655a04b08171a9ad5f1ffd232b7e0178ea53/pyModeS/decoder/bds/bds60.py#L104-L119
def ias60(msg): """Indicated airspeed Args: msg (String): 28 bytes hexadecimal message (BDS60) string Returns: int: indicated airspeed in knots """ d = hex2bin(data(msg)) if d[12] == '0': return None ias = bin2int(d[13:23]) # kts return ias
[ "def", "ias60", "(", "msg", ")", ":", "d", "=", "hex2bin", "(", "data", "(", "msg", ")", ")", "if", "d", "[", "12", "]", "==", "'0'", ":", "return", "None", "ias", "=", "bin2int", "(", "d", "[", "13", ":", "23", "]", ")", "# kts", "return", ...
Indicated airspeed Args: msg (String): 28 bytes hexadecimal message (BDS60) string Returns: int: indicated airspeed in knots
[ "Indicated", "airspeed" ]
python
train
h2oai/h2o-3
scripts/extractGLRMRuntimeJavaLog.py
https://github.com/h2oai/h2o-3/blob/dd62aaa1e7f680a8b16ee14bc66b0fb5195c2ad8/scripts/extractGLRMRuntimeJavaLog.py#L115-L132
def main(argv): """ Main program. Take user input, parse it and call other functions to execute the commands and extract run summary and store run result in json file @return: none """ global g_test_root_dir global g_temp_filename if len(argv) < 2: print("invoke this script as...
[ "def", "main", "(", "argv", ")", ":", "global", "g_test_root_dir", "global", "g_temp_filename", "if", "len", "(", "argv", ")", "<", "2", ":", "print", "(", "\"invoke this script as python extractGLRMRuntimeJavaLog.py javatextlog.\\n\"", ")", "sys", ".", "exit", "(",...
Main program. Take user input, parse it and call other functions to execute the commands and extract run summary and store run result in json file @return: none
[ "Main", "program", ".", "Take", "user", "input", "parse", "it", "and", "call", "other", "functions", "to", "execute", "the", "commands", "and", "extract", "run", "summary", "and", "store", "run", "result", "in", "json", "file" ]
python
test
nats-io/python-nats
nats/io/client.py
https://github.com/nats-io/python-nats/blob/4a409319c409e7e55ce8377b64b406375c5f455b/nats/io/client.py#L983-L1009
def _process_info(self, info_line): """ Process INFO lines sent by the server to reconfigure client with latest updates from cluster to enable server discovery. """ info = tornado.escape.json_decode(info_line.decode()) if 'connect_urls' in info: if info['conn...
[ "def", "_process_info", "(", "self", ",", "info_line", ")", ":", "info", "=", "tornado", ".", "escape", ".", "json_decode", "(", "info_line", ".", "decode", "(", ")", ")", "if", "'connect_urls'", "in", "info", ":", "if", "info", "[", "'connect_urls'", "]...
Process INFO lines sent by the server to reconfigure client with latest updates from cluster to enable server discovery.
[ "Process", "INFO", "lines", "sent", "by", "the", "server", "to", "reconfigure", "client", "with", "latest", "updates", "from", "cluster", "to", "enable", "server", "discovery", "." ]
python
train
stevearc/dql
dql/expressions/selection.py
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/expressions/selection.py#L52-L61
def div(a, b): """ Divide two values, ignoring None """ if a is None: if b is None: return None else: return 1 / b elif b is None: return a return a / b
[ "def", "div", "(", "a", ",", "b", ")", ":", "if", "a", "is", "None", ":", "if", "b", "is", "None", ":", "return", "None", "else", ":", "return", "1", "/", "b", "elif", "b", "is", "None", ":", "return", "a", "return", "a", "/", "b" ]
Divide two values, ignoring None
[ "Divide", "two", "values", "ignoring", "None" ]
python
train
intelsdi-x/snap-plugin-lib-py
snap_plugin/v1/plugin.py
https://github.com/intelsdi-x/snap-plugin-lib-py/blob/8da5d00ac5f9d2b48a7239563ac7788209891ca4/snap_plugin/v1/plugin.py#L63-L79
def _make_standalone_handler(preamble): """Class factory used so that preamble can be passed to :py:class:`_StandaloneHandler` without use of static members""" class _StandaloneHandler(BaseHTTPRequestHandler, object): """HTTP Handler for standalone mode""" def do_GET(self): sel...
[ "def", "_make_standalone_handler", "(", "preamble", ")", ":", "class", "_StandaloneHandler", "(", "BaseHTTPRequestHandler", ",", "object", ")", ":", "\"\"\"HTTP Handler for standalone mode\"\"\"", "def", "do_GET", "(", "self", ")", ":", "self", ".", "send_response", "...
Class factory used so that preamble can be passed to :py:class:`_StandaloneHandler` without use of static members
[ "Class", "factory", "used", "so", "that", "preamble", "can", "be", "passed", "to", ":", "py", ":", "class", ":", "_StandaloneHandler", "without", "use", "of", "static", "members" ]
python
train
mlperf/training
rnn_translator/pytorch/seq2seq/train/fp_optimizers.py
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/seq2seq/train/fp_optimizers.py#L63-L76
def initialize_model(self, model): """ Initializes internal state and build fp32 master copy of weights. :param model: fp16 model """ logging.info('Initializing fp32 clone weights') self.fp16_model = model self.fp16_model.zero_grad() self.fp32_params = [p...
[ "def", "initialize_model", "(", "self", ",", "model", ")", ":", "logging", ".", "info", "(", "'Initializing fp32 clone weights'", ")", "self", ".", "fp16_model", "=", "model", "self", ".", "fp16_model", ".", "zero_grad", "(", ")", "self", ".", "fp32_params", ...
Initializes internal state and build fp32 master copy of weights. :param model: fp16 model
[ "Initializes", "internal", "state", "and", "build", "fp32", "master", "copy", "of", "weights", "." ]
python
train
pantsbuild/pex
pex/link.py
https://github.com/pantsbuild/pex/blob/87b2129d860250d3b9edce75b9cb62f9789ee521/pex/link.py#L57-L63
def from_filename(cls, filename): """Return a :class:`Link` wrapping the local filename.""" result = cls._FROM_FILENAME_CACHE.get(filename) if result is None: result = cls(cls._normalize(filename)) cls._FROM_FILENAME_CACHE.store(filename, result) return result
[ "def", "from_filename", "(", "cls", ",", "filename", ")", ":", "result", "=", "cls", ".", "_FROM_FILENAME_CACHE", ".", "get", "(", "filename", ")", "if", "result", "is", "None", ":", "result", "=", "cls", "(", "cls", ".", "_normalize", "(", "filename", ...
Return a :class:`Link` wrapping the local filename.
[ "Return", "a", ":", "class", ":", "Link", "wrapping", "the", "local", "filename", "." ]
python
train
sorgerlab/indra
indra/util/__init__.py
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/util/__init__.py#L216-L219
def flatten(l): """Flatten a nested list.""" return sum(map(flatten, l), []) \ if isinstance(l, list) or isinstance(l, tuple) else [l]
[ "def", "flatten", "(", "l", ")", ":", "return", "sum", "(", "map", "(", "flatten", ",", "l", ")", ",", "[", "]", ")", "if", "isinstance", "(", "l", ",", "list", ")", "or", "isinstance", "(", "l", ",", "tuple", ")", "else", "[", "l", "]" ]
Flatten a nested list.
[ "Flatten", "a", "nested", "list", "." ]
python
train
mlperf/training
reinforcement/tensorflow/minigo/utils.py
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/utils.py#L41-L47
def parse_game_result(result): "Parse an SGF result string into value target." if re.match(r'[bB]\+', result): return 1 if re.match(r'[wW]\+', result): return -1 return 0
[ "def", "parse_game_result", "(", "result", ")", ":", "if", "re", ".", "match", "(", "r'[bB]\\+'", ",", "result", ")", ":", "return", "1", "if", "re", ".", "match", "(", "r'[wW]\\+'", ",", "result", ")", ":", "return", "-", "1", "return", "0" ]
Parse an SGF result string into value target.
[ "Parse", "an", "SGF", "result", "string", "into", "value", "target", "." ]
python
train
edibledinos/pwnypack
pwnypack/flow.py
https://github.com/edibledinos/pwnypack/blob/e0a5a8e6ef3f4f1f7e1b91ee379711f4a49cb0e6/pwnypack/flow.py#L487-L502
def write(self, data, echo=None): """ Write data to channel. Args: data(bytes): The data to write to the channel. echo(bool): Whether to echo the written data to stdout. Raises: EOFError: If the channel was closed before all data was sent. ""...
[ "def", "write", "(", "self", ",", "data", ",", "echo", "=", "None", ")", ":", "if", "echo", "or", "(", "echo", "is", "None", "and", "self", ".", "echo", ")", ":", "sys", ".", "stdout", ".", "write", "(", "data", ".", "decode", "(", "'latin1'", ...
Write data to channel. Args: data(bytes): The data to write to the channel. echo(bool): Whether to echo the written data to stdout. Raises: EOFError: If the channel was closed before all data was sent.
[ "Write", "data", "to", "channel", "." ]
python
train
visualfabriq/bquery
bquery/benchmarks/bench_pos.py
https://github.com/visualfabriq/bquery/blob/3702e974696e22876944a3339affad2f29e1ee06/bquery/benchmarks/bench_pos.py#L14-L20
def ctime(message=None): "Counts the time spent in some context" t = time.time() yield if message: print message + ":\t", print round(time.time() - t, 4), "sec"
[ "def", "ctime", "(", "message", "=", "None", ")", ":", "t", "=", "time", ".", "time", "(", ")", "yield", "if", "message", ":", "print", "message", "+", "\":\\t\"", ",", "print", "round", "(", "time", ".", "time", "(", ")", "-", "t", ",", "4", "...
Counts the time spent in some context
[ "Counts", "the", "time", "spent", "in", "some", "context" ]
python
train
dmlc/gluon-nlp
scripts/parsing/common/k_means.py
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/k_means.py#L108-L145
def _recenter(self): """ one iteration of k-means """ for split_idx in range(len(self._splits)): split = self._splits[split_idx] len_idx = self._split2len_idx[split] if split == self._splits[-1]: continue right_split = self....
[ "def", "_recenter", "(", "self", ")", ":", "for", "split_idx", "in", "range", "(", "len", "(", "self", ".", "_splits", ")", ")", ":", "split", "=", "self", ".", "_splits", "[", "split_idx", "]", "len_idx", "=", "self", ".", "_split2len_idx", "[", "sp...
one iteration of k-means
[ "one", "iteration", "of", "k", "-", "means" ]
python
train
google/tangent
tangent/comments.py
https://github.com/google/tangent/blob/6533e83af09de7345d1b438512679992f080dcc9/tangent/comments.py#L49-L71
def remove_repeated_comments(node): """Remove comments that repeat themselves. Multiple statements might be annotated with the same comment. This way if one of the statements is deleted during optimization passes, the comment won't be lost. This pass removes sequences of identical comments, leaving only the ...
[ "def", "remove_repeated_comments", "(", "node", ")", ":", "last_comment", "=", "{", "'text'", ":", "None", "}", "for", "_node", "in", "gast", ".", "walk", "(", "node", ")", ":", "if", "anno", ".", "hasanno", "(", "_node", ",", "'comment'", ")", ":", ...
Remove comments that repeat themselves. Multiple statements might be annotated with the same comment. This way if one of the statements is deleted during optimization passes, the comment won't be lost. This pass removes sequences of identical comments, leaving only the first one. Args: node: An AST R...
[ "Remove", "comments", "that", "repeat", "themselves", "." ]
python
train
waqasbhatti/astrobase
astrobase/hatsurveys/hplc.py
https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/hatsurveys/hplc.py#L405-L502
def concatenate_textlcs_for_objectid(lcbasedir, objectid, aperture='TF1', postfix='.gz', sortby='rjd', normalize=True, ...
[ "def", "concatenate_textlcs_for_objectid", "(", "lcbasedir", ",", "objectid", ",", "aperture", "=", "'TF1'", ",", "postfix", "=", "'.gz'", ",", "sortby", "=", "'rjd'", ",", "normalize", "=", "True", ",", "recursive", "=", "True", ")", ":", "LOGINFO", "(", ...
This concatenates all text LCs for an objectid with the given aperture. Does not care about overlaps or duplicates. The light curves must all be from the same aperture. The intended use is to concatenate light curves across CCDs or instrument changes for a single object. These can then be normalized l...
[ "This", "concatenates", "all", "text", "LCs", "for", "an", "objectid", "with", "the", "given", "aperture", "." ]
python
valid
BerkeleyAutomation/autolab_core
autolab_core/csv_model.py
https://github.com/BerkeleyAutomation/autolab_core/blob/8f3813f6401972868cc5e3981ba1b4382d4418d5/autolab_core/csv_model.py#L441-L472
def get_or_create(full_filename, headers_types=None, default_entry=''): """Load a .csv file into a CSVModel if the file exists, or create a new CSVModel with the given filename if the file does not exist. Parameters ---------- full_filename : :obj:`str` The file path...
[ "def", "get_or_create", "(", "full_filename", ",", "headers_types", "=", "None", ",", "default_entry", "=", "''", ")", ":", "# convert dictionaries to list", "if", "isinstance", "(", "headers_types", ",", "dict", ")", ":", "headers_types_list", "=", "[", "(", "k...
Load a .csv file into a CSVModel if the file exists, or create a new CSVModel with the given filename if the file does not exist. Parameters ---------- full_filename : :obj:`str` The file path to a .csv file. headers_types : :obj:`list` of :obj:`tuple` of :obj:`str`...
[ "Load", "a", ".", "csv", "file", "into", "a", "CSVModel", "if", "the", "file", "exists", "or", "create", "a", "new", "CSVModel", "with", "the", "given", "filename", "if", "the", "file", "does", "not", "exist", "." ]
python
train
ArangoDB-Community/pyArango
pyArango/collection.py
https://github.com/ArangoDB-Community/pyArango/blob/dd72e5f6c540e5e148943d615ddf7553bb78ce0b/pyArango/collection.py#L442-L451
def hasField(cls, fieldName) : """returns True/False wether the collection has field K in it's schema. Use the dot notation for the nested fields: address.street""" path = fieldName.split(".") v = cls._fields for k in path : try : v = v[k] except K...
[ "def", "hasField", "(", "cls", ",", "fieldName", ")", ":", "path", "=", "fieldName", ".", "split", "(", "\".\"", ")", "v", "=", "cls", ".", "_fields", "for", "k", "in", "path", ":", "try", ":", "v", "=", "v", "[", "k", "]", "except", "KeyError", ...
returns True/False wether the collection has field K in it's schema. Use the dot notation for the nested fields: address.street
[ "returns", "True", "/", "False", "wether", "the", "collection", "has", "field", "K", "in", "it", "s", "schema", ".", "Use", "the", "dot", "notation", "for", "the", "nested", "fields", ":", "address", ".", "street" ]
python
train
chrisrink10/basilisp
src/basilisp/lang/compiler/__init__.py
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/compiler/__init__.py#L204-L218
def compile_bytecode( code: List[types.CodeType], gctx: GeneratorContext, optimizer: PythonASTOptimizer, module: types.ModuleType, ) -> None: """Compile cached bytecode into the given module. The Basilisp import hook attempts to cache bytecode while compiling Basilisp namespaces. When the c...
[ "def", "compile_bytecode", "(", "code", ":", "List", "[", "types", ".", "CodeType", "]", ",", "gctx", ":", "GeneratorContext", ",", "optimizer", ":", "PythonASTOptimizer", ",", "module", ":", "types", ".", "ModuleType", ",", ")", "->", "None", ":", "_boots...
Compile cached bytecode into the given module. The Basilisp import hook attempts to cache bytecode while compiling Basilisp namespaces. When the cached bytecode is reloaded from disk, it needs to be compiled within a bootstrapped module. This function bootstraps the module and then proceeds to compile ...
[ "Compile", "cached", "bytecode", "into", "the", "given", "module", "." ]
python
test
numberoverzero/bloop
bloop/session.py
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/session.py#L82-L104
def load_items(self, items): """Loads any number of items in chunks, handling continuation tokens. :param items: Unpacked in chunks into "RequestItems" for :func:`boto3.DynamoDB.Client.batch_get_item`. """ loaded_items = {} requests = collections.deque(create_batch_get_chunks(it...
[ "def", "load_items", "(", "self", ",", "items", ")", ":", "loaded_items", "=", "{", "}", "requests", "=", "collections", ".", "deque", "(", "create_batch_get_chunks", "(", "items", ")", ")", "while", "requests", ":", "request", "=", "requests", ".", "pop",...
Loads any number of items in chunks, handling continuation tokens. :param items: Unpacked in chunks into "RequestItems" for :func:`boto3.DynamoDB.Client.batch_get_item`.
[ "Loads", "any", "number", "of", "items", "in", "chunks", "handling", "continuation", "tokens", "." ]
python
train
jeffknupp/sandman2
sandman2/app.py
https://github.com/jeffknupp/sandman2/blob/1ce21d6f7a6df77fa96fab694b0f9bb8469c166b/sandman2/app.py#L95-L123
def register_service(cls, primary_key_type): """Register an API service endpoint. :param cls: The class to register :param str primary_key_type: The type (as a string) of the primary_key field """ view_func = cls.as_view(cls.__name__.lower()) # pylint: disable=no-m...
[ "def", "register_service", "(", "cls", ",", "primary_key_type", ")", ":", "view_func", "=", "cls", ".", "as_view", "(", "cls", ".", "__name__", ".", "lower", "(", ")", ")", "# pylint: disable=no-member", "methods", "=", "set", "(", "cls", ".", "__model__", ...
Register an API service endpoint. :param cls: The class to register :param str primary_key_type: The type (as a string) of the primary_key field
[ "Register", "an", "API", "service", "endpoint", "." ]
python
train
Garee/pytodoist
pytodoist/todoist.py
https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L562-L600
def search_tasks(self, *queries): """Return a list of tasks that match some search criteria. .. note:: Example queries can be found `here <https://todoist.com/Help/timeQuery>`_. .. note:: A standard set of queries are available in the :class:`pytodoist.todoist.Query` cl...
[ "def", "search_tasks", "(", "self", ",", "*", "queries", ")", ":", "queries", "=", "json", ".", "dumps", "(", "queries", ")", "response", "=", "API", ".", "query", "(", "self", ".", "api_token", ",", "queries", ")", "_fail_if_contains_errors", "(", "resp...
Return a list of tasks that match some search criteria. .. note:: Example queries can be found `here <https://todoist.com/Help/timeQuery>`_. .. note:: A standard set of queries are available in the :class:`pytodoist.todoist.Query` class. :param queries: Return tasks th...
[ "Return", "a", "list", "of", "tasks", "that", "match", "some", "search", "criteria", "." ]
python
train
tensorflow/lucid
lucid/misc/gl/meshutil.py
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/misc/gl/meshutil.py#L87-L96
def _unify_rows(a): """Unify lengths of each row of a.""" lens = np.fromiter(map(len, a), np.int32) if not (lens[0] == lens).all(): out = np.zeros((len(a), lens.max()), np.float32) for i, row in enumerate(a): out[i, :lens[i]] = row else: out = np.float32(a) return out
[ "def", "_unify_rows", "(", "a", ")", ":", "lens", "=", "np", ".", "fromiter", "(", "map", "(", "len", ",", "a", ")", ",", "np", ".", "int32", ")", "if", "not", "(", "lens", "[", "0", "]", "==", "lens", ")", ".", "all", "(", ")", ":", "out",...
Unify lengths of each row of a.
[ "Unify", "lengths", "of", "each", "row", "of", "a", "." ]
python
train
kmedian/ctmc
ctmc/ctmc_class.py
https://github.com/kmedian/ctmc/blob/e30747f797ce777fd2aaa1b7ee5a77e91d7db5e4/ctmc/ctmc_class.py#L17-L30
def fit(self, X, y=None): """Calls the ctmc.ctmc function Parameters ---------- X : list of lists (see ctmc function 'data') y not used, present for API consistence purpose. """ self.transmat, self.genmat, self.transcount, self.statetime ...
[ "def", "fit", "(", "self", ",", "X", ",", "y", "=", "None", ")", ":", "self", ".", "transmat", ",", "self", ".", "genmat", ",", "self", ".", "transcount", ",", "self", ".", "statetime", "=", "ctmc", "(", "X", ",", "self", ".", "numstates", ",", ...
Calls the ctmc.ctmc function Parameters ---------- X : list of lists (see ctmc function 'data') y not used, present for API consistence purpose.
[ "Calls", "the", "ctmc", ".", "ctmc", "function" ]
python
train
caseyjlaw/rtpipe
rtpipe/interactive.py
https://github.com/caseyjlaw/rtpipe/blob/ac33e4332cf215091a63afbb3137850876d73ec0/rtpipe/interactive.py#L692-L704
def colorsat(l,m): """ Returns color for given l,m Designed to look like a color wheel that is more saturated in middle. """ lm = np.zeros(len(l), dtype='complex') lm.real = l lm.imag = m red = 0.5*(1+np.cos(np.angle(lm))) green = 0.5*(1+np.cos(np.angle(lm) + 2*3.14/3)) blue = 0.5*(...
[ "def", "colorsat", "(", "l", ",", "m", ")", ":", "lm", "=", "np", ".", "zeros", "(", "len", "(", "l", ")", ",", "dtype", "=", "'complex'", ")", "lm", ".", "real", "=", "l", "lm", ".", "imag", "=", "m", "red", "=", "0.5", "*", "(", "1", "+...
Returns color for given l,m Designed to look like a color wheel that is more saturated in middle.
[ "Returns", "color", "for", "given", "l", "m", "Designed", "to", "look", "like", "a", "color", "wheel", "that", "is", "more", "saturated", "in", "middle", "." ]
python
train
buildbot/buildbot
master/buildbot/process/users/manual.py
https://github.com/buildbot/buildbot/blob/5df3cfae6d760557d99156633c32b1822a1e130c/master/buildbot/process/users/manual.py#L37-L83
def formatResults(self, op, results): """ This formats the results of the database operations for printing back to the caller @param op: operation to perform (add, remove, update, get) @type op: string @param results: results from db queries in perspective_commandline ...
[ "def", "formatResults", "(", "self", ",", "op", ",", "results", ")", ":", "formatted_results", "=", "\"\"", "if", "op", "==", "'add'", ":", "# list, alternating ident, uid", "formatted_results", "+=", "\"user(s) added:\\n\"", "for", "user", "in", "results", ":", ...
This formats the results of the database operations for printing back to the caller @param op: operation to perform (add, remove, update, get) @type op: string @param results: results from db queries in perspective_commandline @type results: list @returns: string conta...
[ "This", "formats", "the", "results", "of", "the", "database", "operations", "for", "printing", "back", "to", "the", "caller" ]
python
train
juju/theblues
theblues/identity_manager.py
https://github.com/juju/theblues/blob/f4431f29e43d04fc32f38f4f86cea45cd4e6ae98/theblues/identity_manager.py#L64-L92
def discharge(self, username, macaroon): """Discharge the macarooon for the identity. Raise a ServerError if an error occurs in the request process. @param username The logged in user. @param macaroon The macaroon returned from the charm store. @return The resulting base64 enco...
[ "def", "discharge", "(", "self", ",", "username", ",", "macaroon", ")", ":", "caveats", "=", "macaroon", ".", "third_party_caveats", "(", ")", "if", "len", "(", "caveats", ")", "!=", "1", ":", "raise", "InvalidMacaroon", "(", "'Invalid number of third party ca...
Discharge the macarooon for the identity. Raise a ServerError if an error occurs in the request process. @param username The logged in user. @param macaroon The macaroon returned from the charm store. @return The resulting base64 encoded macaroon. @raises ServerError when makin...
[ "Discharge", "the", "macarooon", "for", "the", "identity", "." ]
python
train
sbaechler/django-multilingual-search
multilingual/elasticsearch_backend.py
https://github.com/sbaechler/django-multilingual-search/blob/485c690d865da3267b19e073e28d3e2290f36611/multilingual/elasticsearch_backend.py#L96-L106
def clear(self, models=None, commit=True): """ Clears all indexes for the current project. :param models: if specified, only deletes the entries for the given models. :param commit: This is ignored by Haystack (maybe a bug?) """ for language in self.languages: ...
[ "def", "clear", "(", "self", ",", "models", "=", "None", ",", "commit", "=", "True", ")", ":", "for", "language", "in", "self", ".", "languages", ":", "self", ".", "log", ".", "debug", "(", "'clearing index for {0}'", ".", "format", "(", "language", ")...
Clears all indexes for the current project. :param models: if specified, only deletes the entries for the given models. :param commit: This is ignored by Haystack (maybe a bug?)
[ "Clears", "all", "indexes", "for", "the", "current", "project", ".", ":", "param", "models", ":", "if", "specified", "only", "deletes", "the", "entries", "for", "the", "given", "models", ".", ":", "param", "commit", ":", "This", "is", "ignored", "by", "H...
python
train
DallasMorningNews/django-datafreezer
datafreezer/views.py
https://github.com/DallasMorningNews/django-datafreezer/blob/982dcf2015c80a280f1a093e32977cb71d4ea7aa/datafreezer/views.py#L264-L299
def grab_names_from_emails(email_list): """Return a dictionary mapping names to email addresses. Only gives a response if the email is found in the staff API/JSON. Expects an API of the format = [ { 'email': 'foo@bar.net', ... 'fullName': 'Frank Oo' ...
[ "def", "grab_names_from_emails", "(", "email_list", ")", ":", "all_staff", "=", "STAFF_LIST", "emails_names", "=", "{", "}", "for", "email", "in", "email_list", ":", "for", "person", "in", "all_staff", ":", "if", "email", "==", "person", "[", "'email'", "]",...
Return a dictionary mapping names to email addresses. Only gives a response if the email is found in the staff API/JSON. Expects an API of the format = [ { 'email': 'foo@bar.net', ... 'fullName': 'Frank Oo' }, ... ]
[ "Return", "a", "dictionary", "mapping", "names", "to", "email", "addresses", "." ]
python
train
awacha/credolib
credolib/io.py
https://github.com/awacha/credolib/blob/11c0be3eea7257d3d6e13697d3e76ce538f2f1b2/credolib/io.py#L29-L55
def load_headers(fsns:List[int]): """Load header files """ ip = get_ipython() ip.user_ns['_headers'] = {} for type_ in ['raw', 'processed']: print("Loading %d headers (%s)" % (len(fsns), type_), flush=True) processed = type_ == 'processed' headers = [] for f in fsns: ...
[ "def", "load_headers", "(", "fsns", ":", "List", "[", "int", "]", ")", ":", "ip", "=", "get_ipython", "(", ")", "ip", ".", "user_ns", "[", "'_headers'", "]", "=", "{", "}", "for", "type_", "in", "[", "'raw'", ",", "'processed'", "]", ":", "print", ...
Load header files
[ "Load", "header", "files" ]
python
train
flyte/upnpclient
upnpclient/upnp.py
https://github.com/flyte/upnpclient/blob/5529b950df33c0eaf0c24a9a307cf00fe627d0ad/upnpclient/upnp.py#L456-L543
def validate_arg(arg, argdef): """ Validate an incoming (unicode) string argument according the UPnP spec. Raises UPNPError. """ datatype = argdef['datatype'] reasons = set() ranges = { 'ui1': (int, 0, 255), 'ui2': (int, 0, 65535), 'ui4...
[ "def", "validate_arg", "(", "arg", ",", "argdef", ")", ":", "datatype", "=", "argdef", "[", "'datatype'", "]", "reasons", "=", "set", "(", ")", "ranges", "=", "{", "'ui1'", ":", "(", "int", ",", "0", ",", "255", ")", ",", "'ui2'", ":", "(", "int"...
Validate an incoming (unicode) string argument according the UPnP spec. Raises UPNPError.
[ "Validate", "an", "incoming", "(", "unicode", ")", "string", "argument", "according", "the", "UPnP", "spec", ".", "Raises", "UPNPError", "." ]
python
train
koordinates/python-client
koordinates/layers.py
https://github.com/koordinates/python-client/blob/f3dc7cd164f5a9499b2454cd1d4516e9d4b3c252/koordinates/layers.py#L271-L284
def publish(self, version_id=None): """ Creates a publish task just for this version, which publishes as soon as any import is complete. :return: the publish task :rtype: Publish :raises Conflict: If the version is already published, or already has a publish job. """ ...
[ "def", "publish", "(", "self", ",", "version_id", "=", "None", ")", ":", "if", "not", "version_id", ":", "version_id", "=", "self", ".", "version", ".", "id", "target_url", "=", "self", ".", "_client", ".", "get_url", "(", "'VERSION'", ",", "'POST'", "...
Creates a publish task just for this version, which publishes as soon as any import is complete. :return: the publish task :rtype: Publish :raises Conflict: If the version is already published, or already has a publish job.
[ "Creates", "a", "publish", "task", "just", "for", "this", "version", "which", "publishes", "as", "soon", "as", "any", "import", "is", "complete", "." ]
python
train
Enteee/pdml2flow
pdml2flow/autovivification.py
https://github.com/Enteee/pdml2flow/blob/bc9efe379b0b2406bfbbbd8e0f678b1f63805c66/pdml2flow/autovivification.py#L57-L67
def cast_dicts(self, to=DEFAULT, d=DEFAULT): """Returns a copy of d with all dicts casted to the type 'to'.""" if to is DEFAULT: to = type(self) if d is DEFAULT: d = self if isinstance(d, list): return [v for v in (self.cast_dicts(to, v) for v in d)] ...
[ "def", "cast_dicts", "(", "self", ",", "to", "=", "DEFAULT", ",", "d", "=", "DEFAULT", ")", ":", "if", "to", "is", "DEFAULT", ":", "to", "=", "type", "(", "self", ")", "if", "d", "is", "DEFAULT", ":", "d", "=", "self", "if", "isinstance", "(", ...
Returns a copy of d with all dicts casted to the type 'to'.
[ "Returns", "a", "copy", "of", "d", "with", "all", "dicts", "casted", "to", "the", "type", "to", "." ]
python
train
HDI-Project/MLPrimitives
mlprimitives/custom/timeseries_preprocessing.py
https://github.com/HDI-Project/MLPrimitives/blob/bf415f9f751724ff545a1156ddfd7524e320f469/mlprimitives/custom/timeseries_preprocessing.py#L7-L23
def rolling_window_sequences(X, index, window_size, target_size, target_column): """Create rolling window sequences out of timeseries data.""" out_X = list() out_y = list() X_index = list() y_index = list() target = X[:, target_column] for start in range(len(X) - window_size - target_size ...
[ "def", "rolling_window_sequences", "(", "X", ",", "index", ",", "window_size", ",", "target_size", ",", "target_column", ")", ":", "out_X", "=", "list", "(", ")", "out_y", "=", "list", "(", ")", "X_index", "=", "list", "(", ")", "y_index", "=", "list", ...
Create rolling window sequences out of timeseries data.
[ "Create", "rolling", "window", "sequences", "out", "of", "timeseries", "data", "." ]
python
train
pgmpy/pgmpy
pgmpy/base/DAG.py
https://github.com/pgmpy/pgmpy/blob/9381a66aba3c3871d3ccd00672b148d17d63239e/pgmpy/base/DAG.py#L127-L170
def add_nodes_from(self, nodes, weights=None): """ Add multiple nodes to the Graph. **The behviour of adding weights is different than in networkx. Parameters ---------- nodes: iterable container A container of nodes (list, dict, set, or any hashable python ...
[ "def", "add_nodes_from", "(", "self", ",", "nodes", ",", "weights", "=", "None", ")", ":", "nodes", "=", "list", "(", "nodes", ")", "if", "weights", ":", "if", "len", "(", "nodes", ")", "!=", "len", "(", "weights", ")", ":", "raise", "ValueError", ...
Add multiple nodes to the Graph. **The behviour of adding weights is different than in networkx. Parameters ---------- nodes: iterable container A container of nodes (list, dict, set, or any hashable python object). weights: list, tuple (default=None) ...
[ "Add", "multiple", "nodes", "to", "the", "Graph", "." ]
python
train
tommyod/streprogen
streprogen/program.py
https://github.com/tommyod/streprogen/blob/21b903618e8b2d398bceb394d18d7c74ca984def/streprogen/program.py#L415-L439
def _initialize_render_dictionary(self): """Initialize a dictionary for rendered values. Examples ------- >>> program = Program('My training program') >>> program._initialize_render_dictionary() >>> program._rendered is False False """ s...
[ "def", "_initialize_render_dictionary", "(", "self", ")", ":", "self", ".", "_rendered", "=", "dict", "(", ")", "# Iterate over all weeks", "for", "week", "in", "range", "(", "1", ",", "self", ".", "duration", "+", "1", ")", ":", "self", ".", "_rendered", ...
Initialize a dictionary for rendered values. Examples ------- >>> program = Program('My training program') >>> program._initialize_render_dictionary() >>> program._rendered is False False
[ "Initialize", "a", "dictionary", "for", "rendered", "values", ".", "Examples", "-------", ">>>", "program", "=", "Program", "(", "My", "training", "program", ")", ">>>", "program", ".", "_initialize_render_dictionary", "()", ">>>", "program", ".", "_rendered", "...
python
train
materialsproject/pymatgen
pymatgen/electronic_structure/dos.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/electronic_structure/dos.py#L635-L658
def get_site_t2g_eg_resolved_dos(self, site): """ Get the t2g, eg projected DOS for a particular site. Args: site: Site in Structure associated with CompleteDos. Returns: A dict {"e_g": Dos, "t2g": Dos} containing summed e_g and t2g DOS for the site....
[ "def", "get_site_t2g_eg_resolved_dos", "(", "self", ",", "site", ")", ":", "t2g_dos", "=", "[", "]", "eg_dos", "=", "[", "]", "for", "s", ",", "atom_dos", "in", "self", ".", "pdos", ".", "items", "(", ")", ":", "if", "s", "==", "site", ":", "for", ...
Get the t2g, eg projected DOS for a particular site. Args: site: Site in Structure associated with CompleteDos. Returns: A dict {"e_g": Dos, "t2g": Dos} containing summed e_g and t2g DOS for the site.
[ "Get", "the", "t2g", "eg", "projected", "DOS", "for", "a", "particular", "site", "." ]
python
train
google/grumpy
third_party/stdlib/difflib.py
https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/difflib.py#L764-L810
def get_close_matches(word, possibilities, n=3, cutoff=0.6): """Use SequenceMatcher to return list of the best "good enough" matches. word is a sequence for which close matches are desired (typically a string). possibilities is a list of sequences against which to match word (typically a list of s...
[ "def", "get_close_matches", "(", "word", ",", "possibilities", ",", "n", "=", "3", ",", "cutoff", "=", "0.6", ")", ":", "if", "not", "n", ">", "0", ":", "raise", "ValueError", "(", "\"n must be > 0: %r\"", "%", "(", "n", ",", ")", ")", "if", "not", ...
Use SequenceMatcher to return list of the best "good enough" matches. word is a sequence for which close matches are desired (typically a string). possibilities is a list of sequences against which to match word (typically a list of strings). Optional arg n (default 3) is the maximum number of cl...
[ "Use", "SequenceMatcher", "to", "return", "list", "of", "the", "best", "good", "enough", "matches", "." ]
python
valid
jpmml/sklearn2pmml
sklearn2pmml/__init__.py
https://github.com/jpmml/sklearn2pmml/blob/0a455a54323989473c16f9efc9a77cef3ff64c1e/sklearn2pmml/__init__.py#L181-L258
def sklearn2pmml(pipeline, pmml, user_classpath = [], with_repr = False, debug = False, java_encoding = "UTF-8"): """Converts a fitted Scikit-Learn pipeline to PMML. Parameters: ---------- pipeline: PMMLPipeline The pipeline. pmml: string The path to where the PMML document should be stored. user_classpath...
[ "def", "sklearn2pmml", "(", "pipeline", ",", "pmml", ",", "user_classpath", "=", "[", "]", ",", "with_repr", "=", "False", ",", "debug", "=", "False", ",", "java_encoding", "=", "\"UTF-8\"", ")", ":", "if", "debug", ":", "java_version", "=", "_java_version...
Converts a fitted Scikit-Learn pipeline to PMML. Parameters: ---------- pipeline: PMMLPipeline The pipeline. pmml: string The path to where the PMML document should be stored. user_classpath: list of strings, optional The paths to JAR files that provide custom Transformer, Selector and/or Estimator conver...
[ "Converts", "a", "fitted", "Scikit", "-", "Learn", "pipeline", "to", "PMML", "." ]
python
valid
Robpol86/libnl
libnl/msg.py
https://github.com/Robpol86/libnl/blob/274e9fdaa39822d06ef70b799ed4a95937a4d923/libnl/msg.py#L86-L99
def nlmsg_attrdata(nlh, hdrlen): """Head of attributes data. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L143 Positional arguments: nlh -- Netlink message header (nlmsghdr class instance). hdrlen -- length of family specific header (integer). Returns: First attribute (nlat...
[ "def", "nlmsg_attrdata", "(", "nlh", ",", "hdrlen", ")", ":", "data", "=", "nlmsg_data", "(", "nlh", ")", "return", "libnl", ".", "linux_private", ".", "netlink", ".", "nlattr", "(", "bytearray_ptr", "(", "data", ",", "libnl", ".", "linux_private", ".", ...
Head of attributes data. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L143 Positional arguments: nlh -- Netlink message header (nlmsghdr class instance). hdrlen -- length of family specific header (integer). Returns: First attribute (nlattr class instance with others in its pay...
[ "Head", "of", "attributes", "data", "." ]
python
train
zsimic/runez
src/runez/logsetup.py
https://github.com/zsimic/runez/blob/14363b719a1aae1528859a501a22d075ce0abfcc/src/runez/logsetup.py#L513-L522
def _get_formatter(fmt): """ Args: fmt (str | unicode): Format specification Returns: (logging.Formatter): Associated logging formatter """ fmt = _replace_and_pad(fmt, "%(timezone)s", LogManager.spec.timezone) return logging.Formatter(fmt)
[ "def", "_get_formatter", "(", "fmt", ")", ":", "fmt", "=", "_replace_and_pad", "(", "fmt", ",", "\"%(timezone)s\"", ",", "LogManager", ".", "spec", ".", "timezone", ")", "return", "logging", ".", "Formatter", "(", "fmt", ")" ]
Args: fmt (str | unicode): Format specification Returns: (logging.Formatter): Associated logging formatter
[ "Args", ":", "fmt", "(", "str", "|", "unicode", ")", ":", "Format", "specification" ]
python
train
ultrabug/py3status
py3status/formatter.py
https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/formatter.py#L483-L497
def update_commands(self, commands_str): """ update with commands from the block """ commands = dict(parse_qsl(commands_str, keep_blank_values=True)) _if = commands.get("if", self._if) if _if: self._if = Condition(_if) self._set_int(commands, "max_leng...
[ "def", "update_commands", "(", "self", ",", "commands_str", ")", ":", "commands", "=", "dict", "(", "parse_qsl", "(", "commands_str", ",", "keep_blank_values", "=", "True", ")", ")", "_if", "=", "commands", ".", "get", "(", "\"if\"", ",", "self", ".", "_...
update with commands from the block
[ "update", "with", "commands", "from", "the", "block" ]
python
train
bitesofcode/projexui
projexui/completers/xquerycompleter.py
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/completers/xquerycompleter.py#L49-L65
def pathFromIndex( self, index ): """ Returns the joined path from the given model index. This will join together the full path with periods. :param index | <QModelIndex> :return <str> """ item = self._model.itemFromIndex(index...
[ "def", "pathFromIndex", "(", "self", ",", "index", ")", ":", "item", "=", "self", ".", "_model", ".", "itemFromIndex", "(", "index", ")", "out", "=", "[", "]", "while", "(", "item", ")", ":", "out", ".", "append", "(", "nativestring", "(", "item", ...
Returns the joined path from the given model index. This will join together the full path with periods. :param index | <QModelIndex> :return <str>
[ "Returns", "the", "joined", "path", "from", "the", "given", "model", "index", ".", "This", "will", "join", "together", "the", "full", "path", "with", "periods", ".", ":", "param", "index", "|", "<QModelIndex", ">", ":", "return", "<str", ">" ]
python
train
aiidateam/aiida-codtools
aiida_codtools/workflows/cif_clean.py
https://github.com/aiidateam/aiida-codtools/blob/da5e4259b7a2e86cf0cc3f997e11dd36d445fa94/aiida_codtools/workflows/cif_clean.py#L103-L110
def inspect_filter_calculation(self): """Inspect the result of the CifFilterCalculation, verifying that it produced a CifData output node.""" try: node = self.ctx.cif_filter self.ctx.cif = node.outputs.cif except exceptions.NotExistent: self.report('aborting: ...
[ "def", "inspect_filter_calculation", "(", "self", ")", ":", "try", ":", "node", "=", "self", ".", "ctx", ".", "cif_filter", "self", ".", "ctx", ".", "cif", "=", "node", ".", "outputs", ".", "cif", "except", "exceptions", ".", "NotExistent", ":", "self", ...
Inspect the result of the CifFilterCalculation, verifying that it produced a CifData output node.
[ "Inspect", "the", "result", "of", "the", "CifFilterCalculation", "verifying", "that", "it", "produced", "a", "CifData", "output", "node", "." ]
python
train
jobovy/galpy
galpy/orbit/Orbit.py
https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/orbit/Orbit.py#L2453-L2489
def pmra(self,*args,**kwargs): """ NAME: pmra PURPOSE: return proper motion in right ascension (in mas/yr) INPUT: t - (optional) time at which to get pmra (can be Quantity) obs=[X,Y,Z,vx,vy,vz] - (optional) position and velocity of observ...
[ "def", "pmra", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "out", "=", "self", ".", "_orb", ".", "pmra", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "len", "(", "out", ")", "==", "1", ":", "return", "out", "[...
NAME: pmra PURPOSE: return proper motion in right ascension (in mas/yr) INPUT: t - (optional) time at which to get pmra (can be Quantity) obs=[X,Y,Z,vx,vy,vz] - (optional) position and velocity of observer in the Galactocentric ...
[ "NAME", ":" ]
python
train
seleniumbase/SeleniumBase
seleniumbase/fixtures/base_case.py
https://github.com/seleniumbase/SeleniumBase/blob/62e5b43ee1f90a9ed923841bdd53b1b38358f43a/seleniumbase/fixtures/base_case.py#L589-L596
def send_keys(self, selector, new_value, by=By.CSS_SELECTOR, timeout=settings.LARGE_TIMEOUT): """ Same as add_text() -> more reliable, but less name confusion. """ if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT: timeout = self.__get_new_timeout(timeout) ...
[ "def", "send_keys", "(", "self", ",", "selector", ",", "new_value", ",", "by", "=", "By", ".", "CSS_SELECTOR", ",", "timeout", "=", "settings", ".", "LARGE_TIMEOUT", ")", ":", "if", "self", ".", "timeout_multiplier", "and", "timeout", "==", "settings", "."...
Same as add_text() -> more reliable, but less name confusion.
[ "Same", "as", "add_text", "()", "-", ">", "more", "reliable", "but", "less", "name", "confusion", "." ]
python
train
seleniumbase/SeleniumBase
seleniumbase/core/s3_manager.py
https://github.com/seleniumbase/SeleniumBase/blob/62e5b43ee1f90a9ed923841bdd53b1b38358f43a/seleniumbase/core/s3_manager.py#L36-L55
def upload_file(self, file_name, file_path): """ Upload a given file from the file_path to the bucket with the new name/path file_name. """ upload_key = Key(bucket=self.bucket, name=file_name) content_type = "text/plain" if file_name.endswith(".html"): content_typ...
[ "def", "upload_file", "(", "self", ",", "file_name", ",", "file_path", ")", ":", "upload_key", "=", "Key", "(", "bucket", "=", "self", ".", "bucket", ",", "name", "=", "file_name", ")", "content_type", "=", "\"text/plain\"", "if", "file_name", ".", "endswi...
Upload a given file from the file_path to the bucket with the new name/path file_name.
[ "Upload", "a", "given", "file", "from", "the", "file_path", "to", "the", "bucket", "with", "the", "new", "name", "/", "path", "file_name", "." ]
python
train
ff0000/scarlet
scarlet/cms/widgets.py
https://github.com/ff0000/scarlet/blob/6c37befd810916a2d7ffff2cdb2dab57bcb6d12e/scarlet/cms/widgets.py#L640-L660
def update_links(self, request, admin_site=None): """ Called to update the widget's urls. Tries to find the bundle for the model that this foreign key points to and then asks it for the urls for adding and listing and sets them on this widget instance. The urls are only set if re...
[ "def", "update_links", "(", "self", ",", "request", ",", "admin_site", "=", "None", ")", ":", "if", "admin_site", ":", "bundle", "=", "admin_site", ".", "get_bundle_for_model", "(", "self", ".", "model", ".", "to", ")", "if", "bundle", ":", "self", ".", ...
Called to update the widget's urls. Tries to find the bundle for the model that this foreign key points to and then asks it for the urls for adding and listing and sets them on this widget instance. The urls are only set if request.user has permissions on that url. :param reques...
[ "Called", "to", "update", "the", "widget", "s", "urls", ".", "Tries", "to", "find", "the", "bundle", "for", "the", "model", "that", "this", "foreign", "key", "points", "to", "and", "then", "asks", "it", "for", "the", "urls", "for", "adding", "and", "li...
python
train
fedora-infra/fedmsg
fedmsg/crypto/__init__.py
https://github.com/fedora-infra/fedmsg/blob/c21d6b3ce023fc3c0e881c704f5b55fb6e6392d7/fedmsg/crypto/__init__.py#L166-L192
def init(**config): """ Initialize the crypto backend. The backend can be one of two plugins: - 'x509' - Uses x509 certificates. - 'gpg' - Uses GnuPG keys. """ global _implementation global _validate_implementations if config.get('crypto_backend') == 'gpg': _implementa...
[ "def", "init", "(", "*", "*", "config", ")", ":", "global", "_implementation", "global", "_validate_implementations", "if", "config", ".", "get", "(", "'crypto_backend'", ")", "==", "'gpg'", ":", "_implementation", "=", "gpg", "else", ":", "_implementation", "...
Initialize the crypto backend. The backend can be one of two plugins: - 'x509' - Uses x509 certificates. - 'gpg' - Uses GnuPG keys.
[ "Initialize", "the", "crypto", "backend", "." ]
python
train
dagster-io/dagster
python_modules/dagster/dagster/core/execution.py
https://github.com/dagster-io/dagster/blob/4119f8c773089de64831b1dfb9e168e353d401dc/python_modules/dagster/dagster/core/execution.py#L222-L239
def transformed_values(self): '''Return dictionary of transformed results, with keys being output names. Returns None if execution result isn't a success. Reconstructs the pipeline context to materialize values. ''' if self.success and self.transforms: with self.reco...
[ "def", "transformed_values", "(", "self", ")", ":", "if", "self", ".", "success", "and", "self", ".", "transforms", ":", "with", "self", ".", "reconstruct_context", "(", ")", "as", "context", ":", "values", "=", "{", "result", ".", "step_output_data", ".",...
Return dictionary of transformed results, with keys being output names. Returns None if execution result isn't a success. Reconstructs the pipeline context to materialize values.
[ "Return", "dictionary", "of", "transformed", "results", "with", "keys", "being", "output", "names", ".", "Returns", "None", "if", "execution", "result", "isn", "t", "a", "success", "." ]
python
test
ARMmbed/icetea
icetea_lib/tools/tools.py
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/tools.py#L350-L367
def recursive_dictionary_get(keys, dictionary): """ Gets contents of requirement key recursively so users can search for specific keys inside nested requirement dicts. :param keys: key or dot separated string of keys to look for. :param dictionary: Dictionary to search from :return: results of ...
[ "def", "recursive_dictionary_get", "(", "keys", ",", "dictionary", ")", ":", "if", "\".\"", "in", "keys", "and", "len", "(", "keys", ")", ">", "1", ":", "key", "=", "keys", ".", "split", "(", "\".\"", ",", "1", ")", "new_dict", "=", "dictionary", "."...
Gets contents of requirement key recursively so users can search for specific keys inside nested requirement dicts. :param keys: key or dot separated string of keys to look for. :param dictionary: Dictionary to search from :return: results of search or None
[ "Gets", "contents", "of", "requirement", "key", "recursively", "so", "users", "can", "search", "for", "specific", "keys", "inside", "nested", "requirement", "dicts", "." ]
python
train
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/configuration.py
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/configuration.py#L82-L106
def load(self, updates): """Load configuration data""" # Go through in order and override the config (`.mbed_cloud_config.json` loader) for path in self.paths(): if not path: continue abs_path = os.path.abspath(os.path.expanduser(path)) if not ...
[ "def", "load", "(", "self", ",", "updates", ")", ":", "# Go through in order and override the config (`.mbed_cloud_config.json` loader)", "for", "path", "in", "self", ".", "paths", "(", ")", ":", "if", "not", "path", ":", "continue", "abs_path", "=", "os", ".", ...
Load configuration data
[ "Load", "configuration", "data" ]
python
train
bspaans/python-mingus
mingus/extra/lilypond.py
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/extra/lilypond.py#L186-L195
def from_Composition(composition): """Return the LilyPond equivalent of a Composition in a string.""" # warning Throw exception if not hasattr(composition, 'tracks'): return False result = '\\header { title = "%s" composer = "%s" opus = "%s" } '\ % (composition.title, composition.author...
[ "def", "from_Composition", "(", "composition", ")", ":", "# warning Throw exception", "if", "not", "hasattr", "(", "composition", ",", "'tracks'", ")", ":", "return", "False", "result", "=", "'\\\\header { title = \"%s\" composer = \"%s\" opus = \"%s\" } '", "%", "(", "...
Return the LilyPond equivalent of a Composition in a string.
[ "Return", "the", "LilyPond", "equivalent", "of", "a", "Composition", "in", "a", "string", "." ]
python
train
saltstack/salt
salt/states/boto_datapipeline.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_datapipeline.py#L395-L406
def _diff(old_pipeline_definition, new_pipeline_definition): ''' Return string diff of pipeline definitions. ''' old_pipeline_definition.pop('ResponseMetadata', None) new_pipeline_definition.pop('ResponseMetadata', None) diff = salt.utils.data.decode(difflib.unified_diff( salt.utils.jso...
[ "def", "_diff", "(", "old_pipeline_definition", ",", "new_pipeline_definition", ")", ":", "old_pipeline_definition", ".", "pop", "(", "'ResponseMetadata'", ",", "None", ")", "new_pipeline_definition", ".", "pop", "(", "'ResponseMetadata'", ",", "None", ")", "diff", ...
Return string diff of pipeline definitions.
[ "Return", "string", "diff", "of", "pipeline", "definitions", "." ]
python
train
binux/pyspider
pyspider/libs/url.py
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/url.py#L29-L59
def _build_url(url, _params): """Build the actual URL to use.""" # Support for unicode domain names and paths. scheme, netloc, path, params, query, fragment = urlparse(url) netloc = netloc.encode('idna').decode('utf-8') if not path: path = '/' if six.PY2: if isinstance(scheme, ...
[ "def", "_build_url", "(", "url", ",", "_params", ")", ":", "# Support for unicode domain names and paths.", "scheme", ",", "netloc", ",", "path", ",", "params", ",", "query", ",", "fragment", "=", "urlparse", "(", "url", ")", "netloc", "=", "netloc", ".", "e...
Build the actual URL to use.
[ "Build", "the", "actual", "URL", "to", "use", "." ]
python
train
mikedh/trimesh
trimesh/base.py
https://github.com/mikedh/trimesh/blob/25e059bf6d4caa74f62ffd58ce4f61a90ee4e518/trimesh/base.py#L467-L483
def bounds(self): """ The axis aligned bounds of the faces of the mesh. Returns ----------- bounds : (2, 3) float Bounding box with [min, max] coordinates """ # return bounds including ONLY referenced vertices in_mesh = self.vertices[self.refere...
[ "def", "bounds", "(", "self", ")", ":", "# return bounds including ONLY referenced vertices", "in_mesh", "=", "self", ".", "vertices", "[", "self", ".", "referenced_vertices", "]", "# get mesh bounds with min and max", "mesh_bounds", "=", "np", ".", "array", "(", "[",...
The axis aligned bounds of the faces of the mesh. Returns ----------- bounds : (2, 3) float Bounding box with [min, max] coordinates
[ "The", "axis", "aligned", "bounds", "of", "the", "faces", "of", "the", "mesh", "." ]
python
train
OCHA-DAP/hdx-python-utilities
src/hdx/utilities/text.py
https://github.com/OCHA-DAP/hdx-python-utilities/blob/9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3/src/hdx/utilities/text.py#L97-L168
def get_matching_then_nonmatching_text(string_list, separator='', match_min_size=30, ignore='', end_characters='.!\r\n'): # type: (List[str], str, int, str, str) -> str """Returns a string containing matching blocks of text in a list of strings followed by non-matching. ...
[ "def", "get_matching_then_nonmatching_text", "(", "string_list", ",", "separator", "=", "''", ",", "match_min_size", "=", "30", ",", "ignore", "=", "''", ",", "end_characters", "=", "'.!\\r\\n'", ")", ":", "# type: (List[str], str, int, str, str) -> str", "def", "add_...
Returns a string containing matching blocks of text in a list of strings followed by non-matching. Args: string_list (List[str]): List of strings to match separator (str): Separator to add between blocks of text. Defaults to ''. match_min_size (int): Minimum block size to match on. Defaults...
[ "Returns", "a", "string", "containing", "matching", "blocks", "of", "text", "in", "a", "list", "of", "strings", "followed", "by", "non", "-", "matching", "." ]
python
train
gem/oq-engine
openquake/hazardlib/calc/hazard_curve.py
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/calc/hazard_curve.py#L71-L91
def _cluster(param, tom, imtls, gsims, grp_ids, pmap): """ Computes the probability map in case of a cluster group """ pmapclu = AccumDict({grp_id: ProbabilityMap(len(imtls.array), len(gsims)) for grp_id in grp_ids}) # Get temporal occurrence model # Number of occurrence...
[ "def", "_cluster", "(", "param", ",", "tom", ",", "imtls", ",", "gsims", ",", "grp_ids", ",", "pmap", ")", ":", "pmapclu", "=", "AccumDict", "(", "{", "grp_id", ":", "ProbabilityMap", "(", "len", "(", "imtls", ".", "array", ")", ",", "len", "(", "g...
Computes the probability map in case of a cluster group
[ "Computes", "the", "probability", "map", "in", "case", "of", "a", "cluster", "group" ]
python
train
tgalal/yowsup
yowsup/layers/noise/layer.py
https://github.com/tgalal/yowsup/blob/b0739461ba962bf221fc76047d9d60d8ce61bc3e/yowsup/layers/noise/layer.py#L131-L139
def send(self, data): """ :param data: :type data: bytearray | bytes :return: :rtype: """ data = bytes(data) if type(data) is not bytes else data self._wa_noiseprotocol.send(data)
[ "def", "send", "(", "self", ",", "data", ")", ":", "data", "=", "bytes", "(", "data", ")", "if", "type", "(", "data", ")", "is", "not", "bytes", "else", "data", "self", ".", "_wa_noiseprotocol", ".", "send", "(", "data", ")" ]
:param data: :type data: bytearray | bytes :return: :rtype:
[ ":", "param", "data", ":", ":", "type", "data", ":", "bytearray", "|", "bytes", ":", "return", ":", ":", "rtype", ":" ]
python
train
ASKIDA/Selenium2LibraryExtension
src/Selenium2LibraryExtension/keywords/__init__.py
https://github.com/ASKIDA/Selenium2LibraryExtension/blob/5ca3fa776063c6046dff317cb2575e4772d7541f/src/Selenium2LibraryExtension/keywords/__init__.py#L35-L44
def wait_until_element_does_not_have_focus(self, locator, timeout=None): """Waits until the element identified by `locator` doesn't have focus. You might rather want to use `Element Focus Should Not Be Set` | *Argument* | *Description* | *Example* | | locator | Selenium 2 element locator | id=my_id | | timeo...
[ "def", "wait_until_element_does_not_have_focus", "(", "self", ",", "locator", ",", "timeout", "=", "None", ")", ":", "self", ".", "_info", "(", "\"Waiting until '%s' does not have focus\"", "%", "(", "locator", ")", ")", "self", ".", "_wait_until_no_error", "(", "...
Waits until the element identified by `locator` doesn't have focus. You might rather want to use `Element Focus Should Not Be Set` | *Argument* | *Description* | *Example* | | locator | Selenium 2 element locator | id=my_id | | timeout | maximum time to wait before the function throws an element not found erro...
[ "Waits", "until", "the", "element", "identified", "by", "locator", "doesn", "t", "have", "focus", ".", "You", "might", "rather", "want", "to", "use", "Element", "Focus", "Should", "Not", "Be", "Set" ]
python
train
enkore/i3pystatus
i3pystatus/core/io.py
https://github.com/enkore/i3pystatus/blob/14cfde967cecf79b40e223e35a04600f4c875af7/i3pystatus/core/io.py#L158-L176
def suspend_signal_handler(self, signo, frame): """ By default, i3bar sends SIGSTOP to all children when it is not visible (for example, the screen sleeps or you enter full screen mode). This stops the i3pystatus process and all threads within it. For some modules, this is not desirable....
[ "def", "suspend_signal_handler", "(", "self", ",", "signo", ",", "frame", ")", ":", "if", "signo", "!=", "signal", ".", "SIGUSR2", ":", "return", "self", ".", "stopped", "=", "not", "self", ".", "stopped", "if", "self", ".", "stopped", ":", "[", "m", ...
By default, i3bar sends SIGSTOP to all children when it is not visible (for example, the screen sleeps or you enter full screen mode). This stops the i3pystatus process and all threads within it. For some modules, this is not desirable. Thankfully, the i3bar protocol supports setting the "stop_signal" ...
[ "By", "default", "i3bar", "sends", "SIGSTOP", "to", "all", "children", "when", "it", "is", "not", "visible", "(", "for", "example", "the", "screen", "sleeps", "or", "you", "enter", "full", "screen", "mode", ")", ".", "This", "stops", "the", "i3pystatus", ...
python
train
kstateome/django-cas
cas/backends.py
https://github.com/kstateome/django-cas/blob/8a871093966f001b4dadf7d097ac326169f3c066/cas/backends.py#L75-L138
def _internal_verify_cas(ticket, service, suffix): """Verifies CAS 2.0 and 3.0 XML-based authentication ticket. Returns username on success and None on failure. """ params = {'ticket': ticket, 'service': service} if settings.CAS_PROXY_CALLBACK: params['pgtUrl'] = settings.CAS_PROXY_CALLBAC...
[ "def", "_internal_verify_cas", "(", "ticket", ",", "service", ",", "suffix", ")", ":", "params", "=", "{", "'ticket'", ":", "ticket", ",", "'service'", ":", "service", "}", "if", "settings", ".", "CAS_PROXY_CALLBACK", ":", "params", "[", "'pgtUrl'", "]", "...
Verifies CAS 2.0 and 3.0 XML-based authentication ticket. Returns username on success and None on failure.
[ "Verifies", "CAS", "2", ".", "0", "and", "3", ".", "0", "XML", "-", "based", "authentication", "ticket", "." ]
python
train
mkoura/dump2polarion
dump2polarion/csv2sqlite_cli.py
https://github.com/mkoura/dump2polarion/blob/f4bd24e9d5070e282aad15f1e8bb514c0525cd37/dump2polarion/csv2sqlite_cli.py#L80-L113
def main(args=None): """Main function for cli.""" args = get_args(args) utils.init_log(args.log_level) if ".csv" not in args.input_file.lower(): logger.warning("Make sure the input file '%s' is in CSV format", args.input_file) try: records = csvtools.get_imported_data(args.input_f...
[ "def", "main", "(", "args", "=", "None", ")", ":", "args", "=", "get_args", "(", "args", ")", "utils", ".", "init_log", "(", "args", ".", "log_level", ")", "if", "\".csv\"", "not", "in", "args", ".", "input_file", ".", "lower", "(", ")", ":", "logg...
Main function for cli.
[ "Main", "function", "for", "cli", "." ]
python
train
danilobellini/dose
dose/watcher.py
https://github.com/danilobellini/dose/blob/141f48322f7812b7d32e3d5f065d4473a11102a4/dose/watcher.py#L8-L12
def to_unicode(path, errors="replace"): """Given a bytestring/unicode path, return it as unicode.""" if isinstance(path, UNICODE): return path return path.decode(sys.getfilesystemencoding(), errors)
[ "def", "to_unicode", "(", "path", ",", "errors", "=", "\"replace\"", ")", ":", "if", "isinstance", "(", "path", ",", "UNICODE", ")", ":", "return", "path", "return", "path", ".", "decode", "(", "sys", ".", "getfilesystemencoding", "(", ")", ",", "errors"...
Given a bytestring/unicode path, return it as unicode.
[ "Given", "a", "bytestring", "/", "unicode", "path", "return", "it", "as", "unicode", "." ]
python
train
gboeing/osmnx
osmnx/utils.py
https://github.com/gboeing/osmnx/blob/be59fd313bcb68af8fc79242c56194f1247e26e2/osmnx/utils.py#L426-L498
def get_nearest_node(G, point, method='haversine', return_dist=False): """ Return the graph node nearest to some specified (lat, lng) or (y, x) point, and optionally the distance between the node and the point. This function can use either a haversine or euclidean distance calculator. Parameters ...
[ "def", "get_nearest_node", "(", "G", ",", "point", ",", "method", "=", "'haversine'", ",", "return_dist", "=", "False", ")", ":", "start_time", "=", "time", ".", "time", "(", ")", "if", "not", "G", "or", "(", "G", ".", "number_of_nodes", "(", ")", "=...
Return the graph node nearest to some specified (lat, lng) or (y, x) point, and optionally the distance between the node and the point. This function can use either a haversine or euclidean distance calculator. Parameters ---------- G : networkx multidigraph point : tuple The (lat, lng)...
[ "Return", "the", "graph", "node", "nearest", "to", "some", "specified", "(", "lat", "lng", ")", "or", "(", "y", "x", ")", "point", "and", "optionally", "the", "distance", "between", "the", "node", "and", "the", "point", ".", "This", "function", "can", ...
python
train
O365/python-o365
O365/utils/attachment.py
https://github.com/O365/python-o365/blob/02a71cf3775cc6a3c042e003365d6a07c8c75a73/O365/utils/attachment.py#L298-L305
def clear(self): """ Clear the attachments """ for attachment in self.__attachments: if attachment.on_cloud: self.__removed_attachments.append(attachment) self.__attachments = [] self._update_parent_attachments() self._track_changes()
[ "def", "clear", "(", "self", ")", ":", "for", "attachment", "in", "self", ".", "__attachments", ":", "if", "attachment", ".", "on_cloud", ":", "self", ".", "__removed_attachments", ".", "append", "(", "attachment", ")", "self", ".", "__attachments", "=", "...
Clear the attachments
[ "Clear", "the", "attachments" ]
python
train
corydodt/Crosscap
crosscap/openapi.py
https://github.com/corydodt/Crosscap/blob/388a2ec36b8aa85e8f1ed692bb6e43474ba76c8e/crosscap/openapi.py#L168-L184
def representCleanOpenAPIParameter(dumper, data): """ Rename python reserved keyword fields before representing an OpenAPIParameter """ dct = _orderedCleanDict(data) # We are using "in_" as a key for the "in" parameter, since in is a Python keyword. # To represent it correctly, we then have to s...
[ "def", "representCleanOpenAPIParameter", "(", "dumper", ",", "data", ")", ":", "dct", "=", "_orderedCleanDict", "(", "data", ")", "# We are using \"in_\" as a key for the \"in\" parameter, since in is a Python keyword.", "# To represent it correctly, we then have to swap \"in_\" for \"...
Rename python reserved keyword fields before representing an OpenAPIParameter
[ "Rename", "python", "reserved", "keyword", "fields", "before", "representing", "an", "OpenAPIParameter" ]
python
train
fjwCode/cerium
cerium/androiddriver.py
https://github.com/fjwCode/cerium/blob/f6e06e0dcf83a0bc924828e9d6cb81383ed2364f/cerium/androiddriver.py#L470-L480
def app_trim_memory(self, pid: int or str, level: str = 'RUNNING_LOW') -> None: '''Trim memory. Args: level: HIDDEN | RUNNING_MODERATE | BACKGROUNDRUNNING_LOW | \ MODERATE | RUNNING_CRITICAL | COMPLETE ''' _, error = self._execute('-s', self.device_sn, '...
[ "def", "app_trim_memory", "(", "self", ",", "pid", ":", "int", "or", "str", ",", "level", ":", "str", "=", "'RUNNING_LOW'", ")", "->", "None", ":", "_", ",", "error", "=", "self", ".", "_execute", "(", "'-s'", ",", "self", ".", "device_sn", ",", "'...
Trim memory. Args: level: HIDDEN | RUNNING_MODERATE | BACKGROUNDRUNNING_LOW | \ MODERATE | RUNNING_CRITICAL | COMPLETE
[ "Trim", "memory", "." ]
python
train
Erotemic/ubelt
ubelt/util_list.py
https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_list.py#L253-L294
def unique(items, key=None): """ Generates unique items in the order they appear. Args: items (Iterable): list of items key (Callable, optional): custom normalization function. If specified returns items where `key(item)` is unique. Yields: object: a unique item fr...
[ "def", "unique", "(", "items", ",", "key", "=", "None", ")", ":", "seen", "=", "set", "(", ")", "if", "key", "is", "None", ":", "for", "item", "in", "items", ":", "if", "item", "not", "in", "seen", ":", "seen", ".", "add", "(", "item", ")", "...
Generates unique items in the order they appear. Args: items (Iterable): list of items key (Callable, optional): custom normalization function. If specified returns items where `key(item)` is unique. Yields: object: a unique item from the input sequence CommandLine: ...
[ "Generates", "unique", "items", "in", "the", "order", "they", "appear", "." ]
python
valid
log2timeline/plaso
plaso/analysis/browser_search.py
https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/analysis/browser_search.py#L203-L222
def _ExtractYandexSearchQuery(self, url): """Extracts a search query from a Yandex search URL. Yandex: https://www.yandex.com/search/?text=query Args: url (str): URL. Returns: str: search query or None if no query was found. """ if 'text=' not in url: return None _, _, l...
[ "def", "_ExtractYandexSearchQuery", "(", "self", ",", "url", ")", ":", "if", "'text='", "not", "in", "url", ":", "return", "None", "_", ",", "_", ",", "line", "=", "url", ".", "partition", "(", "'text='", ")", "before_and", ",", "_", ",", "_", "=", ...
Extracts a search query from a Yandex search URL. Yandex: https://www.yandex.com/search/?text=query Args: url (str): URL. Returns: str: search query or None if no query was found.
[ "Extracts", "a", "search", "query", "from", "a", "Yandex", "search", "URL", "." ]
python
train
googleads/googleads-python-lib
googleads/adwords.py
https://github.com/googleads/googleads-python-lib/blob/aa3b1b474b0f9789ca55ca46f4b2b57aeae38874/googleads/adwords.py#L1916-L1926
def LessThanOrEqualTo(self, value): """Sets the type of the WHERE clause as "less than or equal to. Args: value: The value to be used in the WHERE condition. Returns: The query builder that this WHERE builder links to. """ self._awql = self._CreateSingleValueCondition(value, '<=') ...
[ "def", "LessThanOrEqualTo", "(", "self", ",", "value", ")", ":", "self", ".", "_awql", "=", "self", ".", "_CreateSingleValueCondition", "(", "value", ",", "'<='", ")", "return", "self", ".", "_query_builder" ]
Sets the type of the WHERE clause as "less than or equal to. Args: value: The value to be used in the WHERE condition. Returns: The query builder that this WHERE builder links to.
[ "Sets", "the", "type", "of", "the", "WHERE", "clause", "as", "less", "than", "or", "equal", "to", "." ]
python
train
Kozea/cairocffi
cairocffi/context.py
https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/context.py#L410-L425
def set_antialias(self, antialias): """Set the :ref:`ANTIALIAS` of the rasterizer used for drawing shapes. This value is a hint, and a particular backend may or may not support a particular value. At the current time, no backend supports :obj:`SUBPIXEL <ANTIALIAS_SUBPIXEL>` ...
[ "def", "set_antialias", "(", "self", ",", "antialias", ")", ":", "cairo", ".", "cairo_set_antialias", "(", "self", ".", "_pointer", ",", "antialias", ")", "self", ".", "_check_status", "(", ")" ]
Set the :ref:`ANTIALIAS` of the rasterizer used for drawing shapes. This value is a hint, and a particular backend may or may not support a particular value. At the current time, no backend supports :obj:`SUBPIXEL <ANTIALIAS_SUBPIXEL>` when drawing shapes. Note that this...
[ "Set", "the", ":", "ref", ":", "ANTIALIAS", "of", "the", "rasterizer", "used", "for", "drawing", "shapes", ".", "This", "value", "is", "a", "hint", "and", "a", "particular", "backend", "may", "or", "may", "not", "support", "a", "particular", "value", "."...
python
train
annoviko/pyclustering
pyclustering/cluster/kmeans.py
https://github.com/annoviko/pyclustering/blob/98aa0dd89fd36f701668fb1eb29c8fb5662bf7d0/pyclustering/cluster/kmeans.py#L544-L557
def __calculate_dataset_difference(self, amount_clusters): """! @brief Calculate distance from each point to each cluster center. """ dataset_differences = numpy.zeros((amount_clusters, len(self.__pointer_data))) for index_center in range(amount_clusters): if ...
[ "def", "__calculate_dataset_difference", "(", "self", ",", "amount_clusters", ")", ":", "dataset_differences", "=", "numpy", ".", "zeros", "(", "(", "amount_clusters", ",", "len", "(", "self", ".", "__pointer_data", ")", ")", ")", "for", "index_center", "in", ...
! @brief Calculate distance from each point to each cluster center.
[ "!" ]
python
valid
saltstack/salt
salt/states/iptables.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/iptables.py#L803-L845
def flush(name, table='filter', family='ipv4', **kwargs): ''' .. versionadded:: 2014.1.0 Flush current iptables state table The table that owns the chain that should be modified family Networking family, either ipv4 or ipv6 ''' ret = {'name': name, 'changes': {...
[ "def", "flush", "(", "name", ",", "table", "=", "'filter'", ",", "family", "=", "'ipv4'", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "None", ",", "'comment'", ...
.. versionadded:: 2014.1.0 Flush current iptables state table The table that owns the chain that should be modified family Networking family, either ipv4 or ipv6
[ "..", "versionadded", "::", "2014", ".", "1", ".", "0" ]
python
train
tanghaibao/goatools
goatools/wr_tbl.py
https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/wr_tbl.py#L86-L117
def wr_xlsx_sections(fout_xlsx, xlsx_data, **kws): """Write xlsx file containing section names followed by lines of namedtuple data.""" from goatools.wr_tbl_class import WrXlsx items_str = "items" if "items" not in kws else kws["items"] prt_hdr_min = 10 num_items = 0 if xlsx_data: # Basi...
[ "def", "wr_xlsx_sections", "(", "fout_xlsx", ",", "xlsx_data", ",", "*", "*", "kws", ")", ":", "from", "goatools", ".", "wr_tbl_class", "import", "WrXlsx", "items_str", "=", "\"items\"", "if", "\"items\"", "not", "in", "kws", "else", "kws", "[", "\"items\"",...
Write xlsx file containing section names followed by lines of namedtuple data.
[ "Write", "xlsx", "file", "containing", "section", "names", "followed", "by", "lines", "of", "namedtuple", "data", "." ]
python
train
tensorflow/tensor2tensor
tensor2tensor/utils/sari_hook.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/sari_hook.py#L224-L252
def sari_score(predictions, labels, features, **unused_kwargs): """Computes the SARI scores from the given source, prediction and targets. An approximate SARI scoring method since we do not glue word pieces or decode the ids and tokenize the output. By default, we use ngram order of 4. Also, this does not have...
[ "def", "sari_score", "(", "predictions", ",", "labels", ",", "features", ",", "*", "*", "unused_kwargs", ")", ":", "if", "\"inputs\"", "not", "in", "features", ":", "raise", "ValueError", "(", "\"sari_score requires inputs feature\"", ")", "# Convert the inputs and ...
Computes the SARI scores from the given source, prediction and targets. An approximate SARI scoring method since we do not glue word pieces or decode the ids and tokenize the output. By default, we use ngram order of 4. Also, this does not have beam search. Args: predictions: tensor, model predictions. ...
[ "Computes", "the", "SARI", "scores", "from", "the", "given", "source", "prediction", "and", "targets", "." ]
python
train
ArangoDB-Community/pyArango
pyArango/collection.py
https://github.com/ArangoDB-Community/pyArango/blob/dd72e5f6c540e5e148943d615ddf7553bb78ce0b/pyArango/collection.py#L333-L344
def ensureHashIndex(self, fields, unique = False, sparse = True, deduplicate = False) : """Creates a hash index if it does not already exist, and returns it""" data = { "type" : "hash", "fields" : fields, "unique" : unique, "sparse" : sparse, "...
[ "def", "ensureHashIndex", "(", "self", ",", "fields", ",", "unique", "=", "False", ",", "sparse", "=", "True", ",", "deduplicate", "=", "False", ")", ":", "data", "=", "{", "\"type\"", ":", "\"hash\"", ",", "\"fields\"", ":", "fields", ",", "\"unique\"",...
Creates a hash index if it does not already exist, and returns it
[ "Creates", "a", "hash", "index", "if", "it", "does", "not", "already", "exist", "and", "returns", "it" ]
python
train
nickw444/nsw-fuel-api-client
nsw_fuel/client.py
https://github.com/nickw444/nsw-fuel-api-client/blob/06bd9ae7ad094d5965fce3a9468785247e1b5a39/nsw_fuel/client.py#L34-L45
def get_fuel_prices(self) -> GetFuelPricesResponse: """Fetches fuel prices for all stations.""" response = requests.get( '{}/prices'.format(API_URL_BASE), headers=self._get_headers(), timeout=self._timeout, ) if not response.ok: raise Fuel...
[ "def", "get_fuel_prices", "(", "self", ")", "->", "GetFuelPricesResponse", ":", "response", "=", "requests", ".", "get", "(", "'{}/prices'", ".", "format", "(", "API_URL_BASE", ")", ",", "headers", "=", "self", ".", "_get_headers", "(", ")", ",", "timeout", ...
Fetches fuel prices for all stations.
[ "Fetches", "fuel", "prices", "for", "all", "stations", "." ]
python
valid
spencerahill/aospy
aospy/automate.py
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/automate.py#L355-L508
def submit_mult_calcs(calc_suite_specs, exec_options=None): """Generate and execute all specified computations. Once the calculations are prepped and submitted for execution, any calculation that triggers any exception or error is skipped, and the rest of the calculations proceed unaffected. This prev...
[ "def", "submit_mult_calcs", "(", "calc_suite_specs", ",", "exec_options", "=", "None", ")", ":", "if", "exec_options", "is", "None", ":", "exec_options", "=", "dict", "(", ")", "if", "exec_options", ".", "pop", "(", "'prompt_verify'", ",", "False", ")", ":",...
Generate and execute all specified computations. Once the calculations are prepped and submitted for execution, any calculation that triggers any exception or error is skipped, and the rest of the calculations proceed unaffected. This prevents an error in a single calculation from crashing a large sui...
[ "Generate", "and", "execute", "all", "specified", "computations", "." ]
python
train
mcrute/pydora
pydora/audio_backend.py
https://github.com/mcrute/pydora/blob/d9e353e7f19da741dcf372246b4d5640cb788488/pydora/audio_backend.py#L137-L148
def _ensure_started(self): """Ensure player backing process is started """ if self._process and self._process.poll() is None: return if not getattr(self, "_cmd"): raise RuntimeError("Player command is not configured") log.debug("Starting playback command...
[ "def", "_ensure_started", "(", "self", ")", ":", "if", "self", ".", "_process", "and", "self", ".", "_process", ".", "poll", "(", ")", "is", "None", ":", "return", "if", "not", "getattr", "(", "self", ",", "\"_cmd\"", ")", ":", "raise", "RuntimeError",...
Ensure player backing process is started
[ "Ensure", "player", "backing", "process", "is", "started" ]
python
valid
05bit/peewee-async
peewee_async.py
https://github.com/05bit/peewee-async/blob/d15f4629da1d9975da4ec37306188e68d288c862/peewee_async.py#L269-L276
async def prefetch(self, query, *subqueries): """Asynchronous version of the `prefetch()` from peewee. :return: Query that has already cached data for subqueries """ query = self._swap_database(query) subqueries = map(self._swap_database, subqueries) return (await prefet...
[ "async", "def", "prefetch", "(", "self", ",", "query", ",", "*", "subqueries", ")", ":", "query", "=", "self", ".", "_swap_database", "(", "query", ")", "subqueries", "=", "map", "(", "self", ".", "_swap_database", ",", "subqueries", ")", "return", "(", ...
Asynchronous version of the `prefetch()` from peewee. :return: Query that has already cached data for subqueries
[ "Asynchronous", "version", "of", "the", "prefetch", "()", "from", "peewee", "." ]
python
train
cgoldberg/sauceclient
sauceclient.py
https://github.com/cgoldberg/sauceclient/blob/aa27b7da8eb2e483adc2754c694fe5082e1fa8f7/sauceclient.py#L76-L87
def request(self, method, url, body=None, content_type='application/json'): """Send http request.""" headers = self.make_auth_headers(content_type) connection = http_client.HTTPSConnection(self.apibase) connection.request(method, url, body, headers=headers) response = connection....
[ "def", "request", "(", "self", ",", "method", ",", "url", ",", "body", "=", "None", ",", "content_type", "=", "'application/json'", ")", ":", "headers", "=", "self", ".", "make_auth_headers", "(", "content_type", ")", "connection", "=", "http_client", ".", ...
Send http request.
[ "Send", "http", "request", "." ]
python
train
ic-labs/django-icekit
icekit/publishing/managers.py
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/publishing/managers.py#L342-L367
def published(self, for_user=UNSET, force_exchange=False): """ Apply additional filtering of published items over that done in `PublishingQuerySet.published` to filter based on additional publising date fields used by Fluent. """ if for_user is not UNSET: retu...
[ "def", "published", "(", "self", ",", "for_user", "=", "UNSET", ",", "force_exchange", "=", "False", ")", ":", "if", "for_user", "is", "not", "UNSET", ":", "return", "self", ".", "visible", "(", ")", "queryset", "=", "super", "(", "PublishingUrlNodeQuerySe...
Apply additional filtering of published items over that done in `PublishingQuerySet.published` to filter based on additional publising date fields used by Fluent.
[ "Apply", "additional", "filtering", "of", "published", "items", "over", "that", "done", "in", "PublishingQuerySet", ".", "published", "to", "filter", "based", "on", "additional", "publising", "date", "fields", "used", "by", "Fluent", "." ]
python
train
edx/edx-enterprise
consent/api/v1/views.py
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/consent/api/v1/views.py#L95-L115
def get_required_query_params(self, request): """ Gets ``username``, ``course_id``, and ``enterprise_customer_uuid``, which are the relevant query parameters for this API endpoint. :param request: The request to this endpoint. :return: The ``username``, ``course_id``, and ``ente...
[ "def", "get_required_query_params", "(", "self", ",", "request", ")", ":", "username", "=", "get_request_value", "(", "request", ",", "self", ".", "REQUIRED_PARAM_USERNAME", ",", "''", ")", "course_id", "=", "get_request_value", "(", "request", ",", "self", ".",...
Gets ``username``, ``course_id``, and ``enterprise_customer_uuid``, which are the relevant query parameters for this API endpoint. :param request: The request to this endpoint. :return: The ``username``, ``course_id``, and ``enterprise_customer_uuid`` from the request.
[ "Gets", "username", "course_id", "and", "enterprise_customer_uuid", "which", "are", "the", "relevant", "query", "parameters", "for", "this", "API", "endpoint", "." ]
python
valid
tensorflow/tensor2tensor
tensor2tensor/rl/rl_utils.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/rl_utils.py#L100-L117
def evaluate_all_configs( hparams, agent_model_dir, eval_fn=_eval_fn_with_learner ): """Evaluate the agent with multiple eval configurations.""" metrics = {} # Iterate over all combinations of sampling temperatures and whether to do # initial no-ops. for sampling_temp in hparams.eval_sampling_temps: #...
[ "def", "evaluate_all_configs", "(", "hparams", ",", "agent_model_dir", ",", "eval_fn", "=", "_eval_fn_with_learner", ")", ":", "metrics", "=", "{", "}", "# Iterate over all combinations of sampling temperatures and whether to do", "# initial no-ops.", "for", "sampling_temp", ...
Evaluate the agent with multiple eval configurations.
[ "Evaluate", "the", "agent", "with", "multiple", "eval", "configurations", "." ]
python
train
andreikop/qutepart
qutepart/rectangularselection.py
https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/rectangularselection.py#L90-L98
def _realToVisibleColumn(self, text, realColumn): """If \t is used, real position of symbol in block and visible position differs This function converts real to visible """ generator = self._visibleCharPositionGenerator(text) for i in range(realColumn): val = next(gen...
[ "def", "_realToVisibleColumn", "(", "self", ",", "text", ",", "realColumn", ")", ":", "generator", "=", "self", ".", "_visibleCharPositionGenerator", "(", "text", ")", "for", "i", "in", "range", "(", "realColumn", ")", ":", "val", "=", "next", "(", "genera...
If \t is used, real position of symbol in block and visible position differs This function converts real to visible
[ "If", "\\", "t", "is", "used", "real", "position", "of", "symbol", "in", "block", "and", "visible", "position", "differs", "This", "function", "converts", "real", "to", "visible" ]
python
train
pypa/pipenv
pipenv/vendor/pyparsing.py
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pyparsing.py#L1329-L1342
def setName( self, name ): """ Define name for this expression, makes debugging and exception messages clearer. Example:: Word(nums).parseString("ABC") # -> Exception: Expected W:(0123...) (at char 0), (line:1, col:1) Word(nums).setName("integer").parseString("ABC") #...
[ "def", "setName", "(", "self", ",", "name", ")", ":", "self", ".", "name", "=", "name", "self", ".", "errmsg", "=", "\"Expected \"", "+", "self", ".", "name", "if", "hasattr", "(", "self", ",", "\"exception\"", ")", ":", "self", ".", "exception", "."...
Define name for this expression, makes debugging and exception messages clearer. Example:: Word(nums).parseString("ABC") # -> Exception: Expected W:(0123...) (at char 0), (line:1, col:1) Word(nums).setName("integer").parseString("ABC") # -> Exception: Expected integer (at char 0), (l...
[ "Define", "name", "for", "this", "expression", "makes", "debugging", "and", "exception", "messages", "clearer", "." ]
python
train
JnyJny/Geometry
Geometry/point.py
https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/point.py#L1353-L1387
def ccw(self, b, c, axis='z'): ''' :b: Point or point equivalent :c: Point or point equivalent :axis: optional string or integer in set('x',0,'y',1,'z',2) :return: float CCW - Counter Clockwise Returns an integer signifying the direction of rotation around 'axis...
[ "def", "ccw", "(", "self", ",", "b", ",", "c", ",", "axis", "=", "'z'", ")", ":", "bsuba", "=", "b", "-", "self", "csuba", "=", "c", "-", "self", "if", "axis", "in", "[", "'z'", ",", "2", "]", ":", "return", "(", "bsuba", ".", "x", "*", "...
:b: Point or point equivalent :c: Point or point equivalent :axis: optional string or integer in set('x',0,'y',1,'z',2) :return: float CCW - Counter Clockwise Returns an integer signifying the direction of rotation around 'axis' described by the angle [b, self, c]. ...
[ ":", "b", ":", "Point", "or", "point", "equivalent", ":", "c", ":", "Point", "or", "point", "equivalent", ":", "axis", ":", "optional", "string", "or", "integer", "in", "set", "(", "x", "0", "y", "1", "z", "2", ")", ":", "return", ":", "float" ]
python
train
Terrance/SkPy
skpy/util.py
https://github.com/Terrance/SkPy/blob/0f9489c94e8ec4d3effab4314497428872a80ad1/skpy/util.py#L70-L83
def chatToId(url): """ Extract the conversation ID from a conversation URL. Matches addresses containing ``conversations/<chat>``. Args: url (str): Skype API URL Returns: str: extracted identifier """ match = re.search(r"conversations/([...
[ "def", "chatToId", "(", "url", ")", ":", "match", "=", "re", ".", "search", "(", "r\"conversations/([0-9]+:[^/]+)\"", ",", "url", ")", "return", "match", ".", "group", "(", "1", ")", "if", "match", "else", "None" ]
Extract the conversation ID from a conversation URL. Matches addresses containing ``conversations/<chat>``. Args: url (str): Skype API URL Returns: str: extracted identifier
[ "Extract", "the", "conversation", "ID", "from", "a", "conversation", "URL", "." ]
python
test
AtteqCom/zsl
src/zsl/resource/json_server_resource.py
https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/resource/json_server_resource.py#L233-L247
def update(self, *args, **kwargs): """Modifies the parameters and adds metadata for update results. Currently it does not support `PUT` method, which works as replacing the resource. This is somehow questionable in relation DB. """ if request.method == 'PUT': logging...
[ "def", "update", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "request", ".", "method", "==", "'PUT'", ":", "logging", ".", "warning", "(", "\"Called not implemented resource method PUT\"", ")", "resource", "=", "super", "(", "Js...
Modifies the parameters and adds metadata for update results. Currently it does not support `PUT` method, which works as replacing the resource. This is somehow questionable in relation DB.
[ "Modifies", "the", "parameters", "and", "adds", "metadata", "for", "update", "results", "." ]
python
train
atarashansky/self-assembling-manifold
utilities.py
https://github.com/atarashansky/self-assembling-manifold/blob/4db4793f65af62047492327716932ba81a67f679/utilities.py#L62-L107
def save_figures(filename, fig_IDs=None, **kwargs): """ Save figures. Parameters ---------- filename - str Name of output file fig_IDs - int, numpy.array, list, optional, default None A list of open figure IDs or a figure ID that will be saved to a pdf/png f...
[ "def", "save_figures", "(", "filename", ",", "fig_IDs", "=", "None", ",", "*", "*", "kwargs", ")", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "if", "(", "fig_IDs", "is", "not", "None", ")", ":", "if", "(", "type", "(", "fig_IDs", ")", ...
Save figures. Parameters ---------- filename - str Name of output file fig_IDs - int, numpy.array, list, optional, default None A list of open figure IDs or a figure ID that will be saved to a pdf/png file respectively. **kwargs - Extra keyword arg...
[ "Save", "figures", ".", "Parameters", "----------", "filename", "-", "str", "Name", "of", "output", "file", "fig_IDs", "-", "int", "numpy", ".", "array", "list", "optional", "default", "None", "A", "list", "of", "open", "figure", "IDs", "or", "a", "figure"...
python
train
phac-nml/sistr_cmd
sistr/src/cgmlst/extras/centroid_cgmlst_alleles.py
https://github.com/phac-nml/sistr_cmd/blob/4630fae72439723b354a94b94fbe76ad2f9f6295/sistr/src/cgmlst/extras/centroid_cgmlst_alleles.py#L55-L69
def allele_clusters(dists, t=0.025): """Flat clusters from distance matrix Args: dists (numpy.array): pdist distance matrix t (float): fcluster (tree cutting) distance threshold Returns: dict of lists: cluster number to list of indices of distances in cluster """ clusters =...
[ "def", "allele_clusters", "(", "dists", ",", "t", "=", "0.025", ")", ":", "clusters", "=", "fcluster", "(", "linkage", "(", "dists", ")", ",", "0.025", ",", "criterion", "=", "'distance'", ")", "cluster_idx", "=", "defaultdict", "(", "list", ")", "for", ...
Flat clusters from distance matrix Args: dists (numpy.array): pdist distance matrix t (float): fcluster (tree cutting) distance threshold Returns: dict of lists: cluster number to list of indices of distances in cluster
[ "Flat", "clusters", "from", "distance", "matrix" ]
python
train
CalebBell/thermo
thermo/chemical.py
https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/chemical.py#L2603-L2621
def isobaric_expansion(self): r'''Isobaric (constant-pressure) expansion of the chemical at its current phase and temperature, in units of [1/K]. .. math:: \beta = \frac{1}{V}\left(\frac{\partial V}{\partial T} \right)_P Examples -------- Radical change in ...
[ "def", "isobaric_expansion", "(", "self", ")", ":", "return", "phase_select_property", "(", "phase", "=", "self", ".", "phase", ",", "l", "=", "self", ".", "isobaric_expansion_l", ",", "g", "=", "self", ".", "isobaric_expansion_g", ")" ]
r'''Isobaric (constant-pressure) expansion of the chemical at its current phase and temperature, in units of [1/K]. .. math:: \beta = \frac{1}{V}\left(\frac{\partial V}{\partial T} \right)_P Examples -------- Radical change in value just above and below the critica...
[ "r", "Isobaric", "(", "constant", "-", "pressure", ")", "expansion", "of", "the", "chemical", "at", "its", "current", "phase", "and", "temperature", "in", "units", "of", "[", "1", "/", "K", "]", "." ]
python
valid
MitalAshok/objecttools
objecttools/serializable.py
https://github.com/MitalAshok/objecttools/blob/bddd14d1f702c8b559d3fcc2099bc22370e16de7/objecttools/serializable.py#L161-L170
def globals(self): """Find the globals of `self` by importing `self.module`""" try: return vars(__import__(self.module, fromlist=self.module.split('.'))) except ImportError: if self.warn_import: warnings.warn(ImportWarning( 'Cannot impo...
[ "def", "globals", "(", "self", ")", ":", "try", ":", "return", "vars", "(", "__import__", "(", "self", ".", "module", ",", "fromlist", "=", "self", ".", "module", ".", "split", "(", "'.'", ")", ")", ")", "except", "ImportError", ":", "if", "self", ...
Find the globals of `self` by importing `self.module`
[ "Find", "the", "globals", "of", "self", "by", "importing", "self", ".", "module" ]
python
train
helixyte/everest
everest/resources/storing.py
https://github.com/helixyte/everest/blob/70c9b93c3061db5cb62428349d18b8fb8566411b/everest/resources/storing.py#L61-L69
def load_into_collection_from_stream(collection, stream, content_type): """ Loads resources from the given resource data stream (of the specified MIME content type) into the given collection resource. """ rpr = as_representer(collection, content_type) with stream: data_el = rpr.data_from...
[ "def", "load_into_collection_from_stream", "(", "collection", ",", "stream", ",", "content_type", ")", ":", "rpr", "=", "as_representer", "(", "collection", ",", "content_type", ")", "with", "stream", ":", "data_el", "=", "rpr", ".", "data_from_stream", "(", "st...
Loads resources from the given resource data stream (of the specified MIME content type) into the given collection resource.
[ "Loads", "resources", "from", "the", "given", "resource", "data", "stream", "(", "of", "the", "specified", "MIME", "content", "type", ")", "into", "the", "given", "collection", "resource", "." ]
python
train
ewels/MultiQC
multiqc/modules/bowtie1/bowtie1.py
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/bowtie1/bowtie1.py#L93-L114
def bowtie_general_stats_table(self): """ Take the parsed stats from the Bowtie report and add it to the basic stats table at the top of the report """ headers = OrderedDict() headers['reads_aligned_percentage'] = { 'title': '% Aligned', 'description': '% reads w...
[ "def", "bowtie_general_stats_table", "(", "self", ")", ":", "headers", "=", "OrderedDict", "(", ")", "headers", "[", "'reads_aligned_percentage'", "]", "=", "{", "'title'", ":", "'% Aligned'", ",", "'description'", ":", "'% reads with at least one reported alignment'", ...
Take the parsed stats from the Bowtie report and add it to the basic stats table at the top of the report
[ "Take", "the", "parsed", "stats", "from", "the", "Bowtie", "report", "and", "add", "it", "to", "the", "basic", "stats", "table", "at", "the", "top", "of", "the", "report" ]
python
train
tetframework/Tonnikala
tonnikala/languages/python/generator.py
https://github.com/tetframework/Tonnikala/blob/99d168657da1b2372ff898254f80808ea8d1b83f/tonnikala/languages/python/generator.py#L72-L97
def adjust_locations(ast_node, first_lineno, first_offset): """ Adjust the locations of the ast nodes, offsetting them to the new lineno and column offset """ line_delta = first_lineno - 1 def _fix(node): if 'lineno' in node._attributes: lineno = node.lineno col...
[ "def", "adjust_locations", "(", "ast_node", ",", "first_lineno", ",", "first_offset", ")", ":", "line_delta", "=", "first_lineno", "-", "1", "def", "_fix", "(", "node", ")", ":", "if", "'lineno'", "in", "node", ".", "_attributes", ":", "lineno", "=", "node...
Adjust the locations of the ast nodes, offsetting them to the new lineno and column offset
[ "Adjust", "the", "locations", "of", "the", "ast", "nodes", "offsetting", "them", "to", "the", "new", "lineno", "and", "column", "offset" ]
python
train
facelessuser/pyspelling
pyspelling/filters/cpp.py
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/cpp.py#L392-L405
def extend_src_text(self, content, context, text_list, category): """Extend the source text list with the gathered text data.""" prefix = self.prefix + '-' if self.prefix else '' for comment, line, encoding in text_list: content.append( filters.SourceText( ...
[ "def", "extend_src_text", "(", "self", ",", "content", ",", "context", ",", "text_list", ",", "category", ")", ":", "prefix", "=", "self", ".", "prefix", "+", "'-'", "if", "self", ".", "prefix", "else", "''", "for", "comment", ",", "line", ",", "encodi...
Extend the source text list with the gathered text data.
[ "Extend", "the", "source", "text", "list", "with", "the", "gathered", "text", "data", "." ]
python
train
eqcorrscan/EQcorrscan
eqcorrscan/core/subspace.py
https://github.com/eqcorrscan/EQcorrscan/blob/3121b4aca801ee5d38f56ca297ce1c0f9515d9ff/eqcorrscan/core/subspace.py#L660-L787
def _subspace_process(streams, lowcut, highcut, filt_order, sampling_rate, multiplex, align, shift_len, reject, no_missed=True, stachans=None, parallel=False, plot=False, cores=1): """ Process stream data, internal function. :type streams: list :param streams...
[ "def", "_subspace_process", "(", "streams", ",", "lowcut", ",", "highcut", ",", "filt_order", ",", "sampling_rate", ",", "multiplex", ",", "align", ",", "shift_len", ",", "reject", ",", "no_missed", "=", "True", ",", "stachans", "=", "None", ",", "parallel",...
Process stream data, internal function. :type streams: list :param streams: List of obspy.core.stream.Stream to be used to \ generate the subspace detector. These should be pre-clustered \ and aligned. :type lowcut: float :param lowcut: Lowcut in Hz, can be None to not apply filter ...
[ "Process", "stream", "data", "internal", "function", "." ]
python
train
Diviyan-Kalainathan/CausalDiscoveryToolbox
cdt/utils/io.py
https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/utils/io.py#L34-L81
def read_causal_pairs(filename, scale=True, **kwargs): """Convert a ChaLearn Cause effect pairs challenge format into numpy.ndarray. :param filename: path of the file to read or DataFrame containing the data :type filename: str or pandas.DataFrame :param scale: Scale the data :type scale: bool ...
[ "def", "read_causal_pairs", "(", "filename", ",", "scale", "=", "True", ",", "*", "*", "kwargs", ")", ":", "def", "convert_row", "(", "row", ",", "scale", ")", ":", "\"\"\"Convert a CCEPC row into numpy.ndarrays.\n\n :param row:\n :type row: pandas.Series\n ...
Convert a ChaLearn Cause effect pairs challenge format into numpy.ndarray. :param filename: path of the file to read or DataFrame containing the data :type filename: str or pandas.DataFrame :param scale: Scale the data :type scale: bool :param kwargs: parameters to be passed to pandas.read_csv ...
[ "Convert", "a", "ChaLearn", "Cause", "effect", "pairs", "challenge", "format", "into", "numpy", ".", "ndarray", "." ]
python
valid
proteanhq/protean
src/protean/core/repository/base.py
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/repository/base.py#L29-L34
def filter(self, criteria: Q, offset: int = 0, limit: int = 10, order_by: list = ()) -> ResultSet: """ Filter objects from the repository. Method must return a `ResultSet` object """
[ "def", "filter", "(", "self", ",", "criteria", ":", "Q", ",", "offset", ":", "int", "=", "0", ",", "limit", ":", "int", "=", "10", ",", "order_by", ":", "list", "=", "(", ")", ")", "->", "ResultSet", ":" ]
Filter objects from the repository. Method must return a `ResultSet` object
[ "Filter", "objects", "from", "the", "repository", ".", "Method", "must", "return", "a", "ResultSet", "object" ]
python
train
awslabs/sockeye
sockeye_contrib/autopilot/autopilot.py
https://github.com/awslabs/sockeye/blob/5d64a1ee1ef3cbba17c6d1d94bc061020c43f6ab/sockeye_contrib/autopilot/autopilot.py#L234-L264
def copy_parallel_text(file_list: List[str], dest_prefix: str): """ Copy pre-compiled raw parallel files with a given prefix. Perform whitespace character normalization to ensure that only ASCII newlines are considered line breaks. :param file_list: List of file pairs to use. :param dest_prefi...
[ "def", "copy_parallel_text", "(", "file_list", ":", "List", "[", "str", "]", ",", "dest_prefix", ":", "str", ")", ":", "# Group files into source-target pairs", "file_sets", "=", "[", "]", "for", "i", "in", "range", "(", "0", ",", "len", "(", "file_list", ...
Copy pre-compiled raw parallel files with a given prefix. Perform whitespace character normalization to ensure that only ASCII newlines are considered line breaks. :param file_list: List of file pairs to use. :param dest_prefix: Prefix for output files.
[ "Copy", "pre", "-", "compiled", "raw", "parallel", "files", "with", "a", "given", "prefix", ".", "Perform", "whitespace", "character", "normalization", "to", "ensure", "that", "only", "ASCII", "newlines", "are", "considered", "line", "breaks", "." ]
python
train