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 |
|---|---|---|---|---|---|---|---|---|
django-parler/django-parler | parler/admin.py | https://github.com/django-parler/django-parler/blob/11ae4af5e8faddb74c69c848870122df4006a54e/parler/admin.py#L125-L132 | def get_form_language(self, request, obj=None):
"""
Return the current language for the currently displayed object fields.
"""
if obj is not None:
return obj.get_current_language()
else:
return self._language(request) | [
"def",
"get_form_language",
"(",
"self",
",",
"request",
",",
"obj",
"=",
"None",
")",
":",
"if",
"obj",
"is",
"not",
"None",
":",
"return",
"obj",
".",
"get_current_language",
"(",
")",
"else",
":",
"return",
"self",
".",
"_language",
"(",
"request",
... | Return the current language for the currently displayed object fields. | [
"Return",
"the",
"current",
"language",
"for",
"the",
"currently",
"displayed",
"object",
"fields",
"."
] | python | train |
tritemio/PyBroMo | pybromo/diffusion.py | https://github.com/tritemio/PyBroMo/blob/b75f82a4551ff37e7c7a7e6954c536451f3e6d06/pybromo/diffusion.py#L382-L397 | def numeric_params(self):
"""A dict containing all the simulation numeric-parameters.
The values are 2-element tuples: first element is the value and
second element is a string describing the parameter (metadata).
"""
nparams = dict(
D = (self.diffusion_coeff.mean(),... | [
"def",
"numeric_params",
"(",
"self",
")",
":",
"nparams",
"=",
"dict",
"(",
"D",
"=",
"(",
"self",
".",
"diffusion_coeff",
".",
"mean",
"(",
")",
",",
"'Diffusion coefficient (m^2/s)'",
")",
",",
"np",
"=",
"(",
"self",
".",
"num_particles",
",",
"'Numb... | A dict containing all the simulation numeric-parameters.
The values are 2-element tuples: first element is the value and
second element is a string describing the parameter (metadata). | [
"A",
"dict",
"containing",
"all",
"the",
"simulation",
"numeric",
"-",
"parameters",
"."
] | python | valid |
oanda/v20-python | src/v20/order.py | https://github.com/oanda/v20-python/blob/f28192f4a31bce038cf6dfa302f5878bec192fe5/src/v20/order.py#L4694-L4709 | def stop_loss(self, accountID, **kwargs):
"""
Shortcut to create a Stop Loss Order in an Account
Args:
accountID : The ID of the Account
kwargs : The arguments to create a StopLossOrderRequest
Returns:
v20.response.Response containing the results fro... | [
"def",
"stop_loss",
"(",
"self",
",",
"accountID",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"create",
"(",
"accountID",
",",
"order",
"=",
"StopLossOrderRequest",
"(",
"*",
"*",
"kwargs",
")",
")"
] | Shortcut to create a Stop Loss Order in an Account
Args:
accountID : The ID of the Account
kwargs : The arguments to create a StopLossOrderRequest
Returns:
v20.response.Response containing the results from submitting
the request | [
"Shortcut",
"to",
"create",
"a",
"Stop",
"Loss",
"Order",
"in",
"an",
"Account"
] | python | train |
phaethon/kamene | kamene/utils6.py | https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/utils6.py#L476-L494 | def in6_ctop(addr):
"""
Convert an IPv6 address in Compact Representation Notation
(RFC 1924) to printable representation ;-)
Returns None on error.
"""
#if len(addr) != 20 or not reduce(lambda x,y: x and y, map(lambda x: x in _rfc1924map, addr)):
if len(addr) != 20 or not all(map(lambda x:... | [
"def",
"in6_ctop",
"(",
"addr",
")",
":",
"#if len(addr) != 20 or not reduce(lambda x,y: x and y, map(lambda x: x in _rfc1924map, addr)):",
"if",
"len",
"(",
"addr",
")",
"!=",
"20",
"or",
"not",
"all",
"(",
"map",
"(",
"lambda",
"x",
":",
"x",
"in",
"_rfc1924map",
... | Convert an IPv6 address in Compact Representation Notation
(RFC 1924) to printable representation ;-)
Returns None on error. | [
"Convert",
"an",
"IPv6",
"address",
"in",
"Compact",
"Representation",
"Notation",
"(",
"RFC",
"1924",
")",
"to",
"printable",
"representation",
";",
"-",
")",
"Returns",
"None",
"on",
"error",
"."
] | python | train |
mcs07/ChemDataExtractor | chemdataextractor/nlp/abbrev.py | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/nlp/abbrev.py#L175-L180 | def detect(self, tokens):
"""Return a (abbr, long) pair for each abbreviation definition."""
results = []
for abbr_span, long_span in self.detect_spans(tokens):
results.append((tokens[abbr_span[0]:abbr_span[1]], tokens[long_span[0]:long_span[1]]))
return results | [
"def",
"detect",
"(",
"self",
",",
"tokens",
")",
":",
"results",
"=",
"[",
"]",
"for",
"abbr_span",
",",
"long_span",
"in",
"self",
".",
"detect_spans",
"(",
"tokens",
")",
":",
"results",
".",
"append",
"(",
"(",
"tokens",
"[",
"abbr_span",
"[",
"0... | Return a (abbr, long) pair for each abbreviation definition. | [
"Return",
"a",
"(",
"abbr",
"long",
")",
"pair",
"for",
"each",
"abbreviation",
"definition",
"."
] | python | train |
botstory/botstory | botstory/integrations/fb/validate.py | https://github.com/botstory/botstory/blob/9c5b2fc7f7a14dbd467d70f60d5ba855ef89dac3/botstory/integrations/fb/validate.py#L22-L40 | def persistent_menu(menu):
"""
more: https://developers.facebook.com/docs/messenger-platform/thread-settings/persistent-menu
:param menu:
:return:
"""
if len(menu) > 3:
raise Invalid('menu should not exceed 3 call to actions')
if any(len(item['call_to_actions']) > 5 for item in men... | [
"def",
"persistent_menu",
"(",
"menu",
")",
":",
"if",
"len",
"(",
"menu",
")",
">",
"3",
":",
"raise",
"Invalid",
"(",
"'menu should not exceed 3 call to actions'",
")",
"if",
"any",
"(",
"len",
"(",
"item",
"[",
"'call_to_actions'",
"]",
")",
">",
"5",
... | more: https://developers.facebook.com/docs/messenger-platform/thread-settings/persistent-menu
:param menu:
:return: | [
"more",
":",
"https",
":",
"//",
"developers",
".",
"facebook",
".",
"com",
"/",
"docs",
"/",
"messenger",
"-",
"platform",
"/",
"thread",
"-",
"settings",
"/",
"persistent",
"-",
"menu"
] | python | train |
GoogleCloudPlatform/appengine-mapreduce | python/src/mapreduce/api/map_job/sample_input_reader.py | https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/api/map_job/sample_input_reader.py#L101-L121 | def validate(cls, job_config):
"""Inherit docs."""
super(SampleInputReader, cls).validate(job_config)
params = job_config.input_reader_params
# Validate count.
if cls.COUNT not in params:
raise errors.BadReaderParamsError("Must specify %s" % cls.COUNT)
if not isinstance(params[cls.COUNT],... | [
"def",
"validate",
"(",
"cls",
",",
"job_config",
")",
":",
"super",
"(",
"SampleInputReader",
",",
"cls",
")",
".",
"validate",
"(",
"job_config",
")",
"params",
"=",
"job_config",
".",
"input_reader_params",
"# Validate count.",
"if",
"cls",
".",
"COUNT",
... | Inherit docs. | [
"Inherit",
"docs",
"."
] | python | train |
nutechsoftware/alarmdecoder | alarmdecoder/devices/usb_device.py | https://github.com/nutechsoftware/alarmdecoder/blob/b0c014089e24455228cb4402cf30ba98157578cd/alarmdecoder/devices/usb_device.py#L358-L419 | def read_line(self, timeout=0.0, purge_buffer=False):
"""
Reads a line from the device.
:param timeout: read timeout
:type timeout: float
:param purge_buffer: Indicates whether to purge the buffer prior to
reading.
:type purge_buffer: bool
... | [
"def",
"read_line",
"(",
"self",
",",
"timeout",
"=",
"0.0",
",",
"purge_buffer",
"=",
"False",
")",
":",
"def",
"timeout_event",
"(",
")",
":",
"\"\"\"Handles read timeout event\"\"\"",
"timeout_event",
".",
"reading",
"=",
"False",
"timeout_event",
".",
"readi... | Reads a line from the device.
:param timeout: read timeout
:type timeout: float
:param purge_buffer: Indicates whether to purge the buffer prior to
reading.
:type purge_buffer: bool
:returns: line that was read
:raises: :py:class:`~alarmdeco... | [
"Reads",
"a",
"line",
"from",
"the",
"device",
"."
] | python | train |
apache/airflow | airflow/contrib/hooks/gcp_pubsub_hook.py | https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/gcp_pubsub_hook.py#L227-L261 | def pull(self, project, subscription, max_messages,
return_immediately=False):
"""Pulls up to ``max_messages`` messages from Pub/Sub subscription.
:param project: the GCP project ID where the subscription exists
:type project: str
:param subscription: the Pub/Sub subscripti... | [
"def",
"pull",
"(",
"self",
",",
"project",
",",
"subscription",
",",
"max_messages",
",",
"return_immediately",
"=",
"False",
")",
":",
"service",
"=",
"self",
".",
"get_conn",
"(",
")",
"full_subscription",
"=",
"_format_subscription",
"(",
"project",
",",
... | Pulls up to ``max_messages`` messages from Pub/Sub subscription.
:param project: the GCP project ID where the subscription exists
:type project: str
:param subscription: the Pub/Sub subscription name to pull from; do not
include the 'projects/{project}/topics/' prefix.
:type... | [
"Pulls",
"up",
"to",
"max_messages",
"messages",
"from",
"Pub",
"/",
"Sub",
"subscription",
"."
] | python | test |
marl/jams | jams/util.py | https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/util.py#L182-L223 | def find_with_extension(in_dir, ext, depth=3, sort=True):
"""Naive depth-search into a directory for files with a given extension.
Parameters
----------
in_dir : str
Path to search.
ext : str
File extension to match.
depth : int
Depth of directories to search.
sort :... | [
"def",
"find_with_extension",
"(",
"in_dir",
",",
"ext",
",",
"depth",
"=",
"3",
",",
"sort",
"=",
"True",
")",
":",
"assert",
"depth",
">=",
"1",
"ext",
"=",
"ext",
".",
"strip",
"(",
"os",
".",
"extsep",
")",
"match",
"=",
"list",
"(",
")",
"fo... | Naive depth-search into a directory for files with a given extension.
Parameters
----------
in_dir : str
Path to search.
ext : str
File extension to match.
depth : int
Depth of directories to search.
sort : bool
Sort the list alphabetically
Returns
-----... | [
"Naive",
"depth",
"-",
"search",
"into",
"a",
"directory",
"for",
"files",
"with",
"a",
"given",
"extension",
"."
] | python | valid |
ael-code/pyFsdb | fsdb/fsdb.py | https://github.com/ael-code/pyFsdb/blob/de33a0d41373307cb32cdd7ba1991b85ff495ee3/fsdb/fsdb.py#L110-L124 | def _copy_content(self, origin, dstPath):
"""copy the content of origin into dstPath
Due to concurrency problem, the content will be first
copied to a temporary file alongside `dstPath` and
then atomically moved to `dstPath`
"""
if hasattr(origin, 'read'):
... | [
"def",
"_copy_content",
"(",
"self",
",",
"origin",
",",
"dstPath",
")",
":",
"if",
"hasattr",
"(",
"origin",
",",
"'read'",
")",
":",
"copy_content",
"(",
"origin",
",",
"dstPath",
",",
"self",
".",
"BLOCK_SIZE",
",",
"self",
".",
"_conf",
"[",
"'fmod... | copy the content of origin into dstPath
Due to concurrency problem, the content will be first
copied to a temporary file alongside `dstPath` and
then atomically moved to `dstPath` | [
"copy",
"the",
"content",
"of",
"origin",
"into",
"dstPath"
] | python | train |
ltalirz/aiida-phtools | aiida_phtools/calculations/distance_matrix.py | https://github.com/ltalirz/aiida-phtools/blob/acec3339425fe92d3f55e725a199123de9a1febc/aiida_phtools/calculations/distance_matrix.py#L127-L138 | def cmdline_params(self, surface_sample_file_name, cell_file_name):
"""Synthesize command line parameters
e.g. [ ['struct.vsa'], ['struct.cell']]
"""
parameters = []
parameters += [surface_sample_file_name]
parameters += [cell_file_name]
parameters += [self._OUT... | [
"def",
"cmdline_params",
"(",
"self",
",",
"surface_sample_file_name",
",",
"cell_file_name",
")",
":",
"parameters",
"=",
"[",
"]",
"parameters",
"+=",
"[",
"surface_sample_file_name",
"]",
"parameters",
"+=",
"[",
"cell_file_name",
"]",
"parameters",
"+=",
"[",
... | Synthesize command line parameters
e.g. [ ['struct.vsa'], ['struct.cell']] | [
"Synthesize",
"command",
"line",
"parameters"
] | python | train |
annoviko/pyclustering | pyclustering/cluster/bang.py | https://github.com/annoviko/pyclustering/blob/98aa0dd89fd36f701668fb1eb29c8fb5662bf7d0/pyclustering/cluster/bang.py#L895-L908 | def __calculate_density(self, amount_points):
"""!
@brief Calculates BANG-block density.
@param[in] amount_points (uint): Amount of points in block.
@return (double) BANG-block density.
"""
volume = self.__spatial_block.get_volume()
if volume != 0.0:
... | [
"def",
"__calculate_density",
"(",
"self",
",",
"amount_points",
")",
":",
"volume",
"=",
"self",
".",
"__spatial_block",
".",
"get_volume",
"(",
")",
"if",
"volume",
"!=",
"0.0",
":",
"return",
"amount_points",
"/",
"volume",
"return",
"0.0"
] | !
@brief Calculates BANG-block density.
@param[in] amount_points (uint): Amount of points in block.
@return (double) BANG-block density. | [
"!"
] | python | valid |
robertpeteuil/multi-cloud-control | mcc/cldcnct.py | https://github.com/robertpeteuil/multi-cloud-control/blob/f1565af1c0b6ed465ff312d3ccc592ba0609f4a2/mcc/cldcnct.py#L198-L211 | def adj_nodes_az(az_nodes):
"""Adjust details specific to Azure."""
for node in az_nodes:
node.cloud = "azure"
node.cloud_disp = "Azure"
node.private_ips = ip_to_str(node.private_ips)
node.public_ips = ip_to_str(node.public_ips)
node.zone = node.extra['location']
... | [
"def",
"adj_nodes_az",
"(",
"az_nodes",
")",
":",
"for",
"node",
"in",
"az_nodes",
":",
"node",
".",
"cloud",
"=",
"\"azure\"",
"node",
".",
"cloud_disp",
"=",
"\"Azure\"",
"node",
".",
"private_ips",
"=",
"ip_to_str",
"(",
"node",
".",
"private_ips",
")",... | Adjust details specific to Azure. | [
"Adjust",
"details",
"specific",
"to",
"Azure",
"."
] | python | train |
michael-lazar/rtv | rtv/packages/praw/__init__.py | https://github.com/michael-lazar/rtv/blob/ccef2af042566ad384977028cf0bde01bc524dda/rtv/packages/praw/__init__.py#L2361-L2377 | def get_multireddits(self, redditor, *args, **kwargs):
"""Return a list of multireddits belonging to a redditor.
:param redditor: The username or Redditor object to find multireddits
from.
:returns: The json response from the server
The additional parameters are passed dire... | [
"def",
"get_multireddits",
"(",
"self",
",",
"redditor",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"redditor",
"=",
"six",
".",
"text_type",
"(",
"redditor",
")",
"url",
"=",
"self",
".",
"config",
"[",
"'multireddit_user'",
"]",
".",
"forma... | Return a list of multireddits belonging to a redditor.
:param redditor: The username or Redditor object to find multireddits
from.
:returns: The json response from the server
The additional parameters are passed directly into
:meth:`~praw.__init__.BaseReddit.request_json`
... | [
"Return",
"a",
"list",
"of",
"multireddits",
"belonging",
"to",
"a",
"redditor",
"."
] | python | train |
programa-stic/barf-project | barf/analysis/gadgets/verifier.py | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/analysis/gadgets/verifier.py#L208-L234 | def _get_constrs_arithmetic(self, gadget):
"""Generate constraints for the BinaryOperation gadgets:
dst <- src1 OP src2
"""
# *dst* register has to have the value of *src1 op src2* for all
# possibles assignments of *src1* and *src2*.
dst = self.analyzer.get_registe... | [
"def",
"_get_constrs_arithmetic",
"(",
"self",
",",
"gadget",
")",
":",
"# *dst* register has to have the value of *src1 op src2* for all",
"# possibles assignments of *src1* and *src2*.",
"dst",
"=",
"self",
".",
"analyzer",
".",
"get_register_expr",
"(",
"gadget",
".",
"des... | Generate constraints for the BinaryOperation gadgets:
dst <- src1 OP src2 | [
"Generate",
"constraints",
"for",
"the",
"BinaryOperation",
"gadgets",
":",
"dst",
"<",
"-",
"src1",
"OP",
"src2"
] | python | train |
python-visualization/folium | folium/folium.py | https://github.com/python-visualization/folium/blob/8595240517135d1637ca4cf7cc624045f1d911b3/folium/folium.py#L408-L420 | def choropleth(self, *args, **kwargs):
"""Call the Choropleth class with the same arguments.
This method may be deleted after a year from now (Nov 2018).
"""
warnings.warn(
'The choropleth method has been deprecated. Instead use the new '
'Choropleth class, whic... | [
"def",
"choropleth",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"warnings",
".",
"warn",
"(",
"'The choropleth method has been deprecated. Instead use the new '",
"'Choropleth class, which has the same arguments. See the example '",
"'notebook \\'GeoJSON... | Call the Choropleth class with the same arguments.
This method may be deleted after a year from now (Nov 2018). | [
"Call",
"the",
"Choropleth",
"class",
"with",
"the",
"same",
"arguments",
"."
] | python | train |
SHTOOLS/SHTOOLS | pyshtools/shclasses/shtensor.py | https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shtensor.py#L1510-L1594 | def plot_eigh(self, colorbar=True, cb_orientation='vertical',
tick_interval=[60, 60], minor_tick_interval=[20, 20],
xlabel='Longitude', ylabel='Latitude',
axes_labelsize=9, tick_labelsize=8, show=True, fname=None,
**kwargs):
"""
Plo... | [
"def",
"plot_eigh",
"(",
"self",
",",
"colorbar",
"=",
"True",
",",
"cb_orientation",
"=",
"'vertical'",
",",
"tick_interval",
"=",
"[",
"60",
",",
"60",
"]",
",",
"minor_tick_interval",
"=",
"[",
"20",
",",
"20",
"]",
",",
"xlabel",
"=",
"'Longitude'",
... | Plot the two eigenvalues and maximum absolute value eigenvalue of the
horizontal tensor.
Usage
-----
x.plot_eigh([tick_interval, minor_tick_interval, xlabel, ylabel,
colorbar, cb_orientation, cb_label, axes_labelsize,
tick_labelsize, show, fname... | [
"Plot",
"the",
"two",
"eigenvalues",
"and",
"maximum",
"absolute",
"value",
"eigenvalue",
"of",
"the",
"horizontal",
"tensor",
"."
] | python | train |
vcs-python/vcspull | vcspull/config.py | https://github.com/vcs-python/vcspull/blob/c1827bf78d2cdebc61d82111c9aa35afd6ea6a25/vcspull/config.py#L268-L299 | def filter_repos(config, repo_dir=None, vcs_url=None, name=None):
"""Return a :py:obj:`list` list of repos from (expanded) config file.
repo_dir, vcs_url and name all support fnmatch.
:param config: the expanded repo config in :py:class:`dict` format.
:type config: dict
:param repo_dir: directory ... | [
"def",
"filter_repos",
"(",
"config",
",",
"repo_dir",
"=",
"None",
",",
"vcs_url",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"repo_list",
"=",
"[",
"]",
"if",
"repo_dir",
":",
"repo_list",
".",
"extend",
"(",
"[",
"r",
"for",
"r",
"in",
"co... | Return a :py:obj:`list` list of repos from (expanded) config file.
repo_dir, vcs_url and name all support fnmatch.
:param config: the expanded repo config in :py:class:`dict` format.
:type config: dict
:param repo_dir: directory of checkout location, fnmatch pattern supported
:type repo_dir: str o... | [
"Return",
"a",
":",
"py",
":",
"obj",
":",
"list",
"list",
"of",
"repos",
"from",
"(",
"expanded",
")",
"config",
"file",
"."
] | python | train |
tomplus/kubernetes_asyncio | kubernetes_asyncio/client/api/core_v1_api.py | https://github.com/tomplus/kubernetes_asyncio/blob/f9ab15317ec921409714c7afef11aeb0f579985d/kubernetes_asyncio/client/api/core_v1_api.py#L7211-L7234 | def create_node(self, body, **kwargs): # noqa: E501
"""create_node # noqa: E501
create a Node # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_node(body, async_req=Tr... | [
"def",
"create_node",
"(",
"self",
",",
"body",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
".",
"create_node_wi... | create_node # noqa: E501
create a Node # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_node(body, async_req=True)
>>> result = thread.get()
:param async_req ... | [
"create_node",
"#",
"noqa",
":",
"E501"
] | python | train |
darothen/xbpch | xbpch/bpch.py | https://github.com/darothen/xbpch/blob/31972dd6fd5f3f7cecc3a46080ce4f43ca23fbe5/xbpch/bpch.py#L222-L241 | def _read_header(self):
""" Process the header information (data model / grid spec) """
self._header_pos = self.fp.tell()
line = self.fp.readline('20sffii')
modelname, res0, res1, halfpolar, center180 = line
self._attributes.update({
"modelname": str(modelname, 'utf... | [
"def",
"_read_header",
"(",
"self",
")",
":",
"self",
".",
"_header_pos",
"=",
"self",
".",
"fp",
".",
"tell",
"(",
")",
"line",
"=",
"self",
".",
"fp",
".",
"readline",
"(",
"'20sffii'",
")",
"modelname",
",",
"res0",
",",
"res1",
",",
"halfpolar",
... | Process the header information (data model / grid spec) | [
"Process",
"the",
"header",
"information",
"(",
"data",
"model",
"/",
"grid",
"spec",
")"
] | python | train |
apache/spark | python/pyspark/serializers.py | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/serializers.py#L588-L597 | def _hack_namedtuple(cls):
""" Make class generated by namedtuple picklable """
name = cls.__name__
fields = cls._fields
def __reduce__(self):
return (_restore, (name, fields, tuple(self)))
cls.__reduce__ = __reduce__
cls._is_namedtuple_ = True
return cls | [
"def",
"_hack_namedtuple",
"(",
"cls",
")",
":",
"name",
"=",
"cls",
".",
"__name__",
"fields",
"=",
"cls",
".",
"_fields",
"def",
"__reduce__",
"(",
"self",
")",
":",
"return",
"(",
"_restore",
",",
"(",
"name",
",",
"fields",
",",
"tuple",
"(",
"se... | Make class generated by namedtuple picklable | [
"Make",
"class",
"generated",
"by",
"namedtuple",
"picklable"
] | python | train |
google/grr | grr/server/grr_response_server/hunt.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/hunt.py#L355-L367 | def UpdateHunt(hunt_id, client_limit=None, client_rate=None, duration=None):
"""Updates a hunt (it must be paused to be updated)."""
hunt_obj = data_store.REL_DB.ReadHuntObject(hunt_id)
if hunt_obj.hunt_state != hunt_obj.HuntState.PAUSED:
raise OnlyPausedHuntCanBeModifiedError(hunt_obj)
data_store.REL_DB.... | [
"def",
"UpdateHunt",
"(",
"hunt_id",
",",
"client_limit",
"=",
"None",
",",
"client_rate",
"=",
"None",
",",
"duration",
"=",
"None",
")",
":",
"hunt_obj",
"=",
"data_store",
".",
"REL_DB",
".",
"ReadHuntObject",
"(",
"hunt_id",
")",
"if",
"hunt_obj",
".",... | Updates a hunt (it must be paused to be updated). | [
"Updates",
"a",
"hunt",
"(",
"it",
"must",
"be",
"paused",
"to",
"be",
"updated",
")",
"."
] | python | train |
codelv/enaml-native | src/enamlnative/ios/app.py | https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/ios/app.py#L43-L47 | def _default_bridge(self):
""" Get an instance of the ENBridge object using ctypes. """
objc = self.objc
ENBridge = objc.objc_getClass('ENBridge')
return objc.objc_msgSend(ENBridge, objc.sel_registerName('instance')) | [
"def",
"_default_bridge",
"(",
"self",
")",
":",
"objc",
"=",
"self",
".",
"objc",
"ENBridge",
"=",
"objc",
".",
"objc_getClass",
"(",
"'ENBridge'",
")",
"return",
"objc",
".",
"objc_msgSend",
"(",
"ENBridge",
",",
"objc",
".",
"sel_registerName",
"(",
"'i... | Get an instance of the ENBridge object using ctypes. | [
"Get",
"an",
"instance",
"of",
"the",
"ENBridge",
"object",
"using",
"ctypes",
"."
] | python | train |
python-security/pyt | pyt/cfg/stmt_visitor.py | https://github.com/python-security/pyt/blob/efc0cfb716e40e0c8df4098f1cc8cf43723cd31f/pyt/cfg/stmt_visitor.py#L598-L714 | def add_blackbox_or_builtin_call(self, node, blackbox): # noqa: C901
"""Processes a blackbox or builtin function when it is called.
Nothing gets assigned to ret_func_foo in the builtin/blackbox case.
Increments self.function_call_index each time it is called, we can refer to it as N in the com... | [
"def",
"add_blackbox_or_builtin_call",
"(",
"self",
",",
"node",
",",
"blackbox",
")",
":",
"# noqa: C901",
"self",
".",
"function_call_index",
"+=",
"1",
"saved_function_call_index",
"=",
"self",
".",
"function_call_index",
"self",
".",
"undecided",
"=",
"False",
... | Processes a blackbox or builtin function when it is called.
Nothing gets assigned to ret_func_foo in the builtin/blackbox case.
Increments self.function_call_index each time it is called, we can refer to it as N in the comments.
Create e.g. ~call_1 = ret_func_foo RestoreNode.
Create e.... | [
"Processes",
"a",
"blackbox",
"or",
"builtin",
"function",
"when",
"it",
"is",
"called",
".",
"Nothing",
"gets",
"assigned",
"to",
"ret_func_foo",
"in",
"the",
"builtin",
"/",
"blackbox",
"case",
"."
] | python | train |
bwohlberg/sporco | sporco/prox/_util.py | https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/prox/_util.py#L20-L66 | def ndto2d(x, axis=-1):
"""Convert a multi-dimensional array into a 2d array, with the axes
specified by the `axis` parameter flattened into an index along
rows, and the remaining axes flattened into an index along the
columns. This operation can not be properly achieved by a simple
reshape operatio... | [
"def",
"ndto2d",
"(",
"x",
",",
"axis",
"=",
"-",
"1",
")",
":",
"# Convert int axis into a tuple",
"if",
"isinstance",
"(",
"axis",
",",
"int",
")",
":",
"axis",
"=",
"(",
"axis",
",",
")",
"# Handle negative axis indices",
"axis",
"=",
"tuple",
"(",
"[... | Convert a multi-dimensional array into a 2d array, with the axes
specified by the `axis` parameter flattened into an index along
rows, and the remaining axes flattened into an index along the
columns. This operation can not be properly achieved by a simple
reshape operation since a reshape would shuffle... | [
"Convert",
"a",
"multi",
"-",
"dimensional",
"array",
"into",
"a",
"2d",
"array",
"with",
"the",
"axes",
"specified",
"by",
"the",
"axis",
"parameter",
"flattened",
"into",
"an",
"index",
"along",
"rows",
"and",
"the",
"remaining",
"axes",
"flattened",
"into... | python | train |
proycon/clam | clam/common/converters.py | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/converters.py#L71-L90 | def convertforinput(self,filepath, metadata=None):
"""Convert from target format into one of the source formats. Relevant if converters are used in InputTemplates. Metadata already is metadata for the to-be-generated file."""
super(CharEncodingConverter,self).convertforinput(filepath, metadata)
... | [
"def",
"convertforinput",
"(",
"self",
",",
"filepath",
",",
"metadata",
"=",
"None",
")",
":",
"super",
"(",
"CharEncodingConverter",
",",
"self",
")",
".",
"convertforinput",
"(",
"filepath",
",",
"metadata",
")",
"shutil",
".",
"copy",
"(",
"filepath",
... | Convert from target format into one of the source formats. Relevant if converters are used in InputTemplates. Metadata already is metadata for the to-be-generated file. | [
"Convert",
"from",
"target",
"format",
"into",
"one",
"of",
"the",
"source",
"formats",
".",
"Relevant",
"if",
"converters",
"are",
"used",
"in",
"InputTemplates",
".",
"Metadata",
"already",
"is",
"metadata",
"for",
"the",
"to",
"-",
"be",
"-",
"generated",... | python | train |
getsentry/sentry-python | sentry_sdk/hub.py | https://github.com/getsentry/sentry-python/blob/a1d77722bdce0b94660ebf50b5c4a4645916d084/sentry_sdk/hub.py#L61-L72 | def init(*args, **kwargs):
"""Initializes the SDK and optionally integrations.
This takes the same arguments as the client constructor.
"""
global _initial_client
client = Client(*args, **kwargs)
Hub.current.bind_client(client)
rv = _InitGuard(client)
if client is not None:
_ini... | [
"def",
"init",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"global",
"_initial_client",
"client",
"=",
"Client",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"Hub",
".",
"current",
".",
"bind_client",
"(",
"client",
")",
"rv",
"=",
"_In... | Initializes the SDK and optionally integrations.
This takes the same arguments as the client constructor. | [
"Initializes",
"the",
"SDK",
"and",
"optionally",
"integrations",
"."
] | python | train |
pysal/esda | esda/tabular.py | https://github.com/pysal/esda/blob/2fafc6ec505e153152a86601d3e0fba080610c20/esda/tabular.py#L100-L154 | def _bivariate_handler(df, x, y=None, w=None, inplace=True, pvalue='sim',
outvals=None, **kwargs):
"""
Compute a descriptive bivariate statistic over two sets of columns, `x` and
`y`, contained in `df`.
Parameters
----------
df : pandas.DataFrame
... | [
"def",
"_bivariate_handler",
"(",
"df",
",",
"x",
",",
"y",
"=",
"None",
",",
"w",
"=",
"None",
",",
"inplace",
"=",
"True",
",",
"pvalue",
"=",
"'sim'",
",",
"outvals",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"real_swapname",
"=",
"kwargs"... | Compute a descriptive bivariate statistic over two sets of columns, `x` and
`y`, contained in `df`.
Parameters
----------
df : pandas.DataFrame
dataframe in which columns `x` and `y` are contained
x : string or list of strings
one or more colum... | [
"Compute",
"a",
"descriptive",
"bivariate",
"statistic",
"over",
"two",
"sets",
"of",
"columns",
"x",
"and",
"y",
"contained",
"in",
"df",
"."
] | python | train |
dropbox/stone | stone/frontend/parser.py | https://github.com/dropbox/stone/blob/2e95cbcd1c48e05cca68c919fd8d24adec6b0f58/stone/frontend/parser.py#L638-L645 | def p_route_deprecation(self, p):
"""route_deprecation : DEPRECATED
| DEPRECATED BY route_name route_version
| empty"""
if len(p) == 5:
p[0] = (True, p[3], p[4])
elif p[1]:
p[0] = (True, None, None) | [
"def",
"p_route_deprecation",
"(",
"self",
",",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
"==",
"5",
":",
"p",
"[",
"0",
"]",
"=",
"(",
"True",
",",
"p",
"[",
"3",
"]",
",",
"p",
"[",
"4",
"]",
")",
"elif",
"p",
"[",
"1",
"]",
":",
"p"... | route_deprecation : DEPRECATED
| DEPRECATED BY route_name route_version
| empty | [
"route_deprecation",
":",
"DEPRECATED",
"|",
"DEPRECATED",
"BY",
"route_name",
"route_version",
"|",
"empty"
] | python | train |
latture/json2table | json2table/json2table.py | https://github.com/latture/json2table/blob/8bd1363f54ee4fd608ffb7677761526184a9da83/json2table/json2table.py#L167-L190 | def _list_of_dicts_to_column_headers(list_of_dicts):
"""
Detects if all entries in an list of ``dict``'s have identical keys.
Returns the keys if all keys are the same and ``None`` otherwise.
Parameters
----------
list_of_dicts : list
List of dictionaries to ... | [
"def",
"_list_of_dicts_to_column_headers",
"(",
"list_of_dicts",
")",
":",
"if",
"len",
"(",
"list_of_dicts",
")",
"<",
"2",
"or",
"not",
"all",
"(",
"isinstance",
"(",
"item",
",",
"dict",
")",
"for",
"item",
"in",
"list_of_dicts",
")",
":",
"return",
"No... | Detects if all entries in an list of ``dict``'s have identical keys.
Returns the keys if all keys are the same and ``None`` otherwise.
Parameters
----------
list_of_dicts : list
List of dictionaries to test for identical keys.
Returns
-------
list or... | [
"Detects",
"if",
"all",
"entries",
"in",
"an",
"list",
"of",
"dict",
"s",
"have",
"identical",
"keys",
".",
"Returns",
"the",
"keys",
"if",
"all",
"keys",
"are",
"the",
"same",
"and",
"None",
"otherwise",
"."
] | python | train |
mikicz/arca | arca/backend/docker.py | https://github.com/mikicz/arca/blob/e67fdc00be473ecf8ec16d024e1a3f2c47ca882c/arca/backend/docker.py#L629-L644 | def tar_runner(self):
""" Returns a tar with the runner script.
"""
script_bytes = self.RUNNER.read_bytes()
tarstream = BytesIO()
tar = tarfile.TarFile(fileobj=tarstream, mode='w')
tarinfo = tarfile.TarInfo(name="runner.py")
tarinfo.size = len(script_bytes)
... | [
"def",
"tar_runner",
"(",
"self",
")",
":",
"script_bytes",
"=",
"self",
".",
"RUNNER",
".",
"read_bytes",
"(",
")",
"tarstream",
"=",
"BytesIO",
"(",
")",
"tar",
"=",
"tarfile",
".",
"TarFile",
"(",
"fileobj",
"=",
"tarstream",
",",
"mode",
"=",
"'w'"... | Returns a tar with the runner script. | [
"Returns",
"a",
"tar",
"with",
"the",
"runner",
"script",
"."
] | python | train |
PmagPy/PmagPy | pmagpy/pmagplotlib.py | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmagplotlib.py#L2967-L3140 | def plot_map_basemap(fignum, lats, lons, Opts):
"""
plot_map_basemap(fignum, lats,lons,Opts)
makes a basemap with lats/lons
requires working installation of Basemap
Parameters:
_______________
fignum : matplotlib figure number
lats : array or list of latitudes
lons : array or lis... | [
"def",
"plot_map_basemap",
"(",
"fignum",
",",
"lats",
",",
"lons",
",",
"Opts",
")",
":",
"if",
"not",
"has_basemap",
":",
"print",
"(",
"'-W- Basemap must be installed to run plot_map_basemap'",
")",
"return",
"fig",
"=",
"plt",
".",
"figure",
"(",
"num",
"=... | plot_map_basemap(fignum, lats,lons,Opts)
makes a basemap with lats/lons
requires working installation of Basemap
Parameters:
_______________
fignum : matplotlib figure number
lats : array or list of latitudes
lons : array or list of longitudes
Opts : dictionary of plotting options:
... | [
"plot_map_basemap",
"(",
"fignum",
"lats",
"lons",
"Opts",
")",
"makes",
"a",
"basemap",
"with",
"lats",
"/",
"lons",
"requires",
"working",
"installation",
"of",
"Basemap",
"Parameters",
":",
"_______________",
"fignum",
":",
"matplotlib",
"figure",
"number",
"... | python | train |
erikvw/django-collect-offline | django_collect_offline/transaction/deserialize.py | https://github.com/erikvw/django-collect-offline/blob/3d5efd66c68e2db4b060a82b070ae490dc399ca7/django_collect_offline/transaction/deserialize.py#L4-L19 | def deserialize(json_text=None):
"""Returns a generator of deserialized objects.
Wraps django deserialize with defaults for JSON
and natural keys.
See https://docs.djangoproject.com/en/2.1/topics/serialization/
"""
return serializers.deserialize(
"json",
json_text,
ens... | [
"def",
"deserialize",
"(",
"json_text",
"=",
"None",
")",
":",
"return",
"serializers",
".",
"deserialize",
"(",
"\"json\"",
",",
"json_text",
",",
"ensure_ascii",
"=",
"True",
",",
"use_natural_foreign_keys",
"=",
"True",
",",
"use_natural_primary_keys",
"=",
"... | Returns a generator of deserialized objects.
Wraps django deserialize with defaults for JSON
and natural keys.
See https://docs.djangoproject.com/en/2.1/topics/serialization/ | [
"Returns",
"a",
"generator",
"of",
"deserialized",
"objects",
"."
] | python | train |
databricks/spark-sklearn | python/spark_sklearn/util.py | https://github.com/databricks/spark-sklearn/blob/cbde36f6311b73d967e2ec8a97040dfd71eca579/python/spark_sklearn/util.py#L34-L40 | def _call_java(sc, java_obj, name, *args):
"""
Method copied from pyspark.ml.wrapper. Uses private Spark APIs.
"""
m = getattr(java_obj, name)
java_args = [_py2java(sc, arg) for arg in args]
return _java2py(sc, m(*java_args)) | [
"def",
"_call_java",
"(",
"sc",
",",
"java_obj",
",",
"name",
",",
"*",
"args",
")",
":",
"m",
"=",
"getattr",
"(",
"java_obj",
",",
"name",
")",
"java_args",
"=",
"[",
"_py2java",
"(",
"sc",
",",
"arg",
")",
"for",
"arg",
"in",
"args",
"]",
"ret... | Method copied from pyspark.ml.wrapper. Uses private Spark APIs. | [
"Method",
"copied",
"from",
"pyspark",
".",
"ml",
".",
"wrapper",
".",
"Uses",
"private",
"Spark",
"APIs",
"."
] | python | train |
swharden/SWHLab | swhlab/core.py | https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/swhlab/core.py#L300-L307 | def get_protocol_sequence(self,sweep):
"""
given a sweep, return the protocol as condensed sequence.
This is better for comparing similarities and determining steps.
There should be no duplicate numbers.
"""
self.setsweep(sweep)
return list(self.protoSeqX),list(se... | [
"def",
"get_protocol_sequence",
"(",
"self",
",",
"sweep",
")",
":",
"self",
".",
"setsweep",
"(",
"sweep",
")",
"return",
"list",
"(",
"self",
".",
"protoSeqX",
")",
",",
"list",
"(",
"self",
".",
"protoSeqY",
")"
] | given a sweep, return the protocol as condensed sequence.
This is better for comparing similarities and determining steps.
There should be no duplicate numbers. | [
"given",
"a",
"sweep",
"return",
"the",
"protocol",
"as",
"condensed",
"sequence",
".",
"This",
"is",
"better",
"for",
"comparing",
"similarities",
"and",
"determining",
"steps",
".",
"There",
"should",
"be",
"no",
"duplicate",
"numbers",
"."
] | python | valid |
chimera0/accel-brain-code | Reinforcement-Learning/pyqlearning/deep_q_learning.py | https://github.com/chimera0/accel-brain-code/blob/03661f6f544bed656269fcd4b3c23c9061629daa/Reinforcement-Learning/pyqlearning/deep_q_learning.py#L166-L179 | def update_q(self, predicted_q_arr, reward_value_arr, next_max_q_arr):
'''
Update Q.
Args:
predicted_q_arr: `np.ndarray` of predicted Q-Values.
reward_value_arr: `np.ndarray` of reward values.
next_max_q_arr: `np.ndarray` of maximum Q-Values ... | [
"def",
"update_q",
"(",
"self",
",",
"predicted_q_arr",
",",
"reward_value_arr",
",",
"next_max_q_arr",
")",
":",
"# Update Q-Value.",
"return",
"predicted_q_arr",
"+",
"(",
"self",
".",
"alpha_value",
"*",
"(",
"reward_value_arr",
"+",
"(",
"self",
".",
"gamma_... | Update Q.
Args:
predicted_q_arr: `np.ndarray` of predicted Q-Values.
reward_value_arr: `np.ndarray` of reward values.
next_max_q_arr: `np.ndarray` of maximum Q-Values in next time step.
Returns:
`np.ndarray` of real Q-Values. | [
"Update",
"Q",
".",
"Args",
":",
"predicted_q_arr",
":",
"np",
".",
"ndarray",
"of",
"predicted",
"Q",
"-",
"Values",
".",
"reward_value_arr",
":",
"np",
".",
"ndarray",
"of",
"reward",
"values",
".",
"next_max_q_arr",
":",
"np",
".",
"ndarray",
"of",
"m... | python | train |
rueckstiess/mtools | mtools/mlogfilter/mlogfilter.py | https://github.com/rueckstiess/mtools/blob/a6a22910c3569c0c8a3908660ca218a4557e4249/mtools/mlogfilter/mlogfilter.py#L214-L236 | def logfile_generator(self):
"""Yield each line of the file, or the next line if several files."""
if not self.args['exclude']:
# ask all filters for a start_limit and fast-forward to the maximum
start_limits = [f.start_limit for f in self.filters
if h... | [
"def",
"logfile_generator",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"args",
"[",
"'exclude'",
"]",
":",
"# ask all filters for a start_limit and fast-forward to the maximum",
"start_limits",
"=",
"[",
"f",
".",
"start_limit",
"for",
"f",
"in",
"self",
"."... | Yield each line of the file, or the next line if several files. | [
"Yield",
"each",
"line",
"of",
"the",
"file",
"or",
"the",
"next",
"line",
"if",
"several",
"files",
"."
] | python | train |
CI-WATER/gsshapy | gsshapy/orm/spn.py | https://github.com/CI-WATER/gsshapy/blob/00fd4af0fd65f1614d75a52fe950a04fb0867f4c/gsshapy/orm/spn.py#L201-L209 | def _writeConnections(self, connections, fileObject):
"""
Write Connections to File Method
"""
for connection in connections:
fileObject.write('CONNECT %s %s %s\n' % (
connection.slinkNumber,
connection.upSjuncNumber,
connect... | [
"def",
"_writeConnections",
"(",
"self",
",",
"connections",
",",
"fileObject",
")",
":",
"for",
"connection",
"in",
"connections",
":",
"fileObject",
".",
"write",
"(",
"'CONNECT %s %s %s\\n'",
"%",
"(",
"connection",
".",
"slinkNumber",
",",
"connection",
"... | Write Connections to File Method | [
"Write",
"Connections",
"to",
"File",
"Method"
] | python | train |
aisthesis/pynance | pynance/tech/movave.py | https://github.com/aisthesis/pynance/blob/9eb0d78b60fe2a324ed328d026fedb6dbe8f7f41/pynance/tech/movave.py#L222-L259 | def ratio_to_ave(window, eqdata, **kwargs):
"""
Return values expressed as ratios to the average over some number
of prior sessions.
Parameters
----------
eqdata : DataFrame
Must contain a column with name matching `selection`, or, if
`selection` is not specified, a column named... | [
"def",
"ratio_to_ave",
"(",
"window",
",",
"eqdata",
",",
"*",
"*",
"kwargs",
")",
":",
"_selection",
"=",
"kwargs",
".",
"get",
"(",
"'selection'",
",",
"'Volume'",
")",
"_skipstartrows",
"=",
"kwargs",
".",
"get",
"(",
"'skipstartrows'",
",",
"0",
")",... | Return values expressed as ratios to the average over some number
of prior sessions.
Parameters
----------
eqdata : DataFrame
Must contain a column with name matching `selection`, or, if
`selection` is not specified, a column named 'Volume'
window : int
Interval over which t... | [
"Return",
"values",
"expressed",
"as",
"ratios",
"to",
"the",
"average",
"over",
"some",
"number",
"of",
"prior",
"sessions",
"."
] | python | train |
globus/globus-cli | globus_cli/commands/transfer.py | https://github.com/globus/globus-cli/blob/336675ff24da64c5ee487243f39ae39fc49a7e14/globus_cli/commands/transfer.py#L143-L268 | def transfer_command(
batch,
sync_level,
recursive,
destination,
source,
label,
preserve_mtime,
verify_checksum,
encrypt,
submission_id,
dry_run,
delete,
deadline,
skip_activation_check,
notify,
perf_cc,
perf_p,
perf_pp,
perf_udt,
):
"""
... | [
"def",
"transfer_command",
"(",
"batch",
",",
"sync_level",
",",
"recursive",
",",
"destination",
",",
"source",
",",
"label",
",",
"preserve_mtime",
",",
"verify_checksum",
",",
"encrypt",
",",
"submission_id",
",",
"dry_run",
",",
"delete",
",",
"deadline",
... | Executor for `globus transfer` | [
"Executor",
"for",
"globus",
"transfer"
] | python | train |
orb-framework/orb | orb/decorators.py | https://github.com/orb-framework/orb/blob/575be2689cb269e65a0a2678232ff940acc19e5a/orb/decorators.py#L12-L52 | def virtual(cls, **options):
"""
Allows for defining virtual columns and collectors on models -- these
are objects that are defined in code and not directly in a data store.
:param cls:
:param options:
:return:
"""
def wrapped(func):
param_name = inflection.underscore(func.__nam... | [
"def",
"virtual",
"(",
"cls",
",",
"*",
"*",
"options",
")",
":",
"def",
"wrapped",
"(",
"func",
")",
":",
"param_name",
"=",
"inflection",
".",
"underscore",
"(",
"func",
".",
"__name__",
")",
"options",
".",
"setdefault",
"(",
"'name'",
",",
"param_n... | Allows for defining virtual columns and collectors on models -- these
are objects that are defined in code and not directly in a data store.
:param cls:
:param options:
:return: | [
"Allows",
"for",
"defining",
"virtual",
"columns",
"and",
"collectors",
"on",
"models",
"--",
"these",
"are",
"objects",
"that",
"are",
"defined",
"in",
"code",
"and",
"not",
"directly",
"in",
"a",
"data",
"store",
"."
] | python | train |
fr33jc/bang | bang/stack.py | https://github.com/fr33jc/bang/blob/8f000713f88d2a9a8c1193b63ca10a6578560c16/bang/stack.py#L348-L376 | def show_inventory(self, pretty=False):
"""
Satisfies the ``--list`` portion of ansible's external inventory API.
Allows ``bang`` to be used as an external inventory script, for example
when running ad-hoc ops tasks. For more details, see:
http://ansible.cc/docs/api.html#extern... | [
"def",
"show_inventory",
"(",
"self",
",",
"pretty",
"=",
"False",
")",
":",
"inv_lists",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"groups_and_vars",
".",
"lists",
")",
"# sort the host lists to help consumers of the inventory (e.g. ansible",
"# playbooks)",
"f... | Satisfies the ``--list`` portion of ansible's external inventory API.
Allows ``bang`` to be used as an external inventory script, for example
when running ad-hoc ops tasks. For more details, see:
http://ansible.cc/docs/api.html#external-inventory-scripts | [
"Satisfies",
"the",
"--",
"list",
"portion",
"of",
"ansible",
"s",
"external",
"inventory",
"API",
"."
] | python | train |
aws/sagemaker-python-sdk | src/sagemaker/estimator.py | https://github.com/aws/sagemaker-python-sdk/blob/a9e724c7d3f5572b68c3903548c792a59d99799a/src/sagemaker/estimator.py#L204-L236 | def fit(self, inputs=None, wait=True, logs=True, job_name=None):
"""Train a model using the input training dataset.
The API calls the Amazon SageMaker CreateTrainingJob API to start model training.
The API uses configuration you provided to create the estimator and the
specified input t... | [
"def",
"fit",
"(",
"self",
",",
"inputs",
"=",
"None",
",",
"wait",
"=",
"True",
",",
"logs",
"=",
"True",
",",
"job_name",
"=",
"None",
")",
":",
"self",
".",
"_prepare_for_training",
"(",
"job_name",
"=",
"job_name",
")",
"self",
".",
"latest_trainin... | Train a model using the input training dataset.
The API calls the Amazon SageMaker CreateTrainingJob API to start model training.
The API uses configuration you provided to create the estimator and the
specified input training data to send the CreatingTrainingJob request to Amazon SageMaker.
... | [
"Train",
"a",
"model",
"using",
"the",
"input",
"training",
"dataset",
"."
] | python | train |
pandas-dev/pandas | pandas/core/strings.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/strings.py#L702-L732 | def _str_extract_noexpand(arr, pat, flags=0):
"""
Find groups in each string in the Series using passed regular
expression. This function is called from
str_extract(expand=False), and can return Series, DataFrame, or
Index.
"""
from pandas import DataFrame, Index
regex = re.compile(pat... | [
"def",
"_str_extract_noexpand",
"(",
"arr",
",",
"pat",
",",
"flags",
"=",
"0",
")",
":",
"from",
"pandas",
"import",
"DataFrame",
",",
"Index",
"regex",
"=",
"re",
".",
"compile",
"(",
"pat",
",",
"flags",
"=",
"flags",
")",
"groups_or_na",
"=",
"_gro... | Find groups in each string in the Series using passed regular
expression. This function is called from
str_extract(expand=False), and can return Series, DataFrame, or
Index. | [
"Find",
"groups",
"in",
"each",
"string",
"in",
"the",
"Series",
"using",
"passed",
"regular",
"expression",
".",
"This",
"function",
"is",
"called",
"from",
"str_extract",
"(",
"expand",
"=",
"False",
")",
"and",
"can",
"return",
"Series",
"DataFrame",
"or"... | python | train |
widdowquinn/pyADHoRe | pyadhore/iadhore.py | https://github.com/widdowquinn/pyADHoRe/blob/b2ebbf6ae9c6afe9262eb0e3d9cf395970e38533/pyadhore/iadhore.py#L194-L212 | def get_multiplicon_properties(self, value):
""" Return a dictionary describing multiplicon data:
id, parent, level, number_of_anchorpoints, profile_length,
is_redundant and the contributing genome segments
"""
sql = '''SELECT id, parent, level, number_of_anchorpoints,
... | [
"def",
"get_multiplicon_properties",
"(",
"self",
",",
"value",
")",
":",
"sql",
"=",
"'''SELECT id, parent, level, number_of_anchorpoints,\n profile_length, is_redundant\n FROM multiplicons WHERE id=:id'''",
"cur",
"=",
"self",
".",
"_dbconn",... | Return a dictionary describing multiplicon data:
id, parent, level, number_of_anchorpoints, profile_length,
is_redundant and the contributing genome segments | [
"Return",
"a",
"dictionary",
"describing",
"multiplicon",
"data",
":",
"id",
"parent",
"level",
"number_of_anchorpoints",
"profile_length",
"is_redundant",
"and",
"the",
"contributing",
"genome",
"segments"
] | python | train |
perseids-project/nemo_plokamos_plugin | nemo_plokamos_plugin/__init__.py | https://github.com/perseids-project/nemo_plokamos_plugin/blob/74a4ab719b1bda225394a51108bfce0f20404ff0/nemo_plokamos_plugin/__init__.py#L84-L103 | def r_plokamos_proxy(self):
""" Proxy to write to the annotation store
:return: response from the remote query store
:rtype: {str: Any}
"""
query = request.data
if self.is_authorized(query,NemoOauthPlugin.current_user()['uri']):
try:
resp = ... | [
"def",
"r_plokamos_proxy",
"(",
"self",
")",
":",
"query",
"=",
"request",
".",
"data",
"if",
"self",
".",
"is_authorized",
"(",
"query",
",",
"NemoOauthPlugin",
".",
"current_user",
"(",
")",
"[",
"'uri'",
"]",
")",
":",
"try",
":",
"resp",
"=",
"requ... | Proxy to write to the annotation store
:return: response from the remote query store
:rtype: {str: Any} | [
"Proxy",
"to",
"write",
"to",
"the",
"annotation",
"store"
] | python | train |
anthill/koala | koala/reader.py | https://github.com/anthill/koala/blob/393089fe081380506e73235db18a32b4e078d222/koala/reader.py#L41-L56 | def repair_central_directory(zipFile, is_file_instance): # source: https://bitbucket.org/openpyxl/openpyxl/src/93604327bce7aac5e8270674579af76d390e09c0/openpyxl/reader/excel.py?at=default&fileviewer=file-view-default
''' trims trailing data from the central directory
code taken from http://stackoverflow.com/a/7... | [
"def",
"repair_central_directory",
"(",
"zipFile",
",",
"is_file_instance",
")",
":",
"# source: https://bitbucket.org/openpyxl/openpyxl/src/93604327bce7aac5e8270674579af76d390e09c0/openpyxl/reader/excel.py?at=default&fileviewer=file-view-default",
"f",
"=",
"zipFile",
"if",
"is_file_insta... | trims trailing data from the central directory
code taken from http://stackoverflow.com/a/7457686/570216, courtesy of Uri Cohen | [
"trims",
"trailing",
"data",
"from",
"the",
"central",
"directory",
"code",
"taken",
"from",
"http",
":",
"//",
"stackoverflow",
".",
"com",
"/",
"a",
"/",
"7457686",
"/",
"570216",
"courtesy",
"of",
"Uri",
"Cohen"
] | python | train |
saltstack/salt | salt/engines/docker_events.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/docker_events.py#L42-L105 | def start(docker_url='unix://var/run/docker.sock',
timeout=CLIENT_TIMEOUT,
tag='salt/engines/docker_events',
filters=None):
'''
Scan for Docker events and fire events
Example Config
.. code-block:: yaml
engines:
- docker_events:
docker_url... | [
"def",
"start",
"(",
"docker_url",
"=",
"'unix://var/run/docker.sock'",
",",
"timeout",
"=",
"CLIENT_TIMEOUT",
",",
"tag",
"=",
"'salt/engines/docker_events'",
",",
"filters",
"=",
"None",
")",
":",
"if",
"__opts__",
".",
"get",
"(",
"'__role'",
")",
"==",
"'m... | Scan for Docker events and fire events
Example Config
.. code-block:: yaml
engines:
- docker_events:
docker_url: unix://var/run/docker.sock
filters:
event:
- start
- stop
- die
- oom
... | [
"Scan",
"for",
"Docker",
"events",
"and",
"fire",
"events"
] | python | train |
enricobacis/wos | wos/utils.py | https://github.com/enricobacis/wos/blob/a51f4d1a983c2c7529caac3e09606a432223630d/wos/utils.py#L34-L37 | def doi_to_wos(wosclient, doi):
"""Convert DOI to WOS identifier."""
results = query(wosclient, 'DO="%s"' % doi, './REC/UID', count=1)
return results[0].lstrip('WOS:') if results else None | [
"def",
"doi_to_wos",
"(",
"wosclient",
",",
"doi",
")",
":",
"results",
"=",
"query",
"(",
"wosclient",
",",
"'DO=\"%s\"'",
"%",
"doi",
",",
"'./REC/UID'",
",",
"count",
"=",
"1",
")",
"return",
"results",
"[",
"0",
"]",
".",
"lstrip",
"(",
"'WOS:'",
... | Convert DOI to WOS identifier. | [
"Convert",
"DOI",
"to",
"WOS",
"identifier",
"."
] | python | train |
broadinstitute/fiss | firecloud/fiss.py | https://github.com/broadinstitute/fiss/blob/dddf91547479506dbbafb69ec84d44dcc4a94ab4/firecloud/fiss.py#L468-L499 | def expand_fc_groups(users):
""" If user is a firecloud group, return all members of the group.
Caveat is that only group admins may do this.
"""
groups = None
for user in users:
fcgroup = None
if '@' not in user:
fcgroup = user
elif user.lower().endswith('@firecl... | [
"def",
"expand_fc_groups",
"(",
"users",
")",
":",
"groups",
"=",
"None",
"for",
"user",
"in",
"users",
":",
"fcgroup",
"=",
"None",
"if",
"'@'",
"not",
"in",
"user",
":",
"fcgroup",
"=",
"user",
"elif",
"user",
".",
"lower",
"(",
")",
".",
"endswith... | If user is a firecloud group, return all members of the group.
Caveat is that only group admins may do this. | [
"If",
"user",
"is",
"a",
"firecloud",
"group",
"return",
"all",
"members",
"of",
"the",
"group",
".",
"Caveat",
"is",
"that",
"only",
"group",
"admins",
"may",
"do",
"this",
"."
] | python | train |
deepmind/sonnet | sonnet/python/modules/basic_rnn.py | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/basic_rnn.py#L583-L649 | def _build(self, input_sequence, state):
"""Connects the BidirectionalRNN module into the graph.
Args:
input_sequence: tensor (time, batch, [feature_1, ..]). It must be
time_major.
state: tuple of states for the forward and backward cores.
Returns:
A dict with forward/backard s... | [
"def",
"_build",
"(",
"self",
",",
"input_sequence",
",",
"state",
")",
":",
"input_shape",
"=",
"input_sequence",
".",
"get_shape",
"(",
")",
"if",
"input_shape",
"[",
"0",
"]",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Time dimension of input (dim 0)... | Connects the BidirectionalRNN module into the graph.
Args:
input_sequence: tensor (time, batch, [feature_1, ..]). It must be
time_major.
state: tuple of states for the forward and backward cores.
Returns:
A dict with forward/backard states and output sequences:
"outputs":{... | [
"Connects",
"the",
"BidirectionalRNN",
"module",
"into",
"the",
"graph",
"."
] | python | train |
trentm/cmdln | examples/svn.py | https://github.com/trentm/cmdln/blob/55e980cf52c9b03e62d2349a7e62c9101d08ae10/examples/svn.py#L223-L238 | def do_copy(self, subcmd, opts, *args):
"""Duplicate something in working copy or repository, remembering history.
usage:
copy SRC DST
SRC and DST can each be either a working copy (WC) path or URL:
WC -> WC: copy and schedule for addition (with history)
... | [
"def",
"do_copy",
"(",
"self",
",",
"subcmd",
",",
"opts",
",",
"*",
"args",
")",
":",
"print",
"\"'svn %s' opts: %s\"",
"%",
"(",
"subcmd",
",",
"opts",
")",
"print",
"\"'svn %s' args: %s\"",
"%",
"(",
"subcmd",
",",
"args",
")"
] | Duplicate something in working copy or repository, remembering history.
usage:
copy SRC DST
SRC and DST can each be either a working copy (WC) path or URL:
WC -> WC: copy and schedule for addition (with history)
WC -> URL: immediately commit a copy of WC to... | [
"Duplicate",
"something",
"in",
"working",
"copy",
"or",
"repository",
"remembering",
"history",
"."
] | python | train |
klen/muffin-oauth | muffin_oauth.py | https://github.com/klen/muffin-oauth/blob/2d169840e2d08b9ba4a2f0915f99344c5f2c4aa6/muffin_oauth.py#L40-L49 | def client(self, client_name, **params):
"""Initialize OAuth client from registry."""
if client_name not in self.cfg.clients:
raise OAuthException('Unconfigured client: %s' % client_name)
if client_name not in ClientRegistry.clients:
raise OAuthException('Unsupported ser... | [
"def",
"client",
"(",
"self",
",",
"client_name",
",",
"*",
"*",
"params",
")",
":",
"if",
"client_name",
"not",
"in",
"self",
".",
"cfg",
".",
"clients",
":",
"raise",
"OAuthException",
"(",
"'Unconfigured client: %s'",
"%",
"client_name",
")",
"if",
"cli... | Initialize OAuth client from registry. | [
"Initialize",
"OAuth",
"client",
"from",
"registry",
"."
] | python | train |
MacHu-GWU/superjson-project | superjson/pkg/dateutil/parser.py | https://github.com/MacHu-GWU/superjson-project/blob/782ca4b2edbd4b4018b8cedee42eeae7c921b917/superjson/pkg/dateutil/parser.py#L623-L1069 | def _parse(self, timestr, dayfirst=None, yearfirst=None, fuzzy=False,
fuzzy_with_tokens=False):
"""
Private method which performs the heavy lifting of parsing, called from
``parse()``, which passes on its ``kwargs`` to this function.
:param timestr:
The string... | [
"def",
"_parse",
"(",
"self",
",",
"timestr",
",",
"dayfirst",
"=",
"None",
",",
"yearfirst",
"=",
"None",
",",
"fuzzy",
"=",
"False",
",",
"fuzzy_with_tokens",
"=",
"False",
")",
":",
"if",
"fuzzy_with_tokens",
":",
"fuzzy",
"=",
"True",
"info",
"=",
... | Private method which performs the heavy lifting of parsing, called from
``parse()``, which passes on its ``kwargs`` to this function.
:param timestr:
The string to parse.
:param dayfirst:
Whether to interpret the first value in an ambiguous 3-integer date
(e... | [
"Private",
"method",
"which",
"performs",
"the",
"heavy",
"lifting",
"of",
"parsing",
"called",
"from",
"parse",
"()",
"which",
"passes",
"on",
"its",
"kwargs",
"to",
"this",
"function",
"."
] | python | valid |
belbio/bel | bel/nanopub/nanopubs.py | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/nanopub/nanopubs.py#L108-L138 | def bel_edges(
self,
nanopub: Mapping[str, Any],
namespace_targets: Mapping[str, List[str]] = {},
rules: List[str] = [],
orthologize_target: str = None,
) -> List[Mapping[str, Any]]:
"""Create BEL Edges from BEL nanopub
Args:
nanopub (Mapping[str,... | [
"def",
"bel_edges",
"(",
"self",
",",
"nanopub",
":",
"Mapping",
"[",
"str",
",",
"Any",
"]",
",",
"namespace_targets",
":",
"Mapping",
"[",
"str",
",",
"List",
"[",
"str",
"]",
"]",
"=",
"{",
"}",
",",
"rules",
":",
"List",
"[",
"str",
"]",
"=",... | Create BEL Edges from BEL nanopub
Args:
nanopub (Mapping[str, Any]): bel nanopub
namespace_targets (Mapping[str, List[str]]): what namespaces to canonicalize
rules (List[str]): which computed edge rules to process, default is all,
look at BEL Specification yam... | [
"Create",
"BEL",
"Edges",
"from",
"BEL",
"nanopub"
] | python | train |
openstack/networking-cisco | networking_cisco/plugins/cisco/cfg_agent/device_drivers/iosxe/iosxe_routing_driver.py | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/cfg_agent/device_drivers/iosxe/iosxe_routing_driver.py#L600-L639 | def _check_response(self, rpc_obj, snippet_name, conf_str=None):
"""This function checks the rpc response object for status.
This function takes as input the response rpc_obj and the snippet name
that was executed. It parses it to see, if the last edit operation was
a success or not.
... | [
"def",
"_check_response",
"(",
"self",
",",
"rpc_obj",
",",
"snippet_name",
",",
"conf_str",
"=",
"None",
")",
":",
"LOG",
".",
"debug",
"(",
"\"RPCReply for %(snippet_name)s is %(rpc_obj)s\"",
",",
"{",
"'snippet_name'",
":",
"snippet_name",
",",
"'rpc_obj'",
":"... | This function checks the rpc response object for status.
This function takes as input the response rpc_obj and the snippet name
that was executed. It parses it to see, if the last edit operation was
a success or not.
<?xml version="1.0" encoding="UTF-8"?>
<rpc-reply mess... | [
"This",
"function",
"checks",
"the",
"rpc",
"response",
"object",
"for",
"status",
"."
] | python | train |
SheffieldML/GPy | GPy/util/netpbmfile.py | https://github.com/SheffieldML/GPy/blob/54c32d79d289d622fb18b898aee65a2a431d90cf/GPy/util/netpbmfile.py#L209-L235 | def _read_data(self, fh, byteorder='>'):
"""Return image data from open file as numpy array."""
fh.seek(len(self.header))
data = fh.read()
dtype = 'u1' if self.maxval < 256 else byteorder + 'u2'
depth = 1 if self.magicnum == b"P7 332" else self.depth
shape = [-1, self.hei... | [
"def",
"_read_data",
"(",
"self",
",",
"fh",
",",
"byteorder",
"=",
"'>'",
")",
":",
"fh",
".",
"seek",
"(",
"len",
"(",
"self",
".",
"header",
")",
")",
"data",
"=",
"fh",
".",
"read",
"(",
")",
"dtype",
"=",
"'u1'",
"if",
"self",
".",
"maxval... | Return image data from open file as numpy array. | [
"Return",
"image",
"data",
"from",
"open",
"file",
"as",
"numpy",
"array",
"."
] | python | train |
inasafe/inasafe | safe/utilities/utilities.py | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/utilities.py#L130-L163 | def humanise_seconds(seconds):
"""Utility function to humanise seconds value into e.g. 10 seconds ago.
The function will try to make a nice phrase of the seconds count
provided.
.. note:: Currently seconds that amount to days are not supported.
:param seconds: Mandatory seconds value e.g. 1100.
... | [
"def",
"humanise_seconds",
"(",
"seconds",
")",
":",
"days",
"=",
"seconds",
"/",
"(",
"3600",
"*",
"24",
")",
"day_modulus",
"=",
"seconds",
"%",
"(",
"3600",
"*",
"24",
")",
"hours",
"=",
"day_modulus",
"/",
"3600",
"hour_modulus",
"=",
"day_modulus",
... | Utility function to humanise seconds value into e.g. 10 seconds ago.
The function will try to make a nice phrase of the seconds count
provided.
.. note:: Currently seconds that amount to days are not supported.
:param seconds: Mandatory seconds value e.g. 1100.
:type seconds: int
:returns: A... | [
"Utility",
"function",
"to",
"humanise",
"seconds",
"value",
"into",
"e",
".",
"g",
".",
"10",
"seconds",
"ago",
"."
] | python | train |
roclark/sportsreference | sportsreference/mlb/roster.py | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/mlb/roster.py#L565-L689 | def _dataframe_fields(self):
"""
Creates a dictionary of all fields to include with DataFrame.
With the result of the calls to class properties changing based on the
class index value, the dictionary should be regenerated every time the
index is changed when the dataframe proper... | [
"def",
"_dataframe_fields",
"(",
"self",
")",
":",
"fields_to_include",
"=",
"{",
"'assists'",
":",
"self",
".",
"assists",
",",
"'at_bats'",
":",
"self",
".",
"at_bats",
",",
"'bases_on_balls'",
":",
"self",
".",
"bases_on_balls",
",",
"'batting_average'",
":... | Creates a dictionary of all fields to include with DataFrame.
With the result of the calls to class properties changing based on the
class index value, the dictionary should be regenerated every time the
index is changed when the dataframe property is requested.
Returns
-------... | [
"Creates",
"a",
"dictionary",
"of",
"all",
"fields",
"to",
"include",
"with",
"DataFrame",
"."
] | python | train |
pneff/wsgiservice | wsgiservice/resource.py | https://github.com/pneff/wsgiservice/blob/03c064ac2e8c53a1aac9c7b99970f23cf79e20f4/wsgiservice/resource.py#L177-L191 | def get_resource(self, resource, **kwargs):
"""Returns a new instance of the resource class passed in as resource.
This is a helper to make future-compatibility easier when new
arguments get added to the constructor.
:param resource: Resource class to instantiate. Gets called with the
... | [
"def",
"get_resource",
"(",
"self",
",",
"resource",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"resource",
"(",
"request",
"=",
"self",
".",
"request",
",",
"response",
"=",
"self",
".",
"response",
",",
"path_params",
"=",
"self",
".",
"path_params",... | Returns a new instance of the resource class passed in as resource.
This is a helper to make future-compatibility easier when new
arguments get added to the constructor.
:param resource: Resource class to instantiate. Gets called with the
named arguments as required for... | [
"Returns",
"a",
"new",
"instance",
"of",
"the",
"resource",
"class",
"passed",
"in",
"as",
"resource",
".",
"This",
"is",
"a",
"helper",
"to",
"make",
"future",
"-",
"compatibility",
"easier",
"when",
"new",
"arguments",
"get",
"added",
"to",
"the",
"const... | python | train |
KnowledgeLinks/rdfframework | rdfframework/connections/blazegraph.py | https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/connections/blazegraph.py#L132-L173 | def check_status(self):
""" tests both the ext_url and local_url to see if the database is
running
returns:
True if a connection can be made
False if the connection cannot me made
"""
def validate_namespace(self):
if not self.... | [
"def",
"check_status",
"(",
"self",
")",
":",
"def",
"validate_namespace",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"has_namespace",
"(",
"self",
".",
"namespace",
")",
":",
"log",
".",
"warning",
"(",
"format_multiline",
"(",
"[",
"\"\"",
",",
... | tests both the ext_url and local_url to see if the database is
running
returns:
True if a connection can be made
False if the connection cannot me made | [
"tests",
"both",
"the",
"ext_url",
"and",
"local_url",
"to",
"see",
"if",
"the",
"database",
"is",
"running"
] | python | train |
CiscoDevNet/webexteamssdk | webexteamssdk/api/messages.py | https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/api/messages.py#L137-L219 | def create(self, roomId=None, toPersonId=None, toPersonEmail=None,
text=None, markdown=None, files=None, **request_parameters):
"""Post a message, and optionally a attachment, to a room.
The files parameter is a list, which accepts multiple values to allow
for future expansion, b... | [
"def",
"create",
"(",
"self",
",",
"roomId",
"=",
"None",
",",
"toPersonId",
"=",
"None",
",",
"toPersonEmail",
"=",
"None",
",",
"text",
"=",
"None",
",",
"markdown",
"=",
"None",
",",
"files",
"=",
"None",
",",
"*",
"*",
"request_parameters",
")",
... | Post a message, and optionally a attachment, to a room.
The files parameter is a list, which accepts multiple values to allow
for future expansion, but currently only one file may be included with
the message.
Args:
roomId(basestring): The room ID.
toPersonId(ba... | [
"Post",
"a",
"message",
"and",
"optionally",
"a",
"attachment",
"to",
"a",
"room",
"."
] | python | test |
pdkit/pdkit | pdkit/tremor_processor.py | https://github.com/pdkit/pdkit/blob/c7120263da2071bb139815fbdb56ca77b544f340/pdkit/tremor_processor.py#L172-L190 | def amplitude_by_welch(self, data_frame):
"""
This methods uses the Welch method :cite:`Welch1967` to obtain the power spectral density, this is a robust
alternative to using fft_signal & amplitude
:param data_frame: the data frame
:type data_frame: pandas.DataF... | [
"def",
"amplitude_by_welch",
"(",
"self",
",",
"data_frame",
")",
":",
"frq",
",",
"Pxx_den",
"=",
"signal",
".",
"welch",
"(",
"data_frame",
".",
"filtered_signal",
".",
"values",
",",
"self",
".",
"sampling_frequency",
",",
"nperseg",
"=",
"self",
".",
"... | This methods uses the Welch method :cite:`Welch1967` to obtain the power spectral density, this is a robust
alternative to using fft_signal & amplitude
:param data_frame: the data frame
:type data_frame: pandas.DataFrame
:return: the ampl
:rtype ampl: float
... | [
"This",
"methods",
"uses",
"the",
"Welch",
"method",
":",
"cite",
":",
"Welch1967",
"to",
"obtain",
"the",
"power",
"spectral",
"density",
"this",
"is",
"a",
"robust",
"alternative",
"to",
"using",
"fft_signal",
"&",
"amplitude"
] | python | train |
pyrogram/pyrogram | pyrogram/vendor/typing/typing.py | https://github.com/pyrogram/pyrogram/blob/e7258a341ba905cfa86264c22040654db732ec1c/pyrogram/vendor/typing/typing.py#L1579-L1592 | def no_type_check_decorator(decorator):
"""Decorator to give another decorator the @no_type_check effect.
This wraps the decorator with something that wraps the decorated
function in @no_type_check.
"""
@functools.wraps(decorator)
def wrapped_decorator(*args, **kwds):
func = decorator(... | [
"def",
"no_type_check_decorator",
"(",
"decorator",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"decorator",
")",
"def",
"wrapped_decorator",
"(",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
":",
"func",
"=",
"decorator",
"(",
"*",
"args",
",",
"*",
"*... | Decorator to give another decorator the @no_type_check effect.
This wraps the decorator with something that wraps the decorated
function in @no_type_check. | [
"Decorator",
"to",
"give",
"another",
"decorator",
"the",
"@no_type_check",
"effect",
"."
] | python | train |
evhub/coconut | coconut/compiler/matching.py | https://github.com/evhub/coconut/blob/ff97177344e7604e89a0a98a977a87ed2a56fc6d/coconut/compiler/matching.py#L642-L650 | def build(self, stmts=None, set_check_var=True, invert=False):
"""Construct code for performing the match then executing stmts."""
out = ""
if set_check_var:
out += self.check_var + " = False\n"
out += self.out()
if stmts is not None:
out += "if " + ("not ... | [
"def",
"build",
"(",
"self",
",",
"stmts",
"=",
"None",
",",
"set_check_var",
"=",
"True",
",",
"invert",
"=",
"False",
")",
":",
"out",
"=",
"\"\"",
"if",
"set_check_var",
":",
"out",
"+=",
"self",
".",
"check_var",
"+",
"\" = False\\n\"",
"out",
"+="... | Construct code for performing the match then executing stmts. | [
"Construct",
"code",
"for",
"performing",
"the",
"match",
"then",
"executing",
"stmts",
"."
] | python | train |
mjirik/io3d | io3d/datawriter.py | https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/datawriter.py#L527-L542 | def saveOverlayToDicomCopy(input_dcmfilelist, output_dicom_dir, overlays,
crinfo, orig_shape):
""" Save overlay to dicom. """
from . import datawriter as dwriter
# import qmisc
if not os.path.exists(output_dicom_dir):
os.makedirs(output_dicom_dir)
import imtools.... | [
"def",
"saveOverlayToDicomCopy",
"(",
"input_dcmfilelist",
",",
"output_dicom_dir",
",",
"overlays",
",",
"crinfo",
",",
"orig_shape",
")",
":",
"from",
".",
"import",
"datawriter",
"as",
"dwriter",
"# import qmisc",
"if",
"not",
"os",
".",
"path",
".",
"exists"... | Save overlay to dicom. | [
"Save",
"overlay",
"to",
"dicom",
"."
] | python | train |
RudolfCardinal/pythonlib | cardinal_pythonlib/file_io.py | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/file_io.py#L104-L109 | def write_text(filename: str, text: str) -> None:
"""
Writes text to a file.
"""
with open(filename, 'w') as f: # type: TextIO
print(text, file=f) | [
"def",
"write_text",
"(",
"filename",
":",
"str",
",",
"text",
":",
"str",
")",
"->",
"None",
":",
"with",
"open",
"(",
"filename",
",",
"'w'",
")",
"as",
"f",
":",
"# type: TextIO",
"print",
"(",
"text",
",",
"file",
"=",
"f",
")"
] | Writes text to a file. | [
"Writes",
"text",
"to",
"a",
"file",
"."
] | python | train |
acorg/dark-matter | dark/blast/alignments.py | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/blast/alignments.py#L145-L193 | def getSubjectSequence(self, title):
"""
Obtain information about a subject sequence given its title.
This information is cached in self._subjectTitleToSubject. It can
be obtained from either a) an sqlite database (given via the
sqliteDatabaseFilename argument to __init__), b) t... | [
"def",
"getSubjectSequence",
"(",
"self",
",",
"title",
")",
":",
"if",
"self",
".",
"params",
".",
"application",
"in",
"{",
"'blastp'",
",",
"'blastx'",
"}",
":",
"readClass",
"=",
"AARead",
"else",
":",
"readClass",
"=",
"DNARead",
"if",
"self",
".",
... | Obtain information about a subject sequence given its title.
This information is cached in self._subjectTitleToSubject. It can
be obtained from either a) an sqlite database (given via the
sqliteDatabaseFilename argument to __init__), b) the FASTA that was
originally given to BLAST (via ... | [
"Obtain",
"information",
"about",
"a",
"subject",
"sequence",
"given",
"its",
"title",
"."
] | python | train |
gamechanger/mongothon | mongothon/queries.py | https://github.com/gamechanger/mongothon/blob/5305bdae8e38d09bfe7881f1edc99ac0a2e6b96b/mongothon/queries.py#L80-L89 | def cursor(self):
"""
Returns a cursor for the currently assembled query, creating it if
it doesn't already exist.
"""
if not self._active_cursor:
self._active_cursor = self.model.find(self.query,
self.projection or No... | [
"def",
"cursor",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_active_cursor",
":",
"self",
".",
"_active_cursor",
"=",
"self",
".",
"model",
".",
"find",
"(",
"self",
".",
"query",
",",
"self",
".",
"projection",
"or",
"None",
",",
"*",
"*",
... | Returns a cursor for the currently assembled query, creating it if
it doesn't already exist. | [
"Returns",
"a",
"cursor",
"for",
"the",
"currently",
"assembled",
"query",
"creating",
"it",
"if",
"it",
"doesn",
"t",
"already",
"exist",
"."
] | python | train |
mdiener/grace | grace/py27/slimit/parser.py | https://github.com/mdiener/grace/blob/2dab13a2cf636da5da989904c5885166fc94d36d/grace/py27/slimit/parser.py#L783-L793 | def p_conditional_expr(self, p):
"""
conditional_expr \
: logical_or_expr
| logical_or_expr CONDOP assignment_expr COLON assignment_expr
"""
if len(p) == 2:
p[0] = p[1]
else:
p[0] = ast.Conditional(
predicate=p[1], c... | [
"def",
"p_conditional_expr",
"(",
"self",
",",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
"==",
"2",
":",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"1",
"]",
"else",
":",
"p",
"[",
"0",
"]",
"=",
"ast",
".",
"Conditional",
"(",
"predicate",
"=",
"... | conditional_expr \
: logical_or_expr
| logical_or_expr CONDOP assignment_expr COLON assignment_expr | [
"conditional_expr",
"\\",
":",
"logical_or_expr",
"|",
"logical_or_expr",
"CONDOP",
"assignment_expr",
"COLON",
"assignment_expr"
] | python | train |
rameshg87/pyremotevbox | pyremotevbox/ZSI/wstools/c14n.py | https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/wstools/c14n.py#L224-L233 | def _do_text(self, node):
'''_do_text(self, node) -> None
Process a text or CDATA node. Render various special characters
as their C14N entity representations.'''
if not _in_subset(self.subset, node): return
s = string.replace(node.data, "&", "&")
s = string.replace(... | [
"def",
"_do_text",
"(",
"self",
",",
"node",
")",
":",
"if",
"not",
"_in_subset",
"(",
"self",
".",
"subset",
",",
"node",
")",
":",
"return",
"s",
"=",
"string",
".",
"replace",
"(",
"node",
".",
"data",
",",
"\"&\"",
",",
"\"&\"",
")",
"s",
... | _do_text(self, node) -> None
Process a text or CDATA node. Render various special characters
as their C14N entity representations. | [
"_do_text",
"(",
"self",
"node",
")",
"-",
">",
"None",
"Process",
"a",
"text",
"or",
"CDATA",
"node",
".",
"Render",
"various",
"special",
"characters",
"as",
"their",
"C14N",
"entity",
"representations",
"."
] | python | train |
xtuml/pyxtuml | xtuml/persist.py | https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/xtuml/persist.py#L185-L193 | def persist_instances(metamodel, path, mode='w'):
'''
Persist all instances in a *metamodel* by serializing them and saving to a
*path* on disk.
'''
with open(path, mode) as f:
for inst in metamodel.instances:
s = serialize_instance(inst)
f.write(s) | [
"def",
"persist_instances",
"(",
"metamodel",
",",
"path",
",",
"mode",
"=",
"'w'",
")",
":",
"with",
"open",
"(",
"path",
",",
"mode",
")",
"as",
"f",
":",
"for",
"inst",
"in",
"metamodel",
".",
"instances",
":",
"s",
"=",
"serialize_instance",
"(",
... | Persist all instances in a *metamodel* by serializing them and saving to a
*path* on disk. | [
"Persist",
"all",
"instances",
"in",
"a",
"*",
"metamodel",
"*",
"by",
"serializing",
"them",
"and",
"saving",
"to",
"a",
"*",
"path",
"*",
"on",
"disk",
"."
] | python | test |
viswa-swami/python-foscam | libpyfoscam/foscam.py | https://github.com/viswa-swami/python-foscam/blob/d76f2f7016959b7b758751637fad103c9032e488/libpyfoscam/foscam.py#L722-L729 | def set_h264_frm_ref_mode(self, mode=1, callback=None):
'''
Set frame shipping reference mode of H264 encode stream.
params:
`mode`: see docstr of meth::get_h264_frm_ref_mode
'''
params = {'mode': mode}
return self.execute_command('setH264FrmRefMode', params, ... | [
"def",
"set_h264_frm_ref_mode",
"(",
"self",
",",
"mode",
"=",
"1",
",",
"callback",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'mode'",
":",
"mode",
"}",
"return",
"self",
".",
"execute_command",
"(",
"'setH264FrmRefMode'",
",",
"params",
",",
"callback"... | Set frame shipping reference mode of H264 encode stream.
params:
`mode`: see docstr of meth::get_h264_frm_ref_mode | [
"Set",
"frame",
"shipping",
"reference",
"mode",
"of",
"H264",
"encode",
"stream",
".",
"params",
":",
"mode",
":",
"see",
"docstr",
"of",
"meth",
"::",
"get_h264_frm_ref_mode"
] | python | train |
KnowledgeLinks/rdfframework | rdfframework/rdfclass/rdfclass.py | https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/rdfclass/rdfclass.py#L32-L49 | def find(value):
"""
returns a dictionary of rdfclasses based on the a lowercase search
args:
value: the value to search by
"""
value = str(value).lower()
rtn_dict = RegistryDictionary()
for attr in dir(MODULE.rdfclass):
if value in attr.l... | [
"def",
"find",
"(",
"value",
")",
":",
"value",
"=",
"str",
"(",
"value",
")",
".",
"lower",
"(",
")",
"rtn_dict",
"=",
"RegistryDictionary",
"(",
")",
"for",
"attr",
"in",
"dir",
"(",
"MODULE",
".",
"rdfclass",
")",
":",
"if",
"value",
"in",
"attr... | returns a dictionary of rdfclasses based on the a lowercase search
args:
value: the value to search by | [
"returns",
"a",
"dictionary",
"of",
"rdfclasses",
"based",
"on",
"the",
"a",
"lowercase",
"search"
] | python | train |
DataBiosphere/toil | src/toil/lib/bioio.py | https://github.com/DataBiosphere/toil/blob/a8252277ff814e7bee0971139c2344f88e44b644/src/toil/lib/bioio.py#L199-L203 | def absSymPath(path):
"""like os.path.abspath except it doesn't dereference symlinks
"""
curr_path = os.getcwd()
return os.path.normpath(os.path.join(curr_path, path)) | [
"def",
"absSymPath",
"(",
"path",
")",
":",
"curr_path",
"=",
"os",
".",
"getcwd",
"(",
")",
"return",
"os",
".",
"path",
".",
"normpath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"curr_path",
",",
"path",
")",
")"
] | like os.path.abspath except it doesn't dereference symlinks | [
"like",
"os",
".",
"path",
".",
"abspath",
"except",
"it",
"doesn",
"t",
"dereference",
"symlinks"
] | python | train |
hyperledger/indy-plenum | stp_zmq/zstack.py | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/stp_zmq/zstack.py#L584-L629 | def connect(self,
name=None,
remoteId=None,
ha=None,
verKeyRaw=None,
publicKeyRaw=None):
"""
Connect to the node specified by name.
"""
if not name:
raise ValueError('Remote name should be specifi... | [
"def",
"connect",
"(",
"self",
",",
"name",
"=",
"None",
",",
"remoteId",
"=",
"None",
",",
"ha",
"=",
"None",
",",
"verKeyRaw",
"=",
"None",
",",
"publicKeyRaw",
"=",
"None",
")",
":",
"if",
"not",
"name",
":",
"raise",
"ValueError",
"(",
"'Remote n... | Connect to the node specified by name. | [
"Connect",
"to",
"the",
"node",
"specified",
"by",
"name",
"."
] | python | train |
carpedm20/fbchat | fbchat/_client.py | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L2372-L2381 | def muteThreadMentions(self, mute=True, thread_id=None):
"""
Mutes thread mentions
:param mute: Boolean. True to mute, False to unmute
:param thread_id: User/Group ID to mute. See :ref:`intro_threads`
"""
thread_id, thread_type = self._getThread(thread_id, None)
... | [
"def",
"muteThreadMentions",
"(",
"self",
",",
"mute",
"=",
"True",
",",
"thread_id",
"=",
"None",
")",
":",
"thread_id",
",",
"thread_type",
"=",
"self",
".",
"_getThread",
"(",
"thread_id",
",",
"None",
")",
"data",
"=",
"{",
"\"mentions_mute_mode\"",
":... | Mutes thread mentions
:param mute: Boolean. True to mute, False to unmute
:param thread_id: User/Group ID to mute. See :ref:`intro_threads` | [
"Mutes",
"thread",
"mentions"
] | python | train |
CalebBell/fluids | fluids/two_phase.py | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/two_phase.py#L2569-L2657 | def two_phase_dP_gravitational(angle, z, alpha_i, rho_li, rho_gi,
alpha_o=None, rho_lo=None, rho_go=None, g=g):
r'''This function handles calculation of two-phase liquid-gas pressure drop
due to gravitation for flow inside channels. This is a discrete
calculation for a segm... | [
"def",
"two_phase_dP_gravitational",
"(",
"angle",
",",
"z",
",",
"alpha_i",
",",
"rho_li",
",",
"rho_gi",
",",
"alpha_o",
"=",
"None",
",",
"rho_lo",
"=",
"None",
",",
"rho_go",
"=",
"None",
",",
"g",
"=",
"g",
")",
":",
"if",
"rho_lo",
"is",
"None"... | r'''This function handles calculation of two-phase liquid-gas pressure drop
due to gravitation for flow inside channels. This is a discrete
calculation for a segment with a known difference in elevation (and ideally
known inlet and outlet pressures so density dependence can be included).
.. math:... | [
"r",
"This",
"function",
"handles",
"calculation",
"of",
"two",
"-",
"phase",
"liquid",
"-",
"gas",
"pressure",
"drop",
"due",
"to",
"gravitation",
"for",
"flow",
"inside",
"channels",
".",
"This",
"is",
"a",
"discrete",
"calculation",
"for",
"a",
"segment",... | python | train |
vinci1it2000/schedula | examples/processing_chain/process.py | https://github.com/vinci1it2000/schedula/blob/addb9fd685be81544b796c51383ac00a31543ce9/examples/processing_chain/process.py#L13-L25 | def read_excel(input_fpath):
"""
Reads the excel file.
:param input_fpath:
Input file path.
:type input_fpath: str
:return:
Raw Data.
:rtype: dict
"""
return {k: v.values for k, v in pd.read_excel(input_fpath).items()} | [
"def",
"read_excel",
"(",
"input_fpath",
")",
":",
"return",
"{",
"k",
":",
"v",
".",
"values",
"for",
"k",
",",
"v",
"in",
"pd",
".",
"read_excel",
"(",
"input_fpath",
")",
".",
"items",
"(",
")",
"}"
] | Reads the excel file.
:param input_fpath:
Input file path.
:type input_fpath: str
:return:
Raw Data.
:rtype: dict | [
"Reads",
"the",
"excel",
"file",
"."
] | python | train |
aparo/pyes | pyes/scriptfields.py | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/scriptfields.py#L48-L59 | def add_parameter(self, field_name, param_name, param_value):
"""
Add a parameter to a field into script_fields
The ScriptFields object will be returned, so calls to this can be chained.
"""
try:
self.fields[field_name]['params'][param_name] = param_value
exc... | [
"def",
"add_parameter",
"(",
"self",
",",
"field_name",
",",
"param_name",
",",
"param_value",
")",
":",
"try",
":",
"self",
".",
"fields",
"[",
"field_name",
"]",
"[",
"'params'",
"]",
"[",
"param_name",
"]",
"=",
"param_value",
"except",
"Exception",
"as... | Add a parameter to a field into script_fields
The ScriptFields object will be returned, so calls to this can be chained. | [
"Add",
"a",
"parameter",
"to",
"a",
"field",
"into",
"script_fields"
] | python | train |
hobson/aima | aima/text.py | https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/text.py#L126-L138 | def query(self, query_text, n=10):
"""Return a list of n (score, docid) pairs for the best matches.
Also handle the special syntax for 'learn: command'."""
if query_text.startswith("learn:"):
doctext = os.popen(query_text[len("learn:"):], 'r').read()
self.index_document(d... | [
"def",
"query",
"(",
"self",
",",
"query_text",
",",
"n",
"=",
"10",
")",
":",
"if",
"query_text",
".",
"startswith",
"(",
"\"learn:\"",
")",
":",
"doctext",
"=",
"os",
".",
"popen",
"(",
"query_text",
"[",
"len",
"(",
"\"learn:\"",
")",
":",
"]",
... | Return a list of n (score, docid) pairs for the best matches.
Also handle the special syntax for 'learn: command'. | [
"Return",
"a",
"list",
"of",
"n",
"(",
"score",
"docid",
")",
"pairs",
"for",
"the",
"best",
"matches",
".",
"Also",
"handle",
"the",
"special",
"syntax",
"for",
"learn",
":",
"command",
"."
] | python | valid |
xflows/rdm | rdm/helpers.py | https://github.com/xflows/rdm/blob/d984e2a0297e5fa8d799953bbd0dba79b05d403d/rdm/helpers.py#L5-L18 | def arff_to_orange_table(arff):
'''
Convert a string in arff format to an Orange table.
:param arff: string in arff format
:return: Orange data table object constructed from the arff string
:rtype: orange.ExampleTable
'''
with tempfile.NamedTemporaryFile(suffix='.arff', delete=... | [
"def",
"arff_to_orange_table",
"(",
"arff",
")",
":",
"with",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"suffix",
"=",
"'.arff'",
",",
"delete",
"=",
"True",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"arff",
")",
"f",
".",
"flush",
"(",
")",
"ta... | Convert a string in arff format to an Orange table.
:param arff: string in arff format
:return: Orange data table object constructed from the arff string
:rtype: orange.ExampleTable | [
"Convert",
"a",
"string",
"in",
"arff",
"format",
"to",
"an",
"Orange",
"table",
"."
] | python | train |
tensorflow/tensorboard | tensorboard/plugins/image/images_plugin.py | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/image/images_plugin.py#L77-L93 | def is_active(self):
"""The images plugin is active iff any run has at least one relevant tag."""
if self._db_connection_provider:
# The plugin is active if one relevant tag can be found in the database.
db = self._db_connection_provider()
cursor = db.execute(
'''
SELECT 1
... | [
"def",
"is_active",
"(",
"self",
")",
":",
"if",
"self",
".",
"_db_connection_provider",
":",
"# The plugin is active if one relevant tag can be found in the database.",
"db",
"=",
"self",
".",
"_db_connection_provider",
"(",
")",
"cursor",
"=",
"db",
".",
"execute",
... | The images plugin is active iff any run has at least one relevant tag. | [
"The",
"images",
"plugin",
"is",
"active",
"iff",
"any",
"run",
"has",
"at",
"least",
"one",
"relevant",
"tag",
"."
] | python | train |
anteater/anteater | anteater/src/get_lists.py | https://github.com/anteater/anteater/blob/a980adbed8563ef92494f565acd371e91f50f155/anteater/src/get_lists.py#L209-L232 | def ignore_directories(self, project):
""" Gathers a list of directories to ignore """
project_list = False
try:
ignore_directories = il['ignore_directories']
except KeyError:
logger.error('Key Error processing ignore_directories list values')
try:
... | [
"def",
"ignore_directories",
"(",
"self",
",",
"project",
")",
":",
"project_list",
"=",
"False",
"try",
":",
"ignore_directories",
"=",
"il",
"[",
"'ignore_directories'",
"]",
"except",
"KeyError",
":",
"logger",
".",
"error",
"(",
"'Key Error processing ignore_d... | Gathers a list of directories to ignore | [
"Gathers",
"a",
"list",
"of",
"directories",
"to",
"ignore"
] | python | train |
erdc/RAPIDpy | RAPIDpy/gis/muskingum.py | https://github.com/erdc/RAPIDpy/blob/50e14e130554b254a00ff23b226cd7e4c6cfe91a/RAPIDpy/gis/muskingum.py#L227-L259 | def CreateMuskingumKFile(lambda_k,
in_kfac_file,
out_k_file):
"""
Creates muskingum k file from kfac file.
Parameters
----------
lambda_k: float
The value for lambda given from RAPID after the calibration process.
If no calibration h... | [
"def",
"CreateMuskingumKFile",
"(",
"lambda_k",
",",
"in_kfac_file",
",",
"out_k_file",
")",
":",
"kfac_table",
"=",
"csv_to_list",
"(",
"in_kfac_file",
")",
"with",
"open_csv",
"(",
"out_k_file",
",",
"'w'",
")",
"as",
"kfile",
":",
"k_writer",
"=",
"csv_writ... | Creates muskingum k file from kfac file.
Parameters
----------
lambda_k: float
The value for lambda given from RAPID after the calibration process.
If no calibration has been performed, 0.35 is reasonable.
in_kfac_file: str
The path to the input kfac file.
out_k_file: str
... | [
"Creates",
"muskingum",
"k",
"file",
"from",
"kfac",
"file",
"."
] | python | train |
ultrabug/py3status | py3status/autodoc.py | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/autodoc.py#L300-L317 | def create_py3_docs():
"""
Create the include files for py3 documentation.
"""
# we want the correct .rst 'type' for our data
trans = {"methods": "function", "exceptions": "exception", "constants": "attribute"}
data = get_py3_info()
for k, v in data.items():
output = []
for n... | [
"def",
"create_py3_docs",
"(",
")",
":",
"# we want the correct .rst 'type' for our data",
"trans",
"=",
"{",
"\"methods\"",
":",
"\"function\"",
",",
"\"exceptions\"",
":",
"\"exception\"",
",",
"\"constants\"",
":",
"\"attribute\"",
"}",
"data",
"=",
"get_py3_info",
... | Create the include files for py3 documentation. | [
"Create",
"the",
"include",
"files",
"for",
"py3",
"documentation",
"."
] | python | train |
fastai/fastai | fastai/train.py | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/train.py#L66-L75 | def on_epoch_end(self, n_epochs:int, last_metrics:MetricsList, **kwargs)->bool:
"If we have `last_metrics` plot them in our pbar graph"
if last_metrics is not None and np.any(last_metrics):
rec = self.learn.recorder
iters = range_of(rec.losses)
val_iter = np.array(rec... | [
"def",
"on_epoch_end",
"(",
"self",
",",
"n_epochs",
":",
"int",
",",
"last_metrics",
":",
"MetricsList",
",",
"*",
"*",
"kwargs",
")",
"->",
"bool",
":",
"if",
"last_metrics",
"is",
"not",
"None",
"and",
"np",
".",
"any",
"(",
"last_metrics",
")",
":"... | If we have `last_metrics` plot them in our pbar graph | [
"If",
"we",
"have",
"last_metrics",
"plot",
"them",
"in",
"our",
"pbar",
"graph"
] | python | train |
pyviz/holoviews | setup.py | https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/setup.py#L55-L77 | def embed_version(basepath, ref='v0.2.2'):
"""
Autover is purely a build time dependency in all cases (conda and
pip) except for when you use pip's remote git support [git+url] as
1) you need a dynamically changing version and 2) the environment
starts off clean with zero dependencies installed.
... | [
"def",
"embed_version",
"(",
"basepath",
",",
"ref",
"=",
"'v0.2.2'",
")",
":",
"import",
"io",
",",
"zipfile",
",",
"importlib",
"try",
":",
"from",
"urllib",
".",
"request",
"import",
"urlopen",
"except",
":",
"from",
"urllib",
"import",
"urlopen",
"try"... | Autover is purely a build time dependency in all cases (conda and
pip) except for when you use pip's remote git support [git+url] as
1) you need a dynamically changing version and 2) the environment
starts off clean with zero dependencies installed.
This function acts as a fallback to make Version avail... | [
"Autover",
"is",
"purely",
"a",
"build",
"time",
"dependency",
"in",
"all",
"cases",
"(",
"conda",
"and",
"pip",
")",
"except",
"for",
"when",
"you",
"use",
"pip",
"s",
"remote",
"git",
"support",
"[",
"git",
"+",
"url",
"]",
"as",
"1",
")",
"you",
... | python | train |
saltstack/salt | salt/returners/pgjsonb.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/pgjsonb.py#L347-L358 | def get_load(jid):
'''
Return the load data that marks a specified jid
'''
with _get_serv(ret=None, commit=True) as cur:
sql = '''SELECT load FROM jids WHERE jid = %s;'''
cur.execute(sql, (jid,))
data = cur.fetchone()
if data:
return data[0]
return {} | [
"def",
"get_load",
"(",
"jid",
")",
":",
"with",
"_get_serv",
"(",
"ret",
"=",
"None",
",",
"commit",
"=",
"True",
")",
"as",
"cur",
":",
"sql",
"=",
"'''SELECT load FROM jids WHERE jid = %s;'''",
"cur",
".",
"execute",
"(",
"sql",
",",
"(",
"jid",
",",
... | Return the load data that marks a specified jid | [
"Return",
"the",
"load",
"data",
"that",
"marks",
"a",
"specified",
"jid"
] | python | train |
OLC-Bioinformatics/sipprverse | pointfinder/PointFinder.py | https://github.com/OLC-Bioinformatics/sipprverse/blob/d4f10cdf8e1a39dac0953db61c21c97efc6006de/pointfinder/PointFinder.py#L933-L1046 | def write_output(gene, gene_name, mis_matches, known_mutations, known_stop_codon, unknown_flag, GENES):
"""
This function takes a gene name a list of mis matches found betreewn subject and query of
this gene, the dictionary of known mutation in the point finder database, and the flag telling
weather th... | [
"def",
"write_output",
"(",
"gene",
",",
"gene_name",
",",
"mis_matches",
",",
"known_mutations",
",",
"known_stop_codon",
",",
"unknown_flag",
",",
"GENES",
")",
":",
"RNA",
"=",
"False",
"known_header",
"=",
"\"Mutation\\tNucleotide change\\tAmino acid change\\tResist... | This function takes a gene name a list of mis matches found betreewn subject and query of
this gene, the dictionary of known mutation in the point finder database, and the flag telling
weather the user wants unknown mutations to be reported.
All mis matches are looked up in the known mutation dict to se if... | [
"This",
"function",
"takes",
"a",
"gene",
"name",
"a",
"list",
"of",
"mis",
"matches",
"found",
"betreewn",
"subject",
"and",
"query",
"of",
"this",
"gene",
"the",
"dictionary",
"of",
"known",
"mutation",
"in",
"the",
"point",
"finder",
"database",
"and",
... | python | train |
log2timeline/plaso | plaso/multi_processing/task_manager.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/multi_processing/task_manager.py#L76-L98 | def PushTask(self, task):
"""Pushes a task onto the heap.
Args:
task (Task): task.
Raises:
ValueError: if the size of the storage file is not set in the task.
"""
storage_file_size = getattr(task, 'storage_file_size', None)
if not storage_file_size:
raise ValueError('Task sto... | [
"def",
"PushTask",
"(",
"self",
",",
"task",
")",
":",
"storage_file_size",
"=",
"getattr",
"(",
"task",
",",
"'storage_file_size'",
",",
"None",
")",
"if",
"not",
"storage_file_size",
":",
"raise",
"ValueError",
"(",
"'Task storage file size not set.'",
")",
"i... | Pushes a task onto the heap.
Args:
task (Task): task.
Raises:
ValueError: if the size of the storage file is not set in the task. | [
"Pushes",
"a",
"task",
"onto",
"the",
"heap",
"."
] | python | train |
cltk/cltk | cltk/text_reuse/text_reuse.py | https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/text_reuse/text_reuse.py#L92-L113 | def compare_sliding_window(self, str_a, str_b, window_length=50, curse_forward=20):
"""
Compare two strings with a sliding window method based on window_length and curse_forward values
:param string_a: str
:param string_b: str
:param window_length: int
:param curse_forwar... | [
"def",
"compare_sliding_window",
"(",
"self",
",",
"str_a",
",",
"str_b",
",",
"window_length",
"=",
"50",
",",
"curse_forward",
"=",
"20",
")",
":",
"if",
"self",
".",
"stem_words",
":",
"stemmer",
"=",
"Stemmer",
"(",
")",
"str_a",
"=",
"stemmer",
".",... | Compare two strings with a sliding window method based on window_length and curse_forward values
:param string_a: str
:param string_b: str
:param window_length: int
:param curse_forward: int
:return: list [[Comparison]] | [
"Compare",
"two",
"strings",
"with",
"a",
"sliding",
"window",
"method",
"based",
"on",
"window_length",
"and",
"curse_forward",
"values",
":",
"param",
"string_a",
":",
"str",
":",
"param",
"string_b",
":",
"str",
":",
"param",
"window_length",
":",
"int",
... | python | train |
synw/dataswim | dataswim/data/select.py | https://github.com/synw/dataswim/blob/4a4a53f80daa7cd8e8409d76a19ce07296269da2/dataswim/data/select.py#L41-L49 | def unique_(self, col):
"""
Returns unique values in a column
"""
try:
df = self.df.drop_duplicates(subset=[col], inplace=False)
return list(df[col])
except Exception as e:
self.err(e, "Can not select unique data") | [
"def",
"unique_",
"(",
"self",
",",
"col",
")",
":",
"try",
":",
"df",
"=",
"self",
".",
"df",
".",
"drop_duplicates",
"(",
"subset",
"=",
"[",
"col",
"]",
",",
"inplace",
"=",
"False",
")",
"return",
"list",
"(",
"df",
"[",
"col",
"]",
")",
"e... | Returns unique values in a column | [
"Returns",
"unique",
"values",
"in",
"a",
"column"
] | python | train |
inveniosoftware/invenio-webhooks | invenio_webhooks/views.py | https://github.com/inveniosoftware/invenio-webhooks/blob/f407cb2245464543ee474a81189fb9d3978bdde5/invenio_webhooks/views.py#L168-L171 | def get(self, receiver_id=None, event_id=None):
"""Handle GET request."""
event = self._get_event(receiver_id, event_id)
return make_response(event) | [
"def",
"get",
"(",
"self",
",",
"receiver_id",
"=",
"None",
",",
"event_id",
"=",
"None",
")",
":",
"event",
"=",
"self",
".",
"_get_event",
"(",
"receiver_id",
",",
"event_id",
")",
"return",
"make_response",
"(",
"event",
")"
] | Handle GET request. | [
"Handle",
"GET",
"request",
"."
] | python | train |
lemieuxl/pyGenClean | pyGenClean/PlateBias/plate_bias.py | https://github.com/lemieuxl/pyGenClean/blob/6173a48ccc0cf3a3bd711b1f2a1fa16248b8bf55/pyGenClean/PlateBias/plate_bias.py#L34-L73 | def main(argString=None):
"""The main function of this module.
:param argString: the options.
:type argString: list
These are the steps:
1. Runs a plate bias analysis using Plink
(:py:func:`executePlateBiasAnalysis`).
2. Extracts the list of significant markers after plate bias analys... | [
"def",
"main",
"(",
"argString",
"=",
"None",
")",
":",
"# Getting and checking the options",
"args",
"=",
"parseArgs",
"(",
"argString",
")",
"checkArgs",
"(",
"args",
")",
"logger",
".",
"info",
"(",
"\"Options used:\"",
")",
"for",
"key",
",",
"value",
"i... | The main function of this module.
:param argString: the options.
:type argString: list
These are the steps:
1. Runs a plate bias analysis using Plink
(:py:func:`executePlateBiasAnalysis`).
2. Extracts the list of significant markers after plate bias analysis
(:py:func:`extractSigni... | [
"The",
"main",
"function",
"of",
"this",
"module",
"."
] | python | train |
SuperCowPowers/bat | bat/live_simulator.py | https://github.com/SuperCowPowers/bat/blob/069e6bc52843dc07760969c531cc442ca7da8e0c/bat/live_simulator.py#L48-L67 | def readrows(self):
"""Using the BroLogReader this method yields each row of the log file
replacing timestamps, looping and emitting rows based on EPS rate
"""
# Loop forever or until max_rows is reached
num_rows = 0
while True:
# Yield the rows from the ... | [
"def",
"readrows",
"(",
"self",
")",
":",
"# Loop forever or until max_rows is reached",
"num_rows",
"=",
"0",
"while",
"True",
":",
"# Yield the rows from the internal reader",
"for",
"row",
"in",
"self",
".",
"log_reader",
".",
"readrows",
"(",
")",
":",
"yield",
... | Using the BroLogReader this method yields each row of the log file
replacing timestamps, looping and emitting rows based on EPS rate | [
"Using",
"the",
"BroLogReader",
"this",
"method",
"yields",
"each",
"row",
"of",
"the",
"log",
"file",
"replacing",
"timestamps",
"looping",
"and",
"emitting",
"rows",
"based",
"on",
"EPS",
"rate"
] | python | train |
graphql-python/graphql-core-next | graphql/language/parser.py | https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/language/parser.py#L928-L940 | def parse_union_type_extension(lexer: Lexer) -> UnionTypeExtensionNode:
"""UnionTypeExtension"""
start = lexer.token
expect_keyword(lexer, "extend")
expect_keyword(lexer, "union")
name = parse_name(lexer)
directives = parse_directives(lexer, True)
types = parse_union_member_types(lexer)
... | [
"def",
"parse_union_type_extension",
"(",
"lexer",
":",
"Lexer",
")",
"->",
"UnionTypeExtensionNode",
":",
"start",
"=",
"lexer",
".",
"token",
"expect_keyword",
"(",
"lexer",
",",
"\"extend\"",
")",
"expect_keyword",
"(",
"lexer",
",",
"\"union\"",
")",
"name",... | UnionTypeExtension | [
"UnionTypeExtension"
] | python | train |
williballenthin/python-pyqt5-hexview | hexview/hexview.py | https://github.com/williballenthin/python-pyqt5-hexview/blob/461feb286dfde60bdbc12b3fb772d650f4b8ba71/hexview/hexview.py#L252-L255 | def _bselect(self, selection, start_bindex, end_bindex):
""" add the given buffer indices to the given QItemSelection, both byte and char panes """
selection.select(self._model.index2qindexb(start_bindex), self._model.index2qindexb(end_bindex))
selection.select(self._model.index2qindexc(start_bi... | [
"def",
"_bselect",
"(",
"self",
",",
"selection",
",",
"start_bindex",
",",
"end_bindex",
")",
":",
"selection",
".",
"select",
"(",
"self",
".",
"_model",
".",
"index2qindexb",
"(",
"start_bindex",
")",
",",
"self",
".",
"_model",
".",
"index2qindexb",
"(... | add the given buffer indices to the given QItemSelection, both byte and char panes | [
"add",
"the",
"given",
"buffer",
"indices",
"to",
"the",
"given",
"QItemSelection",
"both",
"byte",
"and",
"char",
"panes"
] | python | train |
gitpython-developers/GitPython | git/objects/fun.py | https://github.com/gitpython-developers/GitPython/blob/1f66e25c25cde2423917ee18c4704fff83b837d1/git/objects/fun.py#L120-L185 | def traverse_trees_recursive(odb, tree_shas, path_prefix):
"""
:return: list with entries according to the given binary tree-shas.
The result is encoded in a list
of n tuple|None per blob/commit, (n == len(tree_shas)), where
* [0] == 20 byte sha
* [1] == mode as int
* [2]... | [
"def",
"traverse_trees_recursive",
"(",
"odb",
",",
"tree_shas",
",",
"path_prefix",
")",
":",
"trees_data",
"=",
"[",
"]",
"nt",
"=",
"len",
"(",
"tree_shas",
")",
"for",
"tree_sha",
"in",
"tree_shas",
":",
"if",
"tree_sha",
"is",
"None",
":",
"data",
"... | :return: list with entries according to the given binary tree-shas.
The result is encoded in a list
of n tuple|None per blob/commit, (n == len(tree_shas)), where
* [0] == 20 byte sha
* [1] == mode as int
* [2] == path relative to working tree root
The entry tuple is None ... | [
":",
"return",
":",
"list",
"with",
"entries",
"according",
"to",
"the",
"given",
"binary",
"tree",
"-",
"shas",
".",
"The",
"result",
"is",
"encoded",
"in",
"a",
"list",
"of",
"n",
"tuple|None",
"per",
"blob",
"/",
"commit",
"(",
"n",
"==",
"len",
"... | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.