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
UDST/urbansim
urbansim/developer/developer.py
https://github.com/UDST/urbansim/blob/79f815a6503e109f50be270cee92d0f4a34f49ef/urbansim/developer/developer.py#L23-L44
def _max_form(f, colname): """ Assumes dataframe with hierarchical columns with first index equal to the use and second index equal to the attribute. e.g. f.columns equal to:: mixedoffice building_cost building_revenue b...
[ "def", "_max_form", "(", "f", ",", "colname", ")", ":", "df", "=", "f", ".", "stack", "(", "level", "=", "0", ")", "[", "[", "colname", "]", "]", ".", "stack", "(", ")", ".", "unstack", "(", "level", "=", "1", ")", ".", "reset_index", "(", "l...
Assumes dataframe with hierarchical columns with first index equal to the use and second index equal to the attribute. e.g. f.columns equal to:: mixedoffice building_cost building_revenue building_size max_prof...
[ "Assumes", "dataframe", "with", "hierarchical", "columns", "with", "first", "index", "equal", "to", "the", "use", "and", "second", "index", "equal", "to", "the", "attribute", "." ]
python
train
geertj/pyskiplist
pyskiplist/skiplist.py
https://github.com/geertj/pyskiplist/blob/c5f94cf135d42bb277255150d3f570ed807468b2/pyskiplist/skiplist.py#L341-L343
def values(self, start=None, stop=None): """Like :meth:`items` but returns only the values.""" return (item[1] for item in self.items(start, stop))
[ "def", "values", "(", "self", ",", "start", "=", "None", ",", "stop", "=", "None", ")", ":", "return", "(", "item", "[", "1", "]", "for", "item", "in", "self", ".", "items", "(", "start", ",", "stop", ")", ")" ]
Like :meth:`items` but returns only the values.
[ "Like", ":", "meth", ":", "items", "but", "returns", "only", "the", "values", "." ]
python
train
edx/ease
ease/create.py
https://github.com/edx/ease/blob/a7890ed403da94d03726b0639cd8ebda45af6bbb/ease/create.py#L90-L134
def create_generic(numeric_values, textual_values, target, algorithm = util_functions.AlgorithmTypes.regression): """ Creates a model from a generic list numeric values and text values numeric_values - A list of lists that are the predictors textual_values - A list of lists that are the predictors (...
[ "def", "create_generic", "(", "numeric_values", ",", "textual_values", ",", "target", ",", "algorithm", "=", "util_functions", ".", "AlgorithmTypes", ".", "regression", ")", ":", "algorithm", "=", "select_algorithm", "(", "target", ")", "#Initialize a result dictionar...
Creates a model from a generic list numeric values and text values numeric_values - A list of lists that are the predictors textual_values - A list of lists that are the predictors (each item in textual_values corresponds to the similarly indexed counterpart in numeric_values) target - The variable that...
[ "Creates", "a", "model", "from", "a", "generic", "list", "numeric", "values", "and", "text", "values", "numeric_values", "-", "A", "list", "of", "lists", "that", "are", "the", "predictors", "textual_values", "-", "A", "list", "of", "lists", "that", "are", ...
python
valid
jxtech/wechatpy
wechatpy/pay/api/withhold.py
https://github.com/jxtech/wechatpy/blob/4df0da795618c0895a10f1c2cde9e9d5c0a93aaa/wechatpy/pay/api/withhold.py#L158-L174
def query_order(self, transaction_id=None, out_trade_no=None): """ 查询订单 api :param transaction_id: 二选一 微信订单号 微信的订单号,优先使用 :param out_trade_no: 二选一 商户订单号 商户系统内部的订单号,当没提供transaction_id时需要传这个。 :return: 返回的结果信息 """ if not transaction_id and not out_trade_no: ...
[ "def", "query_order", "(", "self", ",", "transaction_id", "=", "None", ",", "out_trade_no", "=", "None", ")", ":", "if", "not", "transaction_id", "and", "not", "out_trade_no", ":", "raise", "ValueError", "(", "\"transaction_id and out_trade_no must be a choice.\"", ...
查询订单 api :param transaction_id: 二选一 微信订单号 微信的订单号,优先使用 :param out_trade_no: 二选一 商户订单号 商户系统内部的订单号,当没提供transaction_id时需要传这个。 :return: 返回的结果信息
[ "查询订单", "api" ]
python
train
riga/tfdeploy
tfdeploy.py
https://github.com/riga/tfdeploy/blob/8481f657d6e3a51d76185a195b993e45f448828a/tfdeploy.py#L863-L877
def print_tensor(td_tensor, indent="| ", max_depth=-1, depth=0): """ print_tensor(td_tensor, indent=" ", max_depth=-1) Prints the dependency graph of a :py:class:`Tensor` *td_tensor*, where each new level is indented by *indent*. When *max_depth* is positive, the graph is truncated at that depth, where...
[ "def", "print_tensor", "(", "td_tensor", ",", "indent", "=", "\"| \"", ",", "max_depth", "=", "-", "1", ",", "depth", "=", "0", ")", ":", "offset", "=", "depth", "*", "indent", "line", "=", "\"td tensor: %s\"", "%", "td_tensor", ".", "name", "if", "t...
print_tensor(td_tensor, indent=" ", max_depth=-1) Prints the dependency graph of a :py:class:`Tensor` *td_tensor*, where each new level is indented by *indent*. When *max_depth* is positive, the graph is truncated at that depth, where each tensor and each op count as a level.
[ "print_tensor", "(", "td_tensor", "indent", "=", "max_depth", "=", "-", "1", ")", "Prints", "the", "dependency", "graph", "of", "a", ":", "py", ":", "class", ":", "Tensor", "*", "td_tensor", "*", "where", "each", "new", "level", "is", "indented", "by", ...
python
train
mcs07/ChemDataExtractor
chemdataextractor/cli/cem.py
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/cli/cem.py#L31-L44
def train_crf(ctx, input, output, clusters): """Train CRF CEM recognizer.""" click.echo('chemdataextractor.crf.train') sentences = [] for line in input: sentence = [] for t in line.split(): token, tag, iob = t.rsplit('/', 2) sentence.append(((token, tag), iob)) ...
[ "def", "train_crf", "(", "ctx", ",", "input", ",", "output", ",", "clusters", ")", ":", "click", ".", "echo", "(", "'chemdataextractor.crf.train'", ")", "sentences", "=", "[", "]", "for", "line", "in", "input", ":", "sentence", "=", "[", "]", "for", "t...
Train CRF CEM recognizer.
[ "Train", "CRF", "CEM", "recognizer", "." ]
python
train
GNS3/gns3-server
gns3server/controller/__init__.py
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/__init__.py#L634-L643
def instance(): """ Singleton to return only on instance of Controller. :returns: instance of Controller """ if not hasattr(Controller, '_instance') or Controller._instance is None: Controller._instance = Controller() return Controller._instance
[ "def", "instance", "(", ")", ":", "if", "not", "hasattr", "(", "Controller", ",", "'_instance'", ")", "or", "Controller", ".", "_instance", "is", "None", ":", "Controller", ".", "_instance", "=", "Controller", "(", ")", "return", "Controller", ".", "_insta...
Singleton to return only on instance of Controller. :returns: instance of Controller
[ "Singleton", "to", "return", "only", "on", "instance", "of", "Controller", "." ]
python
train
EpistasisLab/tpot
tpot/operator_utils.py
https://github.com/EpistasisLab/tpot/blob/b626271e6b5896a73fb9d7d29bebc7aa9100772e/tpot/operator_utils.py#L138-L303
def TPOTOperatorClassFactory(opsourse, opdict, BaseClass=Operator, ArgBaseClass=ARGType, verbose=0): """Dynamically create operator class. Parameters ---------- opsourse: string operator source in config dictionary (key) opdict: dictionary operator params in config dictionary (value...
[ "def", "TPOTOperatorClassFactory", "(", "opsourse", ",", "opdict", ",", "BaseClass", "=", "Operator", ",", "ArgBaseClass", "=", "ARGType", ",", "verbose", "=", "0", ")", ":", "class_profile", "=", "{", "}", "dep_op_list", "=", "{", "}", "# list of nested estim...
Dynamically create operator class. Parameters ---------- opsourse: string operator source in config dictionary (key) opdict: dictionary operator params in config dictionary (value) regression: bool True if it can be used in TPOTRegressor classification: bool True...
[ "Dynamically", "create", "operator", "class", "." ]
python
train
nanoporetech/ont_fast5_api
ont_fast5_api/fast5_file.py
https://github.com/nanoporetech/ont_fast5_api/blob/352b3903155fcf4f19234c4f429dcefaa6d6bc4a/ont_fast5_api/fast5_file.py#L725-L733
def _get_attributes(self, path): """ :param path: filepath within fast5 :return: dictionary of attributes found at ``path`` :rtype dict """ path_grp = self.handle[path] path_attr = path_grp.attrs return dict(path_attr)
[ "def", "_get_attributes", "(", "self", ",", "path", ")", ":", "path_grp", "=", "self", ".", "handle", "[", "path", "]", "path_attr", "=", "path_grp", ".", "attrs", "return", "dict", "(", "path_attr", ")" ]
:param path: filepath within fast5 :return: dictionary of attributes found at ``path`` :rtype dict
[ ":", "param", "path", ":", "filepath", "within", "fast5", ":", "return", ":", "dictionary", "of", "attributes", "found", "at", "path", ":", "rtype", "dict" ]
python
train
victorlei/smop
smop/parse.py
https://github.com/victorlei/smop/blob/bdad96b715d1dd75ce8ab4724f76b9b1bb1f61cd/smop/parse.py#L811-L816
def p_unwind(p): """ unwind : UNWIND_PROTECT stmt_list UNWIND_PROTECT_CLEANUP stmt_list END_UNWIND_PROTECT """ p[0] = node.try_catch( try_stmt=p[2], catch_stmt=node.expr_list(), finally_stmt=p[4])
[ "def", "p_unwind", "(", "p", ")", ":", "p", "[", "0", "]", "=", "node", ".", "try_catch", "(", "try_stmt", "=", "p", "[", "2", "]", ",", "catch_stmt", "=", "node", ".", "expr_list", "(", ")", ",", "finally_stmt", "=", "p", "[", "4", "]", ")" ]
unwind : UNWIND_PROTECT stmt_list UNWIND_PROTECT_CLEANUP stmt_list END_UNWIND_PROTECT
[ "unwind", ":", "UNWIND_PROTECT", "stmt_list", "UNWIND_PROTECT_CLEANUP", "stmt_list", "END_UNWIND_PROTECT" ]
python
train
reingart/gui2py
gui/tools/designer.py
https://github.com/reingart/gui2py/blob/aca0a05f6fcde55c94ad7cc058671a06608b01a4/gui/tools/designer.py#L267-L301
def mouse_up(self, evt, wx_obj=None): "Release the selected object (pass a wx_obj if the event was captured)" self.resizing = False if self.current: wx_obj = self.current if self.parent.wx_obj.HasCapture(): self.parent.wx_obj.ReleaseMouse() se...
[ "def", "mouse_up", "(", "self", ",", "evt", ",", "wx_obj", "=", "None", ")", ":", "self", ".", "resizing", "=", "False", "if", "self", ".", "current", ":", "wx_obj", "=", "self", ".", "current", "if", "self", ".", "parent", ".", "wx_obj", ".", "Has...
Release the selected object (pass a wx_obj if the event was captured)
[ "Release", "the", "selected", "object", "(", "pass", "a", "wx_obj", "if", "the", "event", "was", "captured", ")" ]
python
test
spyder-ide/spyder
spyder/plugins/projects/widgets/explorer.py
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/projects/widgets/explorer.py#L72-L82
def dragMoveEvent(self, event): """Reimplement Qt method""" index = self.indexAt(event.pos()) if index: dst = self.get_filename(index) if osp.isdir(dst): event.acceptProposedAction() else: event.ignore() else: ...
[ "def", "dragMoveEvent", "(", "self", ",", "event", ")", ":", "index", "=", "self", ".", "indexAt", "(", "event", ".", "pos", "(", ")", ")", "if", "index", ":", "dst", "=", "self", ".", "get_filename", "(", "index", ")", "if", "osp", ".", "isdir", ...
Reimplement Qt method
[ "Reimplement", "Qt", "method" ]
python
train
inasafe/inasafe
safe/impact_function/impact_function.py
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/impact_function/impact_function.py#L335-L450
def is_equal(self, other): """Equality checker with message :param other: Other Impact Function to be compared. :type other: ImpactFunction :returns: True if both are the same IF, other wise False and the message. :rtype: bool, str """ properties = [...
[ "def", "is_equal", "(", "self", ",", "other", ")", ":", "properties", "=", "[", "'debug_mode'", ",", "'use_rounding'", ",", "'requested_extent'", ",", "'crs'", ",", "'analysis_extent'", ",", "'datastore'", ",", "'name'", ",", "'title'", ",", "'start_datetime'", ...
Equality checker with message :param other: Other Impact Function to be compared. :type other: ImpactFunction :returns: True if both are the same IF, other wise False and the message. :rtype: bool, str
[ "Equality", "checker", "with", "message" ]
python
train
pyecore/pyecoregen
pyecoregen/ecore.py
https://github.com/pyecore/pyecoregen/blob/8c7a792f46d7d94e5d13e00e2967dd237351a4cf/pyecoregen/ecore.py#L30-L35
def folder_path_for_package(cls, package: ecore.EPackage): """Returns path to folder holding generated artifact for given element.""" parent = package.eContainer() if parent: return os.path.join(cls.folder_path_for_package(parent), package.name) return package.name
[ "def", "folder_path_for_package", "(", "cls", ",", "package", ":", "ecore", ".", "EPackage", ")", ":", "parent", "=", "package", ".", "eContainer", "(", ")", "if", "parent", ":", "return", "os", ".", "path", ".", "join", "(", "cls", ".", "folder_path_for...
Returns path to folder holding generated artifact for given element.
[ "Returns", "path", "to", "folder", "holding", "generated", "artifact", "for", "given", "element", "." ]
python
train
Qiskit/qiskit-terra
qiskit/quantum_info/operators/channel/kraus.py
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/channel/kraus.py#L250-L265
def power(self, n): """The matrix power of the channel. Args: n (int): compute the matrix power of the superoperator matrix. Returns: Kraus: the matrix power of the SuperOp converted to a Kraus channel. Raises: QiskitError: if the input and output d...
[ "def", "power", "(", "self", ",", "n", ")", ":", "if", "n", ">", "0", ":", "return", "super", "(", ")", ".", "power", "(", "n", ")", "return", "Kraus", "(", "SuperOp", "(", "self", ")", ".", "power", "(", "n", ")", ")" ]
The matrix power of the channel. Args: n (int): compute the matrix power of the superoperator matrix. Returns: Kraus: the matrix power of the SuperOp converted to a Kraus channel. Raises: QiskitError: if the input and output dimensions of the Qu...
[ "The", "matrix", "power", "of", "the", "channel", "." ]
python
test
Chilipp/psyplot
psyplot/data.py
https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L3222-L3230
def names(self): """Set of the variable in this list""" ret = set() for arr in self: if isinstance(arr, InteractiveList): ret.update(arr.names) else: ret.add(arr.name) return ret
[ "def", "names", "(", "self", ")", ":", "ret", "=", "set", "(", ")", "for", "arr", "in", "self", ":", "if", "isinstance", "(", "arr", ",", "InteractiveList", ")", ":", "ret", ".", "update", "(", "arr", ".", "names", ")", "else", ":", "ret", ".", ...
Set of the variable in this list
[ "Set", "of", "the", "variable", "in", "this", "list" ]
python
train
ansible/ansible-runner
ansible_runner/runner_config.py
https://github.com/ansible/ansible-runner/blob/8ce485480a5d0b602428d9d64a752e06fb46cdb8/ansible_runner/runner_config.py#L206-L276
def prepare_env(self): """ Manages reading environment metadata files under ``private_data_dir`` and merging/updating with existing values so the :py:class:`ansible_runner.runner.Runner` object can read and use them easily """ try: passwords = self.loader.load_file('e...
[ "def", "prepare_env", "(", "self", ")", ":", "try", ":", "passwords", "=", "self", ".", "loader", ".", "load_file", "(", "'env/passwords'", ",", "Mapping", ")", "self", ".", "expect_passwords", "=", "{", "re", ".", "compile", "(", "pattern", ",", "re", ...
Manages reading environment metadata files under ``private_data_dir`` and merging/updating with existing values so the :py:class:`ansible_runner.runner.Runner` object can read and use them easily
[ "Manages", "reading", "environment", "metadata", "files", "under", "private_data_dir", "and", "merging", "/", "updating", "with", "existing", "values", "so", "the", ":", "py", ":", "class", ":", "ansible_runner", ".", "runner", ".", "Runner", "object", "can", ...
python
train
StellarCN/py-stellar-base
stellar_base/stellarxdr/xdrgen.py
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/stellarxdr/xdrgen.py#L706-L713
def p_version_def(t): """version_def : VERSION ID LBRACE procedure_def procedure_def_list RBRACE EQUALS constant SEMI""" global name_dict id = t[2] value = t[8] lineno = t.lineno(1) if id_unique(id, 'version', lineno): name_dict[id] = const_info(id, value, lineno)
[ "def", "p_version_def", "(", "t", ")", ":", "global", "name_dict", "id", "=", "t", "[", "2", "]", "value", "=", "t", "[", "8", "]", "lineno", "=", "t", ".", "lineno", "(", "1", ")", "if", "id_unique", "(", "id", ",", "'version'", ",", "lineno", ...
version_def : VERSION ID LBRACE procedure_def procedure_def_list RBRACE EQUALS constant SEMI
[ "version_def", ":", "VERSION", "ID", "LBRACE", "procedure_def", "procedure_def_list", "RBRACE", "EQUALS", "constant", "SEMI" ]
python
train
markovmodel/PyEMMA
pyemma/thermo/util/util.py
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/thermo/util/util.py#L401-L416
def assign_unbiased_state_label(memm_list, unbiased_state): r""" Sets the msm label for the given list of estimated MEMM objects. Parameters ---------- memm_list : list of estimated MEMM objects The MEMM objects which shall have the msm label set. unbiased_state : int or None In...
[ "def", "assign_unbiased_state_label", "(", "memm_list", ",", "unbiased_state", ")", ":", "if", "unbiased_state", "is", "None", ":", "return", "for", "memm", "in", "memm_list", ":", "assert", "0", "<=", "unbiased_state", "<", "len", "(", "memm", ".", "models", ...
r""" Sets the msm label for the given list of estimated MEMM objects. Parameters ---------- memm_list : list of estimated MEMM objects The MEMM objects which shall have the msm label set. unbiased_state : int or None Index of the unbiased thermodynamic state (if present).
[ "r", "Sets", "the", "msm", "label", "for", "the", "given", "list", "of", "estimated", "MEMM", "objects", "." ]
python
train
PythonCharmers/python-future
src/future/types/newrange.py
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/types/newrange.py#L90-L100
def index(self, value): """Return the 0-based position of integer `value` in the sequence this range represents.""" try: diff = value - self._start except TypeError: raise ValueError('%r is not in range' % value) quotient, remainder = divmod(diff, self._st...
[ "def", "index", "(", "self", ",", "value", ")", ":", "try", ":", "diff", "=", "value", "-", "self", ".", "_start", "except", "TypeError", ":", "raise", "ValueError", "(", "'%r is not in range'", "%", "value", ")", "quotient", ",", "remainder", "=", "divm...
Return the 0-based position of integer `value` in the sequence this range represents.
[ "Return", "the", "0", "-", "based", "position", "of", "integer", "value", "in", "the", "sequence", "this", "range", "represents", "." ]
python
train
greenelab/PathCORE-T
pathcore/network.py
https://github.com/greenelab/PathCORE-T/blob/9d079d5ebffea2fe9fb9ab557588d51ad67d2c9c/pathcore/network.py#L458-L501
def to_dataframe(self, drop_weights_below=0, whitelist=None): """ Conversion of the network to a pandas.DataFrame. Parameters ----------- drop_weights_below : int (default=0) specify an edge weight threshold - remove all edges with weight below this value whi...
[ "def", "to_dataframe", "(", "self", ",", "drop_weights_below", "=", "0", ",", "whitelist", "=", "None", ")", ":", "network_df_cols", "=", "[", "\"pw0\"", ",", "\"pw1\"", ",", "\"weight\"", "]", "if", "self", ".", "features", ":", "network_df_cols", ".", "a...
Conversion of the network to a pandas.DataFrame. Parameters ----------- drop_weights_below : int (default=0) specify an edge weight threshold - remove all edges with weight below this value whitelist : [set|list](tup(int, int))|None (default=None) option to...
[ "Conversion", "of", "the", "network", "to", "a", "pandas", ".", "DataFrame", "." ]
python
train
gabstopper/smc-python
smc/base/collection.py
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/base/collection.py#L472-L522
def filter(self, *filter, **kw): # @ReservedAssignment """ Filter results for specific element type. keyword arguments can be used to specify a match against the elements attribute directly. It's important to note that if the search filter contains a / or -, the SMC...
[ "def", "filter", "(", "self", ",", "*", "filter", ",", "*", "*", "kw", ")", ":", "# @ReservedAssignment", "iexact", "=", "None", "if", "filter", ":", "_filter", "=", "filter", "[", "0", "]", "exact_match", "=", "kw", ".", "pop", "(", "'exact_match'", ...
Filter results for specific element type. keyword arguments can be used to specify a match against the elements attribute directly. It's important to note that if the search filter contains a / or -, the SMC will only search the name and comment fields. Otherwise other key f...
[ "Filter", "results", "for", "specific", "element", "type", ".", "keyword", "arguments", "can", "be", "used", "to", "specify", "a", "match", "against", "the", "elements", "attribute", "directly", ".", "It", "s", "important", "to", "note", "that", "if", "the",...
python
train
portfoliome/postpy
postpy/admin.py
https://github.com/portfoliome/postpy/blob/fe26199131b15295fc5f669a0ad2a7f47bf490ee/postpy/admin.py#L77-L87
def reset(db_name): """Reset database.""" conn = psycopg2.connect(database='postgres') db = Database(db_name) conn.autocommit = True with conn.cursor() as cursor: cursor.execute(db.drop_statement()) cursor.execute(db.create_statement()) conn.close()
[ "def", "reset", "(", "db_name", ")", ":", "conn", "=", "psycopg2", ".", "connect", "(", "database", "=", "'postgres'", ")", "db", "=", "Database", "(", "db_name", ")", "conn", ".", "autocommit", "=", "True", "with", "conn", ".", "cursor", "(", ")", "...
Reset database.
[ "Reset", "database", "." ]
python
train
undertheseanlp/languageflow
languageflow/evaluation/__init__.py
https://github.com/undertheseanlp/languageflow/blob/1436e0bf72803e02ccf727f41e8fc85ba167d9fe/languageflow/evaluation/__init__.py#L3-L24
def print_cm(cm, labels, hide_zeroes=False, hide_diagonal=False, hide_threshold=None): """pretty print for confusion matrixes""" columnwidth = max([len(x) for x in labels] + [5]) # 5 is value length empty_cell = " " * columnwidth # Print header print(" " + empty_cell, end=" ") for label in l...
[ "def", "print_cm", "(", "cm", ",", "labels", ",", "hide_zeroes", "=", "False", ",", "hide_diagonal", "=", "False", ",", "hide_threshold", "=", "None", ")", ":", "columnwidth", "=", "max", "(", "[", "len", "(", "x", ")", "for", "x", "in", "labels", "]...
pretty print for confusion matrixes
[ "pretty", "print", "for", "confusion", "matrixes" ]
python
valid
apache/incubator-heron
heron/tools/explorer/src/python/logicalplan.py
https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/explorer/src/python/logicalplan.py#L101-L107
def filter_spouts(table, header): """ filter to keep spouts """ spouts_info = [] for row in table: if row[0] == 'spout': spouts_info.append(row) return spouts_info, header
[ "def", "filter_spouts", "(", "table", ",", "header", ")", ":", "spouts_info", "=", "[", "]", "for", "row", "in", "table", ":", "if", "row", "[", "0", "]", "==", "'spout'", ":", "spouts_info", ".", "append", "(", "row", ")", "return", "spouts_info", "...
filter to keep spouts
[ "filter", "to", "keep", "spouts" ]
python
valid
ejeschke/ginga
ginga/examples/reference-viewer/MyGlobalPlugin.py
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/examples/reference-viewer/MyGlobalPlugin.py#L43-L106
def build_gui(self, container): """ This method is called when the plugin is invoked. It builds the GUI used by the plugin into the widget layout passed as ``container``. This method could be called several times if the plugin is opened and closed. The method may be omi...
[ "def", "build_gui", "(", "self", ",", "container", ")", ":", "top", "=", "Widgets", ".", "VBox", "(", ")", "top", ".", "set_border_width", "(", "4", ")", "# this is a little trick for making plugins that work either in", "# a vertical or horizontal orientation. It return...
This method is called when the plugin is invoked. It builds the GUI used by the plugin into the widget layout passed as ``container``. This method could be called several times if the plugin is opened and closed. The method may be omitted if there is no GUI for the plugin. ...
[ "This", "method", "is", "called", "when", "the", "plugin", "is", "invoked", ".", "It", "builds", "the", "GUI", "used", "by", "the", "plugin", "into", "the", "widget", "layout", "passed", "as", "container", ".", "This", "method", "could", "be", "called", ...
python
train
consbio/parserutils
parserutils/urls.py
https://github.com/consbio/parserutils/blob/f13f80db99ed43479336b116e38512e3566e4623/parserutils/urls.py#L24-L35
def get_base_url(url, include_path=False): """ :return: the url without the query or fragment segments """ if not url: return None parts = _urlsplit(url) base_url = _urlunsplit(( parts.scheme, parts.netloc, (parts.path if include_path else ''), None, None )) return base_url if...
[ "def", "get_base_url", "(", "url", ",", "include_path", "=", "False", ")", ":", "if", "not", "url", ":", "return", "None", "parts", "=", "_urlsplit", "(", "url", ")", "base_url", "=", "_urlunsplit", "(", "(", "parts", ".", "scheme", ",", "parts", ".", ...
:return: the url without the query or fragment segments
[ ":", "return", ":", "the", "url", "without", "the", "query", "or", "fragment", "segments" ]
python
train
flatangle/flatlib
flatlib/ephem/tools.py
https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/ephem/tools.py#L41-L51
def isDiurnal(jd, lat, lon): """ Returns true if the sun is above the horizon of a given date and location. """ sun = swe.sweObject(const.SUN, jd) mc = swe.sweHousesLon(jd, lat, lon, const.HOUSES_DEFAULT)[1][1] ra, decl = utils.eqCoords(sun['lon'], sun['lat']) ...
[ "def", "isDiurnal", "(", "jd", ",", "lat", ",", "lon", ")", ":", "sun", "=", "swe", ".", "sweObject", "(", "const", ".", "SUN", ",", "jd", ")", "mc", "=", "swe", ".", "sweHousesLon", "(", "jd", ",", "lat", ",", "lon", ",", "const", ".", "HOUSES...
Returns true if the sun is above the horizon of a given date and location.
[ "Returns", "true", "if", "the", "sun", "is", "above", "the", "horizon", "of", "a", "given", "date", "and", "location", "." ]
python
train
ralphje/imagemounter
imagemounter/cli/shell.py
https://github.com/ralphje/imagemounter/blob/86213781c366cad65096447d91f522f0a3fb4b93/imagemounter/cli/shell.py#L68-L79
def default(self, line): """Overriding default to get access to any argparse commands we have specified.""" if any((line.startswith(x) for x in self.argparse_names())): try: args = self.argparser.parse_args(shlex.split(line)) except Exception: # intentionally ca...
[ "def", "default", "(", "self", ",", "line", ")", ":", "if", "any", "(", "(", "line", ".", "startswith", "(", "x", ")", "for", "x", "in", "self", ".", "argparse_names", "(", ")", ")", ")", ":", "try", ":", "args", "=", "self", ".", "argparser", ...
Overriding default to get access to any argparse commands we have specified.
[ "Overriding", "default", "to", "get", "access", "to", "any", "argparse", "commands", "we", "have", "specified", "." ]
python
train
awslabs/aws-sam-cli
samcli/commands/publish/command.py
https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/commands/publish/command.py#L55-L83
def do_cli(ctx, template, semantic_version): """Publish the application based on command line inputs.""" try: template_data = get_template_data(template) except ValueError as ex: click.secho("Publish Failed", fg='red') raise UserException(str(ex)) # Override SemanticVersion in t...
[ "def", "do_cli", "(", "ctx", ",", "template", ",", "semantic_version", ")", ":", "try", ":", "template_data", "=", "get_template_data", "(", "template", ")", "except", "ValueError", "as", "ex", ":", "click", ".", "secho", "(", "\"Publish Failed\"", ",", "fg"...
Publish the application based on command line inputs.
[ "Publish", "the", "application", "based", "on", "command", "line", "inputs", "." ]
python
train
pypa/pipenv
pipenv/vendor/dotenv/cli.py
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/dotenv/cli.py#L59-L66
def get(ctx, key): '''Retrieve the value for the given key.''' file = ctx.obj['FILE'] stored_value = get_key(file, key) if stored_value: click.echo('%s=%s' % (key, stored_value)) else: exit(1)
[ "def", "get", "(", "ctx", ",", "key", ")", ":", "file", "=", "ctx", ".", "obj", "[", "'FILE'", "]", "stored_value", "=", "get_key", "(", "file", ",", "key", ")", "if", "stored_value", ":", "click", ".", "echo", "(", "'%s=%s'", "%", "(", "key", ",...
Retrieve the value for the given key.
[ "Retrieve", "the", "value", "for", "the", "given", "key", "." ]
python
train
IDSIA/sacred
sacred/experiment.py
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/experiment.py#L390-L406
def log_scalar(self, name, value, step=None): """ Add a new measurement. The measurement will be processed by the MongoDB* observer during a heartbeat event. Other observers are not yet supported. :param name: The name of the metric, e.g. training.loss :param va...
[ "def", "log_scalar", "(", "self", ",", "name", ",", "value", ",", "step", "=", "None", ")", ":", "# Method added in change https://github.com/chovanecm/sacred/issues/4", "# The same as Run.log_scalar", "return", "self", ".", "current_run", ".", "log_scalar", "(", "name"...
Add a new measurement. The measurement will be processed by the MongoDB* observer during a heartbeat event. Other observers are not yet supported. :param name: The name of the metric, e.g. training.loss :param value: The measured value :param step: The step number (inte...
[ "Add", "a", "new", "measurement", "." ]
python
train
dpgaspar/Flask-AppBuilder
flask_appbuilder/api/__init__.py
https://github.com/dpgaspar/Flask-AppBuilder/blob/c293734c1b86e176a3ba57ee2deab6676d125576/flask_appbuilder/api/__init__.py#L640-L649
def _label_columns_json(self, cols=None): """ Prepares dict with labels to be JSON serializable """ ret = {} cols = cols or [] d = {k: v for (k, v) in self.label_columns.items() if k in cols} for key, value in d.items(): ret[key] = as_unicode(_(val...
[ "def", "_label_columns_json", "(", "self", ",", "cols", "=", "None", ")", ":", "ret", "=", "{", "}", "cols", "=", "cols", "or", "[", "]", "d", "=", "{", "k", ":", "v", "for", "(", "k", ",", "v", ")", "in", "self", ".", "label_columns", ".", "...
Prepares dict with labels to be JSON serializable
[ "Prepares", "dict", "with", "labels", "to", "be", "JSON", "serializable" ]
python
train
inasafe/inasafe
safe/utilities/utilities.py
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/utilities.py#L65-L111
def get_error_message(exception, context=None, suggestion=None): """Convert exception into an ErrorMessage containing a stack trace. :param exception: Exception object. :type exception: Exception :param context: Optional context message. :type context: str :param suggestion: Optional suggesti...
[ "def", "get_error_message", "(", "exception", ",", "context", "=", "None", ",", "suggestion", "=", "None", ")", ":", "name", ",", "trace", "=", "humanise_exception", "(", "exception", ")", "problem", "=", "m", ".", "Message", "(", "name", ")", "if", "exc...
Convert exception into an ErrorMessage containing a stack trace. :param exception: Exception object. :type exception: Exception :param context: Optional context message. :type context: str :param suggestion: Optional suggestion. :type suggestion: str .. see also:: https://github.com/inas...
[ "Convert", "exception", "into", "an", "ErrorMessage", "containing", "a", "stack", "trace", "." ]
python
train
tanghaibao/jcvi
jcvi/graphics/graph.py
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/graphics/graph.py#L18-L22
def make_sequence(seq, name="S"): """ Make unique nodes for sequence graph. """ return ["{}_{}_{}".format(name, i, x) for i, x in enumerate(seq)]
[ "def", "make_sequence", "(", "seq", ",", "name", "=", "\"S\"", ")", ":", "return", "[", "\"{}_{}_{}\"", ".", "format", "(", "name", ",", "i", ",", "x", ")", "for", "i", ",", "x", "in", "enumerate", "(", "seq", ")", "]" ]
Make unique nodes for sequence graph.
[ "Make", "unique", "nodes", "for", "sequence", "graph", "." ]
python
train
lwcook/horsetail-matching
horsetailmatching/densitymatching.py
https://github.com/lwcook/horsetail-matching/blob/f3d5f8d01249debbca978f412ce4eae017458119/horsetailmatching/densitymatching.py#L152-L165
def getPDF(self): '''Function that gets vectors of the pdf and target at the last design evaluated. :return: tuple of q values, pdf values, target values ''' if hasattr(self, '_qplot'): return self._qplot, self._hplot, self._tplot else: raise V...
[ "def", "getPDF", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "'_qplot'", ")", ":", "return", "self", ".", "_qplot", ",", "self", ".", "_hplot", ",", "self", ".", "_tplot", "else", ":", "raise", "ValueError", "(", "'''The metric has not been...
Function that gets vectors of the pdf and target at the last design evaluated. :return: tuple of q values, pdf values, target values
[ "Function", "that", "gets", "vectors", "of", "the", "pdf", "and", "target", "at", "the", "last", "design", "evaluated", "." ]
python
train
bmuller/kademlia
kademlia/network.py
https://github.com/bmuller/kademlia/blob/4a8d445c9ee8f3ca10f56107e4445daed4933c8a/kademlia/network.py#L214-L225
def load_state(cls, fname): """ Load the state of this node (the alpha/ksize/id/immediate neighbors) from a cache file with the given fname. """ log.info("Loading state from %s", fname) with open(fname, 'rb') as file: data = pickle.load(file) svr = Ser...
[ "def", "load_state", "(", "cls", ",", "fname", ")", ":", "log", ".", "info", "(", "\"Loading state from %s\"", ",", "fname", ")", "with", "open", "(", "fname", ",", "'rb'", ")", "as", "file", ":", "data", "=", "pickle", ".", "load", "(", "file", ")",...
Load the state of this node (the alpha/ksize/id/immediate neighbors) from a cache file with the given fname.
[ "Load", "the", "state", "of", "this", "node", "(", "the", "alpha", "/", "ksize", "/", "id", "/", "immediate", "neighbors", ")", "from", "a", "cache", "file", "with", "the", "given", "fname", "." ]
python
train
AtomHash/evernode
evernode/classes/base_response.py
https://github.com/AtomHash/evernode/blob/b2fb91555fb937a3f3eba41db56dee26f9b034be/evernode/classes/base_response.py#L35-L39
def message(self, message=None): """ Set response message """ if message is not None: self.response_model.message = message return self.response_model.message
[ "def", "message", "(", "self", ",", "message", "=", "None", ")", ":", "if", "message", "is", "not", "None", ":", "self", ".", "response_model", ".", "message", "=", "message", "return", "self", ".", "response_model", ".", "message" ]
Set response message
[ "Set", "response", "message" ]
python
train
bwohlberg/sporco
sporco/admm/ccmod.py
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/admm/ccmod.py#L895-L946
def ConvCnstrMOD(*args, **kwargs): """A wrapper function that dynamically defines a class derived from one of the implementations of the Convolutional Constrained MOD problems, and returns an object instantiated with the provided parameters. The wrapper is designed to allow the appropriate object to...
[ "def", "ConvCnstrMOD", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Extract method selection argument or set default", "if", "'method'", "in", "kwargs", ":", "method", "=", "kwargs", "[", "'method'", "]", "del", "kwargs", "[", "'method'", "]", "else...
A wrapper function that dynamically defines a class derived from one of the implementations of the Convolutional Constrained MOD problems, and returns an object instantiated with the provided parameters. The wrapper is designed to allow the appropriate object to be created by calling this function using...
[ "A", "wrapper", "function", "that", "dynamically", "defines", "a", "class", "derived", "from", "one", "of", "the", "implementations", "of", "the", "Convolutional", "Constrained", "MOD", "problems", "and", "returns", "an", "object", "instantiated", "with", "the", ...
python
train
lsst-sqre/documenteer
documenteer/sphinxext/lssttasks/pyapisummary.py
https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxext/lssttasks/pyapisummary.py#L244-L265
def _format_import_example(self, task_class): """Generate nodes that show a code sample demonstrating how to import the task class. Parameters ---------- task_class : ``lsst.pipe.base.Task``-type The Task class. Returns ------- nodes : `list`...
[ "def", "_format_import_example", "(", "self", ",", "task_class", ")", ":", "code", "=", "'from {0.__module__} import {0.__name__}'", ".", "format", "(", "task_class", ")", "# This is a bare-bones version of what Sphinx's code-block directive", "# does. The 'language' attr triggers ...
Generate nodes that show a code sample demonstrating how to import the task class. Parameters ---------- task_class : ``lsst.pipe.base.Task``-type The Task class. Returns ------- nodes : `list` of docutils nodes Docutils nodes showing a c...
[ "Generate", "nodes", "that", "show", "a", "code", "sample", "demonstrating", "how", "to", "import", "the", "task", "class", "." ]
python
train
jhuapl-boss/intern
intern/remote/boss/remote.py
https://github.com/jhuapl-boss/intern/blob/d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed/intern/remote/boss/remote.py#L573-L593
def add_user( self, user, first_name=None, last_name=None, email=None, password=None ): """ Add a new user. Args: user (string): User name. first_name (optional[string]): User's first name. Defaults to None. last_n...
[ "def", "add_user", "(", "self", ",", "user", ",", "first_name", "=", "None", ",", "last_name", "=", "None", ",", "email", "=", "None", ",", "password", "=", "None", ")", ":", "self", ".", "project_service", ".", "set_auth", "(", "self", ".", "_token_pr...
Add a new user. Args: user (string): User name. first_name (optional[string]): User's first name. Defaults to None. last_name (optional[string]): User's last name. Defaults to None. email: (optional[string]): User's email address. Defaults to None. ...
[ "Add", "a", "new", "user", "." ]
python
train
mattrobenolt/django-sudo
sudo/utils.py
https://github.com/mattrobenolt/django-sudo/blob/089e21a88bc3ebf9d76ea706f26707d2e4f3f729/sudo/utils.py#L70-L87
def is_safe_url(url, host=None): """ Return ``True`` if the url is a safe redirection (i.e. it doesn't point to a different host and uses a safe scheme). Always returns ``False`` on an empty url. """ if url is not None: url = url.strip() if not url: return False if six.PY...
[ "def", "is_safe_url", "(", "url", ",", "host", "=", "None", ")", ":", "if", "url", "is", "not", "None", ":", "url", "=", "url", ".", "strip", "(", ")", "if", "not", "url", ":", "return", "False", "if", "six", ".", "PY2", ":", "# pragma: nocover", ...
Return ``True`` if the url is a safe redirection (i.e. it doesn't point to a different host and uses a safe scheme). Always returns ``False`` on an empty url.
[ "Return", "True", "if", "the", "url", "is", "a", "safe", "redirection", "(", "i", ".", "e", ".", "it", "doesn", "t", "point", "to", "a", "different", "host", "and", "uses", "a", "safe", "scheme", ")", ".", "Always", "returns", "False", "on", "an", ...
python
train
python-diamond/Diamond
src/diamond/handler/signalfx.py
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/signalfx.py#L71-L84
def get_default_config_help(self): """ Returns the help text for the configuration options for this handler """ config = super(SignalfxHandler, self).get_default_config_help() config.update({ 'url': 'Where to send metrics', 'batch': 'How many to store bef...
[ "def", "get_default_config_help", "(", "self", ")", ":", "config", "=", "super", "(", "SignalfxHandler", ",", "self", ")", ".", "get_default_config_help", "(", ")", "config", ".", "update", "(", "{", "'url'", ":", "'Where to send metrics'", ",", "'batch'", ":"...
Returns the help text for the configuration options for this handler
[ "Returns", "the", "help", "text", "for", "the", "configuration", "options", "for", "this", "handler" ]
python
train
icgood/pysasl
pysasl/__init__.py
https://github.com/icgood/pysasl/blob/241bdd349577cc99f05c4239755c307e6a46018c/pysasl/__init__.py#L326-L338
def plaintext(cls): """Uses only authentication mechanisms that provide the credentials in un-hashed form, typically meaning :attr:`~pysasl.AuthenticationCredentials.has_secret` is True. Returns: A new :class:`SASLAuth` object. """ builtin_mechs = cls._get_b...
[ "def", "plaintext", "(", "cls", ")", ":", "builtin_mechs", "=", "cls", ".", "_get_builtin_mechanisms", "(", ")", "plaintext_mechs", "=", "[", "mech", "for", "_", ",", "mech", "in", "builtin_mechs", ".", "items", "(", ")", "if", "mech", ".", "insecure", "...
Uses only authentication mechanisms that provide the credentials in un-hashed form, typically meaning :attr:`~pysasl.AuthenticationCredentials.has_secret` is True. Returns: A new :class:`SASLAuth` object.
[ "Uses", "only", "authentication", "mechanisms", "that", "provide", "the", "credentials", "in", "un", "-", "hashed", "form", "typically", "meaning", ":", "attr", ":", "~pysasl", ".", "AuthenticationCredentials", ".", "has_secret", "is", "True", "." ]
python
train
newville/wxmplot
wxmplot/config.py
https://github.com/newville/wxmplot/blob/8e0dc037453e5cdf18c968dc5a3d29efd761edee/wxmplot/config.py#L741-L756
def set_logscale(self, xscale='linear', yscale='linear', delay_draw=False): "set log or linear scale for x, y axis" self.xscale = xscale self.yscale = yscale for axes in self.canvas.figure.get_axes(): try: axes.set_yscale(yscale, basey=10)...
[ "def", "set_logscale", "(", "self", ",", "xscale", "=", "'linear'", ",", "yscale", "=", "'linear'", ",", "delay_draw", "=", "False", ")", ":", "self", ".", "xscale", "=", "xscale", "self", ".", "yscale", "=", "yscale", "for", "axes", "in", "self", ".",...
set log or linear scale for x, y axis
[ "set", "log", "or", "linear", "scale", "for", "x", "y", "axis" ]
python
train
klavinslab/coral
coral/analysis/_sequence/melting_temp.py
https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/analysis/_sequence/melting_temp.py#L22-L144
def tm(seq, dna_conc=50, salt_conc=50, parameters='cloning'): '''Calculate nearest-neighbor melting temperature (Tm). :param seq: Sequence for which to calculate the tm. :type seq: coral.DNA :param dna_conc: DNA concentration in nM. :type dna_conc: float :param salt_conc: Salt concentration in ...
[ "def", "tm", "(", "seq", ",", "dna_conc", "=", "50", ",", "salt_conc", "=", "50", ",", "parameters", "=", "'cloning'", ")", ":", "if", "parameters", "==", "'breslauer'", ":", "params", "=", "tm_params", ".", "BRESLAUER", "elif", "parameters", "==", "'sug...
Calculate nearest-neighbor melting temperature (Tm). :param seq: Sequence for which to calculate the tm. :type seq: coral.DNA :param dna_conc: DNA concentration in nM. :type dna_conc: float :param salt_conc: Salt concentration in mM. :type salt_conc: float :param parameters: Nearest-neighbo...
[ "Calculate", "nearest", "-", "neighbor", "melting", "temperature", "(", "Tm", ")", "." ]
python
train
eraclitux/ipcampy
ipcampy/foscam.py
https://github.com/eraclitux/ipcampy/blob/bffd1c4df9006705cffa5b83a090b0db90cbcbcf/ipcampy/foscam.py#L55-L69
def move(self, pos): """Move cam to given preset position. pos - must be within 1 to 16. Returns: CamException in case of errors, "ok" otherwise.""" try: payload = {"address":self.address, "user": self.user, "pwd": self.pswd, "pos": map_position(pos)} resp = requ...
[ "def", "move", "(", "self", ",", "pos", ")", ":", "try", ":", "payload", "=", "{", "\"address\"", ":", "self", ".", "address", ",", "\"user\"", ":", "self", ".", "user", ",", "\"pwd\"", ":", "self", ".", "pswd", ",", "\"pos\"", ":", "map_position", ...
Move cam to given preset position. pos - must be within 1 to 16. Returns: CamException in case of errors, "ok" otherwise.
[ "Move", "cam", "to", "given", "preset", "position", ".", "pos", "-", "must", "be", "within", "1", "to", "16", ".", "Returns", ":", "CamException", "in", "case", "of", "errors", "ok", "otherwise", "." ]
python
train
bokeh/bokeh
bokeh/application/handlers/code_runner.py
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/application/handlers/code_runner.py#L158-L196
def run(self, module, post_check): ''' Execute the configured source code in a module and run any post checks. Args: module (Module) : a module to execute the configured code in. post_check(callable) : a function that can raise an exception if expected p...
[ "def", "run", "(", "self", ",", "module", ",", "post_check", ")", ":", "try", ":", "# Simulate the sys.path behaviour decribed here:", "#", "# https://docs.python.org/2/library/sys.html#sys.path", "_cwd", "=", "os", ".", "getcwd", "(", ")", "_sys_path", "=", "list", ...
Execute the configured source code in a module and run any post checks. Args: module (Module) : a module to execute the configured code in. post_check(callable) : a function that can raise an exception if expected post-conditions are not met after code execution...
[ "Execute", "the", "configured", "source", "code", "in", "a", "module", "and", "run", "any", "post", "checks", "." ]
python
train
emdb-empiar/ahds
ahds/grammar.py
https://github.com/emdb-empiar/ahds/blob/6a752f6806d4f62155cd2e1194de8aabe7195e0f/ahds/grammar.py#L307-L316
def get_parsed_data(fn, *args, **kwargs): """All above functions as a single function :param str fn: file name :return list parsed_data: structured metadata """ file_format = detect_format(fn, *args, **kwargs) data = get_header(fn, file_format, *args, **kwargs) parsed_data = parse_heade...
[ "def", "get_parsed_data", "(", "fn", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "file_format", "=", "detect_format", "(", "fn", ",", "*", "args", ",", "*", "*", "kwargs", ")", "data", "=", "get_header", "(", "fn", ",", "file_format", ",", ...
All above functions as a single function :param str fn: file name :return list parsed_data: structured metadata
[ "All", "above", "functions", "as", "a", "single", "function", ":", "param", "str", "fn", ":", "file", "name", ":", "return", "list", "parsed_data", ":", "structured", "metadata" ]
python
train
sernst/cauldron
cauldron/templating.py
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/templating.py#L148-L165
def render_template(template_name: str, **kwargs): """ Renders the template file with the given filename from within Cauldron's template environment folder. :param template_name: The filename of the template to render. Any path elements should be relative to Cauldron's root template fol...
[ "def", "render_template", "(", "template_name", ":", "str", ",", "*", "*", "kwargs", ")", ":", "return", "get_environment", "(", ")", ".", "get_template", "(", "template_name", ")", ".", "render", "(", "cauldron_template_uid", "=", "make_template_uid", "(", ")...
Renders the template file with the given filename from within Cauldron's template environment folder. :param template_name: The filename of the template to render. Any path elements should be relative to Cauldron's root template folder. :param kwargs: Any elements passed to Jinja2 f...
[ "Renders", "the", "template", "file", "with", "the", "given", "filename", "from", "within", "Cauldron", "s", "template", "environment", "folder", "." ]
python
train
apache/airflow
airflow/utils/dag_processing.py
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/utils/dag_processing.py#L1126-L1227
def heartbeat(self): """ This should be periodically called by the manager loop. This method will kick off new processes to process DAG definition files and read the results from the finished processors. :return: a list of SimpleDags that were produced by processors that ...
[ "def", "heartbeat", "(", "self", ")", ":", "finished_processors", "=", "{", "}", "\"\"\":type : dict[unicode, AbstractDagFileProcessor]\"\"\"", "running_processors", "=", "{", "}", "\"\"\":type : dict[unicode, AbstractDagFileProcessor]\"\"\"", "for", "file_path", ",", "processo...
This should be periodically called by the manager loop. This method will kick off new processes to process DAG definition files and read the results from the finished processors. :return: a list of SimpleDags that were produced by processors that have finished since the last time th...
[ "This", "should", "be", "periodically", "called", "by", "the", "manager", "loop", ".", "This", "method", "will", "kick", "off", "new", "processes", "to", "process", "DAG", "definition", "files", "and", "read", "the", "results", "from", "the", "finished", "pr...
python
test
eqcorrscan/EQcorrscan
eqcorrscan/utils/clustering.py
https://github.com/eqcorrscan/EQcorrscan/blob/3121b4aca801ee5d38f56ca297ce1c0f9515d9ff/eqcorrscan/utils/clustering.py#L840-L906
def space_cluster(catalog, d_thresh, show=True): """ Cluster a catalog by distance only. Will compute the matrix of physical distances between events and utilize the :mod:`scipy.clustering.hierarchy` module to perform the clustering. :type catalog: obspy.core.event.Catalog :param catalog: Cata...
[ "def", "space_cluster", "(", "catalog", ",", "d_thresh", ",", "show", "=", "True", ")", ":", "# Compute the distance matrix and linkage", "dist_mat", "=", "dist_mat_km", "(", "catalog", ")", "dist_vec", "=", "squareform", "(", "dist_mat", ")", "Z", "=", "linkage...
Cluster a catalog by distance only. Will compute the matrix of physical distances between events and utilize the :mod:`scipy.clustering.hierarchy` module to perform the clustering. :type catalog: obspy.core.event.Catalog :param catalog: Catalog of events to clustered :type d_thresh: float :par...
[ "Cluster", "a", "catalog", "by", "distance", "only", "." ]
python
train
pyvisa/pyvisa
pyvisa/shell.py
https://github.com/pyvisa/pyvisa/blob/b8b2d4371e1f00782856aa9176ff1ced6bcb3798/pyvisa/shell.py#L231-L261
def do_timeout(self, args): """Get or set timeout (in ms) for resource in use. Get timeout: timeout Set timeout: timeout <mstimeout> """ if not self.current: print('There are no resources in use. Use the command "open".') retu...
[ "def", "do_timeout", "(", "self", ",", "args", ")", ":", "if", "not", "self", ".", "current", ":", "print", "(", "'There are no resources in use. Use the command \"open\".'", ")", "return", "args", "=", "args", ".", "strip", "(", ")", "if", "not", "args", ":...
Get or set timeout (in ms) for resource in use. Get timeout: timeout Set timeout: timeout <mstimeout>
[ "Get", "or", "set", "timeout", "(", "in", "ms", ")", "for", "resource", "in", "use", "." ]
python
train
dslackw/slpkg
slpkg/repoinfo.py
https://github.com/dslackw/slpkg/blob/dd2e08a80e944d337d157b992167ba631a4343de/slpkg/repoinfo.py#L107-L126
def repository_data(self, repo): """ Grap data packages """ sum_pkgs, size, unsize, last_upd = 0, [], [], "" for line in (Utils().read_file( self.meta.lib_path + repo + "_repo/PACKAGES.TXT").splitlines()): if line.startswith("PACKAGES.TXT;"): ...
[ "def", "repository_data", "(", "self", ",", "repo", ")", ":", "sum_pkgs", ",", "size", ",", "unsize", ",", "last_upd", "=", "0", ",", "[", "]", ",", "[", "]", ",", "\"\"", "for", "line", "in", "(", "Utils", "(", ")", ".", "read_file", "(", "self"...
Grap data packages
[ "Grap", "data", "packages" ]
python
train
chriso/gauged
gauged/drivers/sqlite.py
https://github.com/chriso/gauged/blob/cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976/gauged/drivers/sqlite.py#L90-L105
def replace_blocks(self, blocks): """Replace multiple blocks. blocks must be a list of tuples where each tuple consists of (namespace, offset, key, data, flags)""" start = 0 bulk_insert = self.bulk_insert blocks_len = len(blocks) select = 'SELECT ?,?,?,?,?' query ...
[ "def", "replace_blocks", "(", "self", ",", "blocks", ")", ":", "start", "=", "0", "bulk_insert", "=", "self", ".", "bulk_insert", "blocks_len", "=", "len", "(", "blocks", ")", "select", "=", "'SELECT ?,?,?,?,?'", "query", "=", "'REPLACE INTO gauged_data (namespa...
Replace multiple blocks. blocks must be a list of tuples where each tuple consists of (namespace, offset, key, data, flags)
[ "Replace", "multiple", "blocks", ".", "blocks", "must", "be", "a", "list", "of", "tuples", "where", "each", "tuple", "consists", "of", "(", "namespace", "offset", "key", "data", "flags", ")" ]
python
train
Fizzadar/pyinfra
pyinfra/api/state.py
https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/api/state.py#L400-L409
def is_host_in_limit(self, host): ''' Returns a boolean indicating if the host is within the current state limit. ''' limit_hosts = self.limit_hosts if not isinstance(limit_hosts, list): return True return host in limit_hosts
[ "def", "is_host_in_limit", "(", "self", ",", "host", ")", ":", "limit_hosts", "=", "self", ".", "limit_hosts", "if", "not", "isinstance", "(", "limit_hosts", ",", "list", ")", ":", "return", "True", "return", "host", "in", "limit_hosts" ]
Returns a boolean indicating if the host is within the current state limit.
[ "Returns", "a", "boolean", "indicating", "if", "the", "host", "is", "within", "the", "current", "state", "limit", "." ]
python
train
openego/eDisGo
edisgo/grid/network.py
https://github.com/openego/eDisGo/blob/e6245bdaf236f9c49dbda5a18c1c458290f41e2b/edisgo/grid/network.py#L2996-L3209
def save(self, directory, parameters='all'): """ Saves results to disk. Depending on which results are selected and if they exist, the following directories and files are created: * `powerflow_results` directory * `voltages_pu.csv` See :py:attr:`~pfa_v_m...
[ "def", "save", "(", "self", ",", "directory", ",", "parameters", "=", "'all'", ")", ":", "def", "_save_power_flow_results", "(", "target_dir", ")", ":", "if", "self", ".", "pfa_v_mag_pu", "is", "not", "None", ":", "# create directory", "os", ".", "makedirs",...
Saves results to disk. Depending on which results are selected and if they exist, the following directories and files are created: * `powerflow_results` directory * `voltages_pu.csv` See :py:attr:`~pfa_v_mag_pu` for more information. * `currents.csv` ...
[ "Saves", "results", "to", "disk", "." ]
python
train
mardix/pylot
pylot/utils.py
https://github.com/mardix/pylot/blob/506a33a56ebdfc0925b94015e8cf98ccb16a143c/pylot/utils.py#L264-L274
def bg_thread(func): """ A threading decorator :param func: :return: """ @functools.wraps(func) def wrapper(*args, **kwargs): p = threading.Thread(target=func, args=args, kwargs=kwargs) p.start() return wrapper
[ "def", "bg_thread", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "p", "=", "threading", ".", "Thread", "(", "target", "=", "func", ",", "args", "="...
A threading decorator :param func: :return:
[ "A", "threading", "decorator", ":", "param", "func", ":", ":", "return", ":" ]
python
train
peri-source/peri
peri/logger.py
https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/logger.py#L138-L155
def set_verbosity(self, verbosity='vvv', handlers=None): """ Set the verbosity level of a certain log handler or of all handlers. Parameters ---------- verbosity : 'v' to 'vvvvv' the level of verbosity, more v's is more verbose handlers : string, or list of ...
[ "def", "set_verbosity", "(", "self", ",", "verbosity", "=", "'vvv'", ",", "handlers", "=", "None", ")", ":", "self", ".", "verbosity", "=", "sanitize", "(", "verbosity", ")", "self", ".", "set_level", "(", "v2l", "[", "verbosity", "]", ",", "handlers", ...
Set the verbosity level of a certain log handler or of all handlers. Parameters ---------- verbosity : 'v' to 'vvvvv' the level of verbosity, more v's is more verbose handlers : string, or list of strings handler names can be found in ``peri.logger.types.keys()`...
[ "Set", "the", "verbosity", "level", "of", "a", "certain", "log", "handler", "or", "of", "all", "handlers", "." ]
python
valid
datastax/python-driver
cassandra/io/twistedreactor.py
https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/io/twistedreactor.py#L93-L99
def clientConnectionFailed(self, connector, reason): """ Overridden twisted callback which is called when the connection attempt fails. """ log.debug("Connect failed: %s", reason) self.conn.defunct(reason.value)
[ "def", "clientConnectionFailed", "(", "self", ",", "connector", ",", "reason", ")", ":", "log", ".", "debug", "(", "\"Connect failed: %s\"", ",", "reason", ")", "self", ".", "conn", ".", "defunct", "(", "reason", ".", "value", ")" ]
Overridden twisted callback which is called when the connection attempt fails.
[ "Overridden", "twisted", "callback", "which", "is", "called", "when", "the", "connection", "attempt", "fails", "." ]
python
train
cknoll/ipydex
ipydex/core.py
https://github.com/cknoll/ipydex/blob/ca528ce4c97ee934e48efbd5983c1b7cd88bec9d/ipydex/core.py#L396-L405
def color_exepthook(pdb=0, mode=2): """ Make tracebacks after exceptions colored, verbose, and/or call pdb (python cmd line debugger) at the place where the exception occurs """ modus = ['Plain', 'Context', 'Verbose'][mode] # select the mode sys.excepthook = ultratb.FormattedTB(mode=modus, ...
[ "def", "color_exepthook", "(", "pdb", "=", "0", ",", "mode", "=", "2", ")", ":", "modus", "=", "[", "'Plain'", ",", "'Context'", ",", "'Verbose'", "]", "[", "mode", "]", "# select the mode", "sys", ".", "excepthook", "=", "ultratb", ".", "FormattedTB", ...
Make tracebacks after exceptions colored, verbose, and/or call pdb (python cmd line debugger) at the place where the exception occurs
[ "Make", "tracebacks", "after", "exceptions", "colored", "verbose", "and", "/", "or", "call", "pdb", "(", "python", "cmd", "line", "debugger", ")", "at", "the", "place", "where", "the", "exception", "occurs" ]
python
train
timothyb0912/pylogit
pylogit/bootstrap.py
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/bootstrap.py#L737-L788
def calc_abc_interval(self, conf_percentage, init_vals, epsilon=0.001, **fit_kwargs): """ Calculates Approximate Bootstrap Confidence Intervals for one's model. Parameters ---------- ...
[ "def", "calc_abc_interval", "(", "self", ",", "conf_percentage", ",", "init_vals", ",", "epsilon", "=", "0.001", ",", "*", "*", "fit_kwargs", ")", ":", "print", "(", "\"Calculating Approximate Bootstrap Confidence (ABC) Intervals\"", ")", "print", "(", "time", ".", ...
Calculates Approximate Bootstrap Confidence Intervals for one's model. Parameters ---------- conf_percentage : scalar in the interval (0.0, 100.0). Denotes the confidence-level for the returned endpoints. For instance, to calculate a 95% confidence interval, pass `95`. ...
[ "Calculates", "Approximate", "Bootstrap", "Confidence", "Intervals", "for", "one", "s", "model", "." ]
python
train
bcbio/bcbio-nextgen
bcbio/structural/purecn.py
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/purecn.py#L165-L185
def _remove_overlaps(in_file, out_dir, data): """Remove regions that overlap with next region, these result in issues with PureCN. """ out_file = os.path.join(out_dir, "%s-nooverlaps%s" % utils.splitext_plus(os.path.basename(in_file))) if not utils.file_uptodate(out_file, in_file): with file_tra...
[ "def", "_remove_overlaps", "(", "in_file", ",", "out_dir", ",", "data", ")", ":", "out_file", "=", "os", ".", "path", ".", "join", "(", "out_dir", ",", "\"%s-nooverlaps%s\"", "%", "utils", ".", "splitext_plus", "(", "os", ".", "path", ".", "basename", "(...
Remove regions that overlap with next region, these result in issues with PureCN.
[ "Remove", "regions", "that", "overlap", "with", "next", "region", "these", "result", "in", "issues", "with", "PureCN", "." ]
python
train
Chilipp/model-organization
model_organization/config.py
https://github.com/Chilipp/model-organization/blob/694d1219c7ed7e1b2b17153afa11bdc21169bca2/model_organization/config.py#L748-L755
def save(self): """ Save the entire configuration files """ self.projects.save() self.experiments.save() safe_dump(self.global_config, self._globals_file, default_flow_style=False)
[ "def", "save", "(", "self", ")", ":", "self", ".", "projects", ".", "save", "(", ")", "self", ".", "experiments", ".", "save", "(", ")", "safe_dump", "(", "self", ".", "global_config", ",", "self", ".", "_globals_file", ",", "default_flow_style", "=", ...
Save the entire configuration files
[ "Save", "the", "entire", "configuration", "files" ]
python
train
DataDog/integrations-core
tokumx/datadog_checks/tokumx/vendor/pymongo/collection.py
https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/tokumx/datadog_checks/tokumx/vendor/pymongo/collection.py#L1342-L1353
def _count(self, cmd, collation=None): """Internal count helper.""" with self._socket_for_reads() as (sock_info, slave_ok): res = self._command( sock_info, cmd, slave_ok, allowable_errors=["ns missing"], codec_options=self.__write_response_code...
[ "def", "_count", "(", "self", ",", "cmd", ",", "collation", "=", "None", ")", ":", "with", "self", ".", "_socket_for_reads", "(", ")", "as", "(", "sock_info", ",", "slave_ok", ")", ":", "res", "=", "self", ".", "_command", "(", "sock_info", ",", "cmd...
Internal count helper.
[ "Internal", "count", "helper", "." ]
python
train
tanghaibao/goatools
goatools/anno/opts.py
https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/anno/opts.py#L65-L73
def getfnc_qual_ev(self): """Keep annotaion if it passes potentially modified selection.""" fnc_key = ( self.nd_not2desc[(self._keep_nd, self._keep_not)], self.incexc2num[( self.include_evcodes is not None, self.exclude_evcodes is not None)], ...
[ "def", "getfnc_qual_ev", "(", "self", ")", ":", "fnc_key", "=", "(", "self", ".", "nd_not2desc", "[", "(", "self", ".", "_keep_nd", ",", "self", ".", "_keep_not", ")", "]", ",", "self", ".", "incexc2num", "[", "(", "self", ".", "include_evcodes", "is",...
Keep annotaion if it passes potentially modified selection.
[ "Keep", "annotaion", "if", "it", "passes", "potentially", "modified", "selection", "." ]
python
train
darkfeline/animanager
animanager/db/query/update.py
https://github.com/darkfeline/animanager/blob/55d92e4cbdc12aac8ebe302420d2cff3fa9fa148/animanager/db/query/update.py#L98-L109
def bump(db, aid): """Bump anime regular episode count.""" anime = lookup(db, aid) if anime.complete: return episode = anime.watched_episodes + 1 with db: set_watched(db, aid, get_eptype(db, 'regular').id, episode) set_status( db, aid, anime.enddate an...
[ "def", "bump", "(", "db", ",", "aid", ")", ":", "anime", "=", "lookup", "(", "db", ",", "aid", ")", "if", "anime", ".", "complete", ":", "return", "episode", "=", "anime", ".", "watched_episodes", "+", "1", "with", "db", ":", "set_watched", "(", "d...
Bump anime regular episode count.
[ "Bump", "anime", "regular", "episode", "count", "." ]
python
train
HazyResearch/pdftotree
pdftotree/utils/pdf/layout_utils.py
https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/utils/pdf/layout_utils.py#L217-L273
def recursive_xy_divide(elems, avg_font_size): """ Recursively group/divide the document by white stripes by projecting elements onto alternating axes as intervals. avg_font_size: the minimum gap size between elements below which we consider interval continuous. """ log = logging.getLogger(...
[ "def", "recursive_xy_divide", "(", "elems", ",", "avg_font_size", ")", ":", "log", "=", "logging", ".", "getLogger", "(", "__name__", ")", "log", ".", "info", "(", "avg_font_size", ")", "objects", "=", "list", "(", "elems", ".", "mentions", ")", "objects",...
Recursively group/divide the document by white stripes by projecting elements onto alternating axes as intervals. avg_font_size: the minimum gap size between elements below which we consider interval continuous.
[ "Recursively", "group", "/", "divide", "the", "document", "by", "white", "stripes", "by", "projecting", "elements", "onto", "alternating", "axes", "as", "intervals", "." ]
python
train
openstack/networking-hyperv
networking_hyperv/neutron/agent/layer2.py
https://github.com/openstack/networking-hyperv/blob/7a89306ab0586c95b99debb44d898f70834508b9/networking_hyperv/neutron/agent/layer2.py#L412-L432
def _work(self): """Process the information regarding the available ports.""" if self._refresh_cache: # Inconsistent cache might cause exceptions. For example, # if a port has been removed, it will be known in the next # loop. Using the old switch port can cause excep...
[ "def", "_work", "(", "self", ")", ":", "if", "self", ".", "_refresh_cache", ":", "# Inconsistent cache might cause exceptions. For example,", "# if a port has been removed, it will be known in the next", "# loop. Using the old switch port can cause exceptions.", "LOG", ".", "debug", ...
Process the information regarding the available ports.
[ "Process", "the", "information", "regarding", "the", "available", "ports", "." ]
python
train
pallets/werkzeug
src/werkzeug/_reloader.py
https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/_reloader.py#L153-L178
def restart_with_reloader(self): """Spawn a new Python interpreter with the same arguments as this one, but running the reloader thread. """ while 1: _log("info", " * Restarting with %s" % self.name) args = _get_args_for_reloading() # a weird bug on w...
[ "def", "restart_with_reloader", "(", "self", ")", ":", "while", "1", ":", "_log", "(", "\"info\"", ",", "\" * Restarting with %s\"", "%", "self", ".", "name", ")", "args", "=", "_get_args_for_reloading", "(", ")", "# a weird bug on windows. sometimes unicode strings e...
Spawn a new Python interpreter with the same arguments as this one, but running the reloader thread.
[ "Spawn", "a", "new", "Python", "interpreter", "with", "the", "same", "arguments", "as", "this", "one", "but", "running", "the", "reloader", "thread", "." ]
python
train
SKA-ScienceDataProcessor/integration-prototype
sip/tango_control/tango_master/app/sdp_master_device.py
https://github.com/SKA-ScienceDataProcessor/integration-prototype/blob/8c8006de6ad71dcd44114b0338780738079c87d4/sip/tango_control/tango_master/app/sdp_master_device.py#L118-L126
def _get_service_state(service_id: str): """Get the Service state object for the specified id.""" LOG.debug('Getting state of service %s', service_id) services = get_service_id_list() service_ids = [s for s in services if service_id in s] if len(service_ids) != 1: ret...
[ "def", "_get_service_state", "(", "service_id", ":", "str", ")", ":", "LOG", ".", "debug", "(", "'Getting state of service %s'", ",", "service_id", ")", "services", "=", "get_service_id_list", "(", ")", "service_ids", "=", "[", "s", "for", "s", "in", "services...
Get the Service state object for the specified id.
[ "Get", "the", "Service", "state", "object", "for", "the", "specified", "id", "." ]
python
train
IdentityPython/pysaml2
src/saml2/validate.py
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/validate.py#L310-L334
def validate_value_type(value, spec): """ c_value_type = {'base': 'string', 'enumeration': ['Permit', 'Deny', 'Indeterminate']} {'member': 'anyURI', 'base': 'list'} {'base': 'anyURI'} {'base': 'NCName'} {'base': 'string'} ...
[ "def", "validate_value_type", "(", "value", ",", "spec", ")", ":", "if", "\"maxlen\"", "in", "spec", ":", "return", "len", "(", "value", ")", "<=", "int", "(", "spec", "[", "\"maxlen\"", "]", ")", "if", "spec", "[", "\"base\"", "]", "==", "\"string\"",...
c_value_type = {'base': 'string', 'enumeration': ['Permit', 'Deny', 'Indeterminate']} {'member': 'anyURI', 'base': 'list'} {'base': 'anyURI'} {'base': 'NCName'} {'base': 'string'}
[ "c_value_type", "=", "{", "base", ":", "string", "enumeration", ":", "[", "Permit", "Deny", "Indeterminate", "]", "}", "{", "member", ":", "anyURI", "base", ":", "list", "}", "{", "base", ":", "anyURI", "}", "{", "base", ":", "NCName", "}", "{", "bas...
python
train
FreshXOpenSource/wallaby-frontend-qt
wallaby/frontends/qt/reactor/qt4reactor.py
https://github.com/FreshXOpenSource/wallaby-frontend-qt/blob/eee70d0ec4ce34827f62a1654e28dbff8a8afb1a/wallaby/frontends/qt/reactor/qt4reactor.py#L171-L180
def _remove(self, xer, primary): """ Private method for removing a descriptor from the event loop. It does the inverse job of _add, and also add a check in case of the fd has gone away. """ if xer in primary: notifier = primary.pop(xer) notifier.s...
[ "def", "_remove", "(", "self", ",", "xer", ",", "primary", ")", ":", "if", "xer", "in", "primary", ":", "notifier", "=", "primary", ".", "pop", "(", "xer", ")", "notifier", ".", "shutdown", "(", ")" ]
Private method for removing a descriptor from the event loop. It does the inverse job of _add, and also add a check in case of the fd has gone away.
[ "Private", "method", "for", "removing", "a", "descriptor", "from", "the", "event", "loop", "." ]
python
train
charnley/rmsd
rmsd/calculate_rmsd.py
https://github.com/charnley/rmsd/blob/cd8af499fb63529a1b5b1f880fdb2dab2731544a/rmsd/calculate_rmsd.py#L273-L319
def reorder_distance(p_atoms, q_atoms, p_coord, q_coord): """ Re-orders the input atom list and xyz coordinates by atom type and then by distance of each atom from the centroid. Parameters ---------- atoms : array (N,1) matrix, where N is points holding the atoms' names coord : arra...
[ "def", "reorder_distance", "(", "p_atoms", ",", "q_atoms", ",", "p_coord", ",", "q_coord", ")", ":", "# Find unique atoms", "unique_atoms", "=", "np", ".", "unique", "(", "p_atoms", ")", "# generate full view from q shape to fill in atom view on the fly", "view_reorder", ...
Re-orders the input atom list and xyz coordinates by atom type and then by distance of each atom from the centroid. Parameters ---------- atoms : array (N,1) matrix, where N is points holding the atoms' names coord : array (N,D) matrix, where N is points and D is dimension Retu...
[ "Re", "-", "orders", "the", "input", "atom", "list", "and", "xyz", "coordinates", "by", "atom", "type", "and", "then", "by", "distance", "of", "each", "atom", "from", "the", "centroid", "." ]
python
train
project-rig/rig
rig/machine_control/boot.py
https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/machine_control/boot.py#L62-L164
def boot(hostname, boot_port=consts.BOOT_PORT, scamp_binary=None, sark_struct=None, boot_delay=0.05, post_boot_delay=2.0, sv_overrides=dict(), **kwargs): """Boot a SpiNNaker machine of the given size. Parameters ---------- hostname : str Hostname or IP address of the ...
[ "def", "boot", "(", "hostname", ",", "boot_port", "=", "consts", ".", "BOOT_PORT", ",", "scamp_binary", "=", "None", ",", "sark_struct", "=", "None", ",", "boot_delay", "=", "0.05", ",", "post_boot_delay", "=", "2.0", ",", "sv_overrides", "=", "dict", "(",...
Boot a SpiNNaker machine of the given size. Parameters ---------- hostname : str Hostname or IP address of the SpiNNaker chip to use to boot the system. boot_port : int The port number to sent boot packets to. scamp_binary : filename or None Filename of the binary to boot th...
[ "Boot", "a", "SpiNNaker", "machine", "of", "the", "given", "size", "." ]
python
train
inasafe/inasafe
safe/gui/tools/help/osm_downloader_help.py
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/help/osm_downloader_help.py#L43-L133
def content(): """Helper method that returns just the content. This method was added so that the text could be reused in the dock_help module. .. versionadded:: 3.2.2 :returns: A message object without brand element. :rtype: safe.messaging.message.Message """ message = m.Message() ...
[ "def", "content", "(", ")", ":", "message", "=", "m", ".", "Message", "(", ")", "paragraph", "=", "m", ".", "Paragraph", "(", "m", ".", "Image", "(", "'file:///%s/img/screenshots/'", "'osm-downloader-screenshot.png'", "%", "resources_path", "(", ")", ")", ",...
Helper method that returns just the content. This method was added so that the text could be reused in the dock_help module. .. versionadded:: 3.2.2 :returns: A message object without brand element. :rtype: safe.messaging.message.Message
[ "Helper", "method", "that", "returns", "just", "the", "content", "." ]
python
train
pallets/werkzeug
src/werkzeug/formparser.py
https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/formparser.py#L197-L206
def parse_from_environ(self, environ): """Parses the information from the environment as form data. :param environ: the WSGI environment to be used for parsing. :return: A tuple in the form ``(stream, form, files)``. """ content_type = environ.get("CONTENT_TYPE", "") con...
[ "def", "parse_from_environ", "(", "self", ",", "environ", ")", ":", "content_type", "=", "environ", ".", "get", "(", "\"CONTENT_TYPE\"", ",", "\"\"", ")", "content_length", "=", "get_content_length", "(", "environ", ")", "mimetype", ",", "options", "=", "parse...
Parses the information from the environment as form data. :param environ: the WSGI environment to be used for parsing. :return: A tuple in the form ``(stream, form, files)``.
[ "Parses", "the", "information", "from", "the", "environment", "as", "form", "data", "." ]
python
train
MisterY/gnucash-portfolio
gnucash_portfolio/accounts.py
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/accounts.py#L258-L261
def get_aggregate_by_id(self, account_id: str) -> AccountAggregate: """ Returns the aggregate for the given id """ account = self.get_by_id(account_id) return self.get_account_aggregate(account)
[ "def", "get_aggregate_by_id", "(", "self", ",", "account_id", ":", "str", ")", "->", "AccountAggregate", ":", "account", "=", "self", ".", "get_by_id", "(", "account_id", ")", "return", "self", ".", "get_account_aggregate", "(", "account", ")" ]
Returns the aggregate for the given id
[ "Returns", "the", "aggregate", "for", "the", "given", "id" ]
python
train
trailofbits/manticore
manticore/native/manticore.py
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/manticore.py#L138-L154
def _hook_callback(self, state, pc, instruction): 'Invoke all registered generic hooks' # Ignore symbolic pc. # TODO(yan): Should we ask the solver if any of the hooks are possible, # and execute those that are? if issymbolic(pc): return # Invoke all pc-spe...
[ "def", "_hook_callback", "(", "self", ",", "state", ",", "pc", ",", "instruction", ")", ":", "# Ignore symbolic pc.", "# TODO(yan): Should we ask the solver if any of the hooks are possible,", "# and execute those that are?", "if", "issymbolic", "(", "pc", ")", ":", "return...
Invoke all registered generic hooks
[ "Invoke", "all", "registered", "generic", "hooks" ]
python
valid
jaybaird/python-bloomfilter
pybloom/pybloom.py
https://github.com/jaybaird/python-bloomfilter/blob/2bbe01ad49965bf759e31781e6820408068862ac/pybloom/pybloom.py#L388-L410
def tofile(self, f): """Serialize this ScalableBloomFilter into the file-object `f'.""" f.write(pack(self.FILE_FMT, self.scale, self.ratio, self.initial_capacity, self.error_rate)) # Write #-of-filters f.write(pack(b'<l', len(self.filters))) if len(...
[ "def", "tofile", "(", "self", ",", "f", ")", ":", "f", ".", "write", "(", "pack", "(", "self", ".", "FILE_FMT", ",", "self", ".", "scale", ",", "self", ".", "ratio", ",", "self", ".", "initial_capacity", ",", "self", ".", "error_rate", ")", ")", ...
Serialize this ScalableBloomFilter into the file-object `f'.
[ "Serialize", "this", "ScalableBloomFilter", "into", "the", "file", "-", "object", "f", "." ]
python
train
nickmckay/LiPD-utilities
Python/lipd/misc.py
https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/misc.py#L534-L554
def prompt_protocol(): """ Prompt user if they would like to save pickle file as a dictionary or an object. :return str: Answer """ stop = 3 ans = "" while True and stop > 0: ans = input("Save as (d)ictionary or (o)bject?\n" "* Note:\n" "Dicti...
[ "def", "prompt_protocol", "(", ")", ":", "stop", "=", "3", "ans", "=", "\"\"", "while", "True", "and", "stop", ">", "0", ":", "ans", "=", "input", "(", "\"Save as (d)ictionary or (o)bject?\\n\"", "\"* Note:\\n\"", "\"Dictionaries are more basic, and are compatible wit...
Prompt user if they would like to save pickle file as a dictionary or an object. :return str: Answer
[ "Prompt", "user", "if", "they", "would", "like", "to", "save", "pickle", "file", "as", "a", "dictionary", "or", "an", "object", "." ]
python
train
gem/oq-engine
openquake/baselib/general.py
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/general.py#L973-L985
def random_filter(objects, reduction_factor, seed=42): """ Given a list of objects, returns a sublist by extracting randomly some elements. The reduction factor (< 1) tells how small is the extracted list compared to the original list. """ assert 0 < reduction_factor <= 1, reduction_factor r...
[ "def", "random_filter", "(", "objects", ",", "reduction_factor", ",", "seed", "=", "42", ")", ":", "assert", "0", "<", "reduction_factor", "<=", "1", ",", "reduction_factor", "rnd", "=", "random", ".", "Random", "(", "seed", ")", "out", "=", "[", "]", ...
Given a list of objects, returns a sublist by extracting randomly some elements. The reduction factor (< 1) tells how small is the extracted list compared to the original list.
[ "Given", "a", "list", "of", "objects", "returns", "a", "sublist", "by", "extracting", "randomly", "some", "elements", ".", "The", "reduction", "factor", "(", "<", "1", ")", "tells", "how", "small", "is", "the", "extracted", "list", "compared", "to", "the",...
python
train
theonlypwner/crc32
crc32.py
https://github.com/theonlypwner/crc32/blob/b2c8ee40fecd07b2b0670be592c55fe7122429d8/crc32.py#L215-L314
def get_parser(): ''' Return the command-line parser ''' parser = argparse.ArgumentParser( description="Reverse, undo, and calculate CRC32 checksums") subparsers = parser.add_subparsers(metavar='action') poly_flip_parser = argparse.ArgumentParser(add_help=False) subparser_group = poly_flip_...
[ "def", "get_parser", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "\"Reverse, undo, and calculate CRC32 checksums\"", ")", "subparsers", "=", "parser", ".", "add_subparsers", "(", "metavar", "=", "'action'", ")", "poly_fl...
Return the command-line parser
[ "Return", "the", "command", "-", "line", "parser" ]
python
train
Groundworkstech/pybfd
pybfd/bfd.py
https://github.com/Groundworkstech/pybfd/blob/9e722435929b4ad52212043a6f1e9e9ce60b5d72/pybfd/bfd.py#L537-L542
def my_archieve(self): """Return the my archieve attribute of the BFD file being processed.""" if not self._ptr: raise BfdException("BFD not initialized") return _bfd.get_bfd_attribute(self._ptr, BfdAttributes.MY_ARCHIEVE)
[ "def", "my_archieve", "(", "self", ")", ":", "if", "not", "self", ".", "_ptr", ":", "raise", "BfdException", "(", "\"BFD not initialized\"", ")", "return", "_bfd", ".", "get_bfd_attribute", "(", "self", ".", "_ptr", ",", "BfdAttributes", ".", "MY_ARCHIEVE", ...
Return the my archieve attribute of the BFD file being processed.
[ "Return", "the", "my", "archieve", "attribute", "of", "the", "BFD", "file", "being", "processed", "." ]
python
train
fboender/ansible-cmdb
src/ansiblecmdb/ansible.py
https://github.com/fboender/ansible-cmdb/blob/ebd960ac10684e8c9ec2b12751bba2c4c9504ab7/src/ansiblecmdb/ansible.py#L348-L361
def hosts_in_group(self, groupname): """ Return a list of hostnames that are in a group. """ result = [] for hostname, hostinfo in self.hosts.items(): if groupname == 'all': result.append(hostname) elif 'groups' in hostinfo: ...
[ "def", "hosts_in_group", "(", "self", ",", "groupname", ")", ":", "result", "=", "[", "]", "for", "hostname", ",", "hostinfo", "in", "self", ".", "hosts", ".", "items", "(", ")", ":", "if", "groupname", "==", "'all'", ":", "result", ".", "append", "(...
Return a list of hostnames that are in a group.
[ "Return", "a", "list", "of", "hostnames", "that", "are", "in", "a", "group", "." ]
python
train
Microsoft/LightGBM
python-package/lightgbm/basic.py
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L1792-L1821
def add_valid(self, data, name): """Add validation data. Parameters ---------- data : Dataset Validation data. name : string Name of validation data. Returns ------- self : Booster Booster with set validation data. ...
[ "def", "add_valid", "(", "self", ",", "data", ",", "name", ")", ":", "if", "not", "isinstance", "(", "data", ",", "Dataset", ")", ":", "raise", "TypeError", "(", "'Validation data should be Dataset instance, met {}'", ".", "format", "(", "type", "(", "data", ...
Add validation data. Parameters ---------- data : Dataset Validation data. name : string Name of validation data. Returns ------- self : Booster Booster with set validation data.
[ "Add", "validation", "data", "." ]
python
train
SCIP-Interfaces/PySCIPOpt
examples/unfinished/vrp.py
https://github.com/SCIP-Interfaces/PySCIPOpt/blob/9c960b40d94a48b0304d73dbe28b467b9c065abe/examples/unfinished/vrp.py#L15-L78
def solve_vrp(V,c,m,q,Q): """solve_vrp -- solve the vehicle routing problem. - start with assignment model (depot has a special status) - add cuts until all components of the graph are connected Parameters: - V: set/list of nodes in the graph - c[i,j]: cost for traversing edge (i,j...
[ "def", "solve_vrp", "(", "V", ",", "c", ",", "m", ",", "q", ",", "Q", ")", ":", "def", "addcut", "(", "cut_edges", ")", ":", "\"\"\"addcut: add constraint to eliminate infeasible solutions\n Parameters:\n - cut_edges: list of edges in the current solution, e...
solve_vrp -- solve the vehicle routing problem. - start with assignment model (depot has a special status) - add cuts until all components of the graph are connected Parameters: - V: set/list of nodes in the graph - c[i,j]: cost for traversing edge (i,j) - m: number of vehicles...
[ "solve_vrp", "--", "solve", "the", "vehicle", "routing", "problem", ".", "-", "start", "with", "assignment", "model", "(", "depot", "has", "a", "special", "status", ")", "-", "add", "cuts", "until", "all", "components", "of", "the", "graph", "are", "connec...
python
train
Qiskit/qiskit-terra
qiskit/circuit/quantumcircuit.py
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/circuit/quantumcircuit.py#L155-L182
def combine(self, rhs): """ Append rhs to self if self contains compatible registers. Two circuits are compatible if they contain the same registers or if they contain different registers with unique names. The returned circuit will contain all unique registers between both ...
[ "def", "combine", "(", "self", ",", "rhs", ")", ":", "# Check registers in LHS are compatible with RHS", "self", ".", "_check_compatible_regs", "(", "rhs", ")", "# Make new circuit with combined registers", "combined_qregs", "=", "deepcopy", "(", "self", ".", "qregs", "...
Append rhs to self if self contains compatible registers. Two circuits are compatible if they contain the same registers or if they contain different registers with unique names. The returned circuit will contain all unique registers between both circuits. Return self + rhs as ...
[ "Append", "rhs", "to", "self", "if", "self", "contains", "compatible", "registers", "." ]
python
test
pandas-dev/pandas
pandas/core/frame.py
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/frame.py#L4843-L4953
def nlargest(self, n, columns, keep='first'): """ Return the first `n` rows ordered by `columns` in descending order. Return the first `n` rows with the largest values in `columns`, in descending order. The columns that are not specified are returned as well, but not used for or...
[ "def", "nlargest", "(", "self", ",", "n", ",", "columns", ",", "keep", "=", "'first'", ")", ":", "return", "algorithms", ".", "SelectNFrame", "(", "self", ",", "n", "=", "n", ",", "keep", "=", "keep", ",", "columns", "=", "columns", ")", ".", "nlar...
Return the first `n` rows ordered by `columns` in descending order. Return the first `n` rows with the largest values in `columns`, in descending order. The columns that are not specified are returned as well, but not used for ordering. This method is equivalent to ``df.sort_va...
[ "Return", "the", "first", "n", "rows", "ordered", "by", "columns", "in", "descending", "order", "." ]
python
train
ArchiveTeam/wpull
wpull/application/tasks/download.py
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/application/tasks/download.py#L180-L209
def _build_cookie_jar(cls, session: AppSession): '''Build the cookie jar''' if not session.args.cookies: return if session.args.load_cookies or session.args.save_cookies: session.factory.set('CookieJar', BetterMozillaCookieJar) cookie_jar = session.factory....
[ "def", "_build_cookie_jar", "(", "cls", ",", "session", ":", "AppSession", ")", ":", "if", "not", "session", ".", "args", ".", "cookies", ":", "return", "if", "session", ".", "args", ".", "load_cookies", "or", "session", ".", "args", ".", "save_cookies", ...
Build the cookie jar
[ "Build", "the", "cookie", "jar" ]
python
train
grundic/yagocd
yagocd/resources/__init__.py
https://github.com/grundic/yagocd/blob/4c75336ae6f107c8723d37b15e52169151822127/yagocd/resources/__init__.py#L114-L125
def get_predecessors(self, transitive=False): """ Property for getting predecessors (parents) of current pipeline. This property automatically populates from API call :return: list of :class:`yagocd.resources.pipeline.PipelineEntity`. :rtype: list of yagocd.resources.pipeline.Pi...
[ "def", "get_predecessors", "(", "self", ",", "transitive", "=", "False", ")", ":", "result", "=", "self", ".", "_predecessors", "if", "transitive", ":", "return", "YagocdUtil", ".", "graph_depth_walk", "(", "result", ",", "lambda", "v", ":", "v", ".", "pre...
Property for getting predecessors (parents) of current pipeline. This property automatically populates from API call :return: list of :class:`yagocd.resources.pipeline.PipelineEntity`. :rtype: list of yagocd.resources.pipeline.PipelineEntity
[ "Property", "for", "getting", "predecessors", "(", "parents", ")", "of", "current", "pipeline", ".", "This", "property", "automatically", "populates", "from", "API", "call" ]
python
train
ellmetha/django-machina
machina/apps/forum_permission/shortcuts.py
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_permission/shortcuts.py#L25-L40
def assign_perm(perm, user_or_group, forum=None, has_perm=True): """ Assigns a permission to a user (anonymous or not) or a group. """ user, group = get_identity(user_or_group) perm = ForumPermission.objects.get(codename=perm) if user: return UserForumPermission.objects.create( forum...
[ "def", "assign_perm", "(", "perm", ",", "user_or_group", ",", "forum", "=", "None", ",", "has_perm", "=", "True", ")", ":", "user", ",", "group", "=", "get_identity", "(", "user_or_group", ")", "perm", "=", "ForumPermission", ".", "objects", ".", "get", ...
Assigns a permission to a user (anonymous or not) or a group.
[ "Assigns", "a", "permission", "to", "a", "user", "(", "anonymous", "or", "not", ")", "or", "a", "group", "." ]
python
train
google/python-adb
adb/filesync_protocol.py
https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/filesync_protocol.py#L120-L164
def Push(cls, connection, datafile, filename, st_mode=DEFAULT_PUSH_MODE, mtime=0, progress_callback=None): """Push a file-like object to the device. Args: connection: ADB connection datafile: File-like object for reading from filename: Filename to push to ...
[ "def", "Push", "(", "cls", ",", "connection", ",", "datafile", ",", "filename", ",", "st_mode", "=", "DEFAULT_PUSH_MODE", ",", "mtime", "=", "0", ",", "progress_callback", "=", "None", ")", ":", "fileinfo", "=", "(", "'{},{}'", ".", "format", "(", "filen...
Push a file-like object to the device. Args: connection: ADB connection datafile: File-like object for reading from filename: Filename to push to st_mode: stat mode for filename mtime: modification time progress_callback: callback method that accepts ...
[ "Push", "a", "file", "-", "like", "object", "to", "the", "device", "." ]
python
train
vmlaker/coils
coils/String.py
https://github.com/vmlaker/coils/blob/a3a613b3d661dec010e5879c86e62cbff2519dd0/coils/String.py#L25-L29
def time2string(tstamp, micro=True): """Given a :class:`datetime.datetime` object, return a formatted time string.""" tformat = TIME_FORMAT if micro else TIME_FORMAT[:-len(MICRO)] return tstamp.strftime(tformat)
[ "def", "time2string", "(", "tstamp", ",", "micro", "=", "True", ")", ":", "tformat", "=", "TIME_FORMAT", "if", "micro", "else", "TIME_FORMAT", "[", ":", "-", "len", "(", "MICRO", ")", "]", "return", "tstamp", ".", "strftime", "(", "tformat", ")" ]
Given a :class:`datetime.datetime` object, return a formatted time string.
[ "Given", "a", ":", "class", ":", "datetime", ".", "datetime", "object", "return", "a", "formatted", "time", "string", "." ]
python
train
limpyd/redis-limpyd-jobs
limpyd_jobs/models.py
https://github.com/limpyd/redis-limpyd-jobs/blob/264c71029bad4377d6132bf8bb9c55c44f3b03a2/limpyd_jobs/models.py#L392-L401
def duration(self): """ If the start and end times of the job are defined, return a timedelta, else return None """ try: start, end = self.hmget('start', 'end') return parse(end) - parse(start) except: return None
[ "def", "duration", "(", "self", ")", ":", "try", ":", "start", ",", "end", "=", "self", ".", "hmget", "(", "'start'", ",", "'end'", ")", "return", "parse", "(", "end", ")", "-", "parse", "(", "start", ")", "except", ":", "return", "None" ]
If the start and end times of the job are defined, return a timedelta, else return None
[ "If", "the", "start", "and", "end", "times", "of", "the", "job", "are", "defined", "return", "a", "timedelta", "else", "return", "None" ]
python
train
Opentrons/opentrons
update-server/otupdate/buildroot/file_actions.py
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/update-server/otupdate/buildroot/file_actions.py#L161-L196
def hash_file(path: str, progress_callback: Callable[[float], None], chunk_size: int = 1024, file_size: int = None, algo: str = 'sha256') -> bytes: """ Hash a file and return the hash, providing progress callbacks :param path: The file to hash :pa...
[ "def", "hash_file", "(", "path", ":", "str", ",", "progress_callback", ":", "Callable", "[", "[", "float", "]", ",", "None", "]", ",", "chunk_size", ":", "int", "=", "1024", ",", "file_size", ":", "int", "=", "None", ",", "algo", ":", "str", "=", "...
Hash a file and return the hash, providing progress callbacks :param path: The file to hash :param progress_callback: The callback to call with progress between 0 and 1. May not ever be precisely 1.0. :param chunk_size: If specified, the size of the chunks to hash in one call ...
[ "Hash", "a", "file", "and", "return", "the", "hash", "providing", "progress", "callbacks" ]
python
train
impact27/registrator
registrator/image.py
https://github.com/impact27/registrator/blob/04c099d83e0466207dc5b2e40d9b03db020d4dad/registrator/image.py#L107-L155
def find_rotation_scale(im0, im1, isccs=False): """Compares the images and return the best guess for the rotation angle, and scale difference. Parameters ---------- im0: 2d array First image im1: 2d array Second image isccs: boolean, default False Set to True if the ...
[ "def", "find_rotation_scale", "(", "im0", ",", "im1", ",", "isccs", "=", "False", ")", ":", "# sanitize input", "im0", "=", "np", ".", "asarray", "(", "im0", ",", "dtype", "=", "np", ".", "float32", ")", "im1", "=", "np", ".", "asarray", "(", "im1", ...
Compares the images and return the best guess for the rotation angle, and scale difference. Parameters ---------- im0: 2d array First image im1: 2d array Second image isccs: boolean, default False Set to True if the images are alredy DFT and in CCS representation Re...
[ "Compares", "the", "images", "and", "return", "the", "best", "guess", "for", "the", "rotation", "angle", "and", "scale", "difference", "." ]
python
train
rosenbrockc/fortpy
fortpy/scripts/analyze.py
https://github.com/rosenbrockc/fortpy/blob/1ed0757c52d549e41d9d44bdea68cb89529293a5/fortpy/scripts/analyze.py#L653-L682
def do_postfix(self, arg): """Sets the function to apply to the values of a specific variable before plotting or tabulating values. """ usable, filename, append = self._redirect_split(arg) sargs = usable.split() if len(sargs) == 1 and sargs[0] == "list": self....
[ "def", "do_postfix", "(", "self", ",", "arg", ")", ":", "usable", ",", "filename", ",", "append", "=", "self", ".", "_redirect_split", "(", "arg", ")", "sargs", "=", "usable", ".", "split", "(", ")", "if", "len", "(", "sargs", ")", "==", "1", "and"...
Sets the function to apply to the values of a specific variable before plotting or tabulating values.
[ "Sets", "the", "function", "to", "apply", "to", "the", "values", "of", "a", "specific", "variable", "before", "plotting", "or", "tabulating", "values", "." ]
python
train
Loudr/pale
pale/endpoint.py
https://github.com/Loudr/pale/blob/dc002ee6032c856551143af222ff8f71ed9853fe/pale/endpoint.py#L122-L286
def _execute(self, request, **kwargs): """The top-level execute function for the endpoint. This method is intended to remain as-is, and not be overridden. It gets called by your HTTP framework's route handler, and performs the following actions to process the request: ``authent...
[ "def", "_execute", "(", "self", ",", "request", ",", "*", "*", "kwargs", ")", ":", "try", ":", "self", ".", "_create_context", "(", "request", ")", "self", ".", "_authenticate", "(", ")", "context", "=", "get_current_context", "(", ")", "self", ".", "_...
The top-level execute function for the endpoint. This method is intended to remain as-is, and not be overridden. It gets called by your HTTP framework's route handler, and performs the following actions to process the request: ``authenticate_request`` Validate the Bearer to...
[ "The", "top", "-", "level", "execute", "function", "for", "the", "endpoint", "." ]
python
train
emlazzarin/acrylic
acrylic/datatable.py
https://github.com/emlazzarin/acrylic/blob/08c6702d73b9660ead1024653f4fa016f6340e46/acrylic/datatable.py#L656-L675
def rename(self, old_fieldname, new_fieldname): """ Renames a specific field, and preserves the underlying order. """ if old_fieldname not in self: raise Exception("DataTable does not have field `%s`" % old_fieldname) if not isinstance(new...
[ "def", "rename", "(", "self", ",", "old_fieldname", ",", "new_fieldname", ")", ":", "if", "old_fieldname", "not", "in", "self", ":", "raise", "Exception", "(", "\"DataTable does not have field `%s`\"", "%", "old_fieldname", ")", "if", "not", "isinstance", "(", "...
Renames a specific field, and preserves the underlying order.
[ "Renames", "a", "specific", "field", "and", "preserves", "the", "underlying", "order", "." ]
python
train