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 |
|---|---|---|---|---|---|---|---|---|
wandb/client | wandb/vendor/prompt_toolkit/layout/controls.py | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/layout/controls.py#L532-L588 | def _create_get_processed_line_func(self, cli, document):
"""
Create a function that takes a line number of the current document and
returns a _ProcessedLine(processed_tokens, source_to_display, display_to_source)
tuple.
"""
def transform(lineno, tokens):
" Tr... | [
"def",
"_create_get_processed_line_func",
"(",
"self",
",",
"cli",
",",
"document",
")",
":",
"def",
"transform",
"(",
"lineno",
",",
"tokens",
")",
":",
"\" Transform the tokens for a given line number. \"",
"source_to_display_functions",
"=",
"[",
"]",
"display_to_sou... | Create a function that takes a line number of the current document and
returns a _ProcessedLine(processed_tokens, source_to_display, display_to_source)
tuple. | [
"Create",
"a",
"function",
"that",
"takes",
"a",
"line",
"number",
"of",
"the",
"current",
"document",
"and",
"returns",
"a",
"_ProcessedLine",
"(",
"processed_tokens",
"source_to_display",
"display_to_source",
")",
"tuple",
"."
] | python | train |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_threshold_monitor.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_threshold_monitor.py#L25-L35 | def threshold_monitor_hidden_threshold_monitor_sfp_pause(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
threshold_monitor_hidden = ET.SubElement(config, "threshold-monitor-hidden", xmlns="urn:brocade.com:mgmt:brocade-threshold-monitor")
threshold_monito... | [
"def",
"threshold_monitor_hidden_threshold_monitor_sfp_pause",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"threshold_monitor_hidden",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"threshold-m... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train |
senaite/senaite.core | bika/lims/upgrade/v01_02_009.py | https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/upgrade/v01_02_009.py#L115-L132 | def reindex_client_local_owner_permissions(portal):
"""https://github.com/senaite/senaite.core/issues/957 Reindex bika_setup
objects located in clients to give proper permissions to client contacts.
"""
start = time.time()
bsc = portal.bika_setup_catalog
uids = [c.UID() for c in portal.clients.o... | [
"def",
"reindex_client_local_owner_permissions",
"(",
"portal",
")",
":",
"start",
"=",
"time",
".",
"time",
"(",
")",
"bsc",
"=",
"portal",
".",
"bika_setup_catalog",
"uids",
"=",
"[",
"c",
".",
"UID",
"(",
")",
"for",
"c",
"in",
"portal",
".",
"clients... | https://github.com/senaite/senaite.core/issues/957 Reindex bika_setup
objects located in clients to give proper permissions to client contacts. | [
"https",
":",
"//",
"github",
".",
"com",
"/",
"senaite",
"/",
"senaite",
".",
"core",
"/",
"issues",
"/",
"957",
"Reindex",
"bika_setup",
"objects",
"located",
"in",
"clients",
"to",
"give",
"proper",
"permissions",
"to",
"client",
"contacts",
"."
] | python | train |
weso/CWR-DataApi | data_cwr/accessor.py | https://github.com/weso/CWR-DataApi/blob/f3b6ba8308c901b6ab87073c155c08e30692333c/data_cwr/accessor.py#L39-L53 | def read_csv_file(self, file_name):
"""
Parses a CSV file into a list.
:param file_name: name of the CSV file
:return: a list with the file's contents
"""
result = []
with open(os.path.join(self.__path(), os.path.basename(file_name)),
'rt') as c... | [
"def",
"read_csv_file",
"(",
"self",
",",
"file_name",
")",
":",
"result",
"=",
"[",
"]",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"__path",
"(",
")",
",",
"os",
".",
"path",
".",
"basename",
"(",
"file_name",
")",
"... | Parses a CSV file into a list.
:param file_name: name of the CSV file
:return: a list with the file's contents | [
"Parses",
"a",
"CSV",
"file",
"into",
"a",
"list",
"."
] | python | train |
mixmastamyk/console | console/windows.py | https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/windows.py#L206-L215 | def get_title():
''' Returns console title string.
https://docs.microsoft.com/en-us/windows/console/getconsoletitle
'''
MAX_LEN = 256
buffer_ = create_unicode_buffer(MAX_LEN)
kernel32.GetConsoleTitleW(buffer_, MAX_LEN)
log.debug('%s', buffer_.value)
return buffer_.value | [
"def",
"get_title",
"(",
")",
":",
"MAX_LEN",
"=",
"256",
"buffer_",
"=",
"create_unicode_buffer",
"(",
"MAX_LEN",
")",
"kernel32",
".",
"GetConsoleTitleW",
"(",
"buffer_",
",",
"MAX_LEN",
")",
"log",
".",
"debug",
"(",
"'%s'",
",",
"buffer_",
".",
"value"... | Returns console title string.
https://docs.microsoft.com/en-us/windows/console/getconsoletitle | [
"Returns",
"console",
"title",
"string",
"."
] | python | train |
arviz-devs/arviz | arviz/plots/plot_utils.py | https://github.com/arviz-devs/arviz/blob/d04d8da07f029fd2931f48d2f7f324cf393e5277/arviz/plots/plot_utils.py#L87-L126 | def get_bins(values):
"""
Automatically compute the number of bins for discrete variables.
Parameters
----------
values = numpy array
values
Returns
-------
array with the bins
Notes
-----
Computes the width of the bins by taking the maximun of the Sturges and the ... | [
"def",
"get_bins",
"(",
"values",
")",
":",
"x_min",
"=",
"values",
".",
"min",
"(",
")",
".",
"astype",
"(",
"int",
")",
"x_max",
"=",
"values",
".",
"max",
"(",
")",
".",
"astype",
"(",
"int",
")",
"# Sturges histogram bin estimator",
"bins_sturges",
... | Automatically compute the number of bins for discrete variables.
Parameters
----------
values = numpy array
values
Returns
-------
array with the bins
Notes
-----
Computes the width of the bins by taking the maximun of the Sturges and the Freedman-Diaconis
estimators. ... | [
"Automatically",
"compute",
"the",
"number",
"of",
"bins",
"for",
"discrete",
"variables",
"."
] | python | train |
ethereum/web3.py | web3/contract.py | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/contract.py#L1427-L1454 | def build_transaction_for_function(
address,
web3,
function_name=None,
transaction=None,
contract_abi=None,
fn_abi=None,
*args,
**kwargs):
"""Builds a dictionary with the fields required to make the given transaction
Don't call this directly, inst... | [
"def",
"build_transaction_for_function",
"(",
"address",
",",
"web3",
",",
"function_name",
"=",
"None",
",",
"transaction",
"=",
"None",
",",
"contract_abi",
"=",
"None",
",",
"fn_abi",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"... | Builds a dictionary with the fields required to make the given transaction
Don't call this directly, instead use :meth:`Contract.buildTransaction`
on your contract instance. | [
"Builds",
"a",
"dictionary",
"with",
"the",
"fields",
"required",
"to",
"make",
"the",
"given",
"transaction"
] | python | train |
mar10/wsgidav | wsgidav/samples/virtual_dav_provider.py | https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/samples/virtual_dav_provider.py#L323-L332 | def handle_copy(self, dest_path, depth_infinity):
"""Change semantic of COPY to add resource tags."""
# destPath must be '/by_tag/<tag>/<resname>'
if "/by_tag/" not in dest_path:
raise DAVError(HTTP_FORBIDDEN)
catType, tag, _rest = util.save_split(dest_path.strip("/"), "/", 2... | [
"def",
"handle_copy",
"(",
"self",
",",
"dest_path",
",",
"depth_infinity",
")",
":",
"# destPath must be '/by_tag/<tag>/<resname>'",
"if",
"\"/by_tag/\"",
"not",
"in",
"dest_path",
":",
"raise",
"DAVError",
"(",
"HTTP_FORBIDDEN",
")",
"catType",
",",
"tag",
",",
... | Change semantic of COPY to add resource tags. | [
"Change",
"semantic",
"of",
"COPY",
"to",
"add",
"resource",
"tags",
"."
] | python | valid |
inasafe/inasafe | safe/common/dynamic_translations.py | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/common/dynamic_translations.py#L54-L239 | def dynamic_translations():
"""These listed here so they get translated apriori to loading data."""
# Bangunan DKI
tr('DKI buildings')
# Banjir seperti 2007
tr('Jakarta 2007 flood')
tr('A flood in Jakarta like in 2007')
tr('Jakarta flood like 2007 with pump failure at Pluit, Ancol and Sunter... | [
"def",
"dynamic_translations",
"(",
")",
":",
"# Bangunan DKI",
"tr",
"(",
"'DKI buildings'",
")",
"# Banjir seperti 2007",
"tr",
"(",
"'Jakarta 2007 flood'",
")",
"tr",
"(",
"'A flood in Jakarta like in 2007'",
")",
"tr",
"(",
"'Jakarta flood like 2007 with pump failure at... | These listed here so they get translated apriori to loading data. | [
"These",
"listed",
"here",
"so",
"they",
"get",
"translated",
"apriori",
"to",
"loading",
"data",
"."
] | python | train |
fedora-infra/fmn.rules | fmn/rules/generic.py | https://github.com/fedora-infra/fmn.rules/blob/f9ec790619fcc8b41803077c4dec094e5127fc24/fmn/rules/generic.py#L47-L52 | def _get_users_of_group(config, group):
""" Utility to query fas for users of a group. """
if not group:
return set()
fas = fmn.rules.utils.get_fas(config)
return fmn.rules.utils.get_user_of_group(config, fas, group) | [
"def",
"_get_users_of_group",
"(",
"config",
",",
"group",
")",
":",
"if",
"not",
"group",
":",
"return",
"set",
"(",
")",
"fas",
"=",
"fmn",
".",
"rules",
".",
"utils",
".",
"get_fas",
"(",
"config",
")",
"return",
"fmn",
".",
"rules",
".",
"utils",... | Utility to query fas for users of a group. | [
"Utility",
"to",
"query",
"fas",
"for",
"users",
"of",
"a",
"group",
"."
] | python | train |
draios/python-sdc-client | sdcclient/_common.py | https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_common.py#L583-L618 | def create_user_invite(self, user_email, first_name=None, last_name=None, system_role=None):
'''**Description**
Invites a new user to use Sysdig Monitor. This should result in an email notification to the specified address.
**Arguments**
- **user_email**: the email address of th... | [
"def",
"create_user_invite",
"(",
"self",
",",
"user_email",
",",
"first_name",
"=",
"None",
",",
"last_name",
"=",
"None",
",",
"system_role",
"=",
"None",
")",
":",
"# Look up the list of users to see if this exists, do not create if one exists",
"res",
"=",
"requests... | **Description**
Invites a new user to use Sysdig Monitor. This should result in an email notification to the specified address.
**Arguments**
- **user_email**: the email address of the user that will be invited to use Sysdig Monitor
- **first_name**: the first name of the us... | [
"**",
"Description",
"**",
"Invites",
"a",
"new",
"user",
"to",
"use",
"Sysdig",
"Monitor",
".",
"This",
"should",
"result",
"in",
"an",
"email",
"notification",
"to",
"the",
"specified",
"address",
"."
] | python | test |
Duke-GCB/DukeDSClient | ddsc/ddsclient.py | https://github.com/Duke-GCB/DukeDSClient/blob/117f68fb9bae82e4c81ea487ad5d61ac350f3726/ddsc/ddsclient.py#L153-L175 | def run(self, args):
"""
Upload contents of folders to a project with project_name on remote store.
If follow_symlinks we will traverse symlinked directories.
If content is already on remote site it will not be sent.
:param args: Namespace arguments parsed from the command line.
... | [
"def",
"run",
"(",
"self",
",",
"args",
")",
":",
"project_name_or_id",
"=",
"self",
".",
"create_project_name_or_id_from_args",
"(",
"args",
")",
"folders",
"=",
"args",
".",
"folders",
"# list of local files/folders to upload into the project",
"follow_symlinks",
"=",... | Upload contents of folders to a project with project_name on remote store.
If follow_symlinks we will traverse symlinked directories.
If content is already on remote site it will not be sent.
:param args: Namespace arguments parsed from the command line. | [
"Upload",
"contents",
"of",
"folders",
"to",
"a",
"project",
"with",
"project_name",
"on",
"remote",
"store",
".",
"If",
"follow_symlinks",
"we",
"will",
"traverse",
"symlinked",
"directories",
".",
"If",
"content",
"is",
"already",
"on",
"remote",
"site",
"it... | python | train |
PyCQA/pylint-django | pylint_django/augmentations/__init__.py | https://github.com/PyCQA/pylint-django/blob/0bbee433519f48134df4a797341c4196546a454e/pylint_django/augmentations/__init__.py#L697-L709 | def is_templatetags_module_valid_constant(node):
"""Suppress warnings for valid constants in templatetags module."""
if node.name not in ('register', ):
return False
parent = node.parent
while not isinstance(parent, Module):
parent = parent.parent
if "templatetags." not in parent.n... | [
"def",
"is_templatetags_module_valid_constant",
"(",
"node",
")",
":",
"if",
"node",
".",
"name",
"not",
"in",
"(",
"'register'",
",",
")",
":",
"return",
"False",
"parent",
"=",
"node",
".",
"parent",
"while",
"not",
"isinstance",
"(",
"parent",
",",
"Mod... | Suppress warnings for valid constants in templatetags module. | [
"Suppress",
"warnings",
"for",
"valid",
"constants",
"in",
"templatetags",
"module",
"."
] | python | train |
pandas-dev/pandas | pandas/core/ops.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/ops.py#L38-L58 | def get_op_result_name(left, right):
"""
Find the appropriate name to pin to an operation result. This result
should always be either an Index or a Series.
Parameters
----------
left : {Series, Index}
right : object
Returns
-------
name : object
Usually a string
""... | [
"def",
"get_op_result_name",
"(",
"left",
",",
"right",
")",
":",
"# `left` is always a pd.Series when called from within ops",
"if",
"isinstance",
"(",
"right",
",",
"(",
"ABCSeries",
",",
"pd",
".",
"Index",
")",
")",
":",
"name",
"=",
"_maybe_match_name",
"(",
... | Find the appropriate name to pin to an operation result. This result
should always be either an Index or a Series.
Parameters
----------
left : {Series, Index}
right : object
Returns
-------
name : object
Usually a string | [
"Find",
"the",
"appropriate",
"name",
"to",
"pin",
"to",
"an",
"operation",
"result",
".",
"This",
"result",
"should",
"always",
"be",
"either",
"an",
"Index",
"or",
"a",
"Series",
"."
] | python | train |
saltstack/salt | salt/modules/ssh.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ssh.py#L94-L120 | def _expand_authorized_keys_path(path, user, home):
'''
Expand the AuthorizedKeysFile expression. Defined in man sshd_config(5)
'''
converted_path = ''
had_escape = False
for char in path:
if had_escape:
had_escape = False
if char == '%':
converted... | [
"def",
"_expand_authorized_keys_path",
"(",
"path",
",",
"user",
",",
"home",
")",
":",
"converted_path",
"=",
"''",
"had_escape",
"=",
"False",
"for",
"char",
"in",
"path",
":",
"if",
"had_escape",
":",
"had_escape",
"=",
"False",
"if",
"char",
"==",
"'%'... | Expand the AuthorizedKeysFile expression. Defined in man sshd_config(5) | [
"Expand",
"the",
"AuthorizedKeysFile",
"expression",
".",
"Defined",
"in",
"man",
"sshd_config",
"(",
"5",
")"
] | python | train |
HPAC/matchpy | matchpy/utils.py | https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/utils.py#L367-L428 | def base_solution_linear(a: int, b: int, c: int) -> Iterator[Tuple[int, int]]:
r"""Yield solutions for a basic linear Diophantine equation of the form :math:`ax + by = c`.
First, the equation is normalized by dividing :math:`a, b, c` by their gcd.
Then, the extended Euclidean algorithm (:func:`extended_euc... | [
"def",
"base_solution_linear",
"(",
"a",
":",
"int",
",",
"b",
":",
"int",
",",
"c",
":",
"int",
")",
"->",
"Iterator",
"[",
"Tuple",
"[",
"int",
",",
"int",
"]",
"]",
":",
"if",
"a",
"<=",
"0",
"or",
"b",
"<=",
"0",
":",
"raise",
"ValueError",... | r"""Yield solutions for a basic linear Diophantine equation of the form :math:`ax + by = c`.
First, the equation is normalized by dividing :math:`a, b, c` by their gcd.
Then, the extended Euclidean algorithm (:func:`extended_euclid`) is used to find a base solution :math:`(x_0, y_0)`.
All non-negative sol... | [
"r",
"Yield",
"solutions",
"for",
"a",
"basic",
"linear",
"Diophantine",
"equation",
"of",
"the",
"form",
":",
"math",
":",
"ax",
"+",
"by",
"=",
"c",
"."
] | python | train |
cggh/scikit-allel | allel/stats/distance.py | https://github.com/cggh/scikit-allel/blob/3c979a57a100240ba959dd13f98839349530f215/allel/stats/distance.py#L335-L396 | def plot_pairwise_distance(dist, labels=None, colorbar=True, ax=None,
imshow_kwargs=None):
"""Plot a pairwise distance matrix.
Parameters
----------
dist : array_like
The distance matrix in condensed form.
labels : sequence of strings, optional
Sample labe... | [
"def",
"plot_pairwise_distance",
"(",
"dist",
",",
"labels",
"=",
"None",
",",
"colorbar",
"=",
"True",
",",
"ax",
"=",
"None",
",",
"imshow_kwargs",
"=",
"None",
")",
":",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"# check inputs",
"dist_square",
... | Plot a pairwise distance matrix.
Parameters
----------
dist : array_like
The distance matrix in condensed form.
labels : sequence of strings, optional
Sample labels for the axes.
colorbar : bool, optional
If True, add a colorbar to the current figure.
ax : axes, optional... | [
"Plot",
"a",
"pairwise",
"distance",
"matrix",
"."
] | python | train |
projectatomic/osbs-client | osbs/build/plugins_configuration.py | https://github.com/projectatomic/osbs-client/blob/571fe035dab3a7c02e1dccd5d65ffd75be750458/osbs/build/plugins_configuration.py#L92-L100 | def has_plugin_conf(self, phase, name):
"""
Check whether a plugin is configured.
"""
try:
self.get_plugin_conf(phase, name)
return True
except (KeyError, IndexError):
return False | [
"def",
"has_plugin_conf",
"(",
"self",
",",
"phase",
",",
"name",
")",
":",
"try",
":",
"self",
".",
"get_plugin_conf",
"(",
"phase",
",",
"name",
")",
"return",
"True",
"except",
"(",
"KeyError",
",",
"IndexError",
")",
":",
"return",
"False"
] | Check whether a plugin is configured. | [
"Check",
"whether",
"a",
"plugin",
"is",
"configured",
"."
] | python | train |
kivy/python-for-android | pythonforandroid/pythonpackage.py | https://github.com/kivy/python-for-android/blob/8e0e8056bc22e4d5bd3398a6b0301f38ff167933/pythonforandroid/pythonpackage.py#L146-L231 | def _get_system_python_executable():
""" Returns the path the system-wide python binary.
(In case we're running in a virtualenv or venv)
"""
# This function is required by get_package_as_folder() to work
# inside a virtualenv, since venv creation will fail with
# the virtualenv's local pytho... | [
"def",
"_get_system_python_executable",
"(",
")",
":",
"# This function is required by get_package_as_folder() to work",
"# inside a virtualenv, since venv creation will fail with",
"# the virtualenv's local python binary.",
"# (venv/virtualenv incompatibility)",
"# Abort if not in virtualenv or v... | Returns the path the system-wide python binary.
(In case we're running in a virtualenv or venv) | [
"Returns",
"the",
"path",
"the",
"system",
"-",
"wide",
"python",
"binary",
".",
"(",
"In",
"case",
"we",
"re",
"running",
"in",
"a",
"virtualenv",
"or",
"venv",
")"
] | python | train |
django-auth-ldap/django-auth-ldap | django_auth_ldap/backend.py | https://github.com/django-auth-ldap/django-auth-ldap/blob/9ce3c2825527f8faa1793958b041816e63d839af/django_auth_ldap/backend.py#L901-L917 | def get_group_names(self):
"""
Returns the set of Django group names that this user belongs to by
virtue of LDAP group memberships.
"""
if self._group_names is None:
self._load_cached_attr("_group_names")
if self._group_names is None:
group_infos ... | [
"def",
"get_group_names",
"(",
"self",
")",
":",
"if",
"self",
".",
"_group_names",
"is",
"None",
":",
"self",
".",
"_load_cached_attr",
"(",
"\"_group_names\"",
")",
"if",
"self",
".",
"_group_names",
"is",
"None",
":",
"group_infos",
"=",
"self",
".",
"_... | Returns the set of Django group names that this user belongs to by
virtue of LDAP group memberships. | [
"Returns",
"the",
"set",
"of",
"Django",
"group",
"names",
"that",
"this",
"user",
"belongs",
"to",
"by",
"virtue",
"of",
"LDAP",
"group",
"memberships",
"."
] | python | train |
push-things/django-th | django_th/views.py | https://github.com/push-things/django-th/blob/86c999d16bcf30b6224206e5b40824309834ac8c/django_th/views.py#L108-L164 | def get_context_data(self, **kwargs):
"""
get the data of the view
data are :
1) number of triggers enabled
2) number of triggers disabled
3) number of activated services
4) list of activated services by the connected user
"""
... | [
"def",
"get_context_data",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"triggers_enabled",
"=",
"triggers_disabled",
"=",
"services_activated",
"=",
"(",
")",
"context",
"=",
"super",
"(",
"TriggerListView",
",",
"self",
")",
".",
"get_context_data",
"(",
... | get the data of the view
data are :
1) number of triggers enabled
2) number of triggers disabled
3) number of activated services
4) list of activated services by the connected user | [
"get",
"the",
"data",
"of",
"the",
"view"
] | python | train |
Capitains/MyCapytain | MyCapytain/retrievers/dts/__init__.py | https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/retrievers/dts/__init__.py#L158-L178 | def get_document(
self,
collection_id, ref=None, mimetype="application/tei+xml, application/xml"):
""" Make a navigation request on the DTS API
:param collection_id: Id of the collection
:param ref: If ref is a tuple, it is treated as a range. String or int are treated a... | [
"def",
"get_document",
"(",
"self",
",",
"collection_id",
",",
"ref",
"=",
"None",
",",
"mimetype",
"=",
"\"application/tei+xml, application/xml\"",
")",
":",
"parameters",
"=",
"{",
"\"id\"",
":",
"collection_id",
"}",
"_parse_ref_parameters",
"(",
"parameters",
... | Make a navigation request on the DTS API
:param collection_id: Id of the collection
:param ref: If ref is a tuple, it is treated as a range. String or int are treated as single ref
:param mimetype: Media type to request
:return: Response
:rtype: requests.Response | [
"Make",
"a",
"navigation",
"request",
"on",
"the",
"DTS",
"API"
] | python | train |
SoCo/SoCo | soco/alarms.py | https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/alarms.py#L236-L250 | def remove(self):
"""Remove the alarm from the Sonos system.
There is no need to call `save`. The Python instance is not deleted,
and can be saved back to Sonos again if desired.
"""
self.zone.alarmClock.DestroyAlarm([
('ID', self._alarm_id)
])
alarm_... | [
"def",
"remove",
"(",
"self",
")",
":",
"self",
".",
"zone",
".",
"alarmClock",
".",
"DestroyAlarm",
"(",
"[",
"(",
"'ID'",
",",
"self",
".",
"_alarm_id",
")",
"]",
")",
"alarm_id",
"=",
"self",
".",
"_alarm_id",
"try",
":",
"del",
"Alarm",
".",
"_... | Remove the alarm from the Sonos system.
There is no need to call `save`. The Python instance is not deleted,
and can be saved back to Sonos again if desired. | [
"Remove",
"the",
"alarm",
"from",
"the",
"Sonos",
"system",
"."
] | python | train |
limodou/uliweb | uliweb/contrib/upload/__init__.py | https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/contrib/upload/__init__.py#L82-L111 | def get_filename(self, filename, filesystem=False, convert=False, subpath=''):
"""
Get the filename according to self.to_path, and if filesystem is False
then return unicode filename, otherwise return filesystem encoded filename
@param filename: relative filename, it'll be comb... | [
"def",
"get_filename",
"(",
"self",
",",
"filename",
",",
"filesystem",
"=",
"False",
",",
"convert",
"=",
"False",
",",
"subpath",
"=",
"''",
")",
":",
"from",
"uliweb",
".",
"utils",
".",
"common",
"import",
"safe_unicode",
"#make sure the filename is unicod... | Get the filename according to self.to_path, and if filesystem is False
then return unicode filename, otherwise return filesystem encoded filename
@param filename: relative filename, it'll be combine with self.to_path
@param filesystem: if True, then encoding the filename to filesystem
... | [
"Get",
"the",
"filename",
"according",
"to",
"self",
".",
"to_path",
"and",
"if",
"filesystem",
"is",
"False",
"then",
"return",
"unicode",
"filename",
"otherwise",
"return",
"filesystem",
"encoded",
"filename"
] | python | train |
ewilazarus/yld | yld/__main__.py | https://github.com/ewilazarus/yld/blob/157e474d1055f14ffdfd7e99da6c77d5f17d4307/yld/__main__.py#L81-L99 | def confirm(tag):
"""
Prompts user before proceeding
"""
click.echo()
if click.confirm('Do you want to create the tag {tag}?'.format(
tag=click.style(str(tag), fg='yellow')),
default=True, abort=True):
git.create_tag(tag)
if click.confirm(
'Do you want to pus... | [
"def",
"confirm",
"(",
"tag",
")",
":",
"click",
".",
"echo",
"(",
")",
"if",
"click",
".",
"confirm",
"(",
"'Do you want to create the tag {tag}?'",
".",
"format",
"(",
"tag",
"=",
"click",
".",
"style",
"(",
"str",
"(",
"tag",
")",
",",
"fg",
"=",
... | Prompts user before proceeding | [
"Prompts",
"user",
"before",
"proceeding"
] | python | valid |
EconForge/dolo | dolo/numeric/optimize/newton.py | https://github.com/EconForge/dolo/blob/d91ddf148b009bf79852d9aec70f3a1877e0f79a/dolo/numeric/optimize/newton.py#L81-L151 | def newton(f, x, verbose=False, tol=1e-6, maxit=5, jactype='serial'):
"""Solve nonlinear system using safeguarded Newton iterations
Parameters
----------
Return
------
"""
if verbose:
print = lambda txt: old_print(txt)
else:
print = lambda txt: None
it = 0
e... | [
"def",
"newton",
"(",
"f",
",",
"x",
",",
"verbose",
"=",
"False",
",",
"tol",
"=",
"1e-6",
",",
"maxit",
"=",
"5",
",",
"jactype",
"=",
"'serial'",
")",
":",
"if",
"verbose",
":",
"print",
"=",
"lambda",
"txt",
":",
"old_print",
"(",
"txt",
")",... | Solve nonlinear system using safeguarded Newton iterations
Parameters
----------
Return
------ | [
"Solve",
"nonlinear",
"system",
"using",
"safeguarded",
"Newton",
"iterations"
] | python | train |
jazzband/django-axes | axes/middleware.py | https://github.com/jazzband/django-axes/blob/3e215a174030e43e7ab8c2a79c395eb0eeddc667/axes/middleware.py#L51-L59 | def process_exception(self, request: AxesHttpRequest, exception): # pylint: disable=inconsistent-return-statements
"""
Exception handler that processes exceptions raised by the Axes signal handler when request fails with login.
Only ``axes.exceptions.AxesSignalPermissionDenied`` exception is h... | [
"def",
"process_exception",
"(",
"self",
",",
"request",
":",
"AxesHttpRequest",
",",
"exception",
")",
":",
"# pylint: disable=inconsistent-return-statements",
"if",
"isinstance",
"(",
"exception",
",",
"AxesSignalPermissionDenied",
")",
":",
"return",
"get_lockout_respo... | Exception handler that processes exceptions raised by the Axes signal handler when request fails with login.
Only ``axes.exceptions.AxesSignalPermissionDenied`` exception is handled by this middleware. | [
"Exception",
"handler",
"that",
"processes",
"exceptions",
"raised",
"by",
"the",
"Axes",
"signal",
"handler",
"when",
"request",
"fails",
"with",
"login",
"."
] | python | train |
grundprinzip/pyxplorer | pyxplorer/types.py | https://github.com/grundprinzip/pyxplorer/blob/34c1d166cfef4a94aeb6d5fcb3cbb726d48146e2/pyxplorer/types.py#L91-L105 | def distribution(self, limit=1024):
"""
Build the distribution of distinct values
"""
res = self._qexec("%s, count(*) as __cnt" % self.name(), group="%s" % self.name(),
order="__cnt DESC LIMIT %d" % limit)
dist = []
cnt = self._table.size()
... | [
"def",
"distribution",
"(",
"self",
",",
"limit",
"=",
"1024",
")",
":",
"res",
"=",
"self",
".",
"_qexec",
"(",
"\"%s, count(*) as __cnt\"",
"%",
"self",
".",
"name",
"(",
")",
",",
"group",
"=",
"\"%s\"",
"%",
"self",
".",
"name",
"(",
")",
",",
... | Build the distribution of distinct values | [
"Build",
"the",
"distribution",
"of",
"distinct",
"values"
] | python | train |
nwilming/ocupy | ocupy/parallel.py | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/parallel.py#L70-L88 | def xmlrpc_get_task(self):
"""
Return a new task description: ID and necessary parameters,
all are given in a dictionary
"""
try:
if len(self.reschedule) == 0:
(task_id, cur_task) = next(self.task_iterator)
else:
(task_id, ... | [
"def",
"xmlrpc_get_task",
"(",
"self",
")",
":",
"try",
":",
"if",
"len",
"(",
"self",
".",
"reschedule",
")",
"==",
"0",
":",
"(",
"task_id",
",",
"cur_task",
")",
"=",
"next",
"(",
"self",
".",
"task_iterator",
")",
"else",
":",
"(",
"task_id",
"... | Return a new task description: ID and necessary parameters,
all are given in a dictionary | [
"Return",
"a",
"new",
"task",
"description",
":",
"ID",
"and",
"necessary",
"parameters",
"all",
"are",
"given",
"in",
"a",
"dictionary"
] | python | train |
softlayer/softlayer-python | SoftLayer/CLI/virt/power.py | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/virt/power.py#L16-L25 | def rescue(env, identifier):
"""Reboot into a rescue image."""
vsi = SoftLayer.VSManager(env.client)
vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS')
if not (env.skip_confirmations or
formatting.confirm("This action will reboot this VSI. Continue?")):
raise exceptions.C... | [
"def",
"rescue",
"(",
"env",
",",
"identifier",
")",
":",
"vsi",
"=",
"SoftLayer",
".",
"VSManager",
"(",
"env",
".",
"client",
")",
"vs_id",
"=",
"helpers",
".",
"resolve_id",
"(",
"vsi",
".",
"resolve_ids",
",",
"identifier",
",",
"'VS'",
")",
"if",
... | Reboot into a rescue image. | [
"Reboot",
"into",
"a",
"rescue",
"image",
"."
] | python | train |
nschloe/meshplex | meshplex/base.py | https://github.com/nschloe/meshplex/blob/376cfe8ce7b9917e5398c5d60c87455ff5590913/meshplex/base.py#L259-L273 | def _mark_vertices(self, subdomain):
"""Mark faces/edges which are fully in subdomain.
"""
if subdomain is None:
is_inside = numpy.ones(len(self.node_coords), dtype=bool)
else:
is_inside = subdomain.is_inside(self.node_coords.T).T
if subdomain.is_boun... | [
"def",
"_mark_vertices",
"(",
"self",
",",
"subdomain",
")",
":",
"if",
"subdomain",
"is",
"None",
":",
"is_inside",
"=",
"numpy",
".",
"ones",
"(",
"len",
"(",
"self",
".",
"node_coords",
")",
",",
"dtype",
"=",
"bool",
")",
"else",
":",
"is_inside",
... | Mark faces/edges which are fully in subdomain. | [
"Mark",
"faces",
"/",
"edges",
"which",
"are",
"fully",
"in",
"subdomain",
"."
] | python | train |
sbusard/wagoner | wagoner/utils.py | https://github.com/sbusard/wagoner/blob/7f83d66bbd0e009e4d4232ffdf319bd5a2a5683b/wagoner/utils.py#L76-L85 | def extract_words(lines):
"""
Extract from the given iterable of lines the list of words.
:param lines: an iterable of lines;
:return: a generator of words of lines.
"""
for line in lines:
for word in re.findall(r"\w+", line):
yield word | [
"def",
"extract_words",
"(",
"lines",
")",
":",
"for",
"line",
"in",
"lines",
":",
"for",
"word",
"in",
"re",
".",
"findall",
"(",
"r\"\\w+\"",
",",
"line",
")",
":",
"yield",
"word"
] | Extract from the given iterable of lines the list of words.
:param lines: an iterable of lines;
:return: a generator of words of lines. | [
"Extract",
"from",
"the",
"given",
"iterable",
"of",
"lines",
"the",
"list",
"of",
"words",
"."
] | python | train |
wmayner/pyphi | pyphi/actual.py | https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/actual.py#L197-L215 | def repertoire(self, direction, mechanism, purview):
"""Return the cause or effect repertoire function based on a direction.
Args:
direction (str): The temporal direction, specifiying the cause or
effect repertoire.
"""
system = self.system[direction]
... | [
"def",
"repertoire",
"(",
"self",
",",
"direction",
",",
"mechanism",
",",
"purview",
")",
":",
"system",
"=",
"self",
".",
"system",
"[",
"direction",
"]",
"node_labels",
"=",
"system",
".",
"node_labels",
"if",
"not",
"set",
"(",
"purview",
")",
".",
... | Return the cause or effect repertoire function based on a direction.
Args:
direction (str): The temporal direction, specifiying the cause or
effect repertoire. | [
"Return",
"the",
"cause",
"or",
"effect",
"repertoire",
"function",
"based",
"on",
"a",
"direction",
"."
] | python | train |
hydpy-dev/hydpy | hydpy/core/timetools.py | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/timetools.py#L363-L389 | def to_cfunits(self, unit='hours', utcoffset=None):
"""Return a `units` string agreeing with the NetCDF-CF conventions.
By default, |Date.to_cfunits| takes `hours` as time unit, and the
the actual value of |Options.utcoffset| as time zone information:
>>> from hydpy import Date
... | [
"def",
"to_cfunits",
"(",
"self",
",",
"unit",
"=",
"'hours'",
",",
"utcoffset",
"=",
"None",
")",
":",
"if",
"utcoffset",
"is",
"None",
":",
"utcoffset",
"=",
"hydpy",
".",
"pub",
".",
"options",
".",
"utcoffset",
"string",
"=",
"self",
".",
"to_strin... | Return a `units` string agreeing with the NetCDF-CF conventions.
By default, |Date.to_cfunits| takes `hours` as time unit, and the
the actual value of |Options.utcoffset| as time zone information:
>>> from hydpy import Date
>>> date = Date('1992-10-08 15:15:42')
>>> date.to_cfu... | [
"Return",
"a",
"units",
"string",
"agreeing",
"with",
"the",
"NetCDF",
"-",
"CF",
"conventions",
"."
] | python | train |
Kortemme-Lab/klab | klab/bio/pdbml.py | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/pdbml.py#L104-L123 | def parse_deprecation(self):
'''Checks to see if the PDB file has been deprecated and, if so, what the new ID is.'''
deprecation_tag = self.main_tag.getElementsByTagName("PDBx:pdbx_database_PDB_obs_sprCategory")
assert(len(deprecation_tag) <= 1)
if deprecation_tag:
deprecatio... | [
"def",
"parse_deprecation",
"(",
"self",
")",
":",
"deprecation_tag",
"=",
"self",
".",
"main_tag",
".",
"getElementsByTagName",
"(",
"\"PDBx:pdbx_database_PDB_obs_sprCategory\"",
")",
"assert",
"(",
"len",
"(",
"deprecation_tag",
")",
"<=",
"1",
")",
"if",
"depre... | Checks to see if the PDB file has been deprecated and, if so, what the new ID is. | [
"Checks",
"to",
"see",
"if",
"the",
"PDB",
"file",
"has",
"been",
"deprecated",
"and",
"if",
"so",
"what",
"the",
"new",
"ID",
"is",
"."
] | python | train |
tnkteja/myhelp | virtualEnvironment/lib/python2.7/site-packages/pip/commands/show.py | https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/pip/commands/show.py#L81-L100 | def print_results(distributions, list_all_files):
"""
Print the informations from installed distributions found.
"""
results_printed = False
for dist in distributions:
results_printed = True
logger.info("---")
logger.info("Name: %s" % dist['name'])
logger.info("Versio... | [
"def",
"print_results",
"(",
"distributions",
",",
"list_all_files",
")",
":",
"results_printed",
"=",
"False",
"for",
"dist",
"in",
"distributions",
":",
"results_printed",
"=",
"True",
"logger",
".",
"info",
"(",
"\"---\"",
")",
"logger",
".",
"info",
"(",
... | Print the informations from installed distributions found. | [
"Print",
"the",
"informations",
"from",
"installed",
"distributions",
"found",
"."
] | python | test |
PetrochukM/PyTorch-NLP | torchnlp/encoders/text/static_tokenizer_encoder.py | https://github.com/PetrochukM/PyTorch-NLP/blob/5f7320da5c8d781df072fab3f7e421c6347e5bfa/torchnlp/encoders/text/static_tokenizer_encoder.py#L121-L132 | def decode(self, encoded):
""" Decodes a tensor into a sequence.
Args:
encoded (torch.Tensor): Encoded sequence.
Returns:
str: Sequence decoded from ``encoded``.
"""
encoded = super().decode(encoded)
tokens = [self.itos[index] for index in encode... | [
"def",
"decode",
"(",
"self",
",",
"encoded",
")",
":",
"encoded",
"=",
"super",
"(",
")",
".",
"decode",
"(",
"encoded",
")",
"tokens",
"=",
"[",
"self",
".",
"itos",
"[",
"index",
"]",
"for",
"index",
"in",
"encoded",
"]",
"return",
"self",
".",
... | Decodes a tensor into a sequence.
Args:
encoded (torch.Tensor): Encoded sequence.
Returns:
str: Sequence decoded from ``encoded``. | [
"Decodes",
"a",
"tensor",
"into",
"a",
"sequence",
"."
] | python | train |
UDST/urbansim | urbansim/accounts.py | https://github.com/UDST/urbansim/blob/79f815a6503e109f50be270cee92d0f4a34f49ef/urbansim/accounts.py#L57-L75 | def add_transaction(self, amount, subaccount=None, metadata=None):
"""
Add a new transaction to the account.
Parameters
----------
amount : float
Negative for withdrawls, positive for deposits.
subaccount : object, optional
Any indicator of a suba... | [
"def",
"add_transaction",
"(",
"self",
",",
"amount",
",",
"subaccount",
"=",
"None",
",",
"metadata",
"=",
"None",
")",
":",
"metadata",
"=",
"metadata",
"or",
"{",
"}",
"self",
".",
"transactions",
".",
"append",
"(",
"Transaction",
"(",
"amount",
",",... | Add a new transaction to the account.
Parameters
----------
amount : float
Negative for withdrawls, positive for deposits.
subaccount : object, optional
Any indicator of a subaccount to which this transaction applies.
metadata : dict, optional
... | [
"Add",
"a",
"new",
"transaction",
"to",
"the",
"account",
"."
] | python | train |
royi1000/py-libhdate | hdate/date.py | https://github.com/royi1000/py-libhdate/blob/12af759fb69f1d6403abed3762beaf5ace16a34b/hdate/date.py#L130-L134 | def _jdn(self):
"""Return the Julian date number for the given date."""
if self._last_updated == "gdate":
return conv.gdate_to_jdn(self.gdate)
return conv.hdate_to_jdn(self.hdate) | [
"def",
"_jdn",
"(",
"self",
")",
":",
"if",
"self",
".",
"_last_updated",
"==",
"\"gdate\"",
":",
"return",
"conv",
".",
"gdate_to_jdn",
"(",
"self",
".",
"gdate",
")",
"return",
"conv",
".",
"hdate_to_jdn",
"(",
"self",
".",
"hdate",
")"
] | Return the Julian date number for the given date. | [
"Return",
"the",
"Julian",
"date",
"number",
"for",
"the",
"given",
"date",
"."
] | python | train |
pmacosta/pexdoc | pexdoc/pinspect.py | https://github.com/pmacosta/pexdoc/blob/201ac243e5781347feb75896a4231429fe6da4b1/pexdoc/pinspect.py#L913-L919 | def _in_class(self, node):
"""Find if callable is function or method."""
# Move left one indentation level and check if that callable is a class
indent = self._get_indent(node)
for indent_dict in reversed(self._indent_stack): # pragma: no branch
if (indent_dict["level"] < in... | [
"def",
"_in_class",
"(",
"self",
",",
"node",
")",
":",
"# Move left one indentation level and check if that callable is a class",
"indent",
"=",
"self",
".",
"_get_indent",
"(",
"node",
")",
"for",
"indent_dict",
"in",
"reversed",
"(",
"self",
".",
"_indent_stack",
... | Find if callable is function or method. | [
"Find",
"if",
"callable",
"is",
"function",
"or",
"method",
"."
] | python | train |
JdeRobot/base | src/drivers/MAVLinkServer/MAVProxy/modules/mavproxy_map/__init__.py | https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/modules/mavproxy_map/__init__.py#L338-L348 | def create_vehicle_icon(self, name, colour, follow=False, vehicle_type=None):
'''add a vehicle to the map'''
from MAVProxy.modules.mavproxy_map import mp_slipmap
if vehicle_type is None:
vehicle_type = self.vehicle_type_name
if name in self.have_vehicle and self.have_vehicle[... | [
"def",
"create_vehicle_icon",
"(",
"self",
",",
"name",
",",
"colour",
",",
"follow",
"=",
"False",
",",
"vehicle_type",
"=",
"None",
")",
":",
"from",
"MAVProxy",
".",
"modules",
".",
"mavproxy_map",
"import",
"mp_slipmap",
"if",
"vehicle_type",
"is",
"None... | add a vehicle to the map | [
"add",
"a",
"vehicle",
"to",
"the",
"map"
] | python | train |
aarongarrett/inspyred | inspyred/ec/terminators.py | https://github.com/aarongarrett/inspyred/blob/d5976ab503cc9d51c6f586cbb7bb601a38c01128/inspyred/ec/terminators.py#L100-L122 | def average_fitness_termination(population, num_generations, num_evaluations, args):
"""Return True if the population's average fitness is near its best fitness.
This function calculates the average fitness of the population, as well
as the best fitness. If the difference between those values is less
... | [
"def",
"average_fitness_termination",
"(",
"population",
",",
"num_generations",
",",
"num_evaluations",
",",
"args",
")",
":",
"tolerance",
"=",
"args",
".",
"setdefault",
"(",
"'tolerance'",
",",
"0.001",
")",
"avg_fit",
"=",
"sum",
"(",
"[",
"x",
".",
"fi... | Return True if the population's average fitness is near its best fitness.
This function calculates the average fitness of the population, as well
as the best fitness. If the difference between those values is less
than a specified tolerance, the function returns True.
.. Arguments:
po... | [
"Return",
"True",
"if",
"the",
"population",
"s",
"average",
"fitness",
"is",
"near",
"its",
"best",
"fitness",
".",
"This",
"function",
"calculates",
"the",
"average",
"fitness",
"of",
"the",
"population",
"as",
"well",
"as",
"the",
"best",
"fitness",
".",
... | python | train |
StackStorm/pybind | pybind/nos/v6_0_2f/system_monitor_mail/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/nos/v6_0_2f/system_monitor_mail/__init__.py#L100-L121 | def _set_fru(self, v, load=False):
"""
Setter method for fru, mapped from YANG variable /system_monitor_mail/fru (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_fru is considered as a private
method. Backends looking to populate this variable should
d... | [
"def",
"_set_fru",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"base",
"... | Setter method for fru, mapped from YANG variable /system_monitor_mail/fru (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_fru is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_fru() directly. | [
"Setter",
"method",
"for",
"fru",
"mapped",
"from",
"YANG",
"variable",
"/",
"system_monitor_mail",
"/",
"fru",
"(",
"container",
")",
"If",
"this",
"variable",
"is",
"read",
"-",
"only",
"(",
"config",
":",
"false",
")",
"in",
"the",
"source",
"YANG",
"... | python | train |
pandas-dev/pandas | pandas/core/groupby/groupby.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/groupby/groupby.py#L2092-L2115 | def shift(self, periods=1, freq=None, axis=0, fill_value=None):
"""
Shift each group by periods observations.
Parameters
----------
periods : integer, default 1
number of periods to shift
freq : frequency string
axis : axis to shift, default 0
... | [
"def",
"shift",
"(",
"self",
",",
"periods",
"=",
"1",
",",
"freq",
"=",
"None",
",",
"axis",
"=",
"0",
",",
"fill_value",
"=",
"None",
")",
":",
"if",
"freq",
"is",
"not",
"None",
"or",
"axis",
"!=",
"0",
"or",
"not",
"isna",
"(",
"fill_value",
... | Shift each group by periods observations.
Parameters
----------
periods : integer, default 1
number of periods to shift
freq : frequency string
axis : axis to shift, default 0
fill_value : optional
.. versionadded:: 0.24.0 | [
"Shift",
"each",
"group",
"by",
"periods",
"observations",
"."
] | python | train |
Fizzadar/pyinfra | pyinfra_cli/inventory/__init__.py | https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra_cli/inventory/__init__.py#L111-L217 | def make_inventory(
inventory_filename,
deploy_dir=None,
ssh_port=None,
ssh_user=None,
ssh_key=None,
ssh_key_password=None,
ssh_password=None,
):
'''
Builds a ``pyinfra.api.Inventory`` from the filesystem. If the file does not exist
and doesn't contain a / attempts to use that as... | [
"def",
"make_inventory",
"(",
"inventory_filename",
",",
"deploy_dir",
"=",
"None",
",",
"ssh_port",
"=",
"None",
",",
"ssh_user",
"=",
"None",
",",
"ssh_key",
"=",
"None",
",",
"ssh_key_password",
"=",
"None",
",",
"ssh_password",
"=",
"None",
",",
")",
"... | Builds a ``pyinfra.api.Inventory`` from the filesystem. If the file does not exist
and doesn't contain a / attempts to use that as the only hostname. | [
"Builds",
"a",
"pyinfra",
".",
"api",
".",
"Inventory",
"from",
"the",
"filesystem",
".",
"If",
"the",
"file",
"does",
"not",
"exist",
"and",
"doesn",
"t",
"contain",
"a",
"/",
"attempts",
"to",
"use",
"that",
"as",
"the",
"only",
"hostname",
"."
] | python | train |
malthe/pop | src/pop/client.py | https://github.com/malthe/pop/blob/3b58b91b41d8b9bee546eb40dc280a57500b8bed/src/pop/client.py#L59-L68 | def set_or_create(self, path, *args, **kwargs):
"""Sets the data of a node at the given path, or creates it."""
d = self.set(path, *args, **kwargs)
@d.addErrback
def _error(result):
return self.create(path, *args, **kwargs)
return d | [
"def",
"set_or_create",
"(",
"self",
",",
"path",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"d",
"=",
"self",
".",
"set",
"(",
"path",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"@",
"d",
".",
"addErrback",
"def",
"_error",
"(",... | Sets the data of a node at the given path, or creates it. | [
"Sets",
"the",
"data",
"of",
"a",
"node",
"at",
"the",
"given",
"path",
"or",
"creates",
"it",
"."
] | python | train |
chaimleib/intervaltree | intervaltree/interval.py | https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/interval.py#L100-L110 | def contains_interval(self, other):
"""
Whether other is contained in this Interval.
:param other: Interval
:return: True or False
:rtype: bool
"""
return (
self.begin <= other.begin and
self.end >= other.end
) | [
"def",
"contains_interval",
"(",
"self",
",",
"other",
")",
":",
"return",
"(",
"self",
".",
"begin",
"<=",
"other",
".",
"begin",
"and",
"self",
".",
"end",
">=",
"other",
".",
"end",
")"
] | Whether other is contained in this Interval.
:param other: Interval
:return: True or False
:rtype: bool | [
"Whether",
"other",
"is",
"contained",
"in",
"this",
"Interval",
".",
":",
"param",
"other",
":",
"Interval",
":",
"return",
":",
"True",
"or",
"False",
":",
"rtype",
":",
"bool"
] | python | train |
wtsi-hgi/python-common | hgicommon/data_source/static_from_file.py | https://github.com/wtsi-hgi/python-common/blob/0376a6b574ff46e82e509e90b6cb3693a3dbb577/hgicommon/data_source/static_from_file.py#L217-L231 | def _on_file_moved(self, event: FileSystemMovedEvent):
"""
Called when a file in the monitored directory has been moved.
Breaks move down into a delete and a create (which it is sometimes detected as!).
:param event: the file system event
"""
if not event.is_directory an... | [
"def",
"_on_file_moved",
"(",
"self",
",",
"event",
":",
"FileSystemMovedEvent",
")",
":",
"if",
"not",
"event",
".",
"is_directory",
"and",
"self",
".",
"is_data_file",
"(",
"event",
".",
"src_path",
")",
":",
"delete_event",
"=",
"FileSystemEvent",
"(",
"e... | Called when a file in the monitored directory has been moved.
Breaks move down into a delete and a create (which it is sometimes detected as!).
:param event: the file system event | [
"Called",
"when",
"a",
"file",
"in",
"the",
"monitored",
"directory",
"has",
"been",
"moved",
"."
] | python | valid |
python-rope/rope | rope/base/utils/__init__.py | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/base/utils/__init__.py#L88-L98 | def resolve(str_or_obj):
"""Returns object from string"""
from rope.base.utils.pycompat import string_types
if not isinstance(str_or_obj, string_types):
return str_or_obj
if '.' not in str_or_obj:
str_or_obj += '.'
mod_name, obj_name = str_or_obj.rsplit('.', 1)
__import__(mod_nam... | [
"def",
"resolve",
"(",
"str_or_obj",
")",
":",
"from",
"rope",
".",
"base",
".",
"utils",
".",
"pycompat",
"import",
"string_types",
"if",
"not",
"isinstance",
"(",
"str_or_obj",
",",
"string_types",
")",
":",
"return",
"str_or_obj",
"if",
"'.'",
"not",
"i... | Returns object from string | [
"Returns",
"object",
"from",
"string"
] | python | train |
DataBiosphere/toil | src/toil/utils/toilDebugFile.py | https://github.com/DataBiosphere/toil/blob/a8252277ff814e7bee0971139c2344f88e44b644/src/toil/utils/toilDebugFile.py#L71-L100 | def printContentsOfJobStore(jobStorePath, nameOfJob=None):
"""
Fetch a list of all files contained in the jobStore directory input if
nameOfJob is not declared, otherwise it only prints out the names of files
for that specific job for which it can find a match. Also creates a logFile
containing thi... | [
"def",
"printContentsOfJobStore",
"(",
"jobStorePath",
",",
"nameOfJob",
"=",
"None",
")",
":",
"if",
"nameOfJob",
":",
"glob",
"=",
"\"*\"",
"+",
"nameOfJob",
"+",
"\"*\"",
"logFile",
"=",
"nameOfJob",
"+",
"\"_fileset.txt\"",
"else",
":",
"glob",
"=",
"\"*... | Fetch a list of all files contained in the jobStore directory input if
nameOfJob is not declared, otherwise it only prints out the names of files
for that specific job for which it can find a match. Also creates a logFile
containing this same record of job files in the working directory.
:param jobSto... | [
"Fetch",
"a",
"list",
"of",
"all",
"files",
"contained",
"in",
"the",
"jobStore",
"directory",
"input",
"if",
"nameOfJob",
"is",
"not",
"declared",
"otherwise",
"it",
"only",
"prints",
"out",
"the",
"names",
"of",
"files",
"for",
"that",
"specific",
"job",
... | python | train |
jic-dtool/dtool-create | dtool_create/dataset.py | https://github.com/jic-dtool/dtool-create/blob/12172363d14eaedba2db4c452ef995b14f1b630d/dtool_create/dataset.py#L74-L96 | def _prompt_for_values(d):
"""Update the descriptive metadata interactively.
Uses values entered by the user. Note that the function keeps recursing
whenever a value is another ``CommentedMap`` or a ``list``. The
function works as passing dictionaries and lists into a function edits
the values in p... | [
"def",
"_prompt_for_values",
"(",
"d",
")",
":",
"for",
"key",
",",
"value",
"in",
"d",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"CommentedMap",
")",
":",
"_prompt_for_values",
"(",
"value",
")",
"elif",
"isinstance",
"(",
"v... | Update the descriptive metadata interactively.
Uses values entered by the user. Note that the function keeps recursing
whenever a value is another ``CommentedMap`` or a ``list``. The
function works as passing dictionaries and lists into a function edits
the values in place. | [
"Update",
"the",
"descriptive",
"metadata",
"interactively",
"."
] | python | valid |
darkfeline/animanager | animanager/db/query/select.py | https://github.com/darkfeline/animanager/blob/55d92e4cbdc12aac8ebe302420d2cff3fa9fa148/animanager/db/query/select.py#L76-L147 | def select(
db,
where_query: str,
where_params: SQLParams,
fields: FieldsParam = ALL,
episode_fields: FieldsParam = (),
) -> Iterator[Anime]:
"""Perform an arbitrary SQL SELECT WHERE on the anime table.
By nature of "arbitrary query", this is vulnerable to injection, use... | [
"def",
"select",
"(",
"db",
",",
"where_query",
":",
"str",
",",
"where_params",
":",
"SQLParams",
",",
"fields",
":",
"FieldsParam",
"=",
"ALL",
",",
"episode_fields",
":",
"FieldsParam",
"=",
"(",
")",
",",
")",
"->",
"Iterator",
"[",
"Anime",
"]",
"... | Perform an arbitrary SQL SELECT WHERE on the anime table.
By nature of "arbitrary query", this is vulnerable to injection, use only
trusted values for `where_query`.
This will "lazily" fetch the requested fields as needed. For example,
episodes (which require a separate query per anime) will only be ... | [
"Perform",
"an",
"arbitrary",
"SQL",
"SELECT",
"WHERE",
"on",
"the",
"anime",
"table",
"."
] | python | train |
redhat-cip/dci-control-server | dci/api/v1/components.py | https://github.com/redhat-cip/dci-control-server/blob/b416cf935ec93e4fdd5741f61a21cabecf8454d2/dci/api/v1/components.py#L464-L472 | def retrieve_tags_from_component(user, c_id):
"""Retrieve all tags attached to a component."""
JCT = models.JOIN_COMPONENTS_TAGS
query = (sql.select([models.TAGS])
.select_from(JCT.join(models.TAGS))
.where(JCT.c.component_id == c_id))
rows = flask.g.db_conn.execute(query)
... | [
"def",
"retrieve_tags_from_component",
"(",
"user",
",",
"c_id",
")",
":",
"JCT",
"=",
"models",
".",
"JOIN_COMPONENTS_TAGS",
"query",
"=",
"(",
"sql",
".",
"select",
"(",
"[",
"models",
".",
"TAGS",
"]",
")",
".",
"select_from",
"(",
"JCT",
".",
"join",... | Retrieve all tags attached to a component. | [
"Retrieve",
"all",
"tags",
"attached",
"to",
"a",
"component",
"."
] | python | train |
bcbio/bcbio-nextgen | bcbio/cwl/cwlutils.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/cwl/cwlutils.py#L26-L34 | def to_rec_single(samples, default_keys=None):
"""Convert output into a list of single CWL records.
"""
out = []
for data in samples:
recs = samples_to_records([normalize_missing(utils.to_single_data(data))], default_keys)
assert len(recs) == 1
out.append(recs[0])
return out | [
"def",
"to_rec_single",
"(",
"samples",
",",
"default_keys",
"=",
"None",
")",
":",
"out",
"=",
"[",
"]",
"for",
"data",
"in",
"samples",
":",
"recs",
"=",
"samples_to_records",
"(",
"[",
"normalize_missing",
"(",
"utils",
".",
"to_single_data",
"(",
"data... | Convert output into a list of single CWL records. | [
"Convert",
"output",
"into",
"a",
"list",
"of",
"single",
"CWL",
"records",
"."
] | python | train |
MillionIntegrals/vel | vel/rl/modules/action_head.py | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/modules/action_head.py#L108-L114 | def sample(self, logits, argmax_sampling=False):
""" Sample from a probability space of all actions """
if argmax_sampling:
return torch.argmax(logits, dim=-1)
else:
u = torch.rand_like(logits)
return torch.argmax(logits - torch.log(-torch.log(u)), dim=-1) | [
"def",
"sample",
"(",
"self",
",",
"logits",
",",
"argmax_sampling",
"=",
"False",
")",
":",
"if",
"argmax_sampling",
":",
"return",
"torch",
".",
"argmax",
"(",
"logits",
",",
"dim",
"=",
"-",
"1",
")",
"else",
":",
"u",
"=",
"torch",
".",
"rand_lik... | Sample from a probability space of all actions | [
"Sample",
"from",
"a",
"probability",
"space",
"of",
"all",
"actions"
] | python | train |
wavycloud/pyboto3 | pyboto3/route53.py | https://github.com/wavycloud/pyboto3/blob/924957ccf994303713a4eed90b775ff2ab95b2e5/pyboto3/route53.py#L2976-L3170 | def update_health_check(HealthCheckId=None, HealthCheckVersion=None, IPAddress=None, Port=None, ResourcePath=None, FullyQualifiedDomainName=None, SearchString=None, FailureThreshold=None, Inverted=None, HealthThreshold=None, ChildHealthChecks=None, EnableSNI=None, Regions=None, AlarmIdentifier=None, InsufficientDataHea... | [
"def",
"update_health_check",
"(",
"HealthCheckId",
"=",
"None",
",",
"HealthCheckVersion",
"=",
"None",
",",
"IPAddress",
"=",
"None",
",",
"Port",
"=",
"None",
",",
"ResourcePath",
"=",
"None",
",",
"FullyQualifiedDomainName",
"=",
"None",
",",
"SearchString",... | Updates an existing health check. Note that some values can't be updated.
For more information about updating health checks, see Creating, Updating, and Deleting Health Checks in the Amazon Route 53 Developer Guide .
See also: AWS API Documentation
:example: response = client.update_health_check(
... | [
"Updates",
"an",
"existing",
"health",
"check",
".",
"Note",
"that",
"some",
"values",
"can",
"t",
"be",
"updated",
".",
"For",
"more",
"information",
"about",
"updating",
"health",
"checks",
"see",
"Creating",
"Updating",
"and",
"Deleting",
"Health",
"Checks"... | python | train |
klen/muffin-metrics | muffin_metrics.py | https://github.com/klen/muffin-metrics/blob/b62fc25172e3e1e9fc6dc6c8da3170935ee69f01/muffin_metrics.py#L239-L241 | def incr(self, stat, count=1, rate=1):
"""Increment a stat by `count`."""
return self.send(stat, "%s|c" % count, rate) | [
"def",
"incr",
"(",
"self",
",",
"stat",
",",
"count",
"=",
"1",
",",
"rate",
"=",
"1",
")",
":",
"return",
"self",
".",
"send",
"(",
"stat",
",",
"\"%s|c\"",
"%",
"count",
",",
"rate",
")"
] | Increment a stat by `count`. | [
"Increment",
"a",
"stat",
"by",
"count",
"."
] | python | train |
spacetelescope/drizzlepac | drizzlepac/wfpc2Data.py | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/wfpc2Data.py#L111-L165 | def setInstrumentParameters(self, instrpars):
""" This method overrides the superclass to set default values into
the parameter dictionary, in case empty entries are provided.
"""
pri_header = self._image[0].header
self.proc_unit = instrpars['proc_unit']
instrpars['gn... | [
"def",
"setInstrumentParameters",
"(",
"self",
",",
"instrpars",
")",
":",
"pri_header",
"=",
"self",
".",
"_image",
"[",
"0",
"]",
".",
"header",
"self",
".",
"proc_unit",
"=",
"instrpars",
"[",
"'proc_unit'",
"]",
"instrpars",
"[",
"'gnkeyword'",
"]",
"=... | This method overrides the superclass to set default values into
the parameter dictionary, in case empty entries are provided. | [
"This",
"method",
"overrides",
"the",
"superclass",
"to",
"set",
"default",
"values",
"into",
"the",
"parameter",
"dictionary",
"in",
"case",
"empty",
"entries",
"are",
"provided",
"."
] | python | train |
runfalk/spans | spans/types.py | https://github.com/runfalk/spans/blob/59ed73407a569c3be86cfdb4b8f438cb8c794540/spans/types.py#L445-L503 | def union(self, other):
"""
Merges this range with a given range.
>>> intrange(1, 5).union(intrange(5, 10))
intrange([1,10))
>>> intrange(1, 10).union(intrange(5, 15))
intrange([1,15))
Two ranges can not be merged if the resulting range would be ... | [
"def",
"union",
"(",
"self",
",",
"other",
")",
":",
"if",
"not",
"self",
".",
"is_valid_range",
"(",
"other",
")",
":",
"msg",
"=",
"\"Unsupported type to test for union '{.__class__.__name__}'\"",
"raise",
"TypeError",
"(",
"msg",
".",
"format",
"(",
"other",
... | Merges this range with a given range.
>>> intrange(1, 5).union(intrange(5, 10))
intrange([1,10))
>>> intrange(1, 10).union(intrange(5, 15))
intrange([1,15))
Two ranges can not be merged if the resulting range would be split in
two. This happens when the ... | [
"Merges",
"this",
"range",
"with",
"a",
"given",
"range",
"."
] | python | train |
PyO3/setuptools-rust | setuptools_rust/extension.py | https://github.com/PyO3/setuptools-rust/blob/cd3ecec5749927a5c69b8ea516fc918ae95d18ce/setuptools_rust/extension.py#L106-L122 | def get_lib_name(self):
""" Parse Cargo.toml to get the name of the shared library. """
# We import in here to make sure the the setup_requires are already installed
import toml
cfg = toml.load(self.path)
name = cfg.get("lib", {}).get("name")
if name is None:
... | [
"def",
"get_lib_name",
"(",
"self",
")",
":",
"# We import in here to make sure the the setup_requires are already installed",
"import",
"toml",
"cfg",
"=",
"toml",
".",
"load",
"(",
"self",
".",
"path",
")",
"name",
"=",
"cfg",
".",
"get",
"(",
"\"lib\"",
",",
... | Parse Cargo.toml to get the name of the shared library. | [
"Parse",
"Cargo",
".",
"toml",
"to",
"get",
"the",
"name",
"of",
"the",
"shared",
"library",
"."
] | python | train |
blackecho/Deep-Learning-TensorFlow | yadlt/models/boltzmann/rbm.py | https://github.com/blackecho/Deep-Learning-TensorFlow/blob/ddeb1f2848da7b7bee166ad2152b4afc46bb2086/yadlt/models/boltzmann/rbm.py#L172-L191 | def _create_variables(self, n_features):
"""Create the TensorFlow variables for the model.
:param n_features: number of features
:return: self
"""
w_name = 'weights'
self.W = tf.Variable(tf.truncated_normal(
shape=[n_features, self.num_hidden], stddev=0.1), n... | [
"def",
"_create_variables",
"(",
"self",
",",
"n_features",
")",
":",
"w_name",
"=",
"'weights'",
"self",
".",
"W",
"=",
"tf",
".",
"Variable",
"(",
"tf",
".",
"truncated_normal",
"(",
"shape",
"=",
"[",
"n_features",
",",
"self",
".",
"num_hidden",
"]",... | Create the TensorFlow variables for the model.
:param n_features: number of features
:return: self | [
"Create",
"the",
"TensorFlow",
"variables",
"for",
"the",
"model",
"."
] | python | train |
ynop/audiomate | audiomate/utils/audio.py | https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/utils/audio.py#L7-L24 | def process_buffer(buffer, n_channels):
"""
Merge the read blocks and resample if necessary.
Args:
buffer (list): A list of blocks of samples.
n_channels (int): The number of channels of the input data.
Returns:
np.array: The samples
"""
samples = np.concatenate(buffer)... | [
"def",
"process_buffer",
"(",
"buffer",
",",
"n_channels",
")",
":",
"samples",
"=",
"np",
".",
"concatenate",
"(",
"buffer",
")",
"if",
"n_channels",
">",
"1",
":",
"samples",
"=",
"samples",
".",
"reshape",
"(",
"(",
"-",
"1",
",",
"n_channels",
")",... | Merge the read blocks and resample if necessary.
Args:
buffer (list): A list of blocks of samples.
n_channels (int): The number of channels of the input data.
Returns:
np.array: The samples | [
"Merge",
"the",
"read",
"blocks",
"and",
"resample",
"if",
"necessary",
"."
] | python | train |
decentfox/aioh2 | aioh2/protocol.py | https://github.com/decentfox/aioh2/blob/2f9b76161e99e32317083cd2ebd17ce2ed3e41ab/aioh2/protocol.py#L371-L383 | def set_handler(self, handler):
"""
Connect with a coroutine, which is scheduled when connection is made.
This function will create a task, and when connection is closed,
the task will be canceled.
:param handler:
:return: None
"""
if self._handler:
... | [
"def",
"set_handler",
"(",
"self",
",",
"handler",
")",
":",
"if",
"self",
".",
"_handler",
":",
"raise",
"Exception",
"(",
"'Handler was already set'",
")",
"if",
"handler",
":",
"self",
".",
"_handler",
"=",
"async_task",
"(",
"handler",
",",
"loop",
"="... | Connect with a coroutine, which is scheduled when connection is made.
This function will create a task, and when connection is closed,
the task will be canceled.
:param handler:
:return: None | [
"Connect",
"with",
"a",
"coroutine",
"which",
"is",
"scheduled",
"when",
"connection",
"is",
"made",
"."
] | python | train |
saltstack/salt | salt/modules/udev.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/udev.py#L87-L109 | def info(dev):
'''
Extract all info delivered by udevadm
CLI Example:
.. code-block:: bash
salt '*' udev.info /dev/sda
salt '*' udev.info /sys/class/net/eth0
'''
if 'sys' in dev:
qtype = 'path'
else:
qtype = 'name'
cmd = 'udevadm info --export --query=... | [
"def",
"info",
"(",
"dev",
")",
":",
"if",
"'sys'",
"in",
"dev",
":",
"qtype",
"=",
"'path'",
"else",
":",
"qtype",
"=",
"'name'",
"cmd",
"=",
"'udevadm info --export --query=all --{0}={1}'",
".",
"format",
"(",
"qtype",
",",
"dev",
")",
"udev_result",
"="... | Extract all info delivered by udevadm
CLI Example:
.. code-block:: bash
salt '*' udev.info /dev/sda
salt '*' udev.info /sys/class/net/eth0 | [
"Extract",
"all",
"info",
"delivered",
"by",
"udevadm"
] | python | train |
ClericPy/torequests | torequests/dummy.py | https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/dummy.py#L264-L273 | def submitter(self, f):
"""Decorator to submit a coro-function as NewTask to self.loop with sem control.
Use default_callback frequency of loop."""
f = self._wrap_coro_function_with_sem(f)
@wraps(f)
def wrapped(*args, **kwargs):
return self.submit(f(*args, **kwargs))... | [
"def",
"submitter",
"(",
"self",
",",
"f",
")",
":",
"f",
"=",
"self",
".",
"_wrap_coro_function_with_sem",
"(",
"f",
")",
"@",
"wraps",
"(",
"f",
")",
"def",
"wrapped",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
... | Decorator to submit a coro-function as NewTask to self.loop with sem control.
Use default_callback frequency of loop. | [
"Decorator",
"to",
"submit",
"a",
"coro",
"-",
"function",
"as",
"NewTask",
"to",
"self",
".",
"loop",
"with",
"sem",
"control",
".",
"Use",
"default_callback",
"frequency",
"of",
"loop",
"."
] | python | train |
census-instrumentation/opencensus-python | contrib/opencensus-ext-ocagent/opencensus/ext/ocagent/trace_exporter/utils.py | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-ocagent/opencensus/ext/ocagent/trace_exporter/utils.py#L128-L149 | def set_proto_annotation(pb_annotation, span_data_annotation):
"""Sets properties on the protobuf Span annotation.
:type pb_annotation:
:class: `~opencensus.proto.trace.Span.TimeEvent.Annotation`
:param pb_annotation: protobuf annotation
:type span_data_annotation:
:class: `~opencensus... | [
"def",
"set_proto_annotation",
"(",
"pb_annotation",
",",
"span_data_annotation",
")",
":",
"pb_annotation",
".",
"description",
".",
"value",
"=",
"span_data_annotation",
".",
"description",
"if",
"span_data_annotation",
".",
"attributes",
"is",
"not",
"None",
"and",... | Sets properties on the protobuf Span annotation.
:type pb_annotation:
:class: `~opencensus.proto.trace.Span.TimeEvent.Annotation`
:param pb_annotation: protobuf annotation
:type span_data_annotation:
:class: `~opencensus.trace.time_event.Annotation`
:param span_data_annotation: opencen... | [
"Sets",
"properties",
"on",
"the",
"protobuf",
"Span",
"annotation",
"."
] | python | train |
agile4you/bottle-neck | bottle_neck/response.py | https://github.com/agile4you/bottle-neck/blob/ebc670a4b178255473d68e9b4122ba04e38f4810/bottle_neck/response.py#L262-L275 | def not_implemented(cls, errors=None):
"""Shortcut API for HTTP 501 `Not Implemented` response.
Args:
errors (list): Response key/value data.
Returns:
WSResponse Instance.
"""
if cls.expose_status: # pragma: no cover
cls.response.content_typ... | [
"def",
"not_implemented",
"(",
"cls",
",",
"errors",
"=",
"None",
")",
":",
"if",
"cls",
".",
"expose_status",
":",
"# pragma: no cover",
"cls",
".",
"response",
".",
"content_type",
"=",
"'application/json'",
"cls",
".",
"response",
".",
"_status_line",
"=",
... | Shortcut API for HTTP 501 `Not Implemented` response.
Args:
errors (list): Response key/value data.
Returns:
WSResponse Instance. | [
"Shortcut",
"API",
"for",
"HTTP",
"501",
"Not",
"Implemented",
"response",
"."
] | python | train |
Erotemic/utool | utool/util_dev.py | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dev.py#L1288-L1387 | def get_stats(list_, axis=None, use_nan=False, use_sum=False, use_median=False,
size=False):
"""
Args:
list_ (listlike): values to get statistics of
axis (int): if `list_` is ndarray then this specifies the axis
Returns:
OrderedDict: stats: dictionary of common numpy s... | [
"def",
"get_stats",
"(",
"list_",
",",
"axis",
"=",
"None",
",",
"use_nan",
"=",
"False",
",",
"use_sum",
"=",
"False",
",",
"use_median",
"=",
"False",
",",
"size",
"=",
"False",
")",
":",
"datacast",
"=",
"np",
".",
"float32",
"# Assure input is in num... | Args:
list_ (listlike): values to get statistics of
axis (int): if `list_` is ndarray then this specifies the axis
Returns:
OrderedDict: stats: dictionary of common numpy statistics
(min, max, mean, std, nMin, nMax, shape)
SeeAlso:
get_stats_str
CommandLine:
... | [
"Args",
":",
"list_",
"(",
"listlike",
")",
":",
"values",
"to",
"get",
"statistics",
"of",
"axis",
"(",
"int",
")",
":",
"if",
"list_",
"is",
"ndarray",
"then",
"this",
"specifies",
"the",
"axis"
] | python | train |
mar10/wsgidav | wsgidav/request_server.py | https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/request_server.py#L152-L184 | def _send_response(
self, environ, start_response, root_res, success_code, error_list
):
"""Send WSGI response (single or multistatus).
- If error_list is None or [], then <success_code> is send as response.
- If error_list contains a single error with a URL that matches root_res,
... | [
"def",
"_send_response",
"(",
"self",
",",
"environ",
",",
"start_response",
",",
"root_res",
",",
"success_code",
",",
"error_list",
")",
":",
"assert",
"success_code",
"in",
"(",
"HTTP_CREATED",
",",
"HTTP_NO_CONTENT",
",",
"HTTP_OK",
")",
"if",
"not",
"erro... | Send WSGI response (single or multistatus).
- If error_list is None or [], then <success_code> is send as response.
- If error_list contains a single error with a URL that matches root_res,
then this error is returned.
- If error_list contains more than one error, then '207 Multi-Stat... | [
"Send",
"WSGI",
"response",
"(",
"single",
"or",
"multistatus",
")",
"."
] | python | valid |
flyingrub/scdl | scdl/scdl.py | https://github.com/flyingrub/scdl/blob/e833a22dd6676311b72fadd8a1c80f4a06acfad9/scdl/scdl.py#L562-L588 | def already_downloaded(track, title, filename):
"""
Returns True if the file has already been downloaded
"""
global arguments
already_downloaded = False
if os.path.isfile(filename):
already_downloaded = True
if arguments['--flac'] and can_convert(filename) \
... | [
"def",
"already_downloaded",
"(",
"track",
",",
"title",
",",
"filename",
")",
":",
"global",
"arguments",
"already_downloaded",
"=",
"False",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"filename",
")",
":",
"already_downloaded",
"=",
"True",
"if",
"argume... | Returns True if the file has already been downloaded | [
"Returns",
"True",
"if",
"the",
"file",
"has",
"already",
"been",
"downloaded"
] | python | train |
odlgroup/odl | odl/set/space.py | https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/set/space.py#L926-L935 | def multiply(self, other, out=None):
"""Return ``out = self * other``.
If ``out`` is provided, the result is written to it.
See Also
--------
LinearSpace.multiply
"""
return self.space.multiply(self, other, out=out) | [
"def",
"multiply",
"(",
"self",
",",
"other",
",",
"out",
"=",
"None",
")",
":",
"return",
"self",
".",
"space",
".",
"multiply",
"(",
"self",
",",
"other",
",",
"out",
"=",
"out",
")"
] | Return ``out = self * other``.
If ``out`` is provided, the result is written to it.
See Also
--------
LinearSpace.multiply | [
"Return",
"out",
"=",
"self",
"*",
"other",
"."
] | python | train |
Azure/azure-sdk-for-python | azure-mgmt-policyinsights/azure/mgmt/policyinsights/operations/policy_states_operations.py | https://github.com/Azure/azure-sdk-for-python/blob/d7306fde32f60a293a7567678692bdad31e4b667/azure-mgmt-policyinsights/azure/mgmt/policyinsights/operations/policy_states_operations.py#L148-L227 | def summarize_for_management_group(
self, management_group_name, query_options=None, custom_headers=None, raw=False, **operation_config):
"""Summarizes policy states for the resources under the management group.
:param management_group_name: Management group name.
:type management_g... | [
"def",
"summarize_for_management_group",
"(",
"self",
",",
"management_group_name",
",",
"query_options",
"=",
"None",
",",
"custom_headers",
"=",
"None",
",",
"raw",
"=",
"False",
",",
"*",
"*",
"operation_config",
")",
":",
"top",
"=",
"None",
"if",
"query_o... | Summarizes policy states for the resources under the management group.
:param management_group_name: Management group name.
:type management_group_name: str
:param query_options: Additional parameters for the operation
:type query_options: ~azure.mgmt.policyinsights.models.QueryOptions
... | [
"Summarizes",
"policy",
"states",
"for",
"the",
"resources",
"under",
"the",
"management",
"group",
"."
] | python | test |
mcocdawc/chemcoord | src/chemcoord/cartesian_coordinates/_cartesian_class_core.py | https://github.com/mcocdawc/chemcoord/blob/95561ce387c142227c38fb14a1d182179aef8f5f/src/chemcoord/cartesian_coordinates/_cartesian_class_core.py#L1221-L1271 | def align(self, other, indices=None, ignore_hydrogens=False):
"""Align two Cartesians.
Minimize the RMSD (root mean squared deviation) between
``self`` and ``other``.
Returns a tuple of copies of ``self`` and ``other`` where
both are centered around their centroid and
... | [
"def",
"align",
"(",
"self",
",",
"other",
",",
"indices",
"=",
"None",
",",
"ignore_hydrogens",
"=",
"False",
")",
":",
"m1",
"=",
"(",
"self",
"-",
"self",
".",
"get_centroid",
"(",
")",
")",
".",
"sort_index",
"(",
")",
"m2",
"=",
"(",
"other",
... | Align two Cartesians.
Minimize the RMSD (root mean squared deviation) between
``self`` and ``other``.
Returns a tuple of copies of ``self`` and ``other`` where
both are centered around their centroid and
``other`` is rotated unto ``self``.
The rotation minimises the di... | [
"Align",
"two",
"Cartesians",
"."
] | python | train |
cggh/scikit-allel | allel/model/ndarray.py | https://github.com/cggh/scikit-allel/blob/3c979a57a100240ba959dd13f98839349530f215/allel/model/ndarray.py#L892-L950 | def to_allele_counts(self, max_allele=None, dtype='u1'):
"""Transform genotype calls into allele counts per call.
Parameters
----------
max_allele : int, optional
Highest allele index. Provide this value to speed up computation.
dtype : dtype, optional
Ou... | [
"def",
"to_allele_counts",
"(",
"self",
",",
"max_allele",
"=",
"None",
",",
"dtype",
"=",
"'u1'",
")",
":",
"# determine alleles to count",
"if",
"max_allele",
"is",
"None",
":",
"max_allele",
"=",
"self",
".",
"max",
"(",
")",
"alleles",
"=",
"list",
"("... | Transform genotype calls into allele counts per call.
Parameters
----------
max_allele : int, optional
Highest allele index. Provide this value to speed up computation.
dtype : dtype, optional
Output dtype.
Returns
-------
out : ndarray, ... | [
"Transform",
"genotype",
"calls",
"into",
"allele",
"counts",
"per",
"call",
"."
] | python | train |
merll/docker-map | dockermap/map/client.py | https://github.com/merll/docker-map/blob/e14fe86a6ff5c33d121eb2f9157e9359cb80dd02/dockermap/map/client.py#L446-L460 | def pull_images(self, container, instances=None, map_name=None, **kwargs):
"""
Pulls images for container configurations along their dependency path.
:param container: Container configuration name.
:type container: unicode | str
:param map_name: Container map name.
:type... | [
"def",
"pull_images",
"(",
"self",
",",
"container",
",",
"instances",
"=",
"None",
",",
"map_name",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"run_actions",
"(",
"'pull_images'",
",",
"container",
",",
"map_name",
"=",
"map_... | Pulls images for container configurations along their dependency path.
:param container: Container configuration name.
:type container: unicode | str
:param map_name: Container map name.
:type map_name: unicode | str
:param instances: Not applicable for images.
:type ins... | [
"Pulls",
"images",
"for",
"container",
"configurations",
"along",
"their",
"dependency",
"path",
"."
] | python | train |
apache/incubator-heron | heron/instance/src/python/utils/metrics/metrics_helper.py | https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/instance/src/python/utils/metrics/metrics_helper.py#L238-L241 | def failed_tuple(self, stream_id, fail_latency_ns):
"""Apply updates to the fail metrics"""
self.update_count(self.FAIL_COUNT, key=stream_id)
self.update_reduced_metric(self.FAIL_LATENCY, fail_latency_ns, key=stream_id) | [
"def",
"failed_tuple",
"(",
"self",
",",
"stream_id",
",",
"fail_latency_ns",
")",
":",
"self",
".",
"update_count",
"(",
"self",
".",
"FAIL_COUNT",
",",
"key",
"=",
"stream_id",
")",
"self",
".",
"update_reduced_metric",
"(",
"self",
".",
"FAIL_LATENCY",
",... | Apply updates to the fail metrics | [
"Apply",
"updates",
"to",
"the",
"fail",
"metrics"
] | python | valid |
praekeltfoundation/molo.commenting | molo/commenting/views.py | https://github.com/praekeltfoundation/molo.commenting/blob/94549bd75e4a5c5b3db43149e32d636330b3969c/molo/commenting/views.py#L21-L37 | def report(request, comment_id):
"""
Flags a comment on GET.
Redirects to whatever is provided in request.REQUEST['next'].
"""
comment = get_object_or_404(
django_comments.get_model(), pk=comment_id, site__pk=settings.SITE_ID)
if comment.parent is not None:
messages.info(reques... | [
"def",
"report",
"(",
"request",
",",
"comment_id",
")",
":",
"comment",
"=",
"get_object_or_404",
"(",
"django_comments",
".",
"get_model",
"(",
")",
",",
"pk",
"=",
"comment_id",
",",
"site__pk",
"=",
"settings",
".",
"SITE_ID",
")",
"if",
"comment",
"."... | Flags a comment on GET.
Redirects to whatever is provided in request.REQUEST['next']. | [
"Flags",
"a",
"comment",
"on",
"GET",
"."
] | python | train |
bcbio/bcbio-nextgen | bcbio/structural/validate.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/validate.py#L375-L392 | def evaluate(data):
"""Provide evaluations for multiple callers split by structural variant type.
"""
work_dir = utils.safe_makedir(os.path.join(data["dirs"]["work"], "structural",
dd.get_sample_name(data), "validate"))
truth_sets = tz.get_in(["config", "al... | [
"def",
"evaluate",
"(",
"data",
")",
":",
"work_dir",
"=",
"utils",
".",
"safe_makedir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"data",
"[",
"\"dirs\"",
"]",
"[",
"\"work\"",
"]",
",",
"\"structural\"",
",",
"dd",
".",
"get_sample_name",
"(",
"data"... | Provide evaluations for multiple callers split by structural variant type. | [
"Provide",
"evaluations",
"for",
"multiple",
"callers",
"split",
"by",
"structural",
"variant",
"type",
"."
] | python | train |
timedata-org/loady | loady/whitelist.py | https://github.com/timedata-org/loady/blob/94ffcdb92f15a28f3c85f77bd293a9cb59de4cad/loady/whitelist.py#L64-L69 | def check_entry(*entry):
"""Throws an exception if the entry isn't on the whitelist."""
whitelist = read_whitelist()
if not check_allow_prompt(entry, whitelist):
whitelist.append(entry)
write_whitelist(whitelist) | [
"def",
"check_entry",
"(",
"*",
"entry",
")",
":",
"whitelist",
"=",
"read_whitelist",
"(",
")",
"if",
"not",
"check_allow_prompt",
"(",
"entry",
",",
"whitelist",
")",
":",
"whitelist",
".",
"append",
"(",
"entry",
")",
"write_whitelist",
"(",
"whitelist",
... | Throws an exception if the entry isn't on the whitelist. | [
"Throws",
"an",
"exception",
"if",
"the",
"entry",
"isn",
"t",
"on",
"the",
"whitelist",
"."
] | python | train |
benley/butcher | butcher/targets/base.py | https://github.com/benley/butcher/blob/8b18828ea040af56b7835beab5fd03eab23cc9ee/butcher/targets/base.py#L139-L151 | def is_cached(self):
"""Returns true if this rule is already cached."""
# TODO: cache by target+hash, not per file.
try:
for item in self.rule.output_files:
log.info(item)
self.cachemgr.in_cache(item, self._metahash())
except cache.CacheMiss:
... | [
"def",
"is_cached",
"(",
"self",
")",
":",
"# TODO: cache by target+hash, not per file.",
"try",
":",
"for",
"item",
"in",
"self",
".",
"rule",
".",
"output_files",
":",
"log",
".",
"info",
"(",
"item",
")",
"self",
".",
"cachemgr",
".",
"in_cache",
"(",
"... | Returns true if this rule is already cached. | [
"Returns",
"true",
"if",
"this",
"rule",
"is",
"already",
"cached",
"."
] | python | train |
datamachine/twx.botapi | twx/botapi/botapi.py | https://github.com/datamachine/twx.botapi/blob/c85184da738169e8f9d6d8e62970540f427c486e/twx/botapi/botapi.py#L4306-L4308 | def send_document(self, *args, **kwargs):
"""See :func:`send_document`"""
return send_document(*args, **self._merge_overrides(**kwargs)).run() | [
"def",
"send_document",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"send_document",
"(",
"*",
"args",
",",
"*",
"*",
"self",
".",
"_merge_overrides",
"(",
"*",
"*",
"kwargs",
")",
")",
".",
"run",
"(",
")"
] | See :func:`send_document` | [
"See",
":",
"func",
":",
"send_document"
] | python | train |
jbaiter/gphoto2-cffi | gphoto2cffi/gphoto2.py | https://github.com/jbaiter/gphoto2-cffi/blob/2876d15a58174bd24613cd4106a3ef0cefd48050/gphoto2cffi/gphoto2.py#L571-L574 | def supported_operations(self):
""" All operations supported by the camera. """
return tuple(op for op in backend.CAM_OPS
if self._abilities.operations & op) | [
"def",
"supported_operations",
"(",
"self",
")",
":",
"return",
"tuple",
"(",
"op",
"for",
"op",
"in",
"backend",
".",
"CAM_OPS",
"if",
"self",
".",
"_abilities",
".",
"operations",
"&",
"op",
")"
] | All operations supported by the camera. | [
"All",
"operations",
"supported",
"by",
"the",
"camera",
"."
] | python | train |
spyder-ide/spyder | spyder/utils/misc.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/misc.py#L134-L151 | def remove_backslashes(path):
"""Remove backslashes in *path*
For Windows platforms only.
Returns the path unchanged on other platforms.
This is especially useful when formatting path strings on
Windows platforms for which folder paths may contain backslashes
and provoke unicode decodi... | [
"def",
"remove_backslashes",
"(",
"path",
")",
":",
"if",
"os",
".",
"name",
"==",
"'nt'",
":",
"# Removing trailing single backslash\r",
"if",
"path",
".",
"endswith",
"(",
"'\\\\'",
")",
"and",
"not",
"path",
".",
"endswith",
"(",
"'\\\\\\\\'",
")",
":",
... | Remove backslashes in *path*
For Windows platforms only.
Returns the path unchanged on other platforms.
This is especially useful when formatting path strings on
Windows platforms for which folder paths may contain backslashes
and provoke unicode decoding errors in Python 3 (or in Python 2
... | [
"Remove",
"backslashes",
"in",
"*",
"path",
"*",
"For",
"Windows",
"platforms",
"only",
".",
"Returns",
"the",
"path",
"unchanged",
"on",
"other",
"platforms",
".",
"This",
"is",
"especially",
"useful",
"when",
"formatting",
"path",
"strings",
"on",
"Windows",... | python | train |
OpenKMIP/PyKMIP | kmip/core/objects.py | https://github.com/OpenKMIP/PyKMIP/blob/b51c5b044bd05f8c85a1d65d13a583a4d8fc1b0e/kmip/core/objects.py#L1124-L1194 | def read(self, input_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Read the data encoding the DeviceCredential struct and decode it into
its constituent parts.
Args:
input_stream (stream): A data stream containing encoded object
data, supporting a rea... | [
"def",
"read",
"(",
"self",
",",
"input_stream",
",",
"kmip_version",
"=",
"enums",
".",
"KMIPVersion",
".",
"KMIP_1_0",
")",
":",
"super",
"(",
"DeviceCredential",
",",
"self",
")",
".",
"read",
"(",
"input_stream",
",",
"kmip_version",
"=",
"kmip_version",... | Read the data encoding the DeviceCredential struct and decode it into
its constituent parts.
Args:
input_stream (stream): A data stream containing encoded object
data, supporting a read method; usually a BytearrayStream
object.
kmip_version (KMIPV... | [
"Read",
"the",
"data",
"encoding",
"the",
"DeviceCredential",
"struct",
"and",
"decode",
"it",
"into",
"its",
"constituent",
"parts",
"."
] | python | test |
GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/network_utils.py | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/network_utils.py#L71-L90 | def _CreateInterfaceMapNetifaces(self):
"""Generate a dictionary mapping MAC address to Ethernet interfaces.
Returns:
dict, string MAC addresses mapped to the string network interface name.
"""
interfaces = {}
for interface in netifaces.interfaces():
af_link = netifaces.ifaddresses(int... | [
"def",
"_CreateInterfaceMapNetifaces",
"(",
"self",
")",
":",
"interfaces",
"=",
"{",
"}",
"for",
"interface",
"in",
"netifaces",
".",
"interfaces",
"(",
")",
":",
"af_link",
"=",
"netifaces",
".",
"ifaddresses",
"(",
"interface",
")",
".",
"get",
"(",
"ne... | Generate a dictionary mapping MAC address to Ethernet interfaces.
Returns:
dict, string MAC addresses mapped to the string network interface name. | [
"Generate",
"a",
"dictionary",
"mapping",
"MAC",
"address",
"to",
"Ethernet",
"interfaces",
"."
] | python | train |
DataDog/integrations-core | tokumx/datadog_checks/tokumx/vendor/gridfs/__init__.py | https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/tokumx/datadog_checks/tokumx/vendor/gridfs/__init__.py#L203-L224 | def delete(self, file_id):
"""Delete a file from GridFS by ``"_id"``.
Deletes all data belonging to the file with ``"_id"``:
`file_id`.
.. warning:: Any processes/threads reading from the file while
this method is executing will likely see an invalid/corrupt
file.... | [
"def",
"delete",
"(",
"self",
",",
"file_id",
")",
":",
"self",
".",
"__files",
".",
"delete_one",
"(",
"{",
"\"_id\"",
":",
"file_id",
"}",
")",
"self",
".",
"__chunks",
".",
"delete_many",
"(",
"{",
"\"files_id\"",
":",
"file_id",
"}",
")"
] | Delete a file from GridFS by ``"_id"``.
Deletes all data belonging to the file with ``"_id"``:
`file_id`.
.. warning:: Any processes/threads reading from the file while
this method is executing will likely see an invalid/corrupt
file. Care should be taken to avoid concurr... | [
"Delete",
"a",
"file",
"from",
"GridFS",
"by",
"_id",
"."
] | python | train |
numenta/htmresearch | htmresearch/frameworks/rl/dqn.py | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/rl/dqn.py#L113-L124 | def soft_target_update(self):
"""
Soft update model parameters:
.. math::
\\theta_target = \\tau \\times \\theta_local + (1 - \\tau) \\times \\theta_target ,
with \\tau \\ll 1
See https://arxiv.org/pdf/1509.02971.pdf
"""
for target_param, local_param in zip(self.target.parameters()... | [
"def",
"soft_target_update",
"(",
"self",
")",
":",
"for",
"target_param",
",",
"local_param",
"in",
"zip",
"(",
"self",
".",
"target",
".",
"parameters",
"(",
")",
",",
"self",
".",
"local",
".",
"parameters",
"(",
")",
")",
":",
"target_param",
".",
... | Soft update model parameters:
.. math::
\\theta_target = \\tau \\times \\theta_local + (1 - \\tau) \\times \\theta_target ,
with \\tau \\ll 1
See https://arxiv.org/pdf/1509.02971.pdf | [
"Soft",
"update",
"model",
"parameters",
":"
] | python | train |
snare/scruffy | scruffy/file.py | https://github.com/snare/scruffy/blob/0fedc08cfdb6db927ff93c09f25f24ce5a04c541/scruffy/file.py#L288-L296 | def apply_config(self, applicator):
"""
Replace any config tokens with values from the config.
"""
if type(self._path) == str:
self._path = applicator.apply(self._path)
for key in self._children:
self._children[key].apply_config(applicator) | [
"def",
"apply_config",
"(",
"self",
",",
"applicator",
")",
":",
"if",
"type",
"(",
"self",
".",
"_path",
")",
"==",
"str",
":",
"self",
".",
"_path",
"=",
"applicator",
".",
"apply",
"(",
"self",
".",
"_path",
")",
"for",
"key",
"in",
"self",
".",... | Replace any config tokens with values from the config. | [
"Replace",
"any",
"config",
"tokens",
"with",
"values",
"from",
"the",
"config",
"."
] | python | test |
openstack/python-monascaclient | monascaclient/v2_0/alarm_definitions.py | https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/v2_0/alarm_definitions.py#L49-L58 | def update(self, **kwargs):
"""Update a specific alarm definition."""
url_str = self.base_url + '/%s' % kwargs['alarm_id']
del kwargs['alarm_id']
resp = self.client.create(url=url_str,
method='PUT',
json=kwargs)
... | [
"def",
"update",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"url_str",
"=",
"self",
".",
"base_url",
"+",
"'/%s'",
"%",
"kwargs",
"[",
"'alarm_id'",
"]",
"del",
"kwargs",
"[",
"'alarm_id'",
"]",
"resp",
"=",
"self",
".",
"client",
".",
"create",... | Update a specific alarm definition. | [
"Update",
"a",
"specific",
"alarm",
"definition",
"."
] | python | train |
neurosnap/mudicom | mudicom/lookup.py | https://github.com/neurosnap/mudicom/blob/04011967007409f0c5253b4f308f53a7b0fc99c6/mudicom/lookup.py#L8-L54 | def VR(VR=None, description=None):
""" Value Representation (VR) <-> Description lookup.
:param VR: Takes the VR and returns its description
:param description: Take the description of a VR and returns the VR
"""
value_repr = {
"AE": "Application Entity",
"AS": "Age String",
... | [
"def",
"VR",
"(",
"VR",
"=",
"None",
",",
"description",
"=",
"None",
")",
":",
"value_repr",
"=",
"{",
"\"AE\"",
":",
"\"Application Entity\"",
",",
"\"AS\"",
":",
"\"Age String\"",
",",
"\"AT\"",
":",
"\"Attribute Tag\"",
",",
"\"CS\"",
":",
"\"Code String... | Value Representation (VR) <-> Description lookup.
:param VR: Takes the VR and returns its description
:param description: Take the description of a VR and returns the VR | [
"Value",
"Representation",
"(",
"VR",
")",
"<",
"-",
">",
"Description",
"lookup",
"."
] | python | train |
sunjinopensource/asynmsg | asynmsg.py | https://github.com/sunjinopensource/asynmsg/blob/9c1d14f859cc6702446c3bb30b9916280429bd1d/asynmsg.py#L114-L141 | def run_once(runner_list=None, extra_tick=Sleep(0.001), use_poll=False, auto_stop=True):
"""
:param auto_stop when tick error occur, stop all runners, except:
if error was from a runner tick and the runner has set 'only_stop_self_when_tick_error' to True,
then only this runner stop
"""
i... | [
"def",
"run_once",
"(",
"runner_list",
"=",
"None",
",",
"extra_tick",
"=",
"Sleep",
"(",
"0.001",
")",
",",
"use_poll",
"=",
"False",
",",
"auto_stop",
"=",
"True",
")",
":",
"if",
"runner_list",
"is",
"None",
":",
"runner_list",
"=",
"_runner_list",
"c... | :param auto_stop when tick error occur, stop all runners, except:
if error was from a runner tick and the runner has set 'only_stop_self_when_tick_error' to True,
then only this runner stop | [
":",
"param",
"auto_stop",
"when",
"tick",
"error",
"occur",
"stop",
"all",
"runners",
"except",
":",
"if",
"error",
"was",
"from",
"a",
"runner",
"tick",
"and",
"the",
"runner",
"has",
"set",
"only_stop_self_when_tick_error",
"to",
"True",
"then",
"only",
"... | python | train |
saltstack/salt | salt/modules/boto_cognitoidentity.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_cognitoidentity.py#L179-L218 | def create_identity_pool(IdentityPoolName,
AllowUnauthenticatedIdentities=False,
SupportedLoginProviders=None,
DeveloperProviderName=None,
OpenIdConnectProviderARNs=None,
region=None, key=None, k... | [
"def",
"create_identity_pool",
"(",
"IdentityPoolName",
",",
"AllowUnauthenticatedIdentities",
"=",
"False",
",",
"SupportedLoginProviders",
"=",
"None",
",",
"DeveloperProviderName",
"=",
"None",
",",
"OpenIdConnectProviderARNs",
"=",
"None",
",",
"region",
"=",
"None"... | Creates a new identity pool. All parameters except for IdentityPoolName is optional.
SupportedLoginProviders should be a dictionary mapping provider names to provider app
IDs. OpenIdConnectProviderARNs should be a list of OpenID Connect provider ARNs.
Returns the created identity pool if successful
... | [
"Creates",
"a",
"new",
"identity",
"pool",
".",
"All",
"parameters",
"except",
"for",
"IdentityPoolName",
"is",
"optional",
".",
"SupportedLoginProviders",
"should",
"be",
"a",
"dictionary",
"mapping",
"provider",
"names",
"to",
"provider",
"app",
"IDs",
".",
"O... | python | train |
influxdata/influxdb-python | influxdb/line_protocol.py | https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/influxdb/line_protocol.py#L119-L172 | def make_lines(data, precision=None):
"""Extract points from given dict.
Extracts the points from the given dict and returns a Unicode string
matching the line protocol introduced in InfluxDB 0.9.0.
"""
lines = []
static_tags = data.get('tags')
for point in data['points']:
elements ... | [
"def",
"make_lines",
"(",
"data",
",",
"precision",
"=",
"None",
")",
":",
"lines",
"=",
"[",
"]",
"static_tags",
"=",
"data",
".",
"get",
"(",
"'tags'",
")",
"for",
"point",
"in",
"data",
"[",
"'points'",
"]",
":",
"elements",
"=",
"[",
"]",
"# ad... | Extract points from given dict.
Extracts the points from the given dict and returns a Unicode string
matching the line protocol introduced in InfluxDB 0.9.0. | [
"Extract",
"points",
"from",
"given",
"dict",
"."
] | python | train |
portfoliome/postpy | postpy/ddl.py | https://github.com/portfoliome/postpy/blob/fe26199131b15295fc5f669a0ad2a7f47bf490ee/postpy/ddl.py#L39-L46 | def compile_column(name: str, data_type: str, nullable: bool) -> str:
"""Create column definition statement."""
null_str = 'NULL' if nullable else 'NOT NULL'
return '{name} {data_type} {null},'.format(name=name,
data_type=data_type,
... | [
"def",
"compile_column",
"(",
"name",
":",
"str",
",",
"data_type",
":",
"str",
",",
"nullable",
":",
"bool",
")",
"->",
"str",
":",
"null_str",
"=",
"'NULL'",
"if",
"nullable",
"else",
"'NOT NULL'",
"return",
"'{name} {data_type} {null},'",
".",
"format",
"... | Create column definition statement. | [
"Create",
"column",
"definition",
"statement",
"."
] | python | train |
manahl/arctic | arctic/store/version_store.py | https://github.com/manahl/arctic/blob/57e110b6e182dbab00e7e214dc26f7d9ec47c120/arctic/store/version_store.py#L420-L440 | def get_arctic_version(self, symbol, as_of=None):
"""
Return the numerical representation of the arctic version used to write the last (or as_of) version for
the given symbol.
Parameters
----------
symbol : `str`
symbol name for the item
as_of : `str`... | [
"def",
"get_arctic_version",
"(",
"self",
",",
"symbol",
",",
"as_of",
"=",
"None",
")",
":",
"return",
"self",
".",
"_read_metadata",
"(",
"symbol",
",",
"as_of",
"=",
"as_of",
")",
".",
"get",
"(",
"'arctic_version'",
",",
"0",
")"
] | Return the numerical representation of the arctic version used to write the last (or as_of) version for
the given symbol.
Parameters
----------
symbol : `str`
symbol name for the item
as_of : `str` or int or `datetime.datetime`
Return the data as it was a... | [
"Return",
"the",
"numerical",
"representation",
"of",
"the",
"arctic",
"version",
"used",
"to",
"write",
"the",
"last",
"(",
"or",
"as_of",
")",
"version",
"for",
"the",
"given",
"symbol",
"."
] | python | train |
lambdamusic/Ontospy | ontospy/core/ontospy.py | https://github.com/lambdamusic/Ontospy/blob/eb46cb13792b2b87f21babdf976996318eec7571/ontospy/core/ontospy.py#L594-L631 | def __buildDomainRanges(self, aProp):
"""
extract domain/range details and add to Python objects
"""
domains = chain(aProp.rdflib_graph.objects(
None, rdflib.term.URIRef(u'http://schema.org/domainIncludes')), aProp.rdflib_graph.objects(
None, rdflib.RDFS.domain))... | [
"def",
"__buildDomainRanges",
"(",
"self",
",",
"aProp",
")",
":",
"domains",
"=",
"chain",
"(",
"aProp",
".",
"rdflib_graph",
".",
"objects",
"(",
"None",
",",
"rdflib",
".",
"term",
".",
"URIRef",
"(",
"u'http://schema.org/domainIncludes'",
")",
")",
",",
... | extract domain/range details and add to Python objects | [
"extract",
"domain",
"/",
"range",
"details",
"and",
"add",
"to",
"Python",
"objects"
] | python | train |
Varkal/chuda | chuda/shell.py | https://github.com/Varkal/chuda/blob/0d93b716dede35231c21be97bcc19a656655983f/chuda/shell.py#L224-L243 | def print_live_output(self):
'''
Block and print the output of the command
Raises:
TypeError: If command is blocking
'''
if self.block:
raise TypeError(NON_BLOCKING_ERROR_MESSAGE)
else:
while self.thread.is_alive() or self.old_output_s... | [
"def",
"print_live_output",
"(",
"self",
")",
":",
"if",
"self",
".",
"block",
":",
"raise",
"TypeError",
"(",
"NON_BLOCKING_ERROR_MESSAGE",
")",
"else",
":",
"while",
"self",
".",
"thread",
".",
"is_alive",
"(",
")",
"or",
"self",
".",
"old_output_size",
... | Block and print the output of the command
Raises:
TypeError: If command is blocking | [
"Block",
"and",
"print",
"the",
"output",
"of",
"the",
"command"
] | python | train |
materialsproject/pymatgen | pymatgen/analysis/elasticity/elastic.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/analysis/elasticity/elastic.py#L890-L913 | def find_eq_stress(strains, stresses, tol=1e-10):
"""
Finds stress corresponding to zero strain state in stress-strain list
Args:
strains (Nx3x3 array-like): array corresponding to strains
stresses (Nx3x3 array-like): array corresponding to stresses
tol (float): tolerance to find ze... | [
"def",
"find_eq_stress",
"(",
"strains",
",",
"stresses",
",",
"tol",
"=",
"1e-10",
")",
":",
"stress_array",
"=",
"np",
".",
"array",
"(",
"stresses",
")",
"strain_array",
"=",
"np",
".",
"array",
"(",
"strains",
")",
"eq_stress",
"=",
"stress_array",
"... | Finds stress corresponding to zero strain state in stress-strain list
Args:
strains (Nx3x3 array-like): array corresponding to strains
stresses (Nx3x3 array-like): array corresponding to stresses
tol (float): tolerance to find zero strain state | [
"Finds",
"stress",
"corresponding",
"to",
"zero",
"strain",
"state",
"in",
"stress",
"-",
"strain",
"list"
] | python | train |
phaethon/kamene | kamene/contrib/gsm_um.py | https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/contrib/gsm_um.py#L316-L330 | def channelModeModify(VgcsTargetModeIdentication_presence=0,
MultiRateConfiguration_presence=0):
"""CHANNEL MODE MODIFY Section 9.1.5"""
a = TpPd(pd=0x6)
b = MessageType(mesType=0x8) # 0001000
c = ChannelDescription2()
d = ChannelMode()
packet = a / b / c / d
if VgcsTa... | [
"def",
"channelModeModify",
"(",
"VgcsTargetModeIdentication_presence",
"=",
"0",
",",
"MultiRateConfiguration_presence",
"=",
"0",
")",
":",
"a",
"=",
"TpPd",
"(",
"pd",
"=",
"0x6",
")",
"b",
"=",
"MessageType",
"(",
"mesType",
"=",
"0x8",
")",
"# 0001000",
... | CHANNEL MODE MODIFY Section 9.1.5 | [
"CHANNEL",
"MODE",
"MODIFY",
"Section",
"9",
".",
"1",
".",
"5"
] | python | train |
NLeSC/noodles | noodles/run/threading/sqlite3.py | https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/run/threading/sqlite3.py#L20-L47 | def pass_job(db: JobDB, result_queue: Queue, always_cache=False):
"""Create a pull stream that receives jobs and passes them on to the
database. If the job already has a result, that result is pushed onto
the `result_queue`.
"""
@pull
def pass_job_stream(job_source):
"""Pull stream insta... | [
"def",
"pass_job",
"(",
"db",
":",
"JobDB",
",",
"result_queue",
":",
"Queue",
",",
"always_cache",
"=",
"False",
")",
":",
"@",
"pull",
"def",
"pass_job_stream",
"(",
"job_source",
")",
":",
"\"\"\"Pull stream instance created by `pass_job`.\"\"\"",
"result_sink",
... | Create a pull stream that receives jobs and passes them on to the
database. If the job already has a result, that result is pushed onto
the `result_queue`. | [
"Create",
"a",
"pull",
"stream",
"that",
"receives",
"jobs",
"and",
"passes",
"them",
"on",
"to",
"the",
"database",
".",
"If",
"the",
"job",
"already",
"has",
"a",
"result",
"that",
"result",
"is",
"pushed",
"onto",
"the",
"result_queue",
"."
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.