repo stringlengths 7 55 | path stringlengths 4 223 | url stringlengths 87 315 | code stringlengths 75 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values | avg_line_len float64 7.91 980 |
|---|---|---|---|---|---|---|---|---|---|
MrYsLab/pymata-aio | examples/sparkfun_redbot/sparkfun_experiments/library/redbot.py | https://github.com/MrYsLab/pymata-aio/blob/015081a4628b9d47dfe3f8d6c698ff903f107810/examples/sparkfun_redbot/sparkfun_experiments/library/redbot.py#L147-L151 | def left_stop(self):
"""allows left motor to coast to a stop"""
self.board.digital_write(L_CTRL_1, 0)
self.board.digital_write(L_CTRL_2, 0)
self.board.analog_write(PWM_L, 0) | [
"def",
"left_stop",
"(",
"self",
")",
":",
"self",
".",
"board",
".",
"digital_write",
"(",
"L_CTRL_1",
",",
"0",
")",
"self",
".",
"board",
".",
"digital_write",
"(",
"L_CTRL_2",
",",
"0",
")",
"self",
".",
"board",
".",
"analog_write",
"(",
"PWM_L",
... | allows left motor to coast to a stop | [
"allows",
"left",
"motor",
"to",
"coast",
"to",
"a",
"stop"
] | python | train | 40.2 |
cisco-sas/kitty | kitty/model/low_level/aliases.py | https://github.com/cisco-sas/kitty/blob/cb0760989dcdfe079e43ac574d872d0b18953a32/kitty/model/low_level/aliases.py#L139-L141 | def SInt64(value, min_value=None, max_value=None, encoder=ENC_INT_DEFAULT, fuzzable=True, name=None, full_range=False):
'''Signed 64-bit field'''
return BitField(value, 64, signed=True, min_value=min_value, max_value=max_value, encoder=encoder, fuzzable=fuzzable, name=name, full_range=full_range) | [
"def",
"SInt64",
"(",
"value",
",",
"min_value",
"=",
"None",
",",
"max_value",
"=",
"None",
",",
"encoder",
"=",
"ENC_INT_DEFAULT",
",",
"fuzzable",
"=",
"True",
",",
"name",
"=",
"None",
",",
"full_range",
"=",
"False",
")",
":",
"return",
"BitField",
... | Signed 64-bit field | [
"Signed",
"64",
"-",
"bit",
"field"
] | python | train | 101 |
saltstack/salt | salt/modules/nexus.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nexus.py#L121-L149 | def get_snapshot_version_string(nexus_url, repository, group_id, artifact_id, packaging, version, classifier=None, username=None, password=None):
'''
Gets the specific version string of a snapshot of the desired version of the artifact
nexus_url
URL of nexus instance
repository
... | [
"def",
"get_snapshot_version_string",
"(",
"nexus_url",
",",
"repository",
",",
"group_id",
",",
"artifact_id",
",",
"packaging",
",",
"version",
",",
"classifier",
"=",
"None",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"log",
"."... | Gets the specific version string of a snapshot of the desired version of the artifact
nexus_url
URL of nexus instance
repository
Snapshot repository in nexus to retrieve artifact from, for example: libs-snapshots
group_id
Group Id of the artifact
artifact_id... | [
"Gets",
"the",
"specific",
"version",
"string",
"of",
"a",
"snapshot",
"of",
"the",
"desired",
"version",
"of",
"the",
"artifact"
] | python | train | 52.103448 |
saltstack/salt | salt/cloud/clouds/vmware.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vmware.py#L1748-L1772 | def list_nodes_min(kwargs=None, call=None):
'''
Return a list of all VMs and templates that are on the specified provider, with no details
CLI Example:
.. code-block:: bash
salt-cloud -f list_nodes_min my-vmware-config
'''
if call == 'action':
raise SaltCloudSystemExit(
... | [
"def",
"list_nodes_min",
"(",
"kwargs",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The list_nodes_min function must be called '",
"'with -f or --function.'",
")",
"ret",
"=",
"{",
"}... | Return a list of all VMs and templates that are on the specified provider, with no details
CLI Example:
.. code-block:: bash
salt-cloud -f list_nodes_min my-vmware-config | [
"Return",
"a",
"list",
"of",
"all",
"VMs",
"and",
"templates",
"that",
"are",
"on",
"the",
"specified",
"provider",
"with",
"no",
"details"
] | python | train | 25.84 |
cltk/cltk | cltk/prosody/latin/verse_scanner.py | https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/prosody/latin/verse_scanner.py#L372-L384 | def assign_candidate(self, verse: Verse, candidate: str) -> Verse:
"""
Helper method; make sure that the verse object is properly packaged.
:param verse:
:param candidate:
:return:
"""
verse.scansion = candidate
verse.valid = True
verse.accented =... | [
"def",
"assign_candidate",
"(",
"self",
",",
"verse",
":",
"Verse",
",",
"candidate",
":",
"str",
")",
"->",
"Verse",
":",
"verse",
".",
"scansion",
"=",
"candidate",
"verse",
".",
"valid",
"=",
"True",
"verse",
".",
"accented",
"=",
"self",
".",
"form... | Helper method; make sure that the verse object is properly packaged.
:param verse:
:param candidate:
:return: | [
"Helper",
"method",
";",
"make",
"sure",
"that",
"the",
"verse",
"object",
"is",
"properly",
"packaged",
"."
] | python | train | 31.461538 |
log2timeline/plaso | plaso/parsers/czip_plugins/oxml.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/parsers/czip_plugins/oxml.py#L191-L225 | def _ProduceEvent(
self, parser_mediator, event_data, properties, property_name,
timestamp_description, error_description):
"""Produces an event.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
even... | [
"def",
"_ProduceEvent",
"(",
"self",
",",
"parser_mediator",
",",
"event_data",
",",
"properties",
",",
"property_name",
",",
"timestamp_description",
",",
"error_description",
")",
":",
"time_string",
"=",
"properties",
".",
"get",
"(",
"property_name",
",",
"Non... | Produces an event.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
event_data (OpenXMLEventData): event data.
properties (dict[str, object]): properties.
property_name (str): name of the date and time p... | [
"Produces",
"an",
"event",
"."
] | python | train | 40.257143 |
andymccurdy/redis-py | redis/connection.py | https://github.com/andymccurdy/redis-py/blob/cdfe2befbe00db4a3c48c9ddd6d64dea15f6f0db/redis/connection.py#L148-L157 | def parse_error(self, response):
"Parse an error response"
error_code = response.split(' ')[0]
if error_code in self.EXCEPTION_CLASSES:
response = response[len(error_code) + 1:]
exception_class = self.EXCEPTION_CLASSES[error_code]
if isinstance(exception_class... | [
"def",
"parse_error",
"(",
"self",
",",
"response",
")",
":",
"error_code",
"=",
"response",
".",
"split",
"(",
"' '",
")",
"[",
"0",
"]",
"if",
"error_code",
"in",
"self",
".",
"EXCEPTION_CLASSES",
":",
"response",
"=",
"response",
"[",
"len",
"(",
"e... | Parse an error response | [
"Parse",
"an",
"error",
"response"
] | python | train | 48.2 |
cidles/pressagio | src/pressagio/dbconnector.py | https://github.com/cidles/pressagio/blob/2b3b89ae82316b929244e4c63e393682b2a57e57/src/pressagio/dbconnector.py#L583-L596 | def execute_sql(self, query):
"""
Executes a given query string on an open postgres database.
"""
c = self.con.cursor()
c.execute(query)
result = []
if c.rowcount > 0:
try:
result = c.fetchall()
except psycopg2.ProgrammingE... | [
"def",
"execute_sql",
"(",
"self",
",",
"query",
")",
":",
"c",
"=",
"self",
".",
"con",
".",
"cursor",
"(",
")",
"c",
".",
"execute",
"(",
"query",
")",
"result",
"=",
"[",
"]",
"if",
"c",
".",
"rowcount",
">",
"0",
":",
"try",
":",
"result",
... | Executes a given query string on an open postgres database. | [
"Executes",
"a",
"given",
"query",
"string",
"on",
"an",
"open",
"postgres",
"database",
"."
] | python | train | 25.357143 |
LuqueDaniel/pybooru | pybooru/api_danbooru.py | https://github.com/LuqueDaniel/pybooru/blob/60cd5254684d293b308f0b11b8f4ac2dce101479/pybooru/api_danbooru.py#L132-L139 | def post_unvote(self, post_id):
"""Action lets you unvote for a post (Requires login).
Parameters:
post_id (int):
"""
return self._get('posts/{0}/unvote.json'.format(post_id),
method='PUT', auth=True) | [
"def",
"post_unvote",
"(",
"self",
",",
"post_id",
")",
":",
"return",
"self",
".",
"_get",
"(",
"'posts/{0}/unvote.json'",
".",
"format",
"(",
"post_id",
")",
",",
"method",
"=",
"'PUT'",
",",
"auth",
"=",
"True",
")"
] | Action lets you unvote for a post (Requires login).
Parameters:
post_id (int): | [
"Action",
"lets",
"you",
"unvote",
"for",
"a",
"post",
"(",
"Requires",
"login",
")",
"."
] | python | train | 32.875 |
onelogin/python-saml | src/onelogin/saml2/logout_request.py | https://github.com/onelogin/python-saml/blob/9fe7a72da5b4caa1529c1640b52d2649447ce49b/src/onelogin/saml2/logout_request.py#L283-L302 | def get_session_indexes(request):
"""
Gets the SessionIndexes from the Logout Request
:param request: Logout Request Message
:type request: string|DOMDocument
:return: The SessionIndex value
:rtype: list
"""
if isinstance(request, etree._Element):
... | [
"def",
"get_session_indexes",
"(",
"request",
")",
":",
"if",
"isinstance",
"(",
"request",
",",
"etree",
".",
"_Element",
")",
":",
"elem",
"=",
"request",
"else",
":",
"if",
"isinstance",
"(",
"request",
",",
"Document",
")",
":",
"request",
"=",
"requ... | Gets the SessionIndexes from the Logout Request
:param request: Logout Request Message
:type request: string|DOMDocument
:return: The SessionIndex value
:rtype: list | [
"Gets",
"the",
"SessionIndexes",
"from",
"the",
"Logout",
"Request",
":",
"param",
"request",
":",
"Logout",
"Request",
"Message",
":",
"type",
"request",
":",
"string|DOMDocument",
":",
"return",
":",
"The",
"SessionIndex",
"value",
":",
"rtype",
":",
"list"
... | python | train | 39.45 |
ajdavis/mongo-mockup-db | mockupdb/__init__.py | https://github.com/ajdavis/mongo-mockup-db/blob/ff8a3f793def59e9037397ef60607fbda6949dac/mockupdb/__init__.py#L998-L1014 | def reply_bytes(self, request):
"""Take a `Request` and return an OP_REPLY message as bytes."""
flags = struct.pack("<i", self._flags)
cursor_id = struct.pack("<q", self._cursor_id)
starting_from = struct.pack("<i", self._starting_from)
number_returned = struct.pack("<i", len(sel... | [
"def",
"reply_bytes",
"(",
"self",
",",
"request",
")",
":",
"flags",
"=",
"struct",
".",
"pack",
"(",
"\"<i\"",
",",
"self",
".",
"_flags",
")",
"cursor_id",
"=",
"struct",
".",
"pack",
"(",
"\"<q\"",
",",
"self",
".",
"_cursor_id",
")",
"starting_fro... | Take a `Request` and return an OP_REPLY message as bytes. | [
"Take",
"a",
"Request",
"and",
"return",
"an",
"OP_REPLY",
"message",
"as",
"bytes",
"."
] | python | train | 45.647059 |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/distribute-0.6.31-py2.7.egg/setuptools/dist.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/distribute-0.6.31-py2.7.egg/setuptools/dist.py#L99-L104 | def check_entry_points(dist, attr, value):
"""Verify that entry_points map is parseable"""
try:
pkg_resources.EntryPoint.parse_map(value)
except ValueError, e:
raise DistutilsSetupError(e) | [
"def",
"check_entry_points",
"(",
"dist",
",",
"attr",
",",
"value",
")",
":",
"try",
":",
"pkg_resources",
".",
"EntryPoint",
".",
"parse_map",
"(",
"value",
")",
"except",
"ValueError",
",",
"e",
":",
"raise",
"DistutilsSetupError",
"(",
"e",
")"
] | Verify that entry_points map is parseable | [
"Verify",
"that",
"entry_points",
"map",
"is",
"parseable"
] | python | test | 35.166667 |
etcher-be/emiz | emiz/weather/custom_metar/custom_metar.py | https://github.com/etcher-be/emiz/blob/1c3e32711921d7e600e85558ffe5d337956372de/emiz/weather/custom_metar/custom_metar.py#L63-L116 | def string(self): # noqa: C901
"""
Return a human-readable version of the decoded report.
"""
lines = ["station: %s" % self.station_id]
if self.type:
lines.append("type: %s" % self.report_type())
if self.time:
lines.append("time: %s" % self.time.c... | [
"def",
"string",
"(",
"self",
")",
":",
"# noqa: C901",
"lines",
"=",
"[",
"\"station: %s\"",
"%",
"self",
".",
"station_id",
"]",
"if",
"self",
".",
"type",
":",
"lines",
".",
"append",
"(",
"\"type: %s\"",
"%",
"self",
".",
"report_type",
"(",
")",
"... | Return a human-readable version of the decoded report. | [
"Return",
"a",
"human",
"-",
"readable",
"version",
"of",
"the",
"decoded",
"report",
"."
] | python | train | 45.851852 |
PyCQA/astroid | astroid/raw_building.py | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/raw_building.py#L192-L202 | def object_build_methoddescriptor(node, member, localname):
"""create astroid for a living method descriptor object"""
# FIXME get arguments ?
func = build_function(
getattr(member, "__name__", None) or localname, doc=member.__doc__
)
# set node's arguments to None to notice that we have no ... | [
"def",
"object_build_methoddescriptor",
"(",
"node",
",",
"member",
",",
"localname",
")",
":",
"# FIXME get arguments ?",
"func",
"=",
"build_function",
"(",
"getattr",
"(",
"member",
",",
"\"__name__\"",
",",
"None",
")",
"or",
"localname",
",",
"doc",
"=",
... | create astroid for a living method descriptor object | [
"create",
"astroid",
"for",
"a",
"living",
"method",
"descriptor",
"object"
] | python | train | 41.727273 |
FlaskGuys/Flask-Imagine-AzureAdapter | flask_imagine_azure_adapter/__init__.py | https://github.com/FlaskGuys/Flask-Imagine-AzureAdapter/blob/1ca83fb040602ba1be983a7d1cfd052323a86f1a/flask_imagine_azure_adapter/__init__.py#L111-L127 | def remove_cached_item(self, path):
"""
Remove cached resource item
:param path: str
:return: PIL.Image
"""
item_path = '%s/%s' % (
self.cache_folder,
path.strip('/')
)
self.blob_service.delete_blob(self.container_name,... | [
"def",
"remove_cached_item",
"(",
"self",
",",
"path",
")",
":",
"item_path",
"=",
"'%s/%s'",
"%",
"(",
"self",
".",
"cache_folder",
",",
"path",
".",
"strip",
"(",
"'/'",
")",
")",
"self",
".",
"blob_service",
".",
"delete_blob",
"(",
"self",
".",
"co... | Remove cached resource item
:param path: str
:return: PIL.Image | [
"Remove",
"cached",
"resource",
"item",
":",
"param",
"path",
":",
"str",
":",
"return",
":",
"PIL",
".",
"Image"
] | python | train | 25.705882 |
chaoss/grimoirelab-perceval | perceval/backends/core/git.py | https://github.com/chaoss/grimoirelab-perceval/blob/41c908605e88b7ebc3a536c643fa0f212eaf9e0e/perceval/backends/core/git.py#L1296-L1333 | def _exec(cmd, cwd=None, env=None, ignored_error_codes=None,
encoding='utf-8'):
"""Run a command.
Execute `cmd` command in the directory set by `cwd`. Environment
variables can be set using the `env` dictionary. The output
data is returned as encoded bytes.
Comman... | [
"def",
"_exec",
"(",
"cmd",
",",
"cwd",
"=",
"None",
",",
"env",
"=",
"None",
",",
"ignored_error_codes",
"=",
"None",
",",
"encoding",
"=",
"'utf-8'",
")",
":",
"if",
"ignored_error_codes",
"is",
"None",
":",
"ignored_error_codes",
"=",
"[",
"]",
"logge... | Run a command.
Execute `cmd` command in the directory set by `cwd`. Environment
variables can be set using the `env` dictionary. The output
data is returned as encoded bytes.
Commands which their returning status codes are non-zero will
be treated as failed. Error codes conside... | [
"Run",
"a",
"command",
"."
] | python | test | 38.789474 |
tanghaibao/jcvi | jcvi/apps/ks.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/ks.py#L470-L543 | def calc(args):
"""
%prog calc [prot.fasta] cds.fasta > out.ks
Protein file is optional. If only one file is given, it is assumed to
be CDS sequences with correct frame (frame 0). Results will be written to
stdout. Both protein file and nucleotide file are assumed to be Fasta format,
with adjac... | [
"def",
"calc",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"formats",
".",
"fasta",
"import",
"translate",
"p",
"=",
"OptionParser",
"(",
"calc",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--longest\"",
",",
"action",
"=",
"\"store_true\"",
","... | %prog calc [prot.fasta] cds.fasta > out.ks
Protein file is optional. If only one file is given, it is assumed to
be CDS sequences with correct frame (frame 0). Results will be written to
stdout. Both protein file and nucleotide file are assumed to be Fasta format,
with adjacent records as the pairs to ... | [
"%prog",
"calc",
"[",
"prot",
".",
"fasta",
"]",
"cds",
".",
"fasta",
">",
"out",
".",
"ks"
] | python | train | 41.391892 |
chinapnr/fishbase | fishbase/fish_common.py | https://github.com/chinapnr/fishbase/blob/23c5147a6bc0d8ed36409e55352ffb2c5b0edc82/fishbase/fish_common.py#L924-L969 | def paging(data_list, group_number=1, group_size=10):
"""
获取分组列表数据
:param:
* data_list: (list) 需要获取分组的数据列表
* group_number: (int) 分组信息,默认为 1
* group_size: (int) 分组大小,默认为 10
:return:
* group_data: (list) 分组数据
举例如下::
print('--- paging demo---')
all_re... | [
"def",
"paging",
"(",
"data_list",
",",
"group_number",
"=",
"1",
",",
"group_size",
"=",
"10",
")",
":",
"if",
"not",
"isinstance",
"(",
"data_list",
",",
"list",
")",
":",
"raise",
"TypeError",
"(",
"'data_list should be a list, but we got {}'",
".",
"format... | 获取分组列表数据
:param:
* data_list: (list) 需要获取分组的数据列表
* group_number: (int) 分组信息,默认为 1
* group_size: (int) 分组大小,默认为 10
:return:
* group_data: (list) 分组数据
举例如下::
print('--- paging demo---')
all_records = [1, 2, 3, 4, 5]
print(get_group_list_data(all_reco... | [
"获取分组列表数据"
] | python | train | 33.173913 |
mattjj/pylds | pylds/util.py | https://github.com/mattjj/pylds/blob/e946bfa5aa76e8f8284614561a0f40ffd5d868fb/pylds/util.py#L163-L196 | def logdet_symm_block_tridiag(H_diag, H_upper_diag):
"""
compute the log determinant of a positive definite,
symmetric block tridiag matrix. Use the Kalman
info filter to do so. Specifically, the KF computes
the normalizer:
log Z = 1/2 h^T J^{-1} h -1/2 log |J| +n/2 log 2 \pi
We set ... | [
"def",
"logdet_symm_block_tridiag",
"(",
"H_diag",
",",
"H_upper_diag",
")",
":",
"T",
",",
"D",
",",
"_",
"=",
"H_diag",
".",
"shape",
"assert",
"H_diag",
".",
"ndim",
"==",
"3",
"and",
"H_diag",
".",
"shape",
"[",
"2",
"]",
"==",
"D",
"assert",
"H_... | compute the log determinant of a positive definite,
symmetric block tridiag matrix. Use the Kalman
info filter to do so. Specifically, the KF computes
the normalizer:
log Z = 1/2 h^T J^{-1} h -1/2 log |J| +n/2 log 2 \pi
We set h=0 to get -1/2 log |J| + n/2 log 2 \pi and from
this we solv... | [
"compute",
"the",
"log",
"determinant",
"of",
"a",
"positive",
"definite",
"symmetric",
"block",
"tridiag",
"matrix",
".",
"Use",
"the",
"Kalman",
"info",
"filter",
"to",
"do",
"so",
".",
"Specifically",
"the",
"KF",
"computes",
"the",
"normalizer",
":"
] | python | train | 31.323529 |
python-security/pyt | pyt/cfg/alias_helper.py | https://github.com/python-security/pyt/blob/efc0cfb716e40e0c8df4098f1cc8cf43723cd31f/pyt/cfg/alias_helper.py#L60-L65 | def not_as_alias_handler(names_list):
"""Returns a list of names ignoring any aliases."""
list_ = list()
for alias in names_list:
list_.append(alias.name)
return list_ | [
"def",
"not_as_alias_handler",
"(",
"names_list",
")",
":",
"list_",
"=",
"list",
"(",
")",
"for",
"alias",
"in",
"names_list",
":",
"list_",
".",
"append",
"(",
"alias",
".",
"name",
")",
"return",
"list_"
] | Returns a list of names ignoring any aliases. | [
"Returns",
"a",
"list",
"of",
"names",
"ignoring",
"any",
"aliases",
"."
] | python | train | 31 |
tensorflow/tensor2tensor | tensor2tensor/models/transformer.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/transformer.py#L2551-L2558 | def transformer_librispeech_tpu_v2():
"""HParams for training ASR model on Librispeech on TPU v2."""
hparams = transformer_librispeech_v2()
update_hparams_for_tpu(hparams)
hparams.batch_size = 16
librispeech.set_librispeech_length_hparams(hparams)
return hparams | [
"def",
"transformer_librispeech_tpu_v2",
"(",
")",
":",
"hparams",
"=",
"transformer_librispeech_v2",
"(",
")",
"update_hparams_for_tpu",
"(",
"hparams",
")",
"hparams",
".",
"batch_size",
"=",
"16",
"librispeech",
".",
"set_librispeech_length_hparams",
"(",
"hparams",
... | HParams for training ASR model on Librispeech on TPU v2. | [
"HParams",
"for",
"training",
"ASR",
"model",
"on",
"Librispeech",
"on",
"TPU",
"v2",
"."
] | python | train | 33.5 |
callowayproject/Calloway | calloway/menu.py | https://github.com/callowayproject/Calloway/blob/d22e98d41fbd298ab6393ba7bd84a75528be9f81/calloway/menu.py#L47-L57 | def get_url(self, url_or_dict):
"""
Returns the reversed url given a string or dict and prints errors if MENU_DEBUG is enabled
"""
if isinstance(url_or_dict, basestring):
url_or_dict = {'viewname': url_or_dict}
try:
return reverse(**url_or_dict)
ex... | [
"def",
"get_url",
"(",
"self",
",",
"url_or_dict",
")",
":",
"if",
"isinstance",
"(",
"url_or_dict",
",",
"basestring",
")",
":",
"url_or_dict",
"=",
"{",
"'viewname'",
":",
"url_or_dict",
"}",
"try",
":",
"return",
"reverse",
"(",
"*",
"*",
"url_or_dict",... | Returns the reversed url given a string or dict and prints errors if MENU_DEBUG is enabled | [
"Returns",
"the",
"reversed",
"url",
"given",
"a",
"string",
"or",
"dict",
"and",
"prints",
"errors",
"if",
"MENU_DEBUG",
"is",
"enabled"
] | python | train | 40.090909 |
edeposit/edeposit.amqp.ftp | src/edeposit/amqp/ftp/passwd_reader.py | https://github.com/edeposit/edeposit.amqp.ftp/blob/fcdcbffb6e5d194e1bb4f85f0b8eaa9dbb08aa71/src/edeposit/amqp/ftp/passwd_reader.py#L21-L73 | def load_users(path=settings.LOGIN_FILE):
"""
Read passwd file and return dict with users and all their settings.
Args:
path (str, default settings.LOGIN_FILE): path of the file,
which will be loaded (default :attr:`ftp.settings.LOGIN_FILE`).
Returns:
(dict): username: {pas... | [
"def",
"load_users",
"(",
"path",
"=",
"settings",
".",
"LOGIN_FILE",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"return",
"{",
"}",
"data",
"=",
"\"\"",
"with",
"open",
"(",
"path",
")",
"as",
"f",
":",
"data... | Read passwd file and return dict with users and all their settings.
Args:
path (str, default settings.LOGIN_FILE): path of the file,
which will be loaded (default :attr:`ftp.settings.LOGIN_FILE`).
Returns:
(dict): username: {pass_hash, uid, gid, full_name, home, shell}
Example... | [
"Read",
"passwd",
"file",
"and",
"return",
"dict",
"with",
"users",
"and",
"all",
"their",
"settings",
"."
] | python | train | 23.283019 |
streamlink/streamlink | src/streamlink/session.py | https://github.com/streamlink/streamlink/blob/c8ed1daff14ac03195870238b9b900c1109dd5c1/src/streamlink/session.py#L98-L295 | def set_option(self, key, value):
"""Sets general options used by plugins and streams originating
from this session object.
:param key: key of the option
:param value: value to set the option to
**Available options**:
======================== =========================... | [
"def",
"set_option",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"# Backwards compatibility",
"if",
"key",
"==",
"\"rtmpdump\"",
":",
"key",
"=",
"\"rtmp-rtmpdump\"",
"elif",
"key",
"==",
"\"rtmpdump-proxy\"",
":",
"key",
"=",
"\"rtmp-proxy\"",
"elif",
"k... | Sets general options used by plugins and streams originating
from this session object.
:param key: key of the option
:param value: value to set the option to
**Available options**:
======================== =========================================
hds-live-edge ... | [
"Sets",
"general",
"options",
"used",
"by",
"plugins",
"and",
"streams",
"originating",
"from",
"this",
"session",
"object",
"."
] | python | test | 44.368687 |
tanghaibao/goatools | goatools/cli/gosubdag_plot.py | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/cli/gosubdag_plot.py#L277-L290 | def _chk_docopts(self, kws):
"""Check for common user command-line errors."""
# outfile should contain .png, .png, etc.
outfile = kws['outfile']
if len(kws) == 2 and os.path.basename(kws['obo']) == "go-basic.obo" and \
kws['outfile'] == self.dflt_outfile:
self._er... | [
"def",
"_chk_docopts",
"(",
"self",
",",
"kws",
")",
":",
"# outfile should contain .png, .png, etc.",
"outfile",
"=",
"kws",
"[",
"'outfile'",
"]",
"if",
"len",
"(",
"kws",
")",
"==",
"2",
"and",
"os",
".",
"path",
".",
"basename",
"(",
"kws",
"[",
"'ob... | Check for common user command-line errors. | [
"Check",
"for",
"common",
"user",
"command",
"-",
"line",
"errors",
"."
] | python | train | 48 |
SheffieldML/GPyOpt | GPyOpt/core/task/variables.py | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/task/variables.py#L16-L36 | def expand(self):
"""
Builds a list of single dimensional variables representing current variable.
Examples:
For single dimensional variable, it is returned as is
discrete of (0,2,4) -> discrete of (0,2,4)
For multi dimensional variable, a list of variables is returned, ... | [
"def",
"expand",
"(",
"self",
")",
":",
"expanded_variables",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"dimensionality",
")",
":",
"one_d_variable",
"=",
"deepcopy",
"(",
"self",
")",
"one_d_variable",
".",
"dimensionality",
"=",
"1",
... | Builds a list of single dimensional variables representing current variable.
Examples:
For single dimensional variable, it is returned as is
discrete of (0,2,4) -> discrete of (0,2,4)
For multi dimensional variable, a list of variables is returned, each representing a single dimension
... | [
"Builds",
"a",
"list",
"of",
"single",
"dimensional",
"variables",
"representing",
"current",
"variable",
"."
] | python | train | 43.666667 |
wbond/asn1crypto | asn1crypto/core.py | https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/core.py#L3041-L3054 | def native(self):
"""
The native Python datatype representation of this value
:return:
A unicode string or None
"""
if self.contents is None:
return None
if self._native is None:
self._native = self._map[self.__int__()]
retur... | [
"def",
"native",
"(",
"self",
")",
":",
"if",
"self",
".",
"contents",
"is",
"None",
":",
"return",
"None",
"if",
"self",
".",
"_native",
"is",
"None",
":",
"self",
".",
"_native",
"=",
"self",
".",
"_map",
"[",
"self",
".",
"__int__",
"(",
")",
... | The native Python datatype representation of this value
:return:
A unicode string or None | [
"The",
"native",
"Python",
"datatype",
"representation",
"of",
"this",
"value"
] | python | train | 22.928571 |
apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_layers.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_layers.py#L878-L900 | def convert_flatten(builder, layer, input_names, output_names, keras_layer):
"""Convert a flatten layer from keras to coreml.
Parameters
keras_layer: layer
----------
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object.
"""
input_name, output... | [
"def",
"convert_flatten",
"(",
"builder",
",",
"layer",
",",
"input_names",
",",
"output_names",
",",
"keras_layer",
")",
":",
"input_name",
",",
"output_name",
"=",
"(",
"input_names",
"[",
"0",
"]",
",",
"output_names",
"[",
"0",
"]",
")",
"# blob_order ==... | Convert a flatten layer from keras to coreml.
Parameters
keras_layer: layer
----------
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object. | [
"Convert",
"a",
"flatten",
"layer",
"from",
"keras",
"to",
"coreml",
"."
] | python | train | 34.130435 |
nugget/python-insteonplm | insteonplm/messages/message.py | https://github.com/nugget/python-insteonplm/blob/65548041f1b0729ae1ae904443dd81b0c6cbf1bf/insteonplm/messages/message.py#L164-L184 | def matches_pattern(self, other):
"""Return if the current message matches a message template.
Compare the current message to a template message to test matches
to a pattern.
"""
properties = self._message_properties()
ismatch = False
if isinstance(other, Message... | [
"def",
"matches_pattern",
"(",
"self",
",",
"other",
")",
":",
"properties",
"=",
"self",
".",
"_message_properties",
"(",
")",
"ismatch",
"=",
"False",
"if",
"isinstance",
"(",
"other",
",",
"Message",
")",
"and",
"self",
".",
"code",
"==",
"other",
"."... | Return if the current message matches a message template.
Compare the current message to a template message to test matches
to a pattern. | [
"Return",
"if",
"the",
"current",
"message",
"matches",
"a",
"message",
"template",
"."
] | python | train | 38 |
DataDog/integrations-core | tokumx/datadog_checks/tokumx/vendor/pymongo/common.py | https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/tokumx/datadog_checks/tokumx/vendor/pymongo/common.py#L237-L254 | def validate_positive_float(option, value):
"""Validates that 'value' is a float, or can be converted to one, and is
positive.
"""
errmsg = "%s must be an integer or float" % (option,)
try:
value = float(value)
except ValueError:
raise ValueError(errmsg)
except TypeError:
... | [
"def",
"validate_positive_float",
"(",
"option",
",",
"value",
")",
":",
"errmsg",
"=",
"\"%s must be an integer or float\"",
"%",
"(",
"option",
",",
")",
"try",
":",
"value",
"=",
"float",
"(",
"value",
")",
"except",
"ValueError",
":",
"raise",
"ValueError"... | Validates that 'value' is a float, or can be converted to one, and is
positive. | [
"Validates",
"that",
"value",
"is",
"a",
"float",
"or",
"can",
"be",
"converted",
"to",
"one",
"and",
"is",
"positive",
"."
] | python | train | 36 |
pywbem/pywbem | pywbem/cim_operations.py | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/cim_operations.py#L1425-L1451 | def _configure_logger_handler(cls, log_dest, log_filename):
"""
Return a logging handler for the specified `log_dest`, or `None` if
`log_dest` is `None`.
"""
if log_dest is None:
return None
msg_format = '%(asctime)s-%(name)s-%(message)s'
if log_des... | [
"def",
"_configure_logger_handler",
"(",
"cls",
",",
"log_dest",
",",
"log_filename",
")",
":",
"if",
"log_dest",
"is",
"None",
":",
"return",
"None",
"msg_format",
"=",
"'%(asctime)s-%(name)s-%(message)s'",
"if",
"log_dest",
"==",
"'stderr'",
":",
"# Note: sys.stde... | Return a logging handler for the specified `log_dest`, or `None` if
`log_dest` is `None`. | [
"Return",
"a",
"logging",
"handler",
"for",
"the",
"specified",
"log_dest",
"or",
"None",
"if",
"log_dest",
"is",
"None",
"."
] | python | train | 37.925926 |
RedFantom/ttkwidgets | ttkwidgets/frames/balloon.py | https://github.com/RedFantom/ttkwidgets/blob/02150322060f867b6e59a175522ef84b09168019/ttkwidgets/frames/balloon.py#L129-L144 | def config(self, **kwargs):
"""
Configure resources of the widget.
To get the list of options for this widget, call the method :meth:`~Balloon.keys`.
See :meth:`~Balloon.__init__` for a description of the widget specific option.
"""
self.__headertext = kwargs.pop("header... | [
"def",
"config",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"__headertext",
"=",
"kwargs",
".",
"pop",
"(",
"\"headertext\"",
",",
"self",
".",
"__headertext",
")",
"self",
".",
"__text",
"=",
"kwargs",
".",
"pop",
"(",
"\"text\"",
... | Configure resources of the widget.
To get the list of options for this widget, call the method :meth:`~Balloon.keys`.
See :meth:`~Balloon.__init__` for a description of the widget specific option. | [
"Configure",
"resources",
"of",
"the",
"widget",
"."
] | python | train | 43.6875 |
pltrdy/rouge | rouge/rouge_score.py | https://github.com/pltrdy/rouge/blob/7bf8a83af5ca5c1677b93620b4e1f85ffd63b377/rouge/rouge_score.py#L227-L267 | def _union_lcs(evaluated_sentences, reference_sentence, prev_union=None):
"""
Returns LCS_u(r_i, C) which is the LCS score of the union longest common
subsequence between reference sentence ri and candidate summary C.
For example:
if r_i= w1 w2 w3 w4 w5, and C contains two sentences: c1 = w1 w2 w6 w... | [
"def",
"_union_lcs",
"(",
"evaluated_sentences",
",",
"reference_sentence",
",",
"prev_union",
"=",
"None",
")",
":",
"if",
"prev_union",
"is",
"None",
":",
"prev_union",
"=",
"set",
"(",
")",
"if",
"len",
"(",
"evaluated_sentences",
")",
"<=",
"0",
":",
"... | Returns LCS_u(r_i, C) which is the LCS score of the union longest common
subsequence between reference sentence ri and candidate summary C.
For example:
if r_i= w1 w2 w3 w4 w5, and C contains two sentences: c1 = w1 w2 w6 w7 w8
and c2 = w1 w3 w8 w9 w5, then the longest common subsequence of r_i and c1
... | [
"Returns",
"LCS_u",
"(",
"r_i",
"C",
")",
"which",
"is",
"the",
"LCS",
"score",
"of",
"the",
"union",
"longest",
"common",
"subsequence",
"between",
"reference",
"sentence",
"ri",
"and",
"candidate",
"summary",
"C",
".",
"For",
"example",
":",
"if",
"r_i",... | python | test | 36.487805 |
hthiery/python-fritzhome | pyfritzhome/fritzhome.py | https://github.com/hthiery/python-fritzhome/blob/c74bd178d08a305028f316f7da35202da3526f61/pyfritzhome/fritzhome.py#L505-L520 | def set_hkr_state(self, state):
"""Set the state of the thermostat.
Possible values for state are: 'on', 'off', 'comfort', 'eco'.
"""
try:
value = {
'off': 0,
'on': 100,
'eco': self.eco_temperature,
'comfort': s... | [
"def",
"set_hkr_state",
"(",
"self",
",",
"state",
")",
":",
"try",
":",
"value",
"=",
"{",
"'off'",
":",
"0",
",",
"'on'",
":",
"100",
",",
"'eco'",
":",
"self",
".",
"eco_temperature",
",",
"'comfort'",
":",
"self",
".",
"comfort_temperature",
"}",
... | Set the state of the thermostat.
Possible values for state are: 'on', 'off', 'comfort', 'eco'. | [
"Set",
"the",
"state",
"of",
"the",
"thermostat",
"."
] | python | train | 27.3125 |
ejeschke/ginga | ginga/util/iqcalc.py | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/util/iqcalc.py#L46-L51 | def get_median(data_np):
"""Like :func:`get_mean` but for median."""
i = np.isfinite(data_np)
if not np.any(i):
return np.nan
return np.median(data_np[i]) | [
"def",
"get_median",
"(",
"data_np",
")",
":",
"i",
"=",
"np",
".",
"isfinite",
"(",
"data_np",
")",
"if",
"not",
"np",
".",
"any",
"(",
"i",
")",
":",
"return",
"np",
".",
"nan",
"return",
"np",
".",
"median",
"(",
"data_np",
"[",
"i",
"]",
")... | Like :func:`get_mean` but for median. | [
"Like",
":",
"func",
":",
"get_mean",
"but",
"for",
"median",
"."
] | python | train | 28.833333 |
pgmpy/pgmpy | pgmpy/factors/distributions/GaussianDistribution.py | https://github.com/pgmpy/pgmpy/blob/9381a66aba3c3871d3ccd00672b148d17d63239e/pgmpy/factors/distributions/GaussianDistribution.py#L466-L506 | def product(self, other, inplace=True):
"""
TODO: Make it work when using `*` instead of product.
Returns the product of two gaussian distributions.
Parameters
----------
other: GaussianDistribution
The GaussianDistribution to be multiplied.
inplace... | [
"def",
"product",
"(",
"self",
",",
"other",
",",
"inplace",
"=",
"True",
")",
":",
"return",
"self",
".",
"_operate",
"(",
"other",
",",
"operation",
"=",
"'product'",
",",
"inplace",
"=",
"inplace",
")"
] | TODO: Make it work when using `*` instead of product.
Returns the product of two gaussian distributions.
Parameters
----------
other: GaussianDistribution
The GaussianDistribution to be multiplied.
inplace: boolean
If True, modifies the distribution its... | [
"TODO",
":",
"Make",
"it",
"work",
"when",
"using",
"*",
"instead",
"of",
"product",
"."
] | python | train | 34.634146 |
ZELLMECHANIK-DRESDEN/dclab | dclab/statistics.py | https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/statistics.py#L92-L150 | def get_statistics(ds, methods=None, features=None):
"""Compute statistics for an RT-DC dataset
Parameters
----------
ds: dclab.rtdc_dataset.RTDCBase
The dataset for which to compute the statistics.
methods: list of str or None
The methods wih which to compute the statistics.
... | [
"def",
"get_statistics",
"(",
"ds",
",",
"methods",
"=",
"None",
",",
"features",
"=",
"None",
")",
":",
"if",
"methods",
"is",
"None",
":",
"cls",
"=",
"list",
"(",
"Statistics",
".",
"available_methods",
".",
"keys",
"(",
")",
")",
"# sort the features... | Compute statistics for an RT-DC dataset
Parameters
----------
ds: dclab.rtdc_dataset.RTDCBase
The dataset for which to compute the statistics.
methods: list of str or None
The methods wih which to compute the statistics.
The list of available methods is given with
`dclab... | [
"Compute",
"statistics",
"for",
"an",
"RT",
"-",
"DC",
"dataset"
] | python | train | 35.474576 |
standage/tag | tag/__main__.py | https://github.com/standage/tag/blob/94686adf57115cea1c5235e99299e691f80ba10b/tag/__main__.py#L22-L36 | def main(args=None):
"""
Entry point for the tag CLI.
Isolated as a method so that the CLI can be called by other Python code
(e.g. for testing), in which case the arguments are passed to the function.
If no arguments are passed to the function, parse them from the command
line.
"""
if ... | [
"def",
"main",
"(",
"args",
"=",
"None",
")",
":",
"if",
"args",
"is",
"None",
":",
"args",
"=",
"tag",
".",
"cli",
".",
"parser",
"(",
")",
".",
"parse_args",
"(",
")",
"assert",
"args",
".",
"cmd",
"in",
"mains",
"mainmethod",
"=",
"mains",
"["... | Entry point for the tag CLI.
Isolated as a method so that the CLI can be called by other Python code
(e.g. for testing), in which case the arguments are passed to the function.
If no arguments are passed to the function, parse them from the command
line. | [
"Entry",
"point",
"for",
"the",
"tag",
"CLI",
"."
] | python | train | 29.866667 |
angr/angr | angr/state_plugins/heap/heap_freelist.py | https://github.com/angr/angr/blob/4e2f97d56af5419ee73bdb30482c8dd8ff5f3e40/angr/state_plugins/heap/heap_freelist.py#L73-L78 | def fwd_chunk(self):
"""
Returns the chunk following this chunk in the list of free chunks.
"""
raise NotImplementedError("%s not implemented for %s" % (self.fwd_chunk.__func__.__name__,
self.__class__.__name__)) | [
"def",
"fwd_chunk",
"(",
"self",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"%s not implemented for %s\"",
"%",
"(",
"self",
".",
"fwd_chunk",
".",
"__func__",
".",
"__name__",
",",
"self",
".",
"__class__",
".",
"__name__",
")",
")"
] | Returns the chunk following this chunk in the list of free chunks. | [
"Returns",
"the",
"chunk",
"following",
"this",
"chunk",
"in",
"the",
"list",
"of",
"free",
"chunks",
"."
] | python | train | 50.666667 |
ga4gh/ga4gh-server | ga4gh/server/datamodel/continuous.py | https://github.com/ga4gh/ga4gh-server/blob/1aa18922ef136db8604f6f098cb1732cba6f2a76/ga4gh/server/datamodel/continuous.py#L358-L364 | def populateFromRow(self, continuousSetRecord):
"""
Populates the instance variables of this ContinuousSet from the
specified DB row.
"""
self._filePath = continuousSetRecord.dataurl
self.setAttributesJson(continuousSetRecord.attributes) | [
"def",
"populateFromRow",
"(",
"self",
",",
"continuousSetRecord",
")",
":",
"self",
".",
"_filePath",
"=",
"continuousSetRecord",
".",
"dataurl",
"self",
".",
"setAttributesJson",
"(",
"continuousSetRecord",
".",
"attributes",
")"
] | Populates the instance variables of this ContinuousSet from the
specified DB row. | [
"Populates",
"the",
"instance",
"variables",
"of",
"this",
"ContinuousSet",
"from",
"the",
"specified",
"DB",
"row",
"."
] | python | train | 39.857143 |
Blueqat/Blueqat | blueqat/circuit.py | https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/circuit.py#L312-L340 | def register_gate(name, gateclass, allow_overwrite=False):
"""Register new gate to gate set.
Args:
name (str): The name of gate.
gateclass (type): The type object of gate.
allow_overwrite (bool, optional): If True, allow to overwrite the existing gate.
... | [
"def",
"register_gate",
"(",
"name",
",",
"gateclass",
",",
"allow_overwrite",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"Circuit",
",",
"name",
")",
":",
"if",
"allow_overwrite",
":",
"warnings",
".",
"warn",
"(",
"f\"Circuit has attribute `{name}`.\"",
"... | Register new gate to gate set.
Args:
name (str): The name of gate.
gateclass (type): The type object of gate.
allow_overwrite (bool, optional): If True, allow to overwrite the existing gate.
Otherwise, raise the ValueError.
Raises:
ValueE... | [
"Register",
"new",
"gate",
"to",
"gate",
"set",
"."
] | python | train | 43.862069 |
swharden/SWHLab | swhlab/analysis/protocols.py | https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/swhlab/analysis/protocols.py#L82-L134 | def proto_0111(theABF):
"""protocol: IC ramp for AP shape analysis."""
abf=ABF(theABF)
abf.log.info("analyzing as an IC ramp")
# AP detection
ap=AP(abf)
ap.detect()
# also calculate derivative for each sweep
abf.derivative=True
# create the multi-plot figure
plt.figure(figsize... | [
"def",
"proto_0111",
"(",
"theABF",
")",
":",
"abf",
"=",
"ABF",
"(",
"theABF",
")",
"abf",
".",
"log",
".",
"info",
"(",
"\"analyzing as an IC ramp\"",
")",
"# AP detection",
"ap",
"=",
"AP",
"(",
"abf",
")",
"ap",
".",
"detect",
"(",
")",
"# also cal... | protocol: IC ramp for AP shape analysis. | [
"protocol",
":",
"IC",
"ramp",
"for",
"AP",
"shape",
"analysis",
"."
] | python | valid | 31.735849 |
bioidiap/bob.bio.spear | bob/bio/spear/utils/extraction.py | https://github.com/bioidiap/bob.bio.spear/blob/9f5d13d2e52d3b0c818f4abaa07cda15f62a34cd/bob/bio/spear/utils/extraction.py#L40-L51 | def calc_std(c0, c1=[]):
""" Calculates the variance of the data."""
if c1 == []:
return numpy.std(c0, 0)
prop = float(len(c0)) / float(len(c1))
if prop < 1:
p0 = int(math.ceil(1 / prop))
p1 = 1
else:
p0 = 1
p1 = int(math.ceil(prop))
return numpy.std(numpy... | [
"def",
"calc_std",
"(",
"c0",
",",
"c1",
"=",
"[",
"]",
")",
":",
"if",
"c1",
"==",
"[",
"]",
":",
"return",
"numpy",
".",
"std",
"(",
"c0",
",",
"0",
")",
"prop",
"=",
"float",
"(",
"len",
"(",
"c0",
")",
")",
"/",
"float",
"(",
"len",
"... | Calculates the variance of the data. | [
"Calculates",
"the",
"variance",
"of",
"the",
"data",
"."
] | python | train | 28.583333 |
dschep/ntfy | ntfy/backends/telegram.py | https://github.com/dschep/ntfy/blob/ecfeee960af406a27ebb123495e0ec2733286889/ntfy/backends/telegram.py#L11-L18 | def notify(title, message, retcode=None):
"""Sends message over Telegram using telegram-send, title is ignored."""
if not path.exists(config_file):
if not path.exists(config_dir):
makedirs(config_dir)
print("Follow the instructions to configure the Telegram backend.\n")
confi... | [
"def",
"notify",
"(",
"title",
",",
"message",
",",
"retcode",
"=",
"None",
")",
":",
"if",
"not",
"path",
".",
"exists",
"(",
"config_file",
")",
":",
"if",
"not",
"path",
".",
"exists",
"(",
"config_dir",
")",
":",
"makedirs",
"(",
"config_dir",
")... | Sends message over Telegram using telegram-send, title is ignored. | [
"Sends",
"message",
"over",
"Telegram",
"using",
"telegram",
"-",
"send",
"title",
"is",
"ignored",
"."
] | python | train | 47.125 |
PiotrDabkowski/Js2Py | js2py/internals/code.py | https://github.com/PiotrDabkowski/Js2Py/blob/c0fa43f5679cf91ca8986c5747fcb07a433dc584/js2py/internals/code.py#L76-L104 | def execute_fragment_under_context(self, ctx, start_label, end_label):
''' just like run but returns if moved outside of the specified fragment
# 4 different exectution results
# 0=normal, 1=return, 2=jump_outside, 3=errors
# execute_fragment_under_context returns:
... | [
"def",
"execute_fragment_under_context",
"(",
"self",
",",
"ctx",
",",
"start_label",
",",
"end_label",
")",
":",
"old_curr_ctx",
"=",
"self",
".",
"current_ctx",
"self",
".",
"ctx_depth",
"+=",
"1",
"old_stack_len",
"=",
"len",
"(",
"ctx",
".",
"stack",
")"... | just like run but returns if moved outside of the specified fragment
# 4 different exectution results
# 0=normal, 1=return, 2=jump_outside, 3=errors
# execute_fragment_under_context returns:
# (return_value, typ, return_value/jump_loc/py_error)
# IMPARTANT: It... | [
"just",
"like",
"run",
"but",
"returns",
"if",
"moved",
"outside",
"of",
"the",
"specified",
"fragment",
"#",
"4",
"different",
"exectution",
"results",
"#",
"0",
"=",
"normal",
"1",
"=",
"return",
"2",
"=",
"jump_outside",
"3",
"=",
"errors",
"#",
"exec... | python | valid | 45.655172 |
JensAstrup/pyOutlook | pyOutlook/core/message.py | https://github.com/JensAstrup/pyOutlook/blob/f4ca9d4a8629c0a41f78102ce84fab702a841167/pyOutlook/core/message.py#L358-L370 | def reply_all(self, reply_comment):
"""Replies to everyone on the email, including those on the CC line.
With great power, comes great responsibility.
Args:
reply_comment: The string comment to send to everyone on the email.
"""
payload = '{ "Comment": "' + reply_c... | [
"def",
"reply_all",
"(",
"self",
",",
"reply_comment",
")",
":",
"payload",
"=",
"'{ \"Comment\": \"'",
"+",
"reply_comment",
"+",
"'\"}'",
"endpoint",
"=",
"'https://outlook.office.com/api/v2.0/me/messages/{}/replyall'",
".",
"format",
"(",
"self",
".",
"message_id",
... | Replies to everyone on the email, including those on the CC line.
With great power, comes great responsibility.
Args:
reply_comment: The string comment to send to everyone on the email. | [
"Replies",
"to",
"everyone",
"on",
"the",
"email",
"including",
"those",
"on",
"the",
"CC",
"line",
"."
] | python | train | 37.461538 |
vmonaco/pohmm | pohmm/utils.py | https://github.com/vmonaco/pohmm/blob/c00f8a62d3005a171d424549a55d46c421859ae9/pohmm/utils.py#L88-L103 | def full2ph(trans, n_pstates):
"""
Convert a full transmat to the respective p-state and h-state transmats
"""
n_hstates = len(trans) / n_pstates
htrans = np.zeros((n_pstates, n_pstates, n_hstates, n_hstates))
for pidx1, pidx2 in product(range(n_pstates), range(n_pstates)):
idx1 = pidx1... | [
"def",
"full2ph",
"(",
"trans",
",",
"n_pstates",
")",
":",
"n_hstates",
"=",
"len",
"(",
"trans",
")",
"/",
"n_pstates",
"htrans",
"=",
"np",
".",
"zeros",
"(",
"(",
"n_pstates",
",",
"n_pstates",
",",
"n_hstates",
",",
"n_hstates",
")",
")",
"for",
... | Convert a full transmat to the respective p-state and h-state transmats | [
"Convert",
"a",
"full",
"transmat",
"to",
"the",
"respective",
"p",
"-",
"state",
"and",
"h",
"-",
"state",
"transmats"
] | python | train | 35.3125 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L1134-L1137 | def p_empty_statement(self, p):
"""empty_statement : SEMI"""
p[0] = self.asttypes.EmptyStatement(p[1])
p[0].setpos(p) | [
"def",
"p_empty_statement",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes",
".",
"EmptyStatement",
"(",
"p",
"[",
"1",
"]",
")",
"p",
"[",
"0",
"]",
".",
"setpos",
"(",
"p",
")"
] | empty_statement : SEMI | [
"empty_statement",
":",
"SEMI"
] | python | train | 34.5 |
profitbricks/profitbricks-sdk-python | profitbricks/client.py | https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L2075-L2094 | def get_resource(self, resource_type, resource_id, depth=1):
"""
Retrieves a single resource of a particular type.
:param resource_type: The resource type: datacenter, image,
snapshot or ipblock.
:type resource_type: ``str``
:param ... | [
"def",
"get_resource",
"(",
"self",
",",
"resource_type",
",",
"resource_id",
",",
"depth",
"=",
"1",
")",
":",
"response",
"=",
"self",
".",
"_perform_request",
"(",
"'/um/resources/%s/%s?depth=%s'",
"%",
"(",
"resource_type",
",",
"resource_id",
",",
"str",
... | Retrieves a single resource of a particular type.
:param resource_type: The resource type: datacenter, image,
snapshot or ipblock.
:type resource_type: ``str``
:param resource_id: The unique ID of the resource.
:type resource_id:... | [
"Retrieves",
"a",
"single",
"resource",
"of",
"a",
"particular",
"type",
"."
] | python | valid | 33.45 |
pydata/xarray | xarray/backends/api.py | https://github.com/pydata/xarray/blob/6d93a95d05bdbfc33fff24064f67d29dd891ab58/xarray/backends/api.py#L829-L851 | def dump_to_store(dataset, store, writer=None, encoder=None,
encoding=None, unlimited_dims=None):
"""Store dataset contents to a backends.*DataStore object."""
if writer is None:
writer = ArrayWriter()
if encoding is None:
encoding = {}
variables, attrs = conventions.... | [
"def",
"dump_to_store",
"(",
"dataset",
",",
"store",
",",
"writer",
"=",
"None",
",",
"encoder",
"=",
"None",
",",
"encoding",
"=",
"None",
",",
"unlimited_dims",
"=",
"None",
")",
":",
"if",
"writer",
"is",
"None",
":",
"writer",
"=",
"ArrayWriter",
... | Store dataset contents to a backends.*DataStore object. | [
"Store",
"dataset",
"contents",
"to",
"a",
"backends",
".",
"*",
"DataStore",
"object",
"."
] | python | train | 32.826087 |
lsst-sqre/documenteer | documenteer/requestsutils.py | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/requestsutils.py#L11-L52 | def requests_retry_session(
retries=3,
backoff_factor=0.3,
status_forcelist=(500, 502, 504),
session=None):
"""Create a requests session that handles errors by retrying.
Parameters
----------
retries : `int`, optional
Number of retries to attempt.
backoff_fac... | [
"def",
"requests_retry_session",
"(",
"retries",
"=",
"3",
",",
"backoff_factor",
"=",
"0.3",
",",
"status_forcelist",
"=",
"(",
"500",
",",
"502",
",",
"504",
")",
",",
"session",
"=",
"None",
")",
":",
"session",
"=",
"session",
"or",
"requests",
".",
... | Create a requests session that handles errors by retrying.
Parameters
----------
retries : `int`, optional
Number of retries to attempt.
backoff_factor : `float`, optional
Backoff factor.
status_forcelist : sequence of `str`, optional
Status codes that must be retried.
s... | [
"Create",
"a",
"requests",
"session",
"that",
"handles",
"errors",
"by",
"retrying",
"."
] | python | train | 27.880952 |
angr/claripy | claripy/ast/strings.py | https://github.com/angr/claripy/blob/4ed61924880af1ea8fb778047d896ec0156412a6/claripy/ast/strings.py#L79-L86 | def indexOf(self, pattern, start_idx, bitlength):
"""
Return the start index of the pattern inside the input string in a
Bitvector representation, otherwise it returns -1 (always using a BitVector)
:param bitlength: size of the biitvector holding the result
"""
return St... | [
"def",
"indexOf",
"(",
"self",
",",
"pattern",
",",
"start_idx",
",",
"bitlength",
")",
":",
"return",
"StrIndexOf",
"(",
"self",
",",
"pattern",
",",
"start_idx",
",",
"bitlength",
")"
] | Return the start index of the pattern inside the input string in a
Bitvector representation, otherwise it returns -1 (always using a BitVector)
:param bitlength: size of the biitvector holding the result | [
"Return",
"the",
"start",
"index",
"of",
"the",
"pattern",
"inside",
"the",
"input",
"string",
"in",
"a",
"Bitvector",
"representation",
"otherwise",
"it",
"returns",
"-",
"1",
"(",
"always",
"using",
"a",
"BitVector",
")"
] | python | train | 44.75 |
mayfield/shellish | shellish/command/command.py | https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/command/command.py#L320-L331 | def create_argparser(self):
""" Factory for arg parser. Can be overridden as long as it returns
an ArgParser compatible instance. """
if self.desc:
if self.title:
fulldesc = '%s\n\n%s' % (self.title, self.desc)
else:
fulldesc = self.desc
... | [
"def",
"create_argparser",
"(",
"self",
")",
":",
"if",
"self",
".",
"desc",
":",
"if",
"self",
".",
"title",
":",
"fulldesc",
"=",
"'%s\\n\\n%s'",
"%",
"(",
"self",
".",
"title",
",",
"self",
".",
"desc",
")",
"else",
":",
"fulldesc",
"=",
"self",
... | Factory for arg parser. Can be overridden as long as it returns
an ArgParser compatible instance. | [
"Factory",
"for",
"arg",
"parser",
".",
"Can",
"be",
"overridden",
"as",
"long",
"as",
"it",
"returns",
"an",
"ArgParser",
"compatible",
"instance",
"."
] | python | train | 39.75 |
alphatwirl/alphatwirl | alphatwirl/concurrently/SubprocessRunner.py | https://github.com/alphatwirl/alphatwirl/blob/5138eeba6cd8a334ba52d6c2c022b33c61e3ba38/alphatwirl/concurrently/SubprocessRunner.py#L81-L87 | def wait(self):
"""wait until all jobs finish and return a list of pids
"""
finished_pids = [ ]
while self.running_procs:
finished_pids.extend(self.poll())
return finished_pids | [
"def",
"wait",
"(",
"self",
")",
":",
"finished_pids",
"=",
"[",
"]",
"while",
"self",
".",
"running_procs",
":",
"finished_pids",
".",
"extend",
"(",
"self",
".",
"poll",
"(",
")",
")",
"return",
"finished_pids"
] | wait until all jobs finish and return a list of pids | [
"wait",
"until",
"all",
"jobs",
"finish",
"and",
"return",
"a",
"list",
"of",
"pids"
] | python | valid | 31.714286 |
genepattern/genepattern-python | gp/core.py | https://github.com/genepattern/genepattern-python/blob/9478ea65362b91c72a94f7300c3de8d710bebb71/gp/core.py#L766-L775 | def allow_choice_custom_value(self):
"""
Returns boolean indicating whether choice parameter supports custom value.
If choice parameter supports custom value, user can provide parameter value
other than those provided in choice list.
"""
if 'choiceInfo' not in self.dto[s... | [
"def",
"allow_choice_custom_value",
"(",
"self",
")",
":",
"if",
"'choiceInfo'",
"not",
"in",
"self",
".",
"dto",
"[",
"self",
".",
"name",
"]",
":",
"raise",
"GPException",
"(",
"'not a choice parameter'",
")",
"return",
"self",
".",
"_is_string_true",
"(",
... | Returns boolean indicating whether choice parameter supports custom value.
If choice parameter supports custom value, user can provide parameter value
other than those provided in choice list. | [
"Returns",
"boolean",
"indicating",
"whether",
"choice",
"parameter",
"supports",
"custom",
"value",
"."
] | python | train | 46.9 |
epfl-lts2/pygsp | pygsp/reduction.py | https://github.com/epfl-lts2/pygsp/blob/8ce5bde39206129287375af24fdbcd7edddca8c5/pygsp/reduction.py#L616-L726 | def tree_multiresolution(G, Nlevel, reduction_method='resistance_distance',
compute_full_eigen=False, root=None):
r"""Compute a multiresolution of trees
Parameters
----------
G : Graph
Graph structure of a tree.
Nlevel : Number of times to downsample and coarsen the... | [
"def",
"tree_multiresolution",
"(",
"G",
",",
"Nlevel",
",",
"reduction_method",
"=",
"'resistance_distance'",
",",
"compute_full_eigen",
"=",
"False",
",",
"root",
"=",
"None",
")",
":",
"if",
"not",
"root",
":",
"if",
"hasattr",
"(",
"G",
",",
"'root'",
... | r"""Compute a multiresolution of trees
Parameters
----------
G : Graph
Graph structure of a tree.
Nlevel : Number of times to downsample and coarsen the tree
root : int
The index of the root of the tree. (default = 1)
reduction_method : str
The graph reduction method (de... | [
"r",
"Compute",
"a",
"multiresolution",
"of",
"trees"
] | python | train | 44.621622 |
kibitzr/kibitzr | kibitzr/app.py | https://github.com/kibitzr/kibitzr/blob/749da312488f1dda1ed1093cf4c95aaac0a604f7/kibitzr/app.py#L157-L167 | def before_start(self, checkers):
"""
Loads entry points named kibitzr.before_start
and call each one with two arguments:
1. Application instance;
2. List of configured checkers
"""
for point in entrypoints.get_group_all("kibitzr.before_start"):
... | [
"def",
"before_start",
"(",
"self",
",",
"checkers",
")",
":",
"for",
"point",
"in",
"entrypoints",
".",
"get_group_all",
"(",
"\"kibitzr.before_start\"",
")",
":",
"entry",
"=",
"point",
".",
"load",
"(",
")",
"entry",
"(",
"self",
",",
"checkers",
")"
] | Loads entry points named kibitzr.before_start
and call each one with two arguments:
1. Application instance;
2. List of configured checkers | [
"Loads",
"entry",
"points",
"named",
"kibitzr",
".",
"before_start",
"and",
"call",
"each",
"one",
"with",
"two",
"arguments",
":"
] | python | train | 33.363636 |
pymupdf/PyMuPDF | fitz/fitz.py | https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L411-L451 | def distance_to(self, *args):
"""Return the distance to a rectangle or another point."""
if not len(args) > 0:
raise ValueError("at least one parameter must be given")
x = args[0]
if len(args) > 1:
unit = args[1]
else:
unit = "px"
u = ... | [
"def",
"distance_to",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"not",
"len",
"(",
"args",
")",
">",
"0",
":",
"raise",
"ValueError",
"(",
"\"at least one parameter must be given\"",
")",
"x",
"=",
"args",
"[",
"0",
"]",
"if",
"len",
"(",
"args",
... | Return the distance to a rectangle or another point. | [
"Return",
"the",
"distance",
"to",
"a",
"rectangle",
"or",
"another",
"point",
"."
] | python | train | 33.170732 |
mosdef-hub/mbuild | mbuild/formats/gsdwriter.py | https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/formats/gsdwriter.py#L98-L132 | def _write_particle_information(gsd_file, structure, xyz, ref_distance,
ref_mass, ref_energy, rigid_bodies):
"""Write out the particle information.
"""
gsd_file.particles.N = len(structure.atoms)
gsd_file.particles.position = xyz / ref_distance
types = [atom.name if atom.type == '' else a... | [
"def",
"_write_particle_information",
"(",
"gsd_file",
",",
"structure",
",",
"xyz",
",",
"ref_distance",
",",
"ref_mass",
",",
"ref_energy",
",",
"rigid_bodies",
")",
":",
"gsd_file",
".",
"particles",
".",
"N",
"=",
"len",
"(",
"structure",
".",
"atoms",
"... | Write out the particle information. | [
"Write",
"out",
"the",
"particle",
"information",
"."
] | python | train | 33.628571 |
tensorflow/probability | tensorflow_probability/python/mcmc/random_walk_metropolis.py | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/random_walk_metropolis.py#L112-L170 | def random_walk_uniform_fn(scale=1., name=None):
"""Returns a callable that adds a random uniform perturbation to the input.
For more details on `random_walk_uniform_fn`, see
`random_walk_normal_fn`. `scale` might
be a `Tensor` or a list of `Tensor`s that should broadcast with state parts
of the `current_sta... | [
"def",
"random_walk_uniform_fn",
"(",
"scale",
"=",
"1.",
",",
"name",
"=",
"None",
")",
":",
"def",
"_fn",
"(",
"state_parts",
",",
"seed",
")",
":",
"\"\"\"Adds a uniform perturbation to the input state.\n\n Args:\n state_parts: A list of `Tensor`s of any shape and ... | Returns a callable that adds a random uniform perturbation to the input.
For more details on `random_walk_uniform_fn`, see
`random_walk_normal_fn`. `scale` might
be a `Tensor` or a list of `Tensor`s that should broadcast with state parts
of the `current_state`. The generated uniform perturbation is sampled as ... | [
"Returns",
"a",
"callable",
"that",
"adds",
"a",
"random",
"uniform",
"perturbation",
"to",
"the",
"input",
"."
] | python | test | 41.525424 |
minhhoit/yacms | yacms/utils/views.py | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/utils/views.py#L161-L180 | def render(request, templates, dictionary=None, context_instance=None,
**kwargs):
"""
Mimics ``django.shortcuts.render`` but uses a TemplateResponse for
``yacms.core.middleware.TemplateForDeviceMiddleware``
"""
warnings.warn(
"yacms.utils.views.render is deprecated and will be re... | [
"def",
"render",
"(",
"request",
",",
"templates",
",",
"dictionary",
"=",
"None",
",",
"context_instance",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"warnings",
".",
"warn",
"(",
"\"yacms.utils.views.render is deprecated and will be removed \"",
"\"in a futur... | Mimics ``django.shortcuts.render`` but uses a TemplateResponse for
``yacms.core.middleware.TemplateForDeviceMiddleware`` | [
"Mimics",
"django",
".",
"shortcuts",
".",
"render",
"but",
"uses",
"a",
"TemplateResponse",
"for",
"yacms",
".",
"core",
".",
"middleware",
".",
"TemplateForDeviceMiddleware"
] | python | train | 37.15 |
saltstack/salt | salt/runners/manage.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/manage.py#L254-L287 | def list_not_state(subset=None, show_ip=False, show_ipv4=None):
'''
.. versionadded:: 2015.8.0
.. versionchanged:: 2019.2.0
The 'show_ipv4' argument has been renamed to 'show_ip' as it now
includes IPv6 addresses for IPv6-connected minions.
Print a list of all minions that are NOT up ac... | [
"def",
"list_not_state",
"(",
"subset",
"=",
"None",
",",
"show_ip",
"=",
"False",
",",
"show_ipv4",
"=",
"None",
")",
":",
"show_ip",
"=",
"_show_ip_migration",
"(",
"show_ip",
",",
"show_ipv4",
")",
"connected",
"=",
"list_state",
"(",
"subset",
"=",
"No... | .. versionadded:: 2015.8.0
.. versionchanged:: 2019.2.0
The 'show_ipv4' argument has been renamed to 'show_ip' as it now
includes IPv6 addresses for IPv6-connected minions.
Print a list of all minions that are NOT up according to Salt's presence
detection (no commands will be sent to minion... | [
"..",
"versionadded",
"::",
"2015",
".",
"8",
".",
"0",
"..",
"versionchanged",
"::",
"2019",
".",
"2",
".",
"0",
"The",
"show_ipv4",
"argument",
"has",
"been",
"renamed",
"to",
"show_ip",
"as",
"it",
"now",
"includes",
"IPv6",
"addresses",
"for",
"IPv6"... | python | train | 29.411765 |
chimera0/accel-brain-code | Automatic-Summarization/pysummarization/computabledistance/euclid_distance.py | https://github.com/chimera0/accel-brain-code/blob/03661f6f544bed656269fcd4b3c23c9061629daa/Automatic-Summarization/pysummarization/computabledistance/euclid_distance.py#L11-L22 | def compute(self, x_arr, y_arr):
'''
Compute distance.
Args:
x_arr: `np.ndarray` of vectors.
y_arr: `np.ndarray` of vectors.
Retruns:
`np.ndarray` of distances.
'''
return np.linalg.norm(x_arr - y_arr, axis=-1) | [
"def",
"compute",
"(",
"self",
",",
"x_arr",
",",
"y_arr",
")",
":",
"return",
"np",
".",
"linalg",
".",
"norm",
"(",
"x_arr",
"-",
"y_arr",
",",
"axis",
"=",
"-",
"1",
")"
] | Compute distance.
Args:
x_arr: `np.ndarray` of vectors.
y_arr: `np.ndarray` of vectors.
Retruns:
`np.ndarray` of distances. | [
"Compute",
"distance",
".",
"Args",
":",
"x_arr",
":",
"np",
".",
"ndarray",
"of",
"vectors",
".",
"y_arr",
":",
"np",
".",
"ndarray",
"of",
"vectors",
".",
"Retruns",
":",
"np",
".",
"ndarray",
"of",
"distances",
"."
] | python | train | 25.5 |
pypyr/pypyr-cli | pypyr/context.py | https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/context.py#L363-L403 | def get_formatted_string(self, input_string):
"""Return formatted value for input_string.
get_formatted gets a context[key] value.
get_formatted_string is for any arbitrary string that is not in the
context.
Only valid if input_string is a type string.
Return a string i... | [
"def",
"get_formatted_string",
"(",
"self",
",",
"input_string",
")",
":",
"if",
"isinstance",
"(",
"input_string",
",",
"str",
")",
":",
"try",
":",
"return",
"self",
".",
"get_processed_string",
"(",
"input_string",
")",
"except",
"KeyNotInContextError",
"as",... | Return formatted value for input_string.
get_formatted gets a context[key] value.
get_formatted_string is for any arbitrary string that is not in the
context.
Only valid if input_string is a type string.
Return a string interpolated from the context dictionary.
If inpu... | [
"Return",
"formatted",
"value",
"for",
"input_string",
"."
] | python | train | 38.365854 |
apache/incubator-mxnet | python/mxnet/contrib/onnx/mx2onnx/_op_translations.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/onnx/mx2onnx/_op_translations.py#L1930-L1952 | def convert_random_normal(node, **kwargs):
"""Map MXNet's random_normal operator attributes to onnx's RandomNormal
operator and return the created node.
"""
name, input_nodes, attrs = get_inputs(node, kwargs)
# Converting to float32
mean = float(attrs.get("loc", 0))
scale = float(attrs.get(... | [
"def",
"convert_random_normal",
"(",
"node",
",",
"*",
"*",
"kwargs",
")",
":",
"name",
",",
"input_nodes",
",",
"attrs",
"=",
"get_inputs",
"(",
"node",
",",
"kwargs",
")",
"# Converting to float32",
"mean",
"=",
"float",
"(",
"attrs",
".",
"get",
"(",
... | Map MXNet's random_normal operator attributes to onnx's RandomNormal
operator and return the created node. | [
"Map",
"MXNet",
"s",
"random_normal",
"operator",
"attributes",
"to",
"onnx",
"s",
"RandomNormal",
"operator",
"and",
"return",
"the",
"created",
"node",
"."
] | python | train | 29.652174 |
fermiPy/fermipy | fermipy/castro.py | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/castro.py#L1293-L1318 | def create_from_stack(cls, shape, components, ylims, weights=None):
""" Combine the log-likelihoods from a number of components.
Parameters
----------
shape : tuple
The shape of the return array
components : [~fermipy.castro.CastroData_Base]
The compo... | [
"def",
"create_from_stack",
"(",
"cls",
",",
"shape",
",",
"components",
",",
"ylims",
",",
"weights",
"=",
"None",
")",
":",
"if",
"len",
"(",
"components",
")",
"==",
"0",
":",
"return",
"None",
"norm_vals",
",",
"nll_vals",
",",
"nll_offsets",
"=",
... | Combine the log-likelihoods from a number of components.
Parameters
----------
shape : tuple
The shape of the return array
components : [~fermipy.castro.CastroData_Base]
The components to be stacked
weights : array-like
Returns
------... | [
"Combine",
"the",
"log",
"-",
"likelihoods",
"from",
"a",
"number",
"of",
"components",
"."
] | python | train | 35.730769 |
numenta/nupic | src/nupic/swarming/ModelRunner.py | https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/ModelRunner.py#L292-L391 | def __runTaskMainLoop(self, numIters, learningOffAt=None):
""" Main loop of the OPF Model Runner.
Parameters:
-----------------------------------------------------------------------
recordIterator: Iterator for counting number of records (see _runTask)
learningOffAt: If not None, learning i... | [
"def",
"__runTaskMainLoop",
"(",
"self",
",",
"numIters",
",",
"learningOffAt",
"=",
"None",
")",
":",
"## Reset sequence states in the model, so it starts looking for a new",
"## sequence",
"self",
".",
"_model",
".",
"resetSequenceStates",
"(",
")",
"self",
".",
"_cur... | Main loop of the OPF Model Runner.
Parameters:
-----------------------------------------------------------------------
recordIterator: Iterator for counting number of records (see _runTask)
learningOffAt: If not None, learning is turned off when we reach this
iteration n... | [
"Main",
"loop",
"of",
"the",
"OPF",
"Model",
"Runner",
"."
] | python | valid | 34.78 |
mbi/django-rosetta | rosetta/poutil.py | https://github.com/mbi/django-rosetta/blob/3c249d344eaf667b58a61a0433d65fb2a8c72355/rosetta/poutil.py#L17-L30 | def timestamp_with_timezone(dt=None):
"""
Return a timestamp with a timezone for the configured locale. If all else
fails, consider localtime to be UTC.
"""
dt = dt or datetime.now()
if timezone is None:
return dt.strftime('%Y-%m-%d %H:%M%z')
if not dt.tzinfo:
tz = timezone.... | [
"def",
"timestamp_with_timezone",
"(",
"dt",
"=",
"None",
")",
":",
"dt",
"=",
"dt",
"or",
"datetime",
".",
"now",
"(",
")",
"if",
"timezone",
"is",
"None",
":",
"return",
"dt",
".",
"strftime",
"(",
"'%Y-%m-%d %H:%M%z'",
")",
"if",
"not",
"dt",
".",
... | Return a timestamp with a timezone for the configured locale. If all else
fails, consider localtime to be UTC. | [
"Return",
"a",
"timestamp",
"with",
"a",
"timezone",
"for",
"the",
"configured",
"locale",
".",
"If",
"all",
"else",
"fails",
"consider",
"localtime",
"to",
"be",
"UTC",
"."
] | python | train | 34.642857 |
Fuyukai/ConfigMaster | configmaster/ConfigKey.py | https://github.com/Fuyukai/ConfigMaster/blob/8018aa415da55c84edaa8a49664f674758a14edd/configmaster/ConfigKey.py#L37-L52 | def dump(self) -> dict:
"""
Dumps data from the ConfigKey into a dict.
:return: The keys and values from the ConfigKey encapsulated in a dict.
"""
d = {}
for item in self.__dict__:
if item in ['parsed', 'dump', 'parse_data', 'iter_list', 'safe_load']:
... | [
"def",
"dump",
"(",
"self",
")",
"->",
"dict",
":",
"d",
"=",
"{",
"}",
"for",
"item",
"in",
"self",
".",
"__dict__",
":",
"if",
"item",
"in",
"[",
"'parsed'",
",",
"'dump'",
",",
"'parse_data'",
",",
"'iter_list'",
",",
"'safe_load'",
"]",
":",
"c... | Dumps data from the ConfigKey into a dict.
:return: The keys and values from the ConfigKey encapsulated in a dict. | [
"Dumps",
"data",
"from",
"the",
"ConfigKey",
"into",
"a",
"dict",
".",
":",
"return",
":",
"The",
"keys",
"and",
"values",
"from",
"the",
"ConfigKey",
"encapsulated",
"in",
"a",
"dict",
"."
] | python | train | 39.8125 |
globus/globus-cli | globus_cli/commands/endpoint/show.py | https://github.com/globus/globus-cli/blob/336675ff24da64c5ee487243f39ae39fc49a7e14/globus_cli/commands/endpoint/show.py#L11-L23 | def endpoint_show(endpoint_id):
"""
Executor for `globus endpoint show`
"""
client = get_client()
res = client.get_endpoint(endpoint_id)
formatted_print(
res,
text_format=FORMAT_TEXT_RECORD,
fields=GCP_FIELDS if res["is_globus_connect"] else STANDARD_FIELDS,
) | [
"def",
"endpoint_show",
"(",
"endpoint_id",
")",
":",
"client",
"=",
"get_client",
"(",
")",
"res",
"=",
"client",
".",
"get_endpoint",
"(",
"endpoint_id",
")",
"formatted_print",
"(",
"res",
",",
"text_format",
"=",
"FORMAT_TEXT_RECORD",
",",
"fields",
"=",
... | Executor for `globus endpoint show` | [
"Executor",
"for",
"globus",
"endpoint",
"show"
] | python | train | 23.230769 |
joke2k/faker | faker/providers/profile/__init__.py | https://github.com/joke2k/faker/blob/965824b61132e52d92d1a6ce470396dbbe01c96c/faker/providers/profile/__init__.py#L13-L31 | def simple_profile(self, sex=None):
"""
Generates a basic profile with personal informations
"""
SEX = ["F", "M"]
if sex not in SEX:
sex = self.random_element(SEX)
if sex == 'F':
name = self.generator.name_female()
elif sex == 'M':
... | [
"def",
"simple_profile",
"(",
"self",
",",
"sex",
"=",
"None",
")",
":",
"SEX",
"=",
"[",
"\"F\"",
",",
"\"M\"",
"]",
"if",
"sex",
"not",
"in",
"SEX",
":",
"sex",
"=",
"self",
".",
"random_element",
"(",
"SEX",
")",
"if",
"sex",
"==",
"'F'",
":",... | Generates a basic profile with personal informations | [
"Generates",
"a",
"basic",
"profile",
"with",
"personal",
"informations"
] | python | train | 32.789474 |
pantsbuild/pants | src/python/pants/pantsd/pailgun_server.py | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/pantsd/pailgun_server.py#L60-L82 | def handle(self):
"""Request handler for a single Pailgun request."""
# Parse the Nailgun request portion.
_, _, arguments, environment = NailgunProtocol.parse_request(self.request)
# N.B. the first and second nailgun request arguments (working_dir and command) are currently
# ignored in favor of a... | [
"def",
"handle",
"(",
"self",
")",
":",
"# Parse the Nailgun request portion.",
"_",
",",
"_",
",",
"arguments",
",",
"environment",
"=",
"NailgunProtocol",
".",
"parse_request",
"(",
"self",
".",
"request",
")",
"# N.B. the first and second nailgun request arguments (w... | Request handler for a single Pailgun request. | [
"Request",
"handler",
"for",
"a",
"single",
"Pailgun",
"request",
"."
] | python | train | 52.565217 |
pilliq/scratchpy | scratch/scratch.py | https://github.com/pilliq/scratchpy/blob/a594561c147b1cf6696231c26a0475c7d52b8039/scratch/scratch.py#L200-L210 | def connect(self):
"""
Connects to Scratch.
"""
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
self.socket.connect((self.host, self.port))
except socket.error as (err, msg):
self.connected = False
raise ScratchErro... | [
"def",
"connect",
"(",
"self",
")",
":",
"self",
".",
"socket",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_STREAM",
")",
"try",
":",
"self",
".",
"socket",
".",
"connect",
"(",
"(",
"self",
".",
"host",
"... | Connects to Scratch. | [
"Connects",
"to",
"Scratch",
"."
] | python | train | 33.727273 |
data61/clkhash | clkhash/randomnames.py | https://github.com/data61/clkhash/blob/ec6398d6708a063de83f7c3d6286587bff8e7121/clkhash/randomnames.py#L131-L141 | def load_names(self):
# type: () -> None
""" Loads a name database from package data
Uses data files sourced from
http://www.quietaffiliate.com/free-first-name-and-last-name-databases-csv-and-sql/
"""
self.all_male_first_names = load_csv_data('male-first-names.csv')
... | [
"def",
"load_names",
"(",
"self",
")",
":",
"# type: () -> None",
"self",
".",
"all_male_first_names",
"=",
"load_csv_data",
"(",
"'male-first-names.csv'",
")",
"self",
".",
"all_female_first_names",
"=",
"load_csv_data",
"(",
"'female-first-names.csv'",
")",
"self",
... | Loads a name database from package data
Uses data files sourced from
http://www.quietaffiliate.com/free-first-name-and-last-name-databases-csv-and-sql/ | [
"Loads",
"a",
"name",
"database",
"from",
"package",
"data"
] | python | train | 42 |
twilio/twilio-python | twilio/rest/voice/v1/dialing_permissions/country/__init__.py | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/voice/v1/dialing_permissions/country/__init__.py#L272-L287 | def fetch(self):
"""
Fetch a CountryInstance
:returns: Fetched CountryInstance
:rtype: twilio.rest.voice.v1.dialing_permissions.country.CountryInstance
"""
params = values.of({})
payload = self._version.fetch(
'GET',
self._uri,
... | [
"def",
"fetch",
"(",
"self",
")",
":",
"params",
"=",
"values",
".",
"of",
"(",
"{",
"}",
")",
"payload",
"=",
"self",
".",
"_version",
".",
"fetch",
"(",
"'GET'",
",",
"self",
".",
"_uri",
",",
"params",
"=",
"params",
",",
")",
"return",
"Count... | Fetch a CountryInstance
:returns: Fetched CountryInstance
:rtype: twilio.rest.voice.v1.dialing_permissions.country.CountryInstance | [
"Fetch",
"a",
"CountryInstance"
] | python | train | 26.625 |
lrq3000/pyFileFixity | pyFileFixity/lib/profilers/visual/pympler/classtracker.py | https://github.com/lrq3000/pyFileFixity/blob/fd5ef23bb13835faf1e3baa773619b86a1cc9bdf/pyFileFixity/lib/profilers/visual/pympler/classtracker.py#L141-L150 | def get_size_at_time(self, timestamp):
"""
Get the size of the object at a specific time (snapshot).
If the object was not alive/sized at that instant, return 0.
"""
size = 0
for (t, s) in self.snapshots:
if t == timestamp:
size = s.size
... | [
"def",
"get_size_at_time",
"(",
"self",
",",
"timestamp",
")",
":",
"size",
"=",
"0",
"for",
"(",
"t",
",",
"s",
")",
"in",
"self",
".",
"snapshots",
":",
"if",
"t",
"==",
"timestamp",
":",
"size",
"=",
"s",
".",
"size",
"return",
"size"
] | Get the size of the object at a specific time (snapshot).
If the object was not alive/sized at that instant, return 0. | [
"Get",
"the",
"size",
"of",
"the",
"object",
"at",
"a",
"specific",
"time",
"(",
"snapshot",
")",
".",
"If",
"the",
"object",
"was",
"not",
"alive",
"/",
"sized",
"at",
"that",
"instant",
"return",
"0",
"."
] | python | train | 32.4 |
nickmckay/LiPD-utilities | Python/lipd/lpd_noaa.py | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/lpd_noaa.py#L1113-L1156 | def __create_file(self):
"""
Open text file. Write one section at a time. Close text file. Move completed file to dir_root/noaa/
:return none:
"""
logger_lpd_noaa.info("enter create_file")
self.__get_output_filenames()
for idx, filename in enumerate(self.output_... | [
"def",
"__create_file",
"(",
"self",
")",
":",
"logger_lpd_noaa",
".",
"info",
"(",
"\"enter create_file\"",
")",
"self",
".",
"__get_output_filenames",
"(",
")",
"for",
"idx",
",",
"filename",
"in",
"enumerate",
"(",
"self",
".",
"output_filenames",
")",
":",... | Open text file. Write one section at a time. Close text file. Move completed file to dir_root/noaa/
:return none: | [
"Open",
"text",
"file",
".",
"Write",
"one",
"section",
"at",
"a",
"time",
".",
"Close",
"text",
"file",
".",
"Move",
"completed",
"file",
"to",
"dir_root",
"/",
"noaa",
"/",
":",
"return",
"none",
":"
] | python | train | 42.636364 |
helixyte/everest | everest/entities/attributes.py | https://github.com/helixyte/everest/blob/70c9b93c3061db5cb62428349d18b8fb8566411b/everest/entities/attributes.py#L116-L123 | def get_domain_class_terminal_attribute_iterator(ent):
"""
Returns an iterator over all terminal attributes in the given registered
resource.
"""
for attr in itervalues_(ent.__everest_attributes__):
if attr.kind == RESOURCE_ATTRIBUTE_KINDS.TERMINAL:
yield attr | [
"def",
"get_domain_class_terminal_attribute_iterator",
"(",
"ent",
")",
":",
"for",
"attr",
"in",
"itervalues_",
"(",
"ent",
".",
"__everest_attributes__",
")",
":",
"if",
"attr",
".",
"kind",
"==",
"RESOURCE_ATTRIBUTE_KINDS",
".",
"TERMINAL",
":",
"yield",
"attr"... | Returns an iterator over all terminal attributes in the given registered
resource. | [
"Returns",
"an",
"iterator",
"over",
"all",
"terminal",
"attributes",
"in",
"the",
"given",
"registered",
"resource",
"."
] | python | train | 36.625 |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/dvips.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/dvips.py#L58-L85 | def generate(env):
"""Add Builders and construction variables for dvips to an Environment."""
global PSAction
if PSAction is None:
PSAction = SCons.Action.Action('$PSCOM', '$PSCOMSTR')
global DVIPSAction
if DVIPSAction is None:
DVIPSAction = SCons.Action.Action(DviPsFunction, strfun... | [
"def",
"generate",
"(",
"env",
")",
":",
"global",
"PSAction",
"if",
"PSAction",
"is",
"None",
":",
"PSAction",
"=",
"SCons",
".",
"Action",
".",
"Action",
"(",
"'$PSCOM'",
",",
"'$PSCOMSTR'",
")",
"global",
"DVIPSAction",
"if",
"DVIPSAction",
"is",
"None"... | Add Builders and construction variables for dvips to an Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"dvips",
"to",
"an",
"Environment",
"."
] | python | train | 43.214286 |
simoninireland/epyc | epyc/labnotebook.py | https://github.com/simoninireland/epyc/blob/b3b61007741a0ab3de64df89070a6f30de8ec268/epyc/labnotebook.py#L155-L173 | def addPendingResult( self, ps, jobid ):
"""Add a "pending" result that we expect to get results for.
:param ps: the parameters for the result
:param jobid: an identifier for the pending result"""
k = self._parametersAsIndex(ps)
# retrieve or create the result list
if k... | [
"def",
"addPendingResult",
"(",
"self",
",",
"ps",
",",
"jobid",
")",
":",
"k",
"=",
"self",
".",
"_parametersAsIndex",
"(",
"ps",
")",
"# retrieve or create the result list",
"if",
"k",
"in",
"self",
".",
"_results",
".",
"keys",
"(",
")",
":",
"rs",
"=... | Add a "pending" result that we expect to get results for.
:param ps: the parameters for the result
:param jobid: an identifier for the pending result | [
"Add",
"a",
"pending",
"result",
"that",
"we",
"expect",
"to",
"get",
"results",
"for",
"."
] | python | train | 31.052632 |
brettcannon/caniusepython3 | caniusepython3/pypi.py | https://github.com/brettcannon/caniusepython3/blob/195775d8f1891f73eb90734f3edda0c57e08dbf3/caniusepython3/pypi.py#L78-L90 | def supports_py3(project_name):
"""Check with PyPI if a project supports Python 3."""
log = logging.getLogger("ciu")
log.info("Checking {} ...".format(project_name))
request = requests.get("https://pypi.org/pypi/{}/json".format(project_name))
if request.status_code >= 400:
log = logging.getL... | [
"def",
"supports_py3",
"(",
"project_name",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"\"ciu\"",
")",
"log",
".",
"info",
"(",
"\"Checking {} ...\"",
".",
"format",
"(",
"project_name",
")",
")",
"request",
"=",
"requests",
".",
"get",
"(",
... | Check with PyPI if a project supports Python 3. | [
"Check",
"with",
"PyPI",
"if",
"a",
"project",
"supports",
"Python",
"3",
"."
] | python | train | 48.153846 |
jssimporter/python-jss | jss/contrib/FoundationPlist.py | https://github.com/jssimporter/python-jss/blob/b95185d74e0c0531b0b563f280d4129e21d5fe5d/jss/contrib/FoundationPlist.py#L132-L145 | def writePlistToString(rootObject):
'''Return 'rootObject' as a plist-formatted string.'''
plistData, error = (
NSPropertyListSerialization.
dataFromPropertyList_format_errorDescription_(
rootObject, NSPropertyListXMLFormat_v1_0, None))
if plistData is None:
if error:
... | [
"def",
"writePlistToString",
"(",
"rootObject",
")",
":",
"plistData",
",",
"error",
"=",
"(",
"NSPropertyListSerialization",
".",
"dataFromPropertyList_format_errorDescription_",
"(",
"rootObject",
",",
"NSPropertyListXMLFormat_v1_0",
",",
"None",
")",
")",
"if",
"plis... | Return 'rootObject' as a plist-formatted string. | [
"Return",
"rootObject",
"as",
"a",
"plist",
"-",
"formatted",
"string",
"."
] | python | train | 35.928571 |
CivicSpleen/ambry | ambry/library/search_backends/whoosh_backend.py | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/search_backends/whoosh_backend.py#L278-L300 | def search(self, search_phrase, limit=None):
""" Finds partitions by search phrase.
Args:
search_phrase (str or unicode):
limit (int, optional): how many results to generate. None means without limit.
Yields:
PartitionSearchResult instances.
"""
... | [
"def",
"search",
"(",
"self",
",",
"search_phrase",
",",
"limit",
"=",
"None",
")",
":",
"query_string",
"=",
"self",
".",
"_make_query_from_terms",
"(",
"search_phrase",
")",
"self",
".",
"_parsed_query",
"=",
"query_string",
"schema",
"=",
"self",
".",
"_g... | Finds partitions by search phrase.
Args:
search_phrase (str or unicode):
limit (int, optional): how many results to generate. None means without limit.
Yields:
PartitionSearchResult instances. | [
"Finds",
"partitions",
"by",
"search",
"phrase",
"."
] | python | train | 38.521739 |
tritemio/PyBroMo | pybromo/timestamps.py | https://github.com/tritemio/PyBroMo/blob/b75f82a4551ff37e7c7a7e6954c536451f3e6d06/pybromo/timestamps.py#L338-L346 | def save_photon_hdf5(self, identity=None, overwrite=True, path=None):
"""Create a smFRET Photon-HDF5 file with current timestamps."""
filepath = self.filepath
if path is not None:
filepath = Path(path, filepath.name)
self.merge_da()
data = self._make_photon_hdf5(ident... | [
"def",
"save_photon_hdf5",
"(",
"self",
",",
"identity",
"=",
"None",
",",
"overwrite",
"=",
"True",
",",
"path",
"=",
"None",
")",
":",
"filepath",
"=",
"self",
".",
"filepath",
"if",
"path",
"is",
"not",
"None",
":",
"filepath",
"=",
"Path",
"(",
"... | Create a smFRET Photon-HDF5 file with current timestamps. | [
"Create",
"a",
"smFRET",
"Photon",
"-",
"HDF5",
"file",
"with",
"current",
"timestamps",
"."
] | python | valid | 49.333333 |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L3085-L3108 | def dskp02(handle, dladsc, start, room):
"""
Fetch triangular plates from a type 2 DSK segment.
https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dskp02_c.html
:param handle: DSK file handle.
:type handle: int
:param dladsc: DLA descriptor.
:type dladsc: spiceypy.utils.support_types... | [
"def",
"dskp02",
"(",
"handle",
",",
"dladsc",
",",
"start",
",",
"room",
")",
":",
"handle",
"=",
"ctypes",
".",
"c_int",
"(",
"handle",
")",
"start",
"=",
"ctypes",
".",
"c_int",
"(",
"start",
")",
"room",
"=",
"ctypes",
".",
"c_int",
"(",
"room"... | Fetch triangular plates from a type 2 DSK segment.
https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dskp02_c.html
:param handle: DSK file handle.
:type handle: int
:param dladsc: DLA descriptor.
:type dladsc: spiceypy.utils.support_types.SpiceDLADescr
:param start: Start index.
:ty... | [
"Fetch",
"triangular",
"plates",
"from",
"a",
"type",
"2",
"DSK",
"segment",
"."
] | python | train | 32 |
tensorflow/tensor2tensor | tensor2tensor/envs/env_problem.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/env_problem.py#L540-L566 | def step(self, actions):
"""Takes a step in all environments.
Subclasses should override _step to do the actual reset if something other
than the default implementation is desired.
Args:
actions: Batch of actions.
Returns:
(preprocessed_observations, processed_rewards, dones, infos).
... | [
"def",
"step",
"(",
"self",
",",
"actions",
")",
":",
"observations",
",",
"raw_rewards",
",",
"dones",
",",
"infos",
"=",
"self",
".",
"_step",
"(",
"actions",
")",
"# Process rewards.",
"raw_rewards",
"=",
"raw_rewards",
".",
"astype",
"(",
"np",
".",
... | Takes a step in all environments.
Subclasses should override _step to do the actual reset if something other
than the default implementation is desired.
Args:
actions: Batch of actions.
Returns:
(preprocessed_observations, processed_rewards, dones, infos). | [
"Takes",
"a",
"step",
"in",
"all",
"environments",
"."
] | python | train | 30.148148 |
geronimp/graftM | graftm/search_table.py | https://github.com/geronimp/graftM/blob/c82576517290167f605fd0bc4facd009cee29f48/graftm/search_table.py#L19-L86 | def _interpret_hits(self, results_list, base_list):
'''Sort reads that hit multiple HMMs to the databases to which they had
the highest bit score. Return a dictionary containing HMMs as keys, and
number of hits as the values.
This function is set up so that the read names could... | [
"def",
"_interpret_hits",
"(",
"self",
",",
"results_list",
",",
"base_list",
")",
":",
"logging",
".",
"debug",
"(",
"\"Sorting reads into HMMs by bit score\"",
")",
"run_results",
"=",
"{",
"}",
"########################################################################",
"... | Sort reads that hit multiple HMMs to the databases to which they had
the highest bit score. Return a dictionary containing HMMs as keys, and
number of hits as the values.
This function is set up so that the read names could easily be returned
instead of numbers, for future deve... | [
"Sort",
"reads",
"that",
"hit",
"multiple",
"HMMs",
"to",
"the",
"databases",
"to",
"which",
"they",
"had",
"the",
"highest",
"bit",
"score",
".",
"Return",
"a",
"dictionary",
"containing",
"HMMs",
"as",
"keys",
"and",
"number",
"of",
"hits",
"as",
"the",
... | python | train | 41.455882 |
CalebBell/fluids | fluids/flow_meter.py | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/flow_meter.py#L1089-L1133 | def dP_cone_meter(D, Dc, P1, P2):
r'''Calculates the non-recoverable pressure drop of a cone meter
based on the measured pressures before and at the cone end, and the
geometry of the cone meter according to [1]_.
.. math::
\Delta \bar \omega = (1.09 - 0.813\beta)\Delta P
Param... | [
"def",
"dP_cone_meter",
"(",
"D",
",",
"Dc",
",",
"P1",
",",
"P2",
")",
":",
"dP",
"=",
"P1",
"-",
"P2",
"beta",
"=",
"diameter_ratio_cone_meter",
"(",
"D",
",",
"Dc",
")",
"return",
"(",
"1.09",
"-",
"0.813",
"*",
"beta",
")",
"*",
"dP"
] | r'''Calculates the non-recoverable pressure drop of a cone meter
based on the measured pressures before and at the cone end, and the
geometry of the cone meter according to [1]_.
.. math::
\Delta \bar \omega = (1.09 - 0.813\beta)\Delta P
Parameters
----------
D : float
... | [
"r",
"Calculates",
"the",
"non",
"-",
"recoverable",
"pressure",
"drop",
"of",
"a",
"cone",
"meter",
"based",
"on",
"the",
"measured",
"pressures",
"before",
"and",
"at",
"the",
"cone",
"end",
"and",
"the",
"geometry",
"of",
"the",
"cone",
"meter",
"accord... | python | train | 29.533333 |
eerimoq/bincopy | bincopy.py | https://github.com/eerimoq/bincopy/blob/5e02cd001c3e9b54729425db6bffad5f03e1beac/bincopy.py#L1315-L1338 | def fill(self, value=b'\xff'):
"""Fill all empty space between segments with given value `value`.
"""
previous_segment_maximum_address = None
fill_segments = []
for address, data in self._segments:
maximum_address = address + len(data)
if previous_segm... | [
"def",
"fill",
"(",
"self",
",",
"value",
"=",
"b'\\xff'",
")",
":",
"previous_segment_maximum_address",
"=",
"None",
"fill_segments",
"=",
"[",
"]",
"for",
"address",
",",
"data",
"in",
"self",
".",
"_segments",
":",
"maximum_address",
"=",
"address",
"+",
... | Fill all empty space between segments with given value `value`. | [
"Fill",
"all",
"empty",
"space",
"between",
"segments",
"with",
"given",
"value",
"value",
"."
] | python | train | 36.083333 |
JarryShaw/PyPCAPKit | src/protocols/internet/hopopt.py | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/protocols/internet/hopopt.py#L739-L792 | def _read_opt_rpl(self, code, *, desc):
"""Read HOPOPT RPL option.
Structure of HOPOPT RPL option [RFC 6553]:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
... | [
"def",
"_read_opt_rpl",
"(",
"self",
",",
"code",
",",
"*",
",",
"desc",
")",
":",
"_type",
"=",
"self",
".",
"_read_opt_type",
"(",
"code",
")",
"_size",
"=",
"self",
".",
"_read_unpack",
"(",
"1",
")",
"if",
"_size",
"<",
"4",
":",
"raise",
"Prot... | Read HOPOPT RPL option.
Structure of HOPOPT RPL option [RFC 6553]:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
... | [
"Read",
"HOPOPT",
"RPL",
"option",
"."
] | python | train | 46.981481 |
PythonCharmers/python-future | src/future/backports/datetime.py | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/datetime.py#L784-L793 | def replace(self, year=None, month=None, day=None):
"""Return a new date with new values for the specified fields."""
if year is None:
year = self._year
if month is None:
month = self._month
if day is None:
day = self._day
_check_date_fields(ye... | [
"def",
"replace",
"(",
"self",
",",
"year",
"=",
"None",
",",
"month",
"=",
"None",
",",
"day",
"=",
"None",
")",
":",
"if",
"year",
"is",
"None",
":",
"year",
"=",
"self",
".",
"_year",
"if",
"month",
"is",
"None",
":",
"month",
"=",
"self",
"... | Return a new date with new values for the specified fields. | [
"Return",
"a",
"new",
"date",
"with",
"new",
"values",
"for",
"the",
"specified",
"fields",
"."
] | python | train | 36.4 |
treycucco/bidon | bidon/spreadsheet/excel.py | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/spreadsheet/excel.py#L61-L67 | def merged_cell_ranges(self):
"""Generates the sequence of merged cell ranges in the format:
((col_low, row_low), (col_hi, row_hi))
"""
for rlo, rhi, clo, chi in self.raw_sheet.merged_cells:
yield ((clo, rlo), (chi, rhi)) | [
"def",
"merged_cell_ranges",
"(",
"self",
")",
":",
"for",
"rlo",
",",
"rhi",
",",
"clo",
",",
"chi",
"in",
"self",
".",
"raw_sheet",
".",
"merged_cells",
":",
"yield",
"(",
"(",
"clo",
",",
"rlo",
")",
",",
"(",
"chi",
",",
"rhi",
")",
")"
] | Generates the sequence of merged cell ranges in the format:
((col_low, row_low), (col_hi, row_hi)) | [
"Generates",
"the",
"sequence",
"of",
"merged",
"cell",
"ranges",
"in",
"the",
"format",
":"
] | python | train | 34 |
gem/oq-engine | openquake/baselib/node.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/node.py#L585-L589 | def pprint(self, stream=None, indent=1, width=80, depth=None):
"""
Pretty print the underlying literal Python object
"""
pp.pprint(to_literal(self), stream, indent, width, depth) | [
"def",
"pprint",
"(",
"self",
",",
"stream",
"=",
"None",
",",
"indent",
"=",
"1",
",",
"width",
"=",
"80",
",",
"depth",
"=",
"None",
")",
":",
"pp",
".",
"pprint",
"(",
"to_literal",
"(",
"self",
")",
",",
"stream",
",",
"indent",
",",
"width",... | Pretty print the underlying literal Python object | [
"Pretty",
"print",
"the",
"underlying",
"literal",
"Python",
"object"
] | python | train | 38 |
gwpy/gwpy | gwpy/signal/qtransform.py | https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/signal/qtransform.py#L166-L202 | def transform(self, fseries, **kwargs):
"""Compute the time-frequency plane at fixed Q with the most
significant tile
Parameters
----------
fseries : `~gwpy.timeseries.FrequencySeries`
the complex FFT of a time-series data set
**kwargs
other keyw... | [
"def",
"transform",
"(",
"self",
",",
"fseries",
",",
"*",
"*",
"kwargs",
")",
":",
"weight",
"=",
"1",
"+",
"numpy",
".",
"log10",
"(",
"self",
".",
"qrange",
"[",
"1",
"]",
"/",
"self",
".",
"qrange",
"[",
"0",
"]",
")",
"/",
"numpy",
".",
... | Compute the time-frequency plane at fixed Q with the most
significant tile
Parameters
----------
fseries : `~gwpy.timeseries.FrequencySeries`
the complex FFT of a time-series data set
**kwargs
other keyword arguments to pass to `QPlane.transform`
... | [
"Compute",
"the",
"time",
"-",
"frequency",
"plane",
"at",
"fixed",
"Q",
"with",
"the",
"most",
"significant",
"tile"
] | python | train | 33.567568 |
dereneaton/ipyrad | ipyrad/analysis/tetrad.py | https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/tetrad.py#L744-L754 | def _renamer(self, tre):
""" renames newick from numbers to sample names"""
## get the tre with numbered tree tip labels
names = tre.get_leaves()
## replace numbered names with snames
for name in names:
name.name = self.samples[int(name.name)]
## return with... | [
"def",
"_renamer",
"(",
"self",
",",
"tre",
")",
":",
"## get the tre with numbered tree tip labels",
"names",
"=",
"tre",
".",
"get_leaves",
"(",
")",
"## replace numbered names with snames",
"for",
"name",
"in",
"names",
":",
"name",
".",
"name",
"=",
"self",
... | renames newick from numbers to sample names | [
"renames",
"newick",
"from",
"numbers",
"to",
"sample",
"names"
] | python | valid | 34.090909 |
juju/python-libjuju | juju/unit.py | https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/unit.py#L122-L147 | async def run(self, command, timeout=None):
"""Run command on this unit.
:param str command: The command to run
:param int timeout: Time, in seconds, to wait before command is
considered failed
:returns: A :class:`juju.action.Action` instance.
"""
action = clien... | [
"async",
"def",
"run",
"(",
"self",
",",
"command",
",",
"timeout",
"=",
"None",
")",
":",
"action",
"=",
"client",
".",
"ActionFacade",
".",
"from_connection",
"(",
"self",
".",
"connection",
")",
"log",
".",
"debug",
"(",
"'Running `%s` on %s'",
",",
"... | Run command on this unit.
:param str command: The command to run
:param int timeout: Time, in seconds, to wait before command is
considered failed
:returns: A :class:`juju.action.Action` instance. | [
"Run",
"command",
"on",
"this",
"unit",
"."
] | python | train | 28.730769 |
gem/oq-engine | openquake/hazardlib/gsim/kotha_2016.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/kotha_2016.py#L128-L133 | def _get_site_term(self, C, vs30):
"""
Returns only a linear site amplification term
"""
dg1, dg2 = self._get_regional_site_term(C)
return (C["g1"] + dg1) + (C["g2"] + dg2) * np.log(vs30) | [
"def",
"_get_site_term",
"(",
"self",
",",
"C",
",",
"vs30",
")",
":",
"dg1",
",",
"dg2",
"=",
"self",
".",
"_get_regional_site_term",
"(",
"C",
")",
"return",
"(",
"C",
"[",
"\"g1\"",
"]",
"+",
"dg1",
")",
"+",
"(",
"C",
"[",
"\"g2\"",
"]",
"+",... | Returns only a linear site amplification term | [
"Returns",
"only",
"a",
"linear",
"site",
"amplification",
"term"
] | python | train | 37 |
pyrogram/pyrogram | pyrogram/client/methods/messages/close_poll.py | https://github.com/pyrogram/pyrogram/blob/e7258a341ba905cfa86264c22040654db732ec1c/pyrogram/client/methods/messages/close_poll.py#L26-L67 | def close_poll(
self,
chat_id: Union[int, str],
message_id: id
) -> bool:
"""Use this method to close (stop) a poll.
Closed polls can't be reopened and nobody will be able to vote in it anymore.
Args:
chat_id (``int`` | ``str``):
Unique i... | [
"def",
"close_poll",
"(",
"self",
",",
"chat_id",
":",
"Union",
"[",
"int",
",",
"str",
"]",
",",
"message_id",
":",
"id",
")",
"->",
"bool",
":",
"poll",
"=",
"self",
".",
"get_messages",
"(",
"chat_id",
",",
"message_id",
")",
".",
"poll",
"self",
... | Use this method to close (stop) a poll.
Closed polls can't be reopened and nobody will be able to vote in it anymore.
Args:
chat_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the target chat.
For your personal cloud (Saved Messages) yo... | [
"Use",
"this",
"method",
"to",
"close",
"(",
"stop",
")",
"a",
"poll",
"."
] | python | train | 31.380952 |
Hackerfleet/hfos | hfos/tool/__init__.py | https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/tool/__init__.py#L93-L127 | def _get_credentials(username=None, password=None, dbhost=None):
"""Obtain user credentials by arguments or asking the user"""
# Database salt
system_config = dbhost.objectmodels['systemconfig'].find_one({
'active': True
})
try:
salt = system_config.salt.encode('ascii')
except ... | [
"def",
"_get_credentials",
"(",
"username",
"=",
"None",
",",
"password",
"=",
"None",
",",
"dbhost",
"=",
"None",
")",
":",
"# Database salt",
"system_config",
"=",
"dbhost",
".",
"objectmodels",
"[",
"'systemconfig'",
"]",
".",
"find_one",
"(",
"{",
"'acti... | Obtain user credentials by arguments or asking the user | [
"Obtain",
"user",
"credentials",
"by",
"arguments",
"or",
"asking",
"the",
"user"
] | python | train | 26.8 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/cli/config.py | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/config.py#L97-L105 | def has_default_file(cls):
"""Check if a configuration file exists."""
for filename in cls.config_files:
for searchpath in cls.config_searchpath:
path = os.path.join(searchpath, filename)
if os.path.exists(path):
return True
return... | [
"def",
"has_default_file",
"(",
"cls",
")",
":",
"for",
"filename",
"in",
"cls",
".",
"config_files",
":",
"for",
"searchpath",
"in",
"cls",
".",
"config_searchpath",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"searchpath",
",",
"filename",
"... | Check if a configuration file exists. | [
"Check",
"if",
"a",
"configuration",
"file",
"exists",
"."
] | python | train | 35.333333 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.