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 |
|---|---|---|---|---|---|---|---|---|
annoviko/pyclustering | pyclustering/container/cftree.py | https://github.com/annoviko/pyclustering/blob/98aa0dd89fd36f701668fb1eb29c8fb5662bf7d0/pyclustering/container/cftree.py#L1153-L1183 | def __split_nonleaf_node(self, node):
"""!
@brief Performs splitting of the specified non-leaf node.
@param[in] node (non_leaf_node): Non-leaf node that should be splitted.
@return (list) New pair of non-leaf nodes [non_leaf_node1, non_leaf_node2].
... | [
"def",
"__split_nonleaf_node",
"(",
"self",
",",
"node",
")",
":",
"[",
"farthest_node1",
",",
"farthest_node2",
"]",
"=",
"node",
".",
"get_farthest_successors",
"(",
"self",
".",
"__type_measurement",
")",
"# create new non-leaf nodes\r",
"new_node1",
"=",
"non_le... | !
@brief Performs splitting of the specified non-leaf node.
@param[in] node (non_leaf_node): Non-leaf node that should be splitted.
@return (list) New pair of non-leaf nodes [non_leaf_node1, non_leaf_node2]. | [
"!"
] | python | valid |
markovmodel/msmtools | msmtools/analysis/dense/decomposition.py | https://github.com/markovmodel/msmtools/blob/54dc76dd2113a0e8f3d15d5316abab41402941be/msmtools/analysis/dense/decomposition.py#L258-L317 | def rdl_decomposition(T, k=None, reversible=False, norm='standard', mu=None):
r"""Compute the decomposition into left and right eigenvectors.
Parameters
----------
T : (M, M) ndarray
Transition matrix
k : int (optional)
Number of eigenvector/eigenvalue pairs
norm: {'standard', '... | [
"def",
"rdl_decomposition",
"(",
"T",
",",
"k",
"=",
"None",
",",
"reversible",
"=",
"False",
",",
"norm",
"=",
"'standard'",
",",
"mu",
"=",
"None",
")",
":",
"# auto-set norm",
"if",
"norm",
"==",
"'auto'",
":",
"if",
"is_reversible",
"(",
"T",
")",
... | r"""Compute the decomposition into left and right eigenvectors.
Parameters
----------
T : (M, M) ndarray
Transition matrix
k : int (optional)
Number of eigenvector/eigenvalue pairs
norm: {'standard', 'reversible', 'auto'}
standard: (L'R) = Id, L[:,0] is a probability distrib... | [
"r",
"Compute",
"the",
"decomposition",
"into",
"left",
"and",
"right",
"eigenvectors",
"."
] | python | train |
dmlc/xgboost | python-package/xgboost/sklearn.py | https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/sklearn.py#L803-L839 | def predict_proba(self, data, ntree_limit=None, validate_features=True):
"""
Predict the probability of each `data` example being of a given class.
.. note:: This function is not thread safe
For each booster object, predict can only be called from one thread.
If you wan... | [
"def",
"predict_proba",
"(",
"self",
",",
"data",
",",
"ntree_limit",
"=",
"None",
",",
"validate_features",
"=",
"True",
")",
":",
"test_dmatrix",
"=",
"DMatrix",
"(",
"data",
",",
"missing",
"=",
"self",
".",
"missing",
",",
"nthread",
"=",
"self",
"."... | Predict the probability of each `data` example being of a given class.
.. note:: This function is not thread safe
For each booster object, predict can only be called from one thread.
If you want to run prediction using multiple thread, call ``xgb.copy()`` to make copies
of ... | [
"Predict",
"the",
"probability",
"of",
"each",
"data",
"example",
"being",
"of",
"a",
"given",
"class",
"."
] | python | train |
MostAwesomeDude/gentleman | gentleman/base.py | https://github.com/MostAwesomeDude/gentleman/blob/17fb8ffb922aa4af9d8bcab85e452c9311d41805/gentleman/base.py#L991-L1007 | def PowercycleNode(r, node, force=False):
"""
Powercycles a node.
@type node: string
@param node: Node name
@type force: bool
@param force: Whether to force the operation
@rtype: string
@return: job id
"""
query = {
"force": force,
}
return r.request("post", "/... | [
"def",
"PowercycleNode",
"(",
"r",
",",
"node",
",",
"force",
"=",
"False",
")",
":",
"query",
"=",
"{",
"\"force\"",
":",
"force",
",",
"}",
"return",
"r",
".",
"request",
"(",
"\"post\"",
",",
"\"/2/nodes/%s/powercycle\"",
"%",
"node",
",",
"query",
... | Powercycles a node.
@type node: string
@param node: Node name
@type force: bool
@param force: Whether to force the operation
@rtype: string
@return: job id | [
"Powercycles",
"a",
"node",
"."
] | python | train |
Legobot/Legobot | Legobot/Connectors/Discord.py | https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Connectors/Discord.py#L179-L192 | def on_message(self, message):
"""
Runs on a create_message event from websocket connection
Args:
message (dict): Full message from Discord websocket connection"
"""
if 'content' in message['d']:
metadata = self._parse_metadata(message)
messa... | [
"def",
"on_message",
"(",
"self",
",",
"message",
")",
":",
"if",
"'content'",
"in",
"message",
"[",
"'d'",
"]",
":",
"metadata",
"=",
"self",
".",
"_parse_metadata",
"(",
"message",
")",
"message",
"=",
"Message",
"(",
"text",
"=",
"message",
"[",
"'d... | Runs on a create_message event from websocket connection
Args:
message (dict): Full message from Discord websocket connection" | [
"Runs",
"on",
"a",
"create_message",
"event",
"from",
"websocket",
"connection"
] | python | train |
Gandi/gandi.cli | gandi/cli/core/utils/__init__.py | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/core/utils/__init__.py#L157-L166 | def output_metric(gandi, metrics, key, justify=10):
""" Helper to output metrics."""
for metric in metrics:
key_name = metric[key].pop()
values = [point.get('value', 0) for point in metric['points']]
graph = sparks(values) if max(values) else ''
# need to encode in utf-8 to work ... | [
"def",
"output_metric",
"(",
"gandi",
",",
"metrics",
",",
"key",
",",
"justify",
"=",
"10",
")",
":",
"for",
"metric",
"in",
"metrics",
":",
"key_name",
"=",
"metric",
"[",
"key",
"]",
".",
"pop",
"(",
")",
"values",
"=",
"[",
"point",
".",
"get",... | Helper to output metrics. | [
"Helper",
"to",
"output",
"metrics",
"."
] | python | train |
SeleniumHQ/selenium | py/selenium/webdriver/firefox/firefox_binary.py | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/firefox/firefox_binary.py#L210-L217 | def which(self, fname):
"""Returns the fully qualified path by searching Path of the given
name"""
for pe in os.environ['PATH'].split(os.pathsep):
checkname = os.path.join(pe, fname)
if os.access(checkname, os.X_OK) and not os.path.isdir(checkname):
return... | [
"def",
"which",
"(",
"self",
",",
"fname",
")",
":",
"for",
"pe",
"in",
"os",
".",
"environ",
"[",
"'PATH'",
"]",
".",
"split",
"(",
"os",
".",
"pathsep",
")",
":",
"checkname",
"=",
"os",
".",
"path",
".",
"join",
"(",
"pe",
",",
"fname",
")",... | Returns the fully qualified path by searching Path of the given
name | [
"Returns",
"the",
"fully",
"qualified",
"path",
"by",
"searching",
"Path",
"of",
"the",
"given",
"name"
] | python | train |
coleifer/irc | botnet/worker.py | https://github.com/coleifer/irc/blob/f9d2bd6369aafe6cb0916c9406270ca8ecea2080/botnet/worker.py#L110-L121 | def command_patterns(self):
"""\
Actual messages listened for by the worker bot - note that worker-execute
actually dispatches again by adding the command to the task queue,
from which it is pulled then matched against self.task_patterns
"""
return (
('!regist... | [
"def",
"command_patterns",
"(",
"self",
")",
":",
"return",
"(",
"(",
"'!register-success (?P<cmd_channel>.+)'",
",",
"self",
".",
"require_boss",
"(",
"self",
".",
"register_success",
")",
")",
",",
"(",
"'!worker-execute (?:\\((?P<workers>.+?)\\) )?(?P<task_id>\\d+):(?P... | \
Actual messages listened for by the worker bot - note that worker-execute
actually dispatches again by adding the command to the task queue,
from which it is pulled then matched against self.task_patterns | [
"\\",
"Actual",
"messages",
"listened",
"for",
"by",
"the",
"worker",
"bot",
"-",
"note",
"that",
"worker",
"-",
"execute",
"actually",
"dispatches",
"again",
"by",
"adding",
"the",
"command",
"to",
"the",
"task",
"queue",
"from",
"which",
"it",
"is",
"pul... | python | test |
bigchaindb/bigchaindb-driver | bigchaindb_driver/driver.py | https://github.com/bigchaindb/bigchaindb-driver/blob/c294a535f0696bd19483ae11a4882b74e6fc061e/bigchaindb_driver/driver.py#L403-L435 | def get(self, public_key, spent=None, headers=None):
"""Get transaction outputs by public key. The public_key parameter
must be a base58 encoded ed25519 public key associated with
transaction output ownership.
Args:
public_key (str): Public key for which unfulfilled
... | [
"def",
"get",
"(",
"self",
",",
"public_key",
",",
"spent",
"=",
"None",
",",
"headers",
"=",
"None",
")",
":",
"return",
"self",
".",
"transport",
".",
"forward_request",
"(",
"method",
"=",
"'GET'",
",",
"path",
"=",
"self",
".",
"path",
",",
"para... | Get transaction outputs by public key. The public_key parameter
must be a base58 encoded ed25519 public key associated with
transaction output ownership.
Args:
public_key (str): Public key for which unfulfilled
conditions are sought.
spent (bool): Indicat... | [
"Get",
"transaction",
"outputs",
"by",
"public",
"key",
".",
"The",
"public_key",
"parameter",
"must",
"be",
"a",
"base58",
"encoded",
"ed25519",
"public",
"key",
"associated",
"with",
"transaction",
"output",
"ownership",
"."
] | python | train |
cloudnull/cloudlib | cloudlib/http.py | https://github.com/cloudnull/cloudlib/blob/5038111ce02521caa2558117e3bae9e1e806d315/cloudlib/http.py#L257-L271 | def option(self, url, headers=None, kwargs=None):
"""Make a OPTION request.
To make a OPTION request pass, ``url``
:param url: ``str``
:param headers: ``dict``
:param kwargs: ``dict``
"""
return self._request(
method='option',
url=url,
... | [
"def",
"option",
"(",
"self",
",",
"url",
",",
"headers",
"=",
"None",
",",
"kwargs",
"=",
"None",
")",
":",
"return",
"self",
".",
"_request",
"(",
"method",
"=",
"'option'",
",",
"url",
"=",
"url",
",",
"headers",
"=",
"headers",
",",
"kwargs",
"... | Make a OPTION request.
To make a OPTION request pass, ``url``
:param url: ``str``
:param headers: ``dict``
:param kwargs: ``dict`` | [
"Make",
"a",
"OPTION",
"request",
"."
] | python | train |
watson-developer-cloud/python-sdk | ibm_watson/language_translator_v3.py | https://github.com/watson-developer-cloud/python-sdk/blob/4c2c9df4466fcde88975da9ecd834e6ba95eb353/ibm_watson/language_translator_v3.py#L454-L459 | def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'status') and self.status is not None:
_dict['status'] = self.status
return _dict | [
"def",
"_to_dict",
"(",
"self",
")",
":",
"_dict",
"=",
"{",
"}",
"if",
"hasattr",
"(",
"self",
",",
"'status'",
")",
"and",
"self",
".",
"status",
"is",
"not",
"None",
":",
"_dict",
"[",
"'status'",
"]",
"=",
"self",
".",
"status",
"return",
"_dic... | Return a json dictionary representing this model. | [
"Return",
"a",
"json",
"dictionary",
"representing",
"this",
"model",
"."
] | python | train |
cole/aiosmtplib | src/aiosmtplib/connection.py | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/connection.py#L329-L340 | def _raise_error_if_disconnected(self) -> None:
"""
See if we're still connected, and if not, raise
``SMTPServerDisconnected``.
"""
if (
self.transport is None
or self.protocol is None
or self.transport.is_closing()
):
self.... | [
"def",
"_raise_error_if_disconnected",
"(",
"self",
")",
"->",
"None",
":",
"if",
"(",
"self",
".",
"transport",
"is",
"None",
"or",
"self",
".",
"protocol",
"is",
"None",
"or",
"self",
".",
"transport",
".",
"is_closing",
"(",
")",
")",
":",
"self",
"... | See if we're still connected, and if not, raise
``SMTPServerDisconnected``. | [
"See",
"if",
"we",
"re",
"still",
"connected",
"and",
"if",
"not",
"raise",
"SMTPServerDisconnected",
"."
] | python | train |
maybelinot/df2gspread | df2gspread/gfiles.py | https://github.com/maybelinot/df2gspread/blob/f4cef3800704aceff2ed08a623a594b558d44898/df2gspread/gfiles.py#L19-L66 | def get_file_id(credentials, gfile, write_access=False):
"""
Get file ID by provided path. If file does not exist and
`write_access` is true, it will create whole path for you.
:param credentials: provide own credentials
:param gfile: path to Google Spreadsheet
:param write_... | [
"def",
"get_file_id",
"(",
"credentials",
",",
"gfile",
",",
"write_access",
"=",
"False",
")",
":",
"# auth for apiclient",
"http",
"=",
"credentials",
".",
"authorize",
"(",
"Http",
"(",
")",
")",
"service",
"=",
"discovery",
".",
"build",
"(",
"'drive'",
... | Get file ID by provided path. If file does not exist and
`write_access` is true, it will create whole path for you.
:param credentials: provide own credentials
:param gfile: path to Google Spreadsheet
:param write_access: allows to create full path if file does not exist
:type c... | [
"Get",
"file",
"ID",
"by",
"provided",
"path",
".",
"If",
"file",
"does",
"not",
"exist",
"and",
"write_access",
"is",
"true",
"it",
"will",
"create",
"whole",
"path",
"for",
"you",
"."
] | python | train |
ARMmbed/yotta | yotta/lib/access_common.py | https://github.com/ARMmbed/yotta/blob/56bc1e56c602fa20307b23fe27518e9cd6c11af1/yotta/lib/access_common.py#L208-L240 | def unpackFromCache(cache_key, to_directory):
''' If the specified cache key exists, unpack the tarball into the
specified directory, otherwise raise NotInCache (a KeyError subclass).
'''
if cache_key is None:
raise NotInCache('"None" is never in cache')
cache_key = _encodeCacheKey(cach... | [
"def",
"unpackFromCache",
"(",
"cache_key",
",",
"to_directory",
")",
":",
"if",
"cache_key",
"is",
"None",
":",
"raise",
"NotInCache",
"(",
"'\"None\" is never in cache'",
")",
"cache_key",
"=",
"_encodeCacheKey",
"(",
"cache_key",
")",
"cache_dir",
"=",
"folders... | If the specified cache key exists, unpack the tarball into the
specified directory, otherwise raise NotInCache (a KeyError subclass). | [
"If",
"the",
"specified",
"cache",
"key",
"exists",
"unpack",
"the",
"tarball",
"into",
"the",
"specified",
"directory",
"otherwise",
"raise",
"NotInCache",
"(",
"a",
"KeyError",
"subclass",
")",
"."
] | python | valid |
nepalicalendar/nepalicalendar-py | nepalicalendar/nepcal.py | https://github.com/nepalicalendar/nepalicalendar-py/blob/a589c28b8e085049f30a7287753476b59eca6f50/nepalicalendar/nepcal.py#L29-L32 | def monthrange(cls, year, month):
"""Returns the number of days in a month"""
functions.check_valid_bs_range(NepDate(year, month, 1))
return values.NEPALI_MONTH_DAY_DATA[year][month - 1] | [
"def",
"monthrange",
"(",
"cls",
",",
"year",
",",
"month",
")",
":",
"functions",
".",
"check_valid_bs_range",
"(",
"NepDate",
"(",
"year",
",",
"month",
",",
"1",
")",
")",
"return",
"values",
".",
"NEPALI_MONTH_DAY_DATA",
"[",
"year",
"]",
"[",
"month... | Returns the number of days in a month | [
"Returns",
"the",
"number",
"of",
"days",
"in",
"a",
"month"
] | python | train |
tanghaibao/jcvi | jcvi/formats/chain.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/chain.py#L229-L280 | def frompsl(args):
"""
%prog frompsl old.new.psl old.fasta new.fasta
Generate chain file from psl file. The pipeline is describe in:
<http://genomewiki.ucsc.edu/index.php/Minimal_Steps_For_LiftOver>
"""
from jcvi.formats.sizes import Sizes
p = OptionParser(frompsl.__doc__)
opts, args =... | [
"def",
"frompsl",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"formats",
".",
"sizes",
"import",
"Sizes",
"p",
"=",
"OptionParser",
"(",
"frompsl",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
... | %prog frompsl old.new.psl old.fasta new.fasta
Generate chain file from psl file. The pipeline is describe in:
<http://genomewiki.ucsc.edu/index.php/Minimal_Steps_For_LiftOver> | [
"%prog",
"frompsl",
"old",
".",
"new",
".",
"psl",
"old",
".",
"fasta",
"new",
".",
"fasta"
] | python | train |
tino/pyFirmata | pyfirmata/pyfirmata.py | https://github.com/tino/pyFirmata/blob/05881909c4d7c4e808e9ed457144670b2136706e/pyfirmata/pyfirmata.py#L402-L410 | def enable_reporting(self):
"""Enable reporting of values for the whole port."""
self.reporting = True
msg = bytearray([REPORT_DIGITAL + self.port_number, 1])
self.board.sp.write(msg)
for pin in self.pins:
if pin.mode == INPUT:
pin.reporting = True | [
"def",
"enable_reporting",
"(",
"self",
")",
":",
"self",
".",
"reporting",
"=",
"True",
"msg",
"=",
"bytearray",
"(",
"[",
"REPORT_DIGITAL",
"+",
"self",
".",
"port_number",
",",
"1",
"]",
")",
"self",
".",
"board",
".",
"sp",
".",
"write",
"(",
"ms... | Enable reporting of values for the whole port. | [
"Enable",
"reporting",
"of",
"values",
"for",
"the",
"whole",
"port",
"."
] | python | train |
StagPython/StagPy | stagpy/stagyyparsers.py | https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/stagyyparsers.py#L688-L741 | def read_field_h5(xdmf_file, fieldname, snapshot, header=None):
"""Extract field data from hdf5 files.
Args:
xdmf_file (:class:`pathlib.Path`): path of the xdmf file.
fieldname (str): name of field to extract.
snapshot (int): snapshot number.
header (dict): geometry information.... | [
"def",
"read_field_h5",
"(",
"xdmf_file",
",",
"fieldname",
",",
"snapshot",
",",
"header",
"=",
"None",
")",
":",
"if",
"header",
"is",
"None",
":",
"header",
",",
"xdmf_root",
"=",
"read_geom_h5",
"(",
"xdmf_file",
",",
"snapshot",
")",
"else",
":",
"x... | Extract field data from hdf5 files.
Args:
xdmf_file (:class:`pathlib.Path`): path of the xdmf file.
fieldname (str): name of field to extract.
snapshot (int): snapshot number.
header (dict): geometry information.
Returns:
(dict, numpy.array): geometry information and fie... | [
"Extract",
"field",
"data",
"from",
"hdf5",
"files",
"."
] | python | train |
openstack/networking-cisco | networking_cisco/ml2_drivers/nexus/nexus_restapi_network_driver.py | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/nexus/nexus_restapi_network_driver.py#L468-L535 | def initialize_baremetal_switch_interfaces(self, interfaces):
"""Initialize Nexus interfaces and for initial baremetal event.
This get/create port channel number, applies channel-group to
ethernet interface, and initializes trunking on interface.
:param interfaces: Receive a list of in... | [
"def",
"initialize_baremetal_switch_interfaces",
"(",
"self",
",",
"interfaces",
")",
":",
"if",
"not",
"interfaces",
":",
"return",
"max_ifs",
"=",
"len",
"(",
"interfaces",
")",
"starttime",
"=",
"time",
".",
"time",
"(",
")",
"learned",
",",
"nexus_ip_list"... | Initialize Nexus interfaces and for initial baremetal event.
This get/create port channel number, applies channel-group to
ethernet interface, and initializes trunking on interface.
:param interfaces: Receive a list of interfaces containing:
nexus_host: IP address of Nexus switch
... | [
"Initialize",
"Nexus",
"interfaces",
"and",
"for",
"initial",
"baremetal",
"event",
"."
] | python | train |
haikuginger/beekeeper | beekeeper/variables.py | https://github.com/haikuginger/beekeeper/blob/b647d3add0b407ec5dc3a2a39c4f6dac31243b18/beekeeper/variables.py#L223-L229 | def fill_kwargs(self, **kwargs):
"""
Fill empty variable objects by name with the values from
any present keyword arguments.
"""
for var, val in kwargs.items():
self.setval(var, val) | [
"def",
"fill_kwargs",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"var",
",",
"val",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"self",
".",
"setval",
"(",
"var",
",",
"val",
")"
] | Fill empty variable objects by name with the values from
any present keyword arguments. | [
"Fill",
"empty",
"variable",
"objects",
"by",
"name",
"with",
"the",
"values",
"from",
"any",
"present",
"keyword",
"arguments",
"."
] | python | train |
skelsec/minidump | minidump/minidumpreader.py | https://github.com/skelsec/minidump/blob/0c4dcabe6f11d7a403440919ffa9e3c9889c5212/minidump/minidumpreader.py#L118-L139 | def read(self, size = -1):
"""
Returns data bytes of size size from the current segment. If size is -1 it returns all the remaining data bytes from memory segment
"""
if size < -1:
raise Exception('You shouldnt be doing this')
if size == -1:
t = self.current_segment.remaining_len(self.current_position)
... | [
"def",
"read",
"(",
"self",
",",
"size",
"=",
"-",
"1",
")",
":",
"if",
"size",
"<",
"-",
"1",
":",
"raise",
"Exception",
"(",
"'You shouldnt be doing this'",
")",
"if",
"size",
"==",
"-",
"1",
":",
"t",
"=",
"self",
".",
"current_segment",
".",
"r... | Returns data bytes of size size from the current segment. If size is -1 it returns all the remaining data bytes from memory segment | [
"Returns",
"data",
"bytes",
"of",
"size",
"size",
"from",
"the",
"current",
"segment",
".",
"If",
"size",
"is",
"-",
"1",
"it",
"returns",
"all",
"the",
"remaining",
"data",
"bytes",
"from",
"memory",
"segment"
] | python | train |
IndicoDataSolutions/Passage | passage/models.py | https://github.com/IndicoDataSolutions/Passage/blob/af6e100804dfe332c88bd2cd192e93a807377887/passage/models.py#L62-L108 | def fit(self, trX, trY, batch_size=64, n_epochs=1, len_filter=LenFilter(), snapshot_freq=1, path=None):
"""Train model on given training examples and return the list of costs after each minibatch is processed.
Args:
trX (list) -- Inputs
trY (list) -- Outputs
batch_size (in... | [
"def",
"fit",
"(",
"self",
",",
"trX",
",",
"trY",
",",
"batch_size",
"=",
"64",
",",
"n_epochs",
"=",
"1",
",",
"len_filter",
"=",
"LenFilter",
"(",
")",
",",
"snapshot_freq",
"=",
"1",
",",
"path",
"=",
"None",
")",
":",
"if",
"len_filter",
"is",... | Train model on given training examples and return the list of costs after each minibatch is processed.
Args:
trX (list) -- Inputs
trY (list) -- Outputs
batch_size (int, optional) -- number of examples in a minibatch (default 64)
n_epochs (int, optional) -- number of epo... | [
"Train",
"model",
"on",
"given",
"training",
"examples",
"and",
"return",
"the",
"list",
"of",
"costs",
"after",
"each",
"minibatch",
"is",
"processed",
"."
] | python | valid |
Ex-Mente/auxi.0 | auxi/modelling/process/materials/thermo.py | https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/process/materials/thermo.py#L582-L599 | def _calculate_H(self, T):
"""
Calculate the enthalpy of the package at the specified temperature.
:param T: Temperature. [°C]
:returns: Enthalpy. [kWh]
"""
if self.isCoal:
return self._calculate_Hfr_coal(T)
H = 0.0
for compound in self.mat... | [
"def",
"_calculate_H",
"(",
"self",
",",
"T",
")",
":",
"if",
"self",
".",
"isCoal",
":",
"return",
"self",
".",
"_calculate_Hfr_coal",
"(",
"T",
")",
"H",
"=",
"0.0",
"for",
"compound",
"in",
"self",
".",
"material",
".",
"compounds",
":",
"index",
... | Calculate the enthalpy of the package at the specified temperature.
:param T: Temperature. [°C]
:returns: Enthalpy. [kWh] | [
"Calculate",
"the",
"enthalpy",
"of",
"the",
"package",
"at",
"the",
"specified",
"temperature",
"."
] | python | valid |
apache/incubator-superset | superset/tasks/schedules.py | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/tasks/schedules.py#L190-L204 | def destroy_webdriver(driver):
"""
Destroy a driver
"""
# This is some very flaky code in selenium. Hence the retries
# and catch-all exceptions
try:
retry_call(driver.close, tries=2)
except Exception:
pass
try:
driver.quit()
except Exception:
pass | [
"def",
"destroy_webdriver",
"(",
"driver",
")",
":",
"# This is some very flaky code in selenium. Hence the retries",
"# and catch-all exceptions",
"try",
":",
"retry_call",
"(",
"driver",
".",
"close",
",",
"tries",
"=",
"2",
")",
"except",
"Exception",
":",
"pass",
... | Destroy a driver | [
"Destroy",
"a",
"driver"
] | python | train |
google/tangent | tangent/reverse_ad.py | https://github.com/google/tangent/blob/6533e83af09de7345d1b438512679992f080dcc9/tangent/reverse_ad.py#L684-L792 | def visit_Call(self, node):
"""Create adjoint for call.
We don't allow unpacking of parameters, so we know that each argument
gets passed in explicitly, allowing us to create partials for each.
However, templates might perform parameter unpacking (for cases where
the number of arguments is variable... | [
"def",
"visit_Call",
"(",
"self",
",",
"node",
")",
":",
"# Find the function we are differentiating",
"func",
"=",
"anno",
".",
"getanno",
"(",
"node",
",",
"'func'",
")",
"if",
"func",
"in",
"non_differentiable",
".",
"NON_DIFFERENTIABLE",
":",
"return",
"node... | Create adjoint for call.
We don't allow unpacking of parameters, so we know that each argument
gets passed in explicitly, allowing us to create partials for each.
However, templates might perform parameter unpacking (for cases where
the number of arguments is variable) and express their gradient as a
... | [
"Create",
"adjoint",
"for",
"call",
"."
] | python | train |
pybel/pybel | src/pybel/dsl/namespaces.py | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/dsl/namespaces.py#L18-L20 | def hgnc(name=None, identifier=None) -> Protein:
"""Build an HGNC protein node."""
return Protein(namespace='HGNC', name=name, identifier=identifier) | [
"def",
"hgnc",
"(",
"name",
"=",
"None",
",",
"identifier",
"=",
"None",
")",
"->",
"Protein",
":",
"return",
"Protein",
"(",
"namespace",
"=",
"'HGNC'",
",",
"name",
"=",
"name",
",",
"identifier",
"=",
"identifier",
")"
] | Build an HGNC protein node. | [
"Build",
"an",
"HGNC",
"protein",
"node",
"."
] | python | train |
spacetelescope/drizzlepac | drizzlepac/updatenpol.py | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/updatenpol.py#L257-L265 | def find_d2ifile(flist,detector):
""" Search a list of files for one that matches the detector specified.
"""
d2ifile = None
for f in flist:
fdet = fits.getval(f, 'detector', memmap=False)
if fdet == detector:
d2ifile = f
return d2ifile | [
"def",
"find_d2ifile",
"(",
"flist",
",",
"detector",
")",
":",
"d2ifile",
"=",
"None",
"for",
"f",
"in",
"flist",
":",
"fdet",
"=",
"fits",
".",
"getval",
"(",
"f",
",",
"'detector'",
",",
"memmap",
"=",
"False",
")",
"if",
"fdet",
"==",
"detector",... | Search a list of files for one that matches the detector specified. | [
"Search",
"a",
"list",
"of",
"files",
"for",
"one",
"that",
"matches",
"the",
"detector",
"specified",
"."
] | python | train |
tango-controls/pytango | tango/databaseds/database.py | https://github.com/tango-controls/pytango/blob/9cf78c517c9cdc1081ff6d080a9646a740cc1d36/tango/databaseds/database.py#L809-L824 | def DbDeleteDevice(self, argin):
""" Delete a devcie from database
:param argin: device name
:type: tango.DevString
:return:
:rtype: tango.DevVoid """
self._log.debug("In DbDeleteDevice()")
ret, dev_name, dfm = check_device_name(argin)
if not ret:
... | [
"def",
"DbDeleteDevice",
"(",
"self",
",",
"argin",
")",
":",
"self",
".",
"_log",
".",
"debug",
"(",
"\"In DbDeleteDevice()\"",
")",
"ret",
",",
"dev_name",
",",
"dfm",
"=",
"check_device_name",
"(",
"argin",
")",
"if",
"not",
"ret",
":",
"self",
".",
... | Delete a devcie from database
:param argin: device name
:type: tango.DevString
:return:
:rtype: tango.DevVoid | [
"Delete",
"a",
"devcie",
"from",
"database"
] | python | train |
waqasbhatti/astrobase | astrobase/checkplot/pkl_utils.py | https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/checkplot/pkl_utils.py#L120-L1203 | def _pkl_finder_objectinfo(
objectinfo,
varinfo,
findercmap,
finderconvolve,
sigclip,
normto,
normmingap,
deredden_object=True,
custom_bandpasses=None,
lclistpkl=None,
nbrradiusarcsec=30.0,
maxnumneighbors=5,
plotdpi... | [
"def",
"_pkl_finder_objectinfo",
"(",
"objectinfo",
",",
"varinfo",
",",
"findercmap",
",",
"finderconvolve",
",",
"sigclip",
",",
"normto",
",",
"normmingap",
",",
"deredden_object",
"=",
"True",
",",
"custom_bandpasses",
"=",
"None",
",",
"lclistpkl",
"=",
"No... | This returns the finder chart and object information as a dict.
Parameters
----------
objectinfo : dict or None
If provided, this is a dict containing information on the object whose
light curve is being processed. This function will then be able to look
up and download a finder ch... | [
"This",
"returns",
"the",
"finder",
"chart",
"and",
"object",
"information",
"as",
"a",
"dict",
"."
] | python | valid |
Cadair/jupyter_environment_kernels | environment_kernels/envs_common.py | https://github.com/Cadair/jupyter_environment_kernels/blob/3da304550b511bda7d5d39280379b5ca39bb31bc/environment_kernels/envs_common.py#L124-L138 | def find_exe(env_dir, name):
"""Finds a exe with that name in the environment path"""
if platform.system() == "Windows":
name = name + ".exe"
# find the binary
exe_name = os.path.join(env_dir, name)
if not os.path.exists(exe_name):
exe_name = os.path.join(env_dir, "bin", name)
... | [
"def",
"find_exe",
"(",
"env_dir",
",",
"name",
")",
":",
"if",
"platform",
".",
"system",
"(",
")",
"==",
"\"Windows\"",
":",
"name",
"=",
"name",
"+",
"\".exe\"",
"# find the binary",
"exe_name",
"=",
"os",
".",
"path",
".",
"join",
"(",
"env_dir",
"... | Finds a exe with that name in the environment path | [
"Finds",
"a",
"exe",
"with",
"that",
"name",
"in",
"the",
"environment",
"path"
] | python | train |
theirc/rapidsms-multitenancy | multitenancy/admin.py | https://github.com/theirc/rapidsms-multitenancy/blob/121bd0a628e691a88aade2e10045cba43af2dfcb/multitenancy/admin.py#L67-L73 | def get_queryset(self, request):
"""Limit to TenantGroups that this user can access."""
qs = super(TenantGroupAdmin, self).get_queryset(request)
if not request.user.is_superuser:
qs = qs.filter(tenantrole__user=request.user,
tenantrole__role=TenantRole.ROLE... | [
"def",
"get_queryset",
"(",
"self",
",",
"request",
")",
":",
"qs",
"=",
"super",
"(",
"TenantGroupAdmin",
",",
"self",
")",
".",
"get_queryset",
"(",
"request",
")",
"if",
"not",
"request",
".",
"user",
".",
"is_superuser",
":",
"qs",
"=",
"qs",
".",
... | Limit to TenantGroups that this user can access. | [
"Limit",
"to",
"TenantGroups",
"that",
"this",
"user",
"can",
"access",
"."
] | python | train |
hazelcast/hazelcast-python-client | hazelcast/util.py | https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/util.py#L119-L127 | def validate_serializer(serializer, _type):
"""
Validates the serializer for given type.
:param serializer: (Serializer), the serializer to be validated.
:param _type: (Type), type to be used for serializer validation.
"""
if not issubclass(serializer, _type):
raise ValueError("Serializ... | [
"def",
"validate_serializer",
"(",
"serializer",
",",
"_type",
")",
":",
"if",
"not",
"issubclass",
"(",
"serializer",
",",
"_type",
")",
":",
"raise",
"ValueError",
"(",
"\"Serializer should be an instance of {}\"",
".",
"format",
"(",
"_type",
".",
"__name__",
... | Validates the serializer for given type.
:param serializer: (Serializer), the serializer to be validated.
:param _type: (Type), type to be used for serializer validation. | [
"Validates",
"the",
"serializer",
"for",
"given",
"type",
"."
] | python | train |
theolind/pymysensors | mysensors/__init__.py | https://github.com/theolind/pymysensors/blob/a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6/mysensors/__init__.py#L98-L104 | def add_sensor(self, sensorid=None):
"""Add a sensor to the gateway."""
if sensorid is None:
sensorid = self._get_next_id()
if sensorid is not None and sensorid not in self.sensors:
self.sensors[sensorid] = Sensor(sensorid)
return sensorid if sensorid in self.sens... | [
"def",
"add_sensor",
"(",
"self",
",",
"sensorid",
"=",
"None",
")",
":",
"if",
"sensorid",
"is",
"None",
":",
"sensorid",
"=",
"self",
".",
"_get_next_id",
"(",
")",
"if",
"sensorid",
"is",
"not",
"None",
"and",
"sensorid",
"not",
"in",
"self",
".",
... | Add a sensor to the gateway. | [
"Add",
"a",
"sensor",
"to",
"the",
"gateway",
"."
] | python | train |
tcalmant/ipopo | pelix/ipopo/core.py | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/core.py#L353-L410 | def __try_instantiate(self, component_context, instance):
# type: (ComponentContext, object) -> bool
"""
Instantiates a component, if all of its handlers are there. Returns
False if a handler is missing.
:param component_context: A ComponentContext bean
:param instance: ... | [
"def",
"__try_instantiate",
"(",
"self",
",",
"component_context",
",",
"instance",
")",
":",
"# type: (ComponentContext, object) -> bool",
"with",
"self",
".",
"__instances_lock",
":",
"# Extract information about the component",
"factory_context",
"=",
"component_context",
... | Instantiates a component, if all of its handlers are there. Returns
False if a handler is missing.
:param component_context: A ComponentContext bean
:param instance: The component instance
:return: True if the component has started,
False if a handler is missing | [
"Instantiates",
"a",
"component",
"if",
"all",
"of",
"its",
"handlers",
"are",
"there",
".",
"Returns",
"False",
"if",
"a",
"handler",
"is",
"missing",
"."
] | python | train |
PyMLGame/pymlgame | pymlgame/__init__.py | https://github.com/PyMLGame/pymlgame/blob/450fe77d35f9a26c107586d6954f69c3895bf504/pymlgame/__init__.py#L40-L60 | def get_events(maximum=10):
"""
Get all events since the last time you asked for them. You can define a maximum which is 10 by default.
:param maximum: Maximum number of events
:type maximum: int
:return: List of events
:rtype: list
"""
events = []
for ev in range(0, maximum):
... | [
"def",
"get_events",
"(",
"maximum",
"=",
"10",
")",
":",
"events",
"=",
"[",
"]",
"for",
"ev",
"in",
"range",
"(",
"0",
",",
"maximum",
")",
":",
"try",
":",
"if",
"CONTROLLER",
".",
"queue",
".",
"empty",
"(",
")",
":",
"break",
"else",
":",
... | Get all events since the last time you asked for them. You can define a maximum which is 10 by default.
:param maximum: Maximum number of events
:type maximum: int
:return: List of events
:rtype: list | [
"Get",
"all",
"events",
"since",
"the",
"last",
"time",
"you",
"asked",
"for",
"them",
".",
"You",
"can",
"define",
"a",
"maximum",
"which",
"is",
"10",
"by",
"default",
"."
] | python | train |
rytilahti/python-eq3bt | eq3bt/eq3cli.py | https://github.com/rytilahti/python-eq3bt/blob/595459d9885920cf13b7059a1edd2cf38cede1f0/eq3bt/eq3cli.py#L55-L60 | def mode(dev, target):
""" Gets or sets the active mode. """
click.echo("Current mode: %s" % dev.mode_readable)
if target:
click.echo("Setting mode: %s" % target)
dev.mode = target | [
"def",
"mode",
"(",
"dev",
",",
"target",
")",
":",
"click",
".",
"echo",
"(",
"\"Current mode: %s\"",
"%",
"dev",
".",
"mode_readable",
")",
"if",
"target",
":",
"click",
".",
"echo",
"(",
"\"Setting mode: %s\"",
"%",
"target",
")",
"dev",
".",
"mode",
... | Gets or sets the active mode. | [
"Gets",
"or",
"sets",
"the",
"active",
"mode",
"."
] | python | train |
sammchardy/python-binance | examples/save_historical_data.py | https://github.com/sammchardy/python-binance/blob/31c0d0a32f9edd528c6c2c1dd3044d9a34ce43cc/examples/save_historical_data.py#L60-L136 | def get_historical_klines(symbol, interval, start_str, end_str=None):
"""Get Historical Klines from Binance
See dateparse docs for valid start and end string formats http://dateparser.readthedocs.io/en/latest/
If using offset strings for dates add "UTC" to date string e.g. "now UTC", "11 hours ago UTC"
... | [
"def",
"get_historical_klines",
"(",
"symbol",
",",
"interval",
",",
"start_str",
",",
"end_str",
"=",
"None",
")",
":",
"# create the Binance client, no need for api key",
"client",
"=",
"Client",
"(",
"\"\"",
",",
"\"\"",
")",
"# init our list",
"output_data",
"="... | Get Historical Klines from Binance
See dateparse docs for valid start and end string formats http://dateparser.readthedocs.io/en/latest/
If using offset strings for dates add "UTC" to date string e.g. "now UTC", "11 hours ago UTC"
:param symbol: Name of symbol pair e.g BNBBTC
:type symbol: str
:p... | [
"Get",
"Historical",
"Klines",
"from",
"Binance"
] | python | train |
blockchain/api-v1-client-python | blockchain/wallet.py | https://github.com/blockchain/api-v1-client-python/blob/52ea562f824f04303e75239364e06722bec8620f/blockchain/wallet.py#L84-L95 | def get_balance(self):
"""Fetch the wallet balance. Includes unconfirmed transactions
and possibly double spends.
:return: wallet balance in satoshi
"""
response = util.call_api("merchant/{0}/balance".format(self.identifier), self.build_basic_request(),
... | [
"def",
"get_balance",
"(",
"self",
")",
":",
"response",
"=",
"util",
".",
"call_api",
"(",
"\"merchant/{0}/balance\"",
".",
"format",
"(",
"self",
".",
"identifier",
")",
",",
"self",
".",
"build_basic_request",
"(",
")",
",",
"base_url",
"=",
"self",
"."... | Fetch the wallet balance. Includes unconfirmed transactions
and possibly double spends.
:return: wallet balance in satoshi | [
"Fetch",
"the",
"wallet",
"balance",
".",
"Includes",
"unconfirmed",
"transactions",
"and",
"possibly",
"double",
"spends",
".",
":",
"return",
":",
"wallet",
"balance",
"in",
"satoshi"
] | python | train |
timothyb0912/pylogit | pylogit/base_multinomial_cm_v2.py | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/base_multinomial_cm_v2.py#L1073-L1115 | def _create_fit_summary(self):
"""
Create and store a pandas series that will display to users the
various statistics/values that indicate how well the estimated model
fit the given dataset.
Returns
-------
None.
"""
# Make sure we have all attrib... | [
"def",
"_create_fit_summary",
"(",
"self",
")",
":",
"# Make sure we have all attributes needed to create the results summary",
"needed_attributes",
"=",
"[",
"\"df_model\"",
",",
"\"nobs\"",
",",
"\"null_log_likelihood\"",
",",
"\"log_likelihood\"",
",",
"\"rho_squared\"",
","... | Create and store a pandas series that will display to users the
various statistics/values that indicate how well the estimated model
fit the given dataset.
Returns
-------
None. | [
"Create",
"and",
"store",
"a",
"pandas",
"series",
"that",
"will",
"display",
"to",
"users",
"the",
"various",
"statistics",
"/",
"values",
"that",
"indicate",
"how",
"well",
"the",
"estimated",
"model",
"fit",
"the",
"given",
"dataset",
"."
] | python | train |
uber/rides-python-sdk | uber_rides/request.py | https://github.com/uber/rides-python-sdk/blob/76ecd75ab5235d792ec1010e36eca679ba285127/uber_rides/request.py#L124-L137 | def _send(self, prepared_request):
"""Send a PreparedRequest to the server.
Parameters
prepared_request (requests.PreparedRequest)
Returns
(Response)
A Response object, whichcontains a server's
response to an HTTP request.
"""
... | [
"def",
"_send",
"(",
"self",
",",
"prepared_request",
")",
":",
"session",
"=",
"Session",
"(",
")",
"response",
"=",
"session",
".",
"send",
"(",
"prepared_request",
")",
"return",
"Response",
"(",
"response",
")"
] | Send a PreparedRequest to the server.
Parameters
prepared_request (requests.PreparedRequest)
Returns
(Response)
A Response object, whichcontains a server's
response to an HTTP request. | [
"Send",
"a",
"PreparedRequest",
"to",
"the",
"server",
"."
] | python | train |
ethereum/py-evm | eth/vm/logic/arithmetic.py | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/vm/logic/arithmetic.py#L167-L183 | def signextend(computation: BaseComputation) -> None:
"""
Signed Extend
"""
bits, value = computation.stack_pop(num_items=2, type_hint=constants.UINT256)
if bits <= 31:
testbit = bits * 8 + 7
sign_bit = (1 << testbit)
if value & sign_bit:
result = value | (consta... | [
"def",
"signextend",
"(",
"computation",
":",
"BaseComputation",
")",
"->",
"None",
":",
"bits",
",",
"value",
"=",
"computation",
".",
"stack_pop",
"(",
"num_items",
"=",
"2",
",",
"type_hint",
"=",
"constants",
".",
"UINT256",
")",
"if",
"bits",
"<=",
... | Signed Extend | [
"Signed",
"Extend"
] | python | train |
kstaniek/condoor | condoor/protocols/ssh.py | https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/protocols/ssh.py#L54-L83 | def connect(self, driver):
"""Connect using the SSH protocol specific FSM."""
# 0 1 2
events = [driver.password_re, self.device.prompt_re, driver.unable_to_connect_re,
# 3 4 5 6 ... | [
"def",
"connect",
"(",
"self",
",",
"driver",
")",
":",
"# 0 1 2",
"events",
"=",
"[",
"driver",
".",
"password_re",
",",
"self",
".",
"device",
".",
"prompt_re",
",",
"driver",
".",
"unable_to_connect_re",
","... | Connect using the SSH protocol specific FSM. | [
"Connect",
"using",
"the",
"SSH",
"protocol",
"specific",
"FSM",
"."
] | python | train |
Pytwitcher/pytwitcherapi | src/pytwitcherapi/models.py | https://github.com/Pytwitcher/pytwitcherapi/blob/d53ac5ad5ca113ecb7da542e8cdcbbf8c762b336/src/pytwitcherapi/models.py#L283-L295 | def wrap_get_stream(cls, response):
"""Wrap the response from getting a stream into an instance
and return it
:param response: The response from getting a stream
:type response: :class:`requests.Response`
:returns: the new stream instance
:rtype: :class:`list` of :class:... | [
"def",
"wrap_get_stream",
"(",
"cls",
",",
"response",
")",
":",
"json",
"=",
"response",
".",
"json",
"(",
")",
"s",
"=",
"cls",
".",
"wrap_json",
"(",
"json",
"[",
"'stream'",
"]",
")",
"return",
"s"
] | Wrap the response from getting a stream into an instance
and return it
:param response: The response from getting a stream
:type response: :class:`requests.Response`
:returns: the new stream instance
:rtype: :class:`list` of :class:`stream`
:raises: None | [
"Wrap",
"the",
"response",
"from",
"getting",
"a",
"stream",
"into",
"an",
"instance",
"and",
"return",
"it"
] | python | train |
broadinstitute/fiss | firecloud/fiss.py | https://github.com/broadinstitute/fiss/blob/dddf91547479506dbbafb69ec84d44dcc4a94ab4/firecloud/fiss.py#L1672-L1680 | def _nonempty_project(string):
"""
Argparse validator for ensuring a workspace is provided
"""
value = str(string)
if len(value) == 0:
msg = "No project provided and no default project configured"
raise argparse.ArgumentTypeError(msg)
return value | [
"def",
"_nonempty_project",
"(",
"string",
")",
":",
"value",
"=",
"str",
"(",
"string",
")",
"if",
"len",
"(",
"value",
")",
"==",
"0",
":",
"msg",
"=",
"\"No project provided and no default project configured\"",
"raise",
"argparse",
".",
"ArgumentTypeError",
... | Argparse validator for ensuring a workspace is provided | [
"Argparse",
"validator",
"for",
"ensuring",
"a",
"workspace",
"is",
"provided"
] | python | train |
edeposit/edeposit.amqp.antivirus | src/edeposit/amqp/antivirus/__init__.py | https://github.com/edeposit/edeposit.amqp.antivirus/blob/011b38bbe920819fab99a5891b1e70732321a598/src/edeposit/amqp/antivirus/__init__.py#L24-L58 | def reactToAMQPMessage(message, send_back):
"""
React to given (AMQP) message. `message` is expected to be
:py:func:`collections.namedtuple` structure from :mod:`.structures` filled
with all necessary data.
Args:
message (object): One of the request objects defined in
... | [
"def",
"reactToAMQPMessage",
"(",
"message",
",",
"send_back",
")",
":",
"if",
"_instanceof",
"(",
"message",
",",
"structures",
".",
"ScanFile",
")",
":",
"result",
"=",
"antivirus",
".",
"save_and_scan",
"(",
"message",
".",
"filename",
",",
"message",
"."... | React to given (AMQP) message. `message` is expected to be
:py:func:`collections.namedtuple` structure from :mod:`.structures` filled
with all necessary data.
Args:
message (object): One of the request objects defined in
:mod:`.structures`.
send_back (fn reference)... | [
"React",
"to",
"given",
"(",
"AMQP",
")",
"message",
".",
"message",
"is",
"expected",
"to",
"be",
":",
"py",
":",
"func",
":",
"collections",
".",
"namedtuple",
"structure",
"from",
":",
"mod",
":",
".",
"structures",
"filled",
"with",
"all",
"necessary... | python | train |
pandeylab/pythomics | pythomics/proteomics/structures.py | https://github.com/pandeylab/pythomics/blob/ab0a5651a2e02a25def4d277b35fa09d1631bfcb/pythomics/proteomics/structures.py#L84-L107 | def addModification(self, aa,position, modMass, modType):
"""
!!!!MODIFICATION POSITION IS 0 BASED!!!!!!
Modifications are stored internally as a tuple with this format:
(amino acid modified, index in peptide of amino acid, modification type, modification mass)
ie (M, 7, Oxidatio... | [
"def",
"addModification",
"(",
"self",
",",
"aa",
",",
"position",
",",
"modMass",
",",
"modType",
")",
":",
"#clean up xtandem",
"if",
"not",
"modType",
":",
"#try to figure out what it is",
"tmass",
"=",
"abs",
"(",
"modMass",
")",
"smass",
"=",
"str",
"("... | !!!!MODIFICATION POSITION IS 0 BASED!!!!!!
Modifications are stored internally as a tuple with this format:
(amino acid modified, index in peptide of amino acid, modification type, modification mass)
ie (M, 7, Oxidation, 15.9...)
such as: M35(o) for an oxidized methionine at residue 35 | [
"!!!!MODIFICATION",
"POSITION",
"IS",
"0",
"BASED!!!!!!",
"Modifications",
"are",
"stored",
"internally",
"as",
"a",
"tuple",
"with",
"this",
"format",
":",
"(",
"amino",
"acid",
"modified",
"index",
"in",
"peptide",
"of",
"amino",
"acid",
"modification",
"type"... | python | train |
opencobra/cobrapy | cobra/flux_analysis/variability.py | https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/flux_analysis/variability.py#L304-L335 | def find_essential_reactions(model, threshold=None, processes=None):
"""Return a set of essential reactions.
A reaction is considered essential if restricting its flux to zero
causes the objective, e.g., the growth rate, to also be zero, below the
threshold, or infeasible.
Parameters
--------... | [
"def",
"find_essential_reactions",
"(",
"model",
",",
"threshold",
"=",
"None",
",",
"processes",
"=",
"None",
")",
":",
"if",
"threshold",
"is",
"None",
":",
"threshold",
"=",
"model",
".",
"slim_optimize",
"(",
"error_value",
"=",
"None",
")",
"*",
"1E-0... | Return a set of essential reactions.
A reaction is considered essential if restricting its flux to zero
causes the objective, e.g., the growth rate, to also be zero, below the
threshold, or infeasible.
Parameters
----------
model : cobra.Model
The model to find the essential reactions... | [
"Return",
"a",
"set",
"of",
"essential",
"reactions",
"."
] | python | valid |
maxalbert/tohu | tohu/v6/utils.py | https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v6/utils.py#L113-L128 | def make_dummy_tuples(chars='abcde'):
"""
Helper function to create a list of namedtuples which are useful
for testing and debugging (especially of custom generators).
Example
-------
>>> make_dummy_tuples(chars='abcd')
[Quux(x='AA', y='aa'),
Quux(x='BB', y='bb'),
Quux(x='CC', y='... | [
"def",
"make_dummy_tuples",
"(",
"chars",
"=",
"'abcde'",
")",
":",
"Quux",
"=",
"namedtuple",
"(",
"'Quux'",
",",
"[",
"'x'",
",",
"'y'",
"]",
")",
"some_tuples",
"=",
"[",
"Quux",
"(",
"(",
"c",
"*",
"2",
")",
".",
"upper",
"(",
")",
",",
"c",
... | Helper function to create a list of namedtuples which are useful
for testing and debugging (especially of custom generators).
Example
-------
>>> make_dummy_tuples(chars='abcd')
[Quux(x='AA', y='aa'),
Quux(x='BB', y='bb'),
Quux(x='CC', y='cc'),
Quux(x='DD', y='dd')] | [
"Helper",
"function",
"to",
"create",
"a",
"list",
"of",
"namedtuples",
"which",
"are",
"useful",
"for",
"testing",
"and",
"debugging",
"(",
"especially",
"of",
"custom",
"generators",
")",
"."
] | python | train |
Sheeprider/BitBucket-api | bitbucket/ssh.py | https://github.com/Sheeprider/BitBucket-api/blob/be45515d506d87f14807a676f3c2f20d79674b75/bitbucket/ssh.py#L24-L28 | def get(self, key_id=None):
""" Get one of the ssh keys associated with your account.
"""
url = self.bitbucket.url('GET_SSH_KEY', key_id=key_id)
return self.bitbucket.dispatch('GET', url, auth=self.bitbucket.auth) | [
"def",
"get",
"(",
"self",
",",
"key_id",
"=",
"None",
")",
":",
"url",
"=",
"self",
".",
"bitbucket",
".",
"url",
"(",
"'GET_SSH_KEY'",
",",
"key_id",
"=",
"key_id",
")",
"return",
"self",
".",
"bitbucket",
".",
"dispatch",
"(",
"'GET'",
",",
"url",... | Get one of the ssh keys associated with your account. | [
"Get",
"one",
"of",
"the",
"ssh",
"keys",
"associated",
"with",
"your",
"account",
"."
] | python | train |
marcelm/xopen | src/xopen/__init__.py | https://github.com/marcelm/xopen/blob/891ca71fb9b8b2b599de74caa4ed92206e5719f2/src/xopen/__init__.py#L290-L343 | def xopen(filename, mode='r', compresslevel=6, threads=None):
"""
A replacement for the "open" function that can also open files that have
been compressed with gzip, bzip2 or xz. If the filename is '-', standard
output (mode 'w') or input (mode 'r') is returned.
The file type is determined based on... | [
"def",
"xopen",
"(",
"filename",
",",
"mode",
"=",
"'r'",
",",
"compresslevel",
"=",
"6",
",",
"threads",
"=",
"None",
")",
":",
"if",
"mode",
"in",
"(",
"'r'",
",",
"'w'",
",",
"'a'",
")",
":",
"mode",
"+=",
"'t'",
"if",
"mode",
"not",
"in",
"... | A replacement for the "open" function that can also open files that have
been compressed with gzip, bzip2 or xz. If the filename is '-', standard
output (mode 'w') or input (mode 'r') is returned.
The file type is determined based on the filename: .gz is gzip, .bz2 is bzip2 and .xz is
xz/lzma.
Whe... | [
"A",
"replacement",
"for",
"the",
"open",
"function",
"that",
"can",
"also",
"open",
"files",
"that",
"have",
"been",
"compressed",
"with",
"gzip",
"bzip2",
"or",
"xz",
".",
"If",
"the",
"filename",
"is",
"-",
"standard",
"output",
"(",
"mode",
"w",
")",... | python | train |
alorence/django-modern-rpc | modernrpc/core.py | https://github.com/alorence/django-modern-rpc/blob/6dc42857d35764b24e2c09334f4b578629a75f9e/modernrpc/core.py#L162-L178 | def html_doc(self):
"""Methods docstring, as HTML"""
if not self.raw_docstring:
result = ''
elif settings.MODERNRPC_DOC_FORMAT.lower() in ('rst', 'restructred', 'restructuredtext'):
from docutils.core import publish_parts
result = publish_parts(self.raw_docst... | [
"def",
"html_doc",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"raw_docstring",
":",
"result",
"=",
"''",
"elif",
"settings",
".",
"MODERNRPC_DOC_FORMAT",
".",
"lower",
"(",
")",
"in",
"(",
"'rst'",
",",
"'restructred'",
",",
"'restructuredtext'",
")"... | Methods docstring, as HTML | [
"Methods",
"docstring",
"as",
"HTML"
] | python | train |
apple/turicreate | src/unity/python/turicreate/toolkits/_mxnet/_mxnet_utils.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_mxnet/_mxnet_utils.py#L100-L108 | def get_gpus_in_use(max_devices=None):
"""
Like get_num_gpus_in_use, but returns a list of dictionaries with just
queried GPU information.
"""
from turicreate.util import _get_cuda_gpus
gpu_indices = get_gpu_ids_in_use(max_devices=max_devices)
gpus = _get_cuda_gpus()
return [gpus[index] ... | [
"def",
"get_gpus_in_use",
"(",
"max_devices",
"=",
"None",
")",
":",
"from",
"turicreate",
".",
"util",
"import",
"_get_cuda_gpus",
"gpu_indices",
"=",
"get_gpu_ids_in_use",
"(",
"max_devices",
"=",
"max_devices",
")",
"gpus",
"=",
"_get_cuda_gpus",
"(",
")",
"r... | Like get_num_gpus_in_use, but returns a list of dictionaries with just
queried GPU information. | [
"Like",
"get_num_gpus_in_use",
"but",
"returns",
"a",
"list",
"of",
"dictionaries",
"with",
"just",
"queried",
"GPU",
"information",
"."
] | python | train |
etal/biofrills | biofrills/alnutils.py | https://github.com/etal/biofrills/blob/36684bb6c7632f96215e8b2b4ebc86640f331bcd/biofrills/alnutils.py#L95-L100 | def col_frequencies(col, weights=None, gap_chars='-.'):
"""Frequencies of each residue type (totaling 1.0) in a single column."""
counts = col_counts(col, weights, gap_chars)
# Reduce to frequencies
scale = 1.0 / sum(counts.values())
return dict((aa, cnt * scale) for aa, cnt in counts.iteritems()) | [
"def",
"col_frequencies",
"(",
"col",
",",
"weights",
"=",
"None",
",",
"gap_chars",
"=",
"'-.'",
")",
":",
"counts",
"=",
"col_counts",
"(",
"col",
",",
"weights",
",",
"gap_chars",
")",
"# Reduce to frequencies",
"scale",
"=",
"1.0",
"/",
"sum",
"(",
"... | Frequencies of each residue type (totaling 1.0) in a single column. | [
"Frequencies",
"of",
"each",
"residue",
"type",
"(",
"totaling",
"1",
".",
"0",
")",
"in",
"a",
"single",
"column",
"."
] | python | train |
sijis/sumologic-python | src/sumologic/collectors.py | https://github.com/sijis/sumologic-python/blob/b50200907837f0d452d14ead5e647b8e24e2e9e5/src/sumologic/collectors.py#L51-L64 | def find(self, name):
"""Returns a dict of collector's details if found.
Args:
name (str): name of collector searching for
"""
collectors = self.get_collectors()
for collector in collectors:
if name.lower() == collector['name'].lower():
s... | [
"def",
"find",
"(",
"self",
",",
"name",
")",
":",
"collectors",
"=",
"self",
".",
"get_collectors",
"(",
")",
"for",
"collector",
"in",
"collectors",
":",
"if",
"name",
".",
"lower",
"(",
")",
"==",
"collector",
"[",
"'name'",
"]",
".",
"lower",
"("... | Returns a dict of collector's details if found.
Args:
name (str): name of collector searching for | [
"Returns",
"a",
"dict",
"of",
"collector",
"s",
"details",
"if",
"found",
"."
] | python | train |
geophysics-ubonn/reda | lib/reda/utils/norrec.py | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/utils/norrec.py#L12-L45 | def average_repetitions(df, keys_mean):
"""average duplicate measurements. This requires that IDs and norrec labels
were assigned using the *assign_norrec_to_df* function.
Parameters
----------
df
DataFrame
keys_mean: list
list of keys to average. For all other keys the first en... | [
"def",
"average_repetitions",
"(",
"df",
",",
"keys_mean",
")",
":",
"if",
"'norrec'",
"not",
"in",
"df",
".",
"columns",
":",
"raise",
"Exception",
"(",
"'The \"norrec\" column is required for this function to work!'",
")",
"# Get column order to restore later",
"cols",
... | average duplicate measurements. This requires that IDs and norrec labels
were assigned using the *assign_norrec_to_df* function.
Parameters
----------
df
DataFrame
keys_mean: list
list of keys to average. For all other keys the first entry will be
used. | [
"average",
"duplicate",
"measurements",
".",
"This",
"requires",
"that",
"IDs",
"and",
"norrec",
"labels",
"were",
"assigned",
"using",
"the",
"*",
"assign_norrec_to_df",
"*",
"function",
"."
] | python | train |
evandempsey/fp-growth | pyfpgrowth/pyfpgrowth.py | https://github.com/evandempsey/fp-growth/blob/6bf4503024e86c5bbea8a05560594f2f7f061c15/pyfpgrowth/pyfpgrowth.py#L39-L45 | def add_child(self, value):
"""
Add a node as a child node.
"""
child = FPNode(value, 1, self)
self.children.append(child)
return child | [
"def",
"add_child",
"(",
"self",
",",
"value",
")",
":",
"child",
"=",
"FPNode",
"(",
"value",
",",
"1",
",",
"self",
")",
"self",
".",
"children",
".",
"append",
"(",
"child",
")",
"return",
"child"
] | Add a node as a child node. | [
"Add",
"a",
"node",
"as",
"a",
"child",
"node",
"."
] | python | train |
ARMmbed/mbed-cloud-sdk-python | src/mbed_cloud/_backends/device_directory/apis/default_api.py | https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/_backends/device_directory/apis/default_api.py#L535-L559 | def device_log_list(self, **kwargs): # noqa: E501
"""DEPRECATED: List all device events. # noqa: E501
DEPRECATED: List all device events. Use `/v3/device-events/` instead. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, plea... | [
"def",
"device_log_list",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'asynchronous'",
")",
":",
"return",
"self",
".",
"device_log_list_with_htt... | DEPRECATED: List all device events. # noqa: E501
DEPRECATED: List all device events. Use `/v3/device-events/` instead. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass asynchronous=True
>>> thread = api.device_log_... | [
"DEPRECATED",
":",
"List",
"all",
"device",
"events",
".",
"#",
"noqa",
":",
"E501"
] | python | train |
saltstack/salt | salt/client/mixins.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/mixins.py#L279-L444 | def low(self, fun, low, print_event=True, full_return=False):
'''
Execute a function from low data
Low data includes:
required:
- fun: the name of the function to run
optional:
- arg: a list of args to pass to fun
- kwarg: k... | [
"def",
"low",
"(",
"self",
",",
"fun",
",",
"low",
",",
"print_event",
"=",
"True",
",",
"full_return",
"=",
"False",
")",
":",
"# fire the mminion loading (if not already done) here",
"# this is not to clutter the output with the module loading",
"# if we have a high debug l... | Execute a function from low data
Low data includes:
required:
- fun: the name of the function to run
optional:
- arg: a list of args to pass to fun
- kwarg: kwargs for fun
- __user__: user who is running the command
... | [
"Execute",
"a",
"function",
"from",
"low",
"data",
"Low",
"data",
"includes",
":",
"required",
":",
"-",
"fun",
":",
"the",
"name",
"of",
"the",
"function",
"to",
"run",
"optional",
":",
"-",
"arg",
":",
"a",
"list",
"of",
"args",
"to",
"pass",
"to",... | python | train |
mabuchilab/QNET | src/qnet/convert/to_sympy_matrix.py | https://github.com/mabuchilab/QNET/blob/cc20d26dad78691d34c67173e5cd67dcac94208a/src/qnet/convert/to_sympy_matrix.py#L27-L33 | def SympyCreate(n):
"""Creation operator for a Hilbert space of dimension `n`, as an instance
of `sympy.Matrix`"""
a = sympy.zeros(n)
for i in range(1, n):
a += sympy.sqrt(i) * basis_state(i, n) * basis_state(i-1, n).H
return a | [
"def",
"SympyCreate",
"(",
"n",
")",
":",
"a",
"=",
"sympy",
".",
"zeros",
"(",
"n",
")",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"n",
")",
":",
"a",
"+=",
"sympy",
".",
"sqrt",
"(",
"i",
")",
"*",
"basis_state",
"(",
"i",
",",
"n",
")",
... | Creation operator for a Hilbert space of dimension `n`, as an instance
of `sympy.Matrix` | [
"Creation",
"operator",
"for",
"a",
"Hilbert",
"space",
"of",
"dimension",
"n",
"as",
"an",
"instance",
"of",
"sympy",
".",
"Matrix"
] | python | train |
tensorpack/tensorpack | examples/FasterRCNN/model_frcnn.py | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_frcnn.py#L128-L172 | def fastrcnn_losses(labels, label_logits, fg_boxes, fg_box_logits):
"""
Args:
labels: n,
label_logits: nxC
fg_boxes: nfgx4, encoded
fg_box_logits: nfgxCx4 or nfgx1x4 if class agnostic
Returns:
label_loss, box_loss
"""
label_loss = tf.nn.sparse_softmax_cross_e... | [
"def",
"fastrcnn_losses",
"(",
"labels",
",",
"label_logits",
",",
"fg_boxes",
",",
"fg_box_logits",
")",
":",
"label_loss",
"=",
"tf",
".",
"nn",
".",
"sparse_softmax_cross_entropy_with_logits",
"(",
"labels",
"=",
"labels",
",",
"logits",
"=",
"label_logits",
... | Args:
labels: n,
label_logits: nxC
fg_boxes: nfgx4, encoded
fg_box_logits: nfgxCx4 or nfgx1x4 if class agnostic
Returns:
label_loss, box_loss | [
"Args",
":",
"labels",
":",
"n",
"label_logits",
":",
"nxC",
"fg_boxes",
":",
"nfgx4",
"encoded",
"fg_box_logits",
":",
"nfgxCx4",
"or",
"nfgx1x4",
"if",
"class",
"agnostic"
] | python | train |
apache/spark | python/pyspark/sql/udf.py | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/udf.py#L232-L341 | def register(self, name, f, returnType=None):
"""Register a Python function (including lambda function) or a user-defined function
as a SQL function.
:param name: name of the user-defined function in SQL statements.
:param f: a Python function, or a user-defined function. The user-defin... | [
"def",
"register",
"(",
"self",
",",
"name",
",",
"f",
",",
"returnType",
"=",
"None",
")",
":",
"# This is to check whether the input function is from a user-defined function or",
"# Python function.",
"if",
"hasattr",
"(",
"f",
",",
"'asNondeterministic'",
")",
":",
... | Register a Python function (including lambda function) or a user-defined function
as a SQL function.
:param name: name of the user-defined function in SQL statements.
:param f: a Python function, or a user-defined function. The user-defined function can
be either row-at-a-time or ve... | [
"Register",
"a",
"Python",
"function",
"(",
"including",
"lambda",
"function",
")",
"or",
"a",
"user",
"-",
"defined",
"function",
"as",
"a",
"SQL",
"function",
"."
] | python | train |
hydpy-dev/hydpy | hydpy/models/lland/lland_control.py | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/models/lland/lland_control.py#L661-L679 | def trim(self, lower=None, upper=None):
"""Trim upper values in accordance with :math:`EQI1 \\leq EQB`.
>>> from hydpy.models.lland import *
>>> parameterstep('1d')
>>> eqi1.value = 2.0
>>> eqb(1.0)
>>> eqb
eqb(2.0)
>>> eqb(2.0)
>>> eqb
eq... | [
"def",
"trim",
"(",
"self",
",",
"lower",
"=",
"None",
",",
"upper",
"=",
"None",
")",
":",
"if",
"lower",
"is",
"None",
":",
"lower",
"=",
"getattr",
"(",
"self",
".",
"subpars",
".",
"eqi1",
",",
"'value'",
",",
"None",
")",
"super",
"(",
")",
... | Trim upper values in accordance with :math:`EQI1 \\leq EQB`.
>>> from hydpy.models.lland import *
>>> parameterstep('1d')
>>> eqi1.value = 2.0
>>> eqb(1.0)
>>> eqb
eqb(2.0)
>>> eqb(2.0)
>>> eqb
eqb(2.0)
>>> eqb(3.0)
>>> eqb
... | [
"Trim",
"upper",
"values",
"in",
"accordance",
"with",
":",
"math",
":",
"EQI1",
"\\\\",
"leq",
"EQB",
"."
] | python | train |
aewallin/allantools | examples/gradev-demo.py | https://github.com/aewallin/allantools/blob/b5c695a5af4379fcea4d4ce93a066cb902e7ee0a/examples/gradev-demo.py#L34-L52 | def example2():
"""
Compute the GRADEV of a nonstationary white phase noise.
"""
N=1000 # number of samples
f = 1 # data samples per second
s=1+5/N*np.arange(0,N)
y=s*np.random.randn(1,N)[0,:]
x = [xx for xx in np.linspace(1,len(y),len(y))]
x_ax, y_ax, (err_l, err_h) , ns = allan.gra... | [
"def",
"example2",
"(",
")",
":",
"N",
"=",
"1000",
"# number of samples",
"f",
"=",
"1",
"# data samples per second",
"s",
"=",
"1",
"+",
"5",
"/",
"N",
"*",
"np",
".",
"arange",
"(",
"0",
",",
"N",
")",
"y",
"=",
"s",
"*",
"np",
".",
"random",
... | Compute the GRADEV of a nonstationary white phase noise. | [
"Compute",
"the",
"GRADEV",
"of",
"a",
"nonstationary",
"white",
"phase",
"noise",
"."
] | python | train |
limix/limix-core | limix_core/util/preprocess.py | https://github.com/limix/limix-core/blob/5c590b4d351409f83ca320844b4897ce92203814/limix_core/util/preprocess.py#L5-L20 | def standardize(Y,in_place=False):
"""
standardize Y in a way that is robust to missing values
in_place: create a copy or carry out inplace opreations?
"""
if in_place:
YY = Y
else:
YY = Y.copy()
for i in range(YY.shape[1]):
Iok = ~SP.isnan(YY[:,i])
Ym = YY[Io... | [
"def",
"standardize",
"(",
"Y",
",",
"in_place",
"=",
"False",
")",
":",
"if",
"in_place",
":",
"YY",
"=",
"Y",
"else",
":",
"YY",
"=",
"Y",
".",
"copy",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"YY",
".",
"shape",
"[",
"1",
"]",
")",
":",
... | standardize Y in a way that is robust to missing values
in_place: create a copy or carry out inplace opreations? | [
"standardize",
"Y",
"in",
"a",
"way",
"that",
"is",
"robust",
"to",
"missing",
"values",
"in_place",
":",
"create",
"a",
"copy",
"or",
"carry",
"out",
"inplace",
"opreations?"
] | python | train |
saltstack/salt | salt/states/mount.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/mount.py#L731-L827 | def swap(name, persist=True, config='/etc/fstab'):
'''
Activates a swap device
.. code-block:: yaml
/root/swapfile:
mount.swap
.. note::
``swap`` does not currently support LABEL
'''
ret = {'name': name,
'changes': {},
'result': True,
... | [
"def",
"swap",
"(",
"name",
",",
"persist",
"=",
"True",
",",
"config",
"=",
"'/etc/fstab'",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''",
"}",
"on_",
... | Activates a swap device
.. code-block:: yaml
/root/swapfile:
mount.swap
.. note::
``swap`` does not currently support LABEL | [
"Activates",
"a",
"swap",
"device"
] | python | train |
OpenHumans/open-humans-api | ohapi/projects.py | https://github.com/OpenHumans/open-humans-api/blob/ca2a28cf5d55cfdae13dd222ba58c25565bdb86e/ohapi/projects.py#L94-L137 | def download_member_shared(cls, member_data, target_member_dir, source=None,
max_size=MAX_SIZE_DEFAULT, id_filename=False):
"""
Download files to sync a local dir to match OH member shared data.
Files are downloaded to match their "basename" on Open Humans.
... | [
"def",
"download_member_shared",
"(",
"cls",
",",
"member_data",
",",
"target_member_dir",
",",
"source",
"=",
"None",
",",
"max_size",
"=",
"MAX_SIZE_DEFAULT",
",",
"id_filename",
"=",
"False",
")",
":",
"logging",
".",
"debug",
"(",
"'Download member shared data... | Download files to sync a local dir to match OH member shared data.
Files are downloaded to match their "basename" on Open Humans.
If there are multiple files with the same name, the most recent is
downloaded.
:param member_data: This field is data related to member in a project.
... | [
"Download",
"files",
"to",
"sync",
"a",
"local",
"dir",
"to",
"match",
"OH",
"member",
"shared",
"data",
"."
] | python | train |
quodlibet/mutagen | mutagen/id3/_tags.py | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/id3/_tags.py#L286-L326 | def _add(self, frame, strict):
"""Add a frame.
Args:
frame (Frame): the frame to add
strict (bool): if this should raise in case it can't be added
and frames shouldn't be merged.
"""
if not isinstance(frame, Frame):
raise TypeError("%... | [
"def",
"_add",
"(",
"self",
",",
"frame",
",",
"strict",
")",
":",
"if",
"not",
"isinstance",
"(",
"frame",
",",
"Frame",
")",
":",
"raise",
"TypeError",
"(",
"\"%r not a Frame instance\"",
"%",
"frame",
")",
"orig_frame",
"=",
"frame",
"frame",
"=",
"fr... | Add a frame.
Args:
frame (Frame): the frame to add
strict (bool): if this should raise in case it can't be added
and frames shouldn't be merged. | [
"Add",
"a",
"frame",
"."
] | python | train |
ranaroussi/qtpylib | qtpylib/instrument.py | https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/instrument.py#L536-L560 | def get_margin_requirement(self):
""" Get margin requirements for intrument (futures only)
:Retruns:
margin : dict
margin requirements for instrument
(all values are ``None`` for non-futures instruments)
"""
contract = self.get_contract()
... | [
"def",
"get_margin_requirement",
"(",
"self",
")",
":",
"contract",
"=",
"self",
".",
"get_contract",
"(",
")",
"if",
"contract",
".",
"m_secType",
"==",
"\"FUT\"",
":",
"return",
"futures",
".",
"get_ib_futures",
"(",
"contract",
".",
"m_symbol",
",",
"cont... | Get margin requirements for intrument (futures only)
:Retruns:
margin : dict
margin requirements for instrument
(all values are ``None`` for non-futures instruments) | [
"Get",
"margin",
"requirements",
"for",
"intrument",
"(",
"futures",
"only",
")"
] | python | train |
splunk/splunk-sdk-python | splunklib/client.py | https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L2920-L2938 | def create(self, query, **kwargs):
""" Creates a search using a search query and any additional parameters
you provide.
:param query: The search query.
:type query: ``string``
:param kwargs: Additiona parameters (optional). For a list of available
parameters, see `Se... | [
"def",
"create",
"(",
"self",
",",
"query",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"kwargs",
".",
"get",
"(",
"\"exec_mode\"",
",",
"None",
")",
"==",
"\"oneshot\"",
":",
"raise",
"TypeError",
"(",
"\"Cannot specify exec_mode=oneshot; use the oneshot method in... | Creates a search using a search query and any additional parameters
you provide.
:param query: The search query.
:type query: ``string``
:param kwargs: Additiona parameters (optional). For a list of available
parameters, see `Search job parameters
<http://dev.spl... | [
"Creates",
"a",
"search",
"using",
"a",
"search",
"query",
"and",
"any",
"additional",
"parameters",
"you",
"provide",
"."
] | python | train |
adamzap/landslide | landslide/rst.py | https://github.com/adamzap/landslide/blob/59b0403d7a7cca4b8ff6ba7fb76efb9748b3f832/landslide/rst.py#L82-L100 | def html_body(input_string, source_path=None, destination_path=None,
input_encoding='unicode', doctitle=1, initial_header_level=1):
"""
Given an input string, returns an HTML fragment as a string.
The return value is the contents of the <body> element.
Parameters (see `html_parts()` for ... | [
"def",
"html_body",
"(",
"input_string",
",",
"source_path",
"=",
"None",
",",
"destination_path",
"=",
"None",
",",
"input_encoding",
"=",
"'unicode'",
",",
"doctitle",
"=",
"1",
",",
"initial_header_level",
"=",
"1",
")",
":",
"parts",
"=",
"html_parts",
"... | Given an input string, returns an HTML fragment as a string.
The return value is the contents of the <body> element.
Parameters (see `html_parts()` for the remainder):
- `output_encoding`: The desired encoding of the output. If a Unicode
string is desired, use the default value of "unicode" . | [
"Given",
"an",
"input",
"string",
"returns",
"an",
"HTML",
"fragment",
"as",
"a",
"string",
"."
] | python | train |
ianmiell/shutit | shutit_pexpect.py | https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_pexpect.py#L1907-L1923 | def whoarewe(self,
note=None,
loglevel=logging.DEBUG):
"""Returns the current group.
@param note: See send()
@return: the first group found
@rtype: string
"""
shutit = self.shutit
shutit.handle_note(note)
res = self.send_and_get_output(' command id -n -g',
... | [
"def",
"whoarewe",
"(",
"self",
",",
"note",
"=",
"None",
",",
"loglevel",
"=",
"logging",
".",
"DEBUG",
")",
":",
"shutit",
"=",
"self",
".",
"shutit",
"shutit",
".",
"handle_note",
"(",
"note",
")",
"res",
"=",
"self",
".",
"send_and_get_output",
"("... | Returns the current group.
@param note: See send()
@return: the first group found
@rtype: string | [
"Returns",
"the",
"current",
"group",
"."
] | python | train |
MacHu-GWU/pymongo_mate-project | pymongo_mate/pkg/pandas_mate/csv_io.py | https://github.com/MacHu-GWU/pymongo_mate-project/blob/be53170c2db54cb705b9e548d32ef26c773ff7f3/pymongo_mate/pkg/pandas_mate/csv_io.py#L56-L113 | def index_row_dict_from_csv(path,
index_col=None,
iterator=False,
chunksize=None,
skiprows=None,
nrows=None,
use_ordered_dict=True,
... | [
"def",
"index_row_dict_from_csv",
"(",
"path",
",",
"index_col",
"=",
"None",
",",
"iterator",
"=",
"False",
",",
"chunksize",
"=",
"None",
",",
"skiprows",
"=",
"None",
",",
"nrows",
"=",
"None",
",",
"use_ordered_dict",
"=",
"True",
",",
"*",
"*",
"kwa... | Read the csv into a dictionary. The key is it's index, the value
is the dictionary form of the row.
:param path: csv file path.
:param index_col: None or str, the column that used as index.
:param iterator:
:param chunksize:
:param skiprows:
:param nrows:
:param use_ordered_dict:
:... | [
"Read",
"the",
"csv",
"into",
"a",
"dictionary",
".",
"The",
"key",
"is",
"it",
"s",
"index",
"the",
"value",
"is",
"the",
"dictionary",
"form",
"of",
"the",
"row",
"."
] | python | train |
graphistry/pygraphistry | graphistry/plotter.py | https://github.com/graphistry/pygraphistry/blob/3dfc50e60232c6f5fedd6e5fa9d3048b606944b8/graphistry/plotter.py#L68-L170 | def bind(self, source=None, destination=None, node=None,
edge_title=None, edge_label=None, edge_color=None, edge_weight=None,
point_title=None, point_label=None, point_color=None, point_size=None):
"""Relate data attributes to graph structure and visual representation.
To faci... | [
"def",
"bind",
"(",
"self",
",",
"source",
"=",
"None",
",",
"destination",
"=",
"None",
",",
"node",
"=",
"None",
",",
"edge_title",
"=",
"None",
",",
"edge_label",
"=",
"None",
",",
"edge_color",
"=",
"None",
",",
"edge_weight",
"=",
"None",
",",
"... | Relate data attributes to graph structure and visual representation.
To facilitate reuse and replayable notebooks, the binding call is chainable. Invocation does not effect the old binding: it instead returns a new Plotter instance with the new bindings added to the existing ones. Both the old and new bindings... | [
"Relate",
"data",
"attributes",
"to",
"graph",
"structure",
"and",
"visual",
"representation",
"."
] | python | train |
lrq3000/pyFileFixity | pyFileFixity/lib/brownanrs/rs.py | https://github.com/lrq3000/pyFileFixity/blob/fd5ef23bb13835faf1e3baa773619b86a1cc9bdf/pyFileFixity/lib/brownanrs/rs.py#L890-L918 | def _old_forney(self, omega, X, k=None):
'''Computes the error magnitudes (only works with errors or erasures under t = floor((n-k)/2), not with erasures above (n-k)//2)'''
# XXX Is floor division okay here? Should this be ceiling?
if not k: k = self.k
t = (self.n - k) // 2
Y = ... | [
"def",
"_old_forney",
"(",
"self",
",",
"omega",
",",
"X",
",",
"k",
"=",
"None",
")",
":",
"# XXX Is floor division okay here? Should this be ceiling?",
"if",
"not",
"k",
":",
"k",
"=",
"self",
".",
"k",
"t",
"=",
"(",
"self",
".",
"n",
"-",
"k",
")",... | Computes the error magnitudes (only works with errors or erasures under t = floor((n-k)/2), not with erasures above (n-k)//2) | [
"Computes",
"the",
"error",
"magnitudes",
"(",
"only",
"works",
"with",
"errors",
"or",
"erasures",
"under",
"t",
"=",
"floor",
"((",
"n",
"-",
"k",
")",
"/",
"2",
")",
"not",
"with",
"erasures",
"above",
"(",
"n",
"-",
"k",
")",
"//",
"2",
")"
] | python | train |
readbeyond/aeneas | aeneas/globalfunctions.py | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/globalfunctions.py#L1119-L1133 | def human_readable_number(number, suffix=""):
"""
Format the given number into a human-readable string.
Code adapted from http://stackoverflow.com/a/1094933
:param variant number: the number (int or float)
:param string suffix: the unit of the number
:rtype: string
"""
for unit in ["",... | [
"def",
"human_readable_number",
"(",
"number",
",",
"suffix",
"=",
"\"\"",
")",
":",
"for",
"unit",
"in",
"[",
"\"\"",
",",
"\"K\"",
",",
"\"M\"",
",",
"\"G\"",
",",
"\"T\"",
",",
"\"P\"",
",",
"\"E\"",
",",
"\"Z\"",
"]",
":",
"if",
"abs",
"(",
"nu... | Format the given number into a human-readable string.
Code adapted from http://stackoverflow.com/a/1094933
:param variant number: the number (int or float)
:param string suffix: the unit of the number
:rtype: string | [
"Format",
"the",
"given",
"number",
"into",
"a",
"human",
"-",
"readable",
"string",
"."
] | python | train |
acorg/dark-matter | dark/blast/alignments.py | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/blast/alignments.py#L96-L143 | def iter(self):
"""
Extract BLAST records and yield C{ReadAlignments} instances.
For each file except the first, check that the BLAST parameters are
compatible with those found (above, in __init__) in the first file.
@return: A generator that yields C{ReadAlignments} instances.... | [
"def",
"iter",
"(",
"self",
")",
":",
"# Note that self._reader is already initialized (in __init__) for",
"# the first input file. This is less clean than it could be, but it",
"# makes testing easier, since open() is then only called once for",
"# each input file.",
"count",
"=",
"0",
"r... | Extract BLAST records and yield C{ReadAlignments} instances.
For each file except the first, check that the BLAST parameters are
compatible with those found (above, in __init__) in the first file.
@return: A generator that yields C{ReadAlignments} instances. | [
"Extract",
"BLAST",
"records",
"and",
"yield",
"C",
"{",
"ReadAlignments",
"}",
"instances",
"."
] | python | train |
python-astrodynamics/spacetrack | spacetrack/aio.py | https://github.com/python-astrodynamics/spacetrack/blob/18f63b7de989a31b983d140a11418e01bd6fd398/spacetrack/aio.py#L242-L256 | async def _download_predicate_data(self, class_, controller):
"""Get raw predicate information for given request class, and cache for
subsequent calls.
"""
await self.authenticate()
url = ('{0}{1}/modeldef/class/{2}'
.format(self.base_url, controller, class_))
... | [
"async",
"def",
"_download_predicate_data",
"(",
"self",
",",
"class_",
",",
"controller",
")",
":",
"await",
"self",
".",
"authenticate",
"(",
")",
"url",
"=",
"(",
"'{0}{1}/modeldef/class/{2}'",
".",
"format",
"(",
"self",
".",
"base_url",
",",
"controller",... | Get raw predicate information for given request class, and cache for
subsequent calls. | [
"Get",
"raw",
"predicate",
"information",
"for",
"given",
"request",
"class",
"and",
"cache",
"for",
"subsequent",
"calls",
"."
] | python | train |
Rockhopper-Technologies/enlighten | enlighten/_manager.py | https://github.com/Rockhopper-Technologies/enlighten/blob/857855f940e6c1bb84d0be849b999a18fff5bf5a/enlighten/_manager.py#L169-L209 | def _resize_handler(self, *args, **kwarg): # pylint: disable=unused-argument
"""
Called when a window resize signal is detected
Resets the scroll window
"""
# Make sure only one resize handler is running
try:
assert self.resize_lock
except Assertion... | [
"def",
"_resize_handler",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwarg",
")",
":",
"# pylint: disable=unused-argument",
"# Make sure only one resize handler is running",
"try",
":",
"assert",
"self",
".",
"resize_lock",
"except",
"AssertionError",
":",
"self",... | Called when a window resize signal is detected
Resets the scroll window | [
"Called",
"when",
"a",
"window",
"resize",
"signal",
"is",
"detected"
] | python | train |
abourget/gevent-socketio | socketio/namespace.py | https://github.com/abourget/gevent-socketio/blob/1cdb1594a315326987a17ce0924ea448a82fab01/socketio/namespace.py#L227-L240 | def call_method_with_acl(self, method_name, packet, *args):
"""You should always use this function to call the methods,
as it checks if the user is allowed according to the ACLs.
If you override :meth:`process_packet` or
:meth:`process_event`, you should definitely want to use this
... | [
"def",
"call_method_with_acl",
"(",
"self",
",",
"method_name",
",",
"packet",
",",
"*",
"args",
")",
":",
"if",
"not",
"self",
".",
"is_method_allowed",
"(",
"method_name",
")",
":",
"self",
".",
"error",
"(",
"'method_access_denied'",
",",
"'You do not have ... | You should always use this function to call the methods,
as it checks if the user is allowed according to the ACLs.
If you override :meth:`process_packet` or
:meth:`process_event`, you should definitely want to use this
instead of ``getattr(self, 'my_method')()`` | [
"You",
"should",
"always",
"use",
"this",
"function",
"to",
"call",
"the",
"methods",
"as",
"it",
"checks",
"if",
"the",
"user",
"is",
"allowed",
"according",
"to",
"the",
"ACLs",
"."
] | python | valid |
d0c-s4vage/pfp | pfp/interp.py | https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L1301-L1336 | def _handle_struct_ref(self, node, scope, ctxt, stream):
"""TODO: Docstring for _handle_struct_ref.
:node: TODO
:scope: TODO
:ctxt: TODO
:stream: TODO
:returns: TODO
"""
self._dlog("handling struct ref")
# name
# field
struct = s... | [
"def",
"_handle_struct_ref",
"(",
"self",
",",
"node",
",",
"scope",
",",
"ctxt",
",",
"stream",
")",
":",
"self",
".",
"_dlog",
"(",
"\"handling struct ref\"",
")",
"# name",
"# field",
"struct",
"=",
"self",
".",
"_handle_node",
"(",
"node",
".",
"name",... | TODO: Docstring for _handle_struct_ref.
:node: TODO
:scope: TODO
:ctxt: TODO
:stream: TODO
:returns: TODO | [
"TODO",
":",
"Docstring",
"for",
"_handle_struct_ref",
"."
] | python | train |
cmap/cmapPy | cmapPy/pandasGEXpress/concat.py | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/concat.py#L106-L155 | def concat_main(args):
""" Separate method from main() in order to make testing easier and to
enable command-line access. """
# Get files directly
if args.input_filepaths is not None:
files = args.input_filepaths
# Or find them
else:
files = get_file_list(args.file_wildcard)
... | [
"def",
"concat_main",
"(",
"args",
")",
":",
"# Get files directly",
"if",
"args",
".",
"input_filepaths",
"is",
"not",
"None",
":",
"files",
"=",
"args",
".",
"input_filepaths",
"# Or find them",
"else",
":",
"files",
"=",
"get_file_list",
"(",
"args",
".",
... | Separate method from main() in order to make testing easier and to
enable command-line access. | [
"Separate",
"method",
"from",
"main",
"()",
"in",
"order",
"to",
"make",
"testing",
"easier",
"and",
"to",
"enable",
"command",
"-",
"line",
"access",
"."
] | python | train |
monarch-initiative/dipper | dipper/models/Pathway.py | https://github.com/monarch-initiative/dipper/blob/24cc80db355bbe15776edc5c7b41e0886959ba41/dipper/models/Pathway.py#L73-L85 | def addComponentToPathway(self, component_id, pathway_id):
"""
This can be used directly when the component is directly involved in
the pathway. If a transforming event is performed on the component
first, then the addGeneToPathway should be used instead.
:param pathway_id:
... | [
"def",
"addComponentToPathway",
"(",
"self",
",",
"component_id",
",",
"pathway_id",
")",
":",
"self",
".",
"graph",
".",
"addTriple",
"(",
"component_id",
",",
"self",
".",
"globaltt",
"[",
"'involved in'",
"]",
",",
"pathway_id",
")",
"return"
] | This can be used directly when the component is directly involved in
the pathway. If a transforming event is performed on the component
first, then the addGeneToPathway should be used instead.
:param pathway_id:
:param component_id:
:return: | [
"This",
"can",
"be",
"used",
"directly",
"when",
"the",
"component",
"is",
"directly",
"involved",
"in",
"the",
"pathway",
".",
"If",
"a",
"transforming",
"event",
"is",
"performed",
"on",
"the",
"component",
"first",
"then",
"the",
"addGeneToPathway",
"should... | python | train |
Julian/jsonschema | jsonschema/_utils.py | https://github.com/Julian/jsonschema/blob/a72332004cdc3ba456de7918bc32059822b2f69a/jsonschema/_utils.py#L122-L139 | def types_msg(instance, types):
"""
Create an error message for a failure to match the given types.
If the ``instance`` is an object and contains a ``name`` property, it will
be considered to be a description of that object and used as its type.
Otherwise the message is simply the reprs of the giv... | [
"def",
"types_msg",
"(",
"instance",
",",
"types",
")",
":",
"reprs",
"=",
"[",
"]",
"for",
"type",
"in",
"types",
":",
"try",
":",
"reprs",
".",
"append",
"(",
"repr",
"(",
"type",
"[",
"\"name\"",
"]",
")",
")",
"except",
"Exception",
":",
"reprs... | Create an error message for a failure to match the given types.
If the ``instance`` is an object and contains a ``name`` property, it will
be considered to be a description of that object and used as its type.
Otherwise the message is simply the reprs of the given ``types``. | [
"Create",
"an",
"error",
"message",
"for",
"a",
"failure",
"to",
"match",
"the",
"given",
"types",
"."
] | python | train |
dropbox/stone | stone/frontend/ir_generator.py | https://github.com/dropbox/stone/blob/2e95cbcd1c48e05cca68c919fd8d24adec6b0f58/stone/frontend/ir_generator.py#L916-L955 | def _create_struct_field(self, env, stone_field):
"""
This function resolves symbols to objects that we've instantiated in
the current environment. For example, a field with data type named
"String" is pointed to a String() object.
The caller needs to ensure that this stone_fiel... | [
"def",
"_create_struct_field",
"(",
"self",
",",
"env",
",",
"stone_field",
")",
":",
"if",
"isinstance",
"(",
"stone_field",
",",
"AstVoidField",
")",
":",
"raise",
"InvalidSpec",
"(",
"'Struct field %s cannot have a Void type.'",
"%",
"quote",
"(",
"stone_field",
... | This function resolves symbols to objects that we've instantiated in
the current environment. For example, a field with data type named
"String" is pointed to a String() object.
The caller needs to ensure that this stone_field is for a Struct and not
for a Union.
Returns:
... | [
"This",
"function",
"resolves",
"symbols",
"to",
"objects",
"that",
"we",
"ve",
"instantiated",
"in",
"the",
"current",
"environment",
".",
"For",
"example",
"a",
"field",
"with",
"data",
"type",
"named",
"String",
"is",
"pointed",
"to",
"a",
"String",
"()",... | python | train |
WalletGuild/desw | desw/server.py | https://github.com/WalletGuild/desw/blob/f966c612e675961d9dbd8268749e349ba10a47c2/desw/server.py#L336-L370 | def network_info(network):
"""
Get information about the transaction network indicated.
Returned info is: enabled/disabled, available hot wallet balance,
& the transaction fee.
---
description: Get information about the transaction network indicated.
operationId: getinfo
produces:
... | [
"def",
"network_info",
"(",
"network",
")",
":",
"lnet",
"=",
"network",
".",
"lower",
"(",
")",
"isenabled",
"=",
"lnet",
"in",
"ps",
"fee",
"=",
"float",
"(",
"CFG",
".",
"get",
"(",
"lnet",
",",
"'FEE'",
")",
")",
"roughAvail",
"=",
"str",
"(",
... | Get information about the transaction network indicated.
Returned info is: enabled/disabled, available hot wallet balance,
& the transaction fee.
---
description: Get information about the transaction network indicated.
operationId: getinfo
produces:
- application/json
parameters:
... | [
"Get",
"information",
"about",
"the",
"transaction",
"network",
"indicated",
".",
"Returned",
"info",
"is",
":",
"enabled",
"/",
"disabled",
"available",
"hot",
"wallet",
"balance",
"&",
"the",
"transaction",
"fee",
".",
"---",
"description",
":",
"Get",
"info... | python | train |
geronimp/graftM | graftm/hmmsearcher.py | https://github.com/geronimp/graftM/blob/c82576517290167f605fd0bc4facd009cee29f48/graftm/hmmsearcher.py#L25-L69 | def hmmsearch(self, input_pipe, hmms, output_files):
r"""Run HMMsearch with all the HMMs, generating output files
Parameters
----------
input_pipe: String
A string which is a partial command line. When this command is run
is outputs to STDOUT fasta formatted prot... | [
"def",
"hmmsearch",
"(",
"self",
",",
"input_pipe",
",",
"hmms",
",",
"output_files",
")",
":",
"# Check input and output paths are the same length",
"if",
"len",
"(",
"hmms",
")",
"!=",
"len",
"(",
"output_files",
")",
":",
"raise",
"Exception",
"(",
"\"Program... | r"""Run HMMsearch with all the HMMs, generating output files
Parameters
----------
input_pipe: String
A string which is a partial command line. When this command is run
is outputs to STDOUT fasta formatted protein sequences, which
hmmsearch runs on.
h... | [
"r",
"Run",
"HMMsearch",
"with",
"all",
"the",
"HMMs",
"generating",
"output",
"files"
] | python | train |
suurjaak/InputScope | inputscope/webui.py | https://github.com/suurjaak/InputScope/blob/245ff045163a1995e8cd5ac558d0a93024eb86eb/inputscope/webui.py#L52-L64 | def keyboard(table, day=None):
"""Handler for showing the keyboard statistics page."""
cols, group = "realkey AS key, COUNT(*) AS count", "realkey"
where = (("day", day),) if day else ()
counts_display = counts = db.fetch(table, cols, where, group, "count DESC")
if "combos" == table:
c... | [
"def",
"keyboard",
"(",
"table",
",",
"day",
"=",
"None",
")",
":",
"cols",
",",
"group",
"=",
"\"realkey AS key, COUNT(*) AS count\"",
",",
"\"realkey\"",
"where",
"=",
"(",
"(",
"\"day\"",
",",
"day",
")",
",",
")",
"if",
"day",
"else",
"(",
")",
"co... | Handler for showing the keyboard statistics page. | [
"Handler",
"for",
"showing",
"the",
"keyboard",
"statistics",
"page",
"."
] | python | train |
shtalinberg/django-actions-logger | actionslog/registry.py | https://github.com/shtalinberg/django-actions-logger/blob/2a7200bfb277ace47464a77b57aa475a9710271a/actionslog/registry.py#L27-L45 | def register(self, model, include_fields=[], exclude_fields=[]):
"""
Register a model with actionslog. Actionslog will then track mutations on this model's instances.
:param model: The model to register.
:type model: Model
:param include_fields: The fields to include. Implicitly... | [
"def",
"register",
"(",
"self",
",",
"model",
",",
"include_fields",
"=",
"[",
"]",
",",
"exclude_fields",
"=",
"[",
"]",
")",
":",
"if",
"issubclass",
"(",
"model",
",",
"Model",
")",
":",
"self",
".",
"_registry",
"[",
"model",
"]",
"=",
"{",
"'i... | Register a model with actionslog. Actionslog will then track mutations on this model's instances.
:param model: The model to register.
:type model: Model
:param include_fields: The fields to include. Implicitly excludes all other fields.
:type include_fields: list
:param exclude... | [
"Register",
"a",
"model",
"with",
"actionslog",
".",
"Actionslog",
"will",
"then",
"track",
"mutations",
"on",
"this",
"model",
"s",
"instances",
"."
] | python | train |
materialsproject/pymatgen | pymatgen/analysis/local_env.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/analysis/local_env.py#L1553-L1588 | def solid_angle(center, coords):
"""
Helper method to calculate the solid angle of a set of coords from the
center.
Args:
center (3x1 array): Center to measure solid angle from.
coords (Nx3 array): List of coords to determine solid angle.
Returns:
The solid angle.
"""
... | [
"def",
"solid_angle",
"(",
"center",
",",
"coords",
")",
":",
"# Compute the displacement from the center",
"r",
"=",
"[",
"np",
".",
"subtract",
"(",
"c",
",",
"center",
")",
"for",
"c",
"in",
"coords",
"]",
"# Compute the magnitude of each vector",
"r_norm",
"... | Helper method to calculate the solid angle of a set of coords from the
center.
Args:
center (3x1 array): Center to measure solid angle from.
coords (Nx3 array): List of coords to determine solid angle.
Returns:
The solid angle. | [
"Helper",
"method",
"to",
"calculate",
"the",
"solid",
"angle",
"of",
"a",
"set",
"of",
"coords",
"from",
"the",
"center",
"."
] | python | train |
rocky/python-filecache | pyficache/main.py | https://github.com/rocky/python-filecache/blob/60709ccd837ef5df001faf3cb02d4979ba342a23/pyficache/main.py#L436-L443 | def remove_remap_file(filename):
"""Remove any mapping for *filename* and return that if it exists"""
global file2file_remap
if filename in file2file_remap:
retval = file2file_remap[filename]
del file2file_remap[filename]
return retval
return None | [
"def",
"remove_remap_file",
"(",
"filename",
")",
":",
"global",
"file2file_remap",
"if",
"filename",
"in",
"file2file_remap",
":",
"retval",
"=",
"file2file_remap",
"[",
"filename",
"]",
"del",
"file2file_remap",
"[",
"filename",
"]",
"return",
"retval",
"return"... | Remove any mapping for *filename* and return that if it exists | [
"Remove",
"any",
"mapping",
"for",
"*",
"filename",
"*",
"and",
"return",
"that",
"if",
"it",
"exists"
] | python | train |
ciena/afkak | afkak/_util.py | https://github.com/ciena/afkak/blob/6f5e05ba6f135ea3c29cdb80efda009f7845569a/afkak/_util.py#L27-L44 | def _coerce_topic(topic):
"""
Ensure that the topic name is text string of a valid length.
:param topic: Kafka topic name. Valid characters are in the set ``[a-zA-Z0-9._-]``.
:raises ValueError: when the topic name exceeds 249 bytes
:raises TypeError: when the topic is not :class:`unicode` or :clas... | [
"def",
"_coerce_topic",
"(",
"topic",
")",
":",
"if",
"not",
"isinstance",
"(",
"topic",
",",
"string_types",
")",
":",
"raise",
"TypeError",
"(",
"'topic={!r} must be text'",
".",
"format",
"(",
"topic",
")",
")",
"if",
"not",
"isinstance",
"(",
"topic",
... | Ensure that the topic name is text string of a valid length.
:param topic: Kafka topic name. Valid characters are in the set ``[a-zA-Z0-9._-]``.
:raises ValueError: when the topic name exceeds 249 bytes
:raises TypeError: when the topic is not :class:`unicode` or :class:`str` | [
"Ensure",
"that",
"the",
"topic",
"name",
"is",
"text",
"string",
"of",
"a",
"valid",
"length",
"."
] | python | train |
datajoint/datajoint-python | datajoint/table.py | https://github.com/datajoint/datajoint-python/blob/4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c/datajoint/table.py#L421-L440 | def drop(self):
"""
Drop the table and all tables that reference it, recursively.
User is prompted for confirmation if config['safemode'] is set to True.
"""
if self.restriction:
raise DataJointError('A relation with an applied restriction condition cannot be dropped.... | [
"def",
"drop",
"(",
"self",
")",
":",
"if",
"self",
".",
"restriction",
":",
"raise",
"DataJointError",
"(",
"'A relation with an applied restriction condition cannot be dropped.'",
"' Call drop() on the unrestricted Table.'",
")",
"self",
".",
"connection",
".",
"dependenc... | Drop the table and all tables that reference it, recursively.
User is prompted for confirmation if config['safemode'] is set to True. | [
"Drop",
"the",
"table",
"and",
"all",
"tables",
"that",
"reference",
"it",
"recursively",
".",
"User",
"is",
"prompted",
"for",
"confirmation",
"if",
"config",
"[",
"safemode",
"]",
"is",
"set",
"to",
"True",
"."
] | python | train |
n1analytics/python-paillier | examples/federated_learning_with_encryption.py | https://github.com/n1analytics/python-paillier/blob/955f8c0bfa9623be15b75462b121d28acf70f04b/examples/federated_learning_with_encryption.py#L160-L164 | def fit(self, n_iter, eta=0.01):
"""Linear regression for n_iter"""
for _ in range(n_iter):
gradient = self.compute_gradient()
self.gradient_step(gradient, eta) | [
"def",
"fit",
"(",
"self",
",",
"n_iter",
",",
"eta",
"=",
"0.01",
")",
":",
"for",
"_",
"in",
"range",
"(",
"n_iter",
")",
":",
"gradient",
"=",
"self",
".",
"compute_gradient",
"(",
")",
"self",
".",
"gradient_step",
"(",
"gradient",
",",
"eta",
... | Linear regression for n_iter | [
"Linear",
"regression",
"for",
"n_iter"
] | python | train |
mitsei/dlkit | dlkit/records/assessment/basic/drag_and_drop_records.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/records/assessment/basic/drag_and_drop_records.py#L756-L775 | def add_droppable(self, droppable_text, name='', reuse=1, drop_behavior_type=None):
"""stub"""
if not isinstance(droppable_text, DisplayText):
raise InvalidArgument('droppable_text is not a DisplayText object')
if not isinstance(reuse, int):
raise InvalidArgument('reuse m... | [
"def",
"add_droppable",
"(",
"self",
",",
"droppable_text",
",",
"name",
"=",
"''",
",",
"reuse",
"=",
"1",
",",
"drop_behavior_type",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"droppable_text",
",",
"DisplayText",
")",
":",
"raise",
"InvalidA... | stub | [
"stub"
] | python | train |
iotile/coretools | iotilegateway/iotilegateway/supervisor/client.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/supervisor/client.py#L235-L250 | async def service_info(self, name):
"""Pull descriptive info of a service by name.
Information returned includes the service's user friendly
name and whether it was preregistered or added dynamically.
Returns:
dict: A dictionary of service information with the following key... | [
"async",
"def",
"service_info",
"(",
"self",
",",
"name",
")",
":",
"return",
"await",
"self",
".",
"send_command",
"(",
"OPERATIONS",
".",
"CMD_QUERY_INFO",
",",
"{",
"'name'",
":",
"name",
"}",
",",
"MESSAGES",
".",
"QueryInfoResponse",
",",
"timeout",
"... | Pull descriptive info of a service by name.
Information returned includes the service's user friendly
name and whether it was preregistered or added dynamically.
Returns:
dict: A dictionary of service information with the following keys
set:
long_nam... | [
"Pull",
"descriptive",
"info",
"of",
"a",
"service",
"by",
"name",
"."
] | python | train |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L12507-L12552 | def spkw05(handle, body, center, inframe, first, last, segid, gm, n, states,
epochs):
# see libspice args for solution to array[][N] problem
"""
Write an SPK segment of type 5 given a time-ordered set of
discrete states and epochs, and the gravitational parameter
of a central body.
h... | [
"def",
"spkw05",
"(",
"handle",
",",
"body",
",",
"center",
",",
"inframe",
",",
"first",
",",
"last",
",",
"segid",
",",
"gm",
",",
"n",
",",
"states",
",",
"epochs",
")",
":",
"# see libspice args for solution to array[][N] problem",
"handle",
"=",
"ctypes... | Write an SPK segment of type 5 given a time-ordered set of
discrete states and epochs, and the gravitational parameter
of a central body.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkw05_c.html
:param handle: Handle of an SPK file open for writing.
:type handle: int
:param body: ... | [
"Write",
"an",
"SPK",
"segment",
"of",
"type",
"5",
"given",
"a",
"time",
"-",
"ordered",
"set",
"of",
"discrete",
"states",
"and",
"epochs",
"and",
"the",
"gravitational",
"parameter",
"of",
"a",
"central",
"body",
"."
] | python | train |
yamcs/yamcs-python | yamcs-client/yamcs/mdb/client.py | https://github.com/yamcs/yamcs-python/blob/1082fee8a299010cc44416bbb7518fac0ef08b48/yamcs-client/yamcs/mdb/client.py#L89-L109 | def list_containers(self, page_size=None):
"""
Lists the containers visible to this client.
Containers are returned in lexicographical order.
:rtype: :class:`.Container` iterator
"""
params = {}
if page_size is not None:
params['limit'] = page_size
... | [
"def",
"list_containers",
"(",
"self",
",",
"page_size",
"=",
"None",
")",
":",
"params",
"=",
"{",
"}",
"if",
"page_size",
"is",
"not",
"None",
":",
"params",
"[",
"'limit'",
"]",
"=",
"page_size",
"return",
"pagination",
".",
"Iterator",
"(",
"client",... | Lists the containers visible to this client.
Containers are returned in lexicographical order.
:rtype: :class:`.Container` iterator | [
"Lists",
"the",
"containers",
"visible",
"to",
"this",
"client",
"."
] | python | train |
myaooo/pysbrl | pysbrl/utils.py | https://github.com/myaooo/pysbrl/blob/74bba8c6913a7f82e32313108f8c3e025b89d9c7/pysbrl/utils.py#L12-L20 | def before_save(file_or_dir):
"""
make sure that the dedicated path exists (create if not exist)
:param file_or_dir:
:return: None
"""
dir_name = os.path.dirname(os.path.abspath(file_or_dir))
if not os.path.exists(dir_name):
os.makedirs(dir_name) | [
"def",
"before_save",
"(",
"file_or_dir",
")",
":",
"dir_name",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"file_or_dir",
")",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"dir_name",
")",
":",
... | make sure that the dedicated path exists (create if not exist)
:param file_or_dir:
:return: None | [
"make",
"sure",
"that",
"the",
"dedicated",
"path",
"exists",
"(",
"create",
"if",
"not",
"exist",
")",
":",
"param",
"file_or_dir",
":",
":",
"return",
":",
"None"
] | python | train |
ninapavlich/django-imagekit-cropper | imagekit_cropper/utils.py | https://github.com/ninapavlich/django-imagekit-cropper/blob/c1c2dc5c3c4724492052e5d244e9de1cc362dbcc/imagekit_cropper/utils.py#L32-L50 | def instance_ik_model_receiver(fn):
"""
A method decorator that filters out sign_original_specals coming from models that don't
have fields that function as ImageFieldSourceGroup sources.
"""
@wraps(fn)
def receiver(self, sender, **kwargs):
# print 'inspect.isclass(sender? %s'%(inspect.... | [
"def",
"instance_ik_model_receiver",
"(",
"fn",
")",
":",
"@",
"wraps",
"(",
"fn",
")",
"def",
"receiver",
"(",
"self",
",",
"sender",
",",
"*",
"*",
"kwargs",
")",
":",
"# print 'inspect.isclass(sender? %s'%(inspect.isclass(sender))",
"if",
"not",
"inspect",
".... | A method decorator that filters out sign_original_specals coming from models that don't
have fields that function as ImageFieldSourceGroup sources. | [
"A",
"method",
"decorator",
"that",
"filters",
"out",
"sign_original_specals",
"coming",
"from",
"models",
"that",
"don",
"t",
"have",
"fields",
"that",
"function",
"as",
"ImageFieldSourceGroup",
"sources",
"."
] | python | train |
joedborg/CoPing | CoPing/ping.py | https://github.com/joedborg/CoPing/blob/2239729ee4107b999c1cba696d94f7d48ab73d36/CoPing/ping.py#L157-L192 | def do(self):
"""
Send one ICMP ECHO_REQUEST and receive the response until self.timeout.
"""
try: # One could use UDP here, but it's obscure
current_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.getprotobyname("icmp"))
except socket.error as (errno, ... | [
"def",
"do",
"(",
"self",
")",
":",
"try",
":",
"# One could use UDP here, but it's obscure",
"current_socket",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_RAW",
",",
"socket",
".",
"getprotobyname",
"(",
"\"icmp\"",
... | Send one ICMP ECHO_REQUEST and receive the response until self.timeout. | [
"Send",
"one",
"ICMP",
"ECHO_REQUEST",
"and",
"receive",
"the",
"response",
"until",
"self",
".",
"timeout",
"."
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.