repo stringlengths 7 54 | path stringlengths 4 192 | url stringlengths 87 284 | code stringlengths 78 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|
pypa/pipenv | pipenv/vendor/jinja2/filters.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/filters.py#L701-L734 | def do_slice(value, slices, fill_with=None):
"""Slice an iterator and return a list of lists containing
those items. Useful if you want to create a div containing
three ul tags that represent columns:
.. sourcecode:: html+jinja
<div class="columwrapper">
{%- for column in items|slice... | [
"def",
"do_slice",
"(",
"value",
",",
"slices",
",",
"fill_with",
"=",
"None",
")",
":",
"seq",
"=",
"list",
"(",
"value",
")",
"length",
"=",
"len",
"(",
"seq",
")",
"items_per_slice",
"=",
"length",
"//",
"slices",
"slices_with_extra",
"=",
"length",
... | Slice an iterator and return a list of lists containing
those items. Useful if you want to create a div containing
three ul tags that represent columns:
.. sourcecode:: html+jinja
<div class="columwrapper">
{%- for column in items|slice(3) %}
<ul class="column-{{ loop.index }... | [
"Slice",
"an",
"iterator",
"and",
"return",
"a",
"list",
"of",
"lists",
"containing",
"those",
"items",
".",
"Useful",
"if",
"you",
"want",
"to",
"create",
"a",
"div",
"containing",
"three",
"ul",
"tags",
"that",
"represent",
"columns",
":"
] | python | train |
obriencj/python-javatools | javatools/jarutil.py | https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/jarutil.py#L221-L240 | def create_jar(jar_file, entries):
"""
Create JAR from given entries.
:param jar_file: filename of the created JAR
:type jar_file: str
:param entries: files to put into the JAR
:type entries: list[str]
:return: None
"""
# 'jar' adds separate entries for directories, also for empty o... | [
"def",
"create_jar",
"(",
"jar_file",
",",
"entries",
")",
":",
"# 'jar' adds separate entries for directories, also for empty ones.",
"with",
"ZipFile",
"(",
"jar_file",
",",
"\"w\"",
")",
"as",
"jar",
":",
"jar",
".",
"writestr",
"(",
"\"META-INF/\"",
",",
"\"\"",... | Create JAR from given entries.
:param jar_file: filename of the created JAR
:type jar_file: str
:param entries: files to put into the JAR
:type entries: list[str]
:return: None | [
"Create",
"JAR",
"from",
"given",
"entries",
".",
":",
"param",
"jar_file",
":",
"filename",
"of",
"the",
"created",
"JAR",
":",
"type",
"jar_file",
":",
"str",
":",
"param",
"entries",
":",
"files",
"to",
"put",
"into",
"the",
"JAR",
":",
"type",
"ent... | python | train |
guaix-ucm/numina | numina/types/datatype.py | https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/types/datatype.py#L50-L66 | def validate(self, obj):
"""Validate convertibility to internal representation
Returns
-------
bool
True if 'obj' matches the data type
Raises
-------
ValidationError
If the validation fails
"""
if not isinstance(obj, self.... | [
"def",
"validate",
"(",
"self",
",",
"obj",
")",
":",
"if",
"not",
"isinstance",
"(",
"obj",
",",
"self",
".",
"internal_type",
")",
":",
"raise",
"ValidationError",
"(",
"obj",
",",
"self",
".",
"internal_type",
")",
"return",
"True"
] | Validate convertibility to internal representation
Returns
-------
bool
True if 'obj' matches the data type
Raises
-------
ValidationError
If the validation fails | [
"Validate",
"convertibility",
"to",
"internal",
"representation"
] | python | train |
tehmaze/diagram | diagram.py | https://github.com/tehmaze/diagram/blob/1701526a91c14dc8ebc6452c45c8ec9a563a56db/diagram.py#L79-L97 | def size(self):
"""Get the current terminal size."""
for fd in range(3):
cr = self._ioctl_GWINSZ(fd)
if cr:
break
if not cr:
try:
fd = os.open(os.ctermid(), os.O_RDONLY)
cr = self._ioctl_GWINSZ(fd)
... | [
"def",
"size",
"(",
"self",
")",
":",
"for",
"fd",
"in",
"range",
"(",
"3",
")",
":",
"cr",
"=",
"self",
".",
"_ioctl_GWINSZ",
"(",
"fd",
")",
"if",
"cr",
":",
"break",
"if",
"not",
"cr",
":",
"try",
":",
"fd",
"=",
"os",
".",
"open",
"(",
... | Get the current terminal size. | [
"Get",
"the",
"current",
"terminal",
"size",
"."
] | python | valid |
the01/paps-settings | paps_settings/plugin.py | https://github.com/the01/paps-settings/blob/48fb65eb0fa7929a0bb381c6dad28d0197b44c83/paps_settings/plugin.py#L116-L249 | def handle_msg(self, payload):
"""
Handle message for network plugin protocol
:param payload: Received message
:type payload: dict
:return: Response to send (if set)
:rtype: None | dict
"""
self.debug(u"\n{}".format(pformat(payload)))
msg = payloa... | [
"def",
"handle_msg",
"(",
"self",
",",
"payload",
")",
":",
"self",
".",
"debug",
"(",
"u\"\\n{}\"",
".",
"format",
"(",
"pformat",
"(",
"payload",
")",
")",
")",
"msg",
"=",
"payload",
"[",
"'msg'",
"]",
"res",
"=",
"{",
"'msg'",
":",
"msg",
",",
... | Handle message for network plugin protocol
:param payload: Received message
:type payload: dict
:return: Response to send (if set)
:rtype: None | dict | [
"Handle",
"message",
"for",
"network",
"plugin",
"protocol"
] | python | train |
aliyun/aliyun-odps-python-sdk | odps/tunnel/pb/wire_format.py | https://github.com/aliyun/aliyun-odps-python-sdk/blob/4b0de18f5864386df6068f26f026e62f932c41e4/odps/tunnel/pb/wire_format.py#L210-L220 | def _var_uint64_byte_size_no_tag(uint64):
"""Returns the bytes required to serialize a single varint.
uint64 must be unsigned.
"""
if uint64 > UINT64_MAX:
raise errors.EncodeError('Value out of range: %d' % uint64)
bytes = 1
while uint64 > 0x7f:
bytes += 1
uint64 >>= 7
... | [
"def",
"_var_uint64_byte_size_no_tag",
"(",
"uint64",
")",
":",
"if",
"uint64",
">",
"UINT64_MAX",
":",
"raise",
"errors",
".",
"EncodeError",
"(",
"'Value out of range: %d'",
"%",
"uint64",
")",
"bytes",
"=",
"1",
"while",
"uint64",
">",
"0x7f",
":",
"bytes",... | Returns the bytes required to serialize a single varint.
uint64 must be unsigned. | [
"Returns",
"the",
"bytes",
"required",
"to",
"serialize",
"a",
"single",
"varint",
".",
"uint64",
"must",
"be",
"unsigned",
"."
] | python | train |
workforce-data-initiative/skills-utils | skills_utils/iteration.py | https://github.com/workforce-data-initiative/skills-utils/blob/4cf9b7c2938984f34bbcc33d45482d23c52c7539/skills_utils/iteration.py#L23-L33 | def group(self):
"""Yield a group from the iterable"""
yield self.current
# start enumerate at 1 because we already yielded the last saved item
for num, item in enumerate(self.iterator, 1):
self.current = item
if num == self.limit:
break
... | [
"def",
"group",
"(",
"self",
")",
":",
"yield",
"self",
".",
"current",
"# start enumerate at 1 because we already yielded the last saved item",
"for",
"num",
",",
"item",
"in",
"enumerate",
"(",
"self",
".",
"iterator",
",",
"1",
")",
":",
"self",
".",
"current... | Yield a group from the iterable | [
"Yield",
"a",
"group",
"from",
"the",
"iterable"
] | python | train |
mitsei/dlkit | dlkit/handcar/learning/sessions.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/handcar/learning/sessions.py#L897-L911 | def can_delete_objectives(self):
"""Tests if this user can delete Objectives.
A return of true does not guarantee successful authorization. A
return of false indicates that it is known deleting an Objective
will result in a PermissionDenied. This is intended as a hint
to an appli... | [
"def",
"can_delete_objectives",
"(",
"self",
")",
":",
"url_path",
"=",
"construct_url",
"(",
"'authorization'",
",",
"bank_id",
"=",
"self",
".",
"_catalog_idstr",
")",
"return",
"self",
".",
"_get_request",
"(",
"url_path",
")",
"[",
"'objectiveHints'",
"]",
... | Tests if this user can delete Objectives.
A return of true does not guarantee successful authorization. A
return of false indicates that it is known deleting an Objective
will result in a PermissionDenied. This is intended as a hint
to an application that may opt not to offer delete oper... | [
"Tests",
"if",
"this",
"user",
"can",
"delete",
"Objectives",
".",
"A",
"return",
"of",
"true",
"does",
"not",
"guarantee",
"successful",
"authorization",
".",
"A",
"return",
"of",
"false",
"indicates",
"that",
"it",
"is",
"known",
"deleting",
"an",
"Objecti... | python | train |
jtwhite79/pyemu | pyemu/mat/mat_handler.py | https://github.com/jtwhite79/pyemu/blob/c504d8e7a4097cec07655a6318d275739bd8148a/pyemu/mat/mat_handler.py#L860-L872 | def as_2d(self):
""" get a 2D representation of x. If not self.isdiagonal, simply
return reference to self.x, otherwise, constructs and returns
a 2D, diagonal ndarray
Returns
-------
numpy.ndarray : numpy.ndarray
"""
if not self.isdiagonal:
... | [
"def",
"as_2d",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"isdiagonal",
":",
"return",
"self",
".",
"x",
"return",
"np",
".",
"diag",
"(",
"self",
".",
"x",
".",
"flatten",
"(",
")",
")"
] | get a 2D representation of x. If not self.isdiagonal, simply
return reference to self.x, otherwise, constructs and returns
a 2D, diagonal ndarray
Returns
-------
numpy.ndarray : numpy.ndarray | [
"get",
"a",
"2D",
"representation",
"of",
"x",
".",
"If",
"not",
"self",
".",
"isdiagonal",
"simply",
"return",
"reference",
"to",
"self",
".",
"x",
"otherwise",
"constructs",
"and",
"returns",
"a",
"2D",
"diagonal",
"ndarray"
] | python | train |
napalm-automation/napalm-yang | interactive_demo/ansible/callback/selective.py | https://github.com/napalm-automation/napalm-yang/blob/998e8a933171d010b8544bcc5dc448e2b68051e2/interactive_demo/ansible/callback/selective.py#L264-L288 | def v2_runner_on_skipped(self, result, **kwargs):
"""Run when a task is skipped."""
if self._display.verbosity > 1:
self._print_task()
self.last_skipped = False
line_length = 120
spaces = " " * (31 - len(result._host.name) - 4)
line = " * {}... | [
"def",
"v2_runner_on_skipped",
"(",
"self",
",",
"result",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"_display",
".",
"verbosity",
">",
"1",
":",
"self",
".",
"_print_task",
"(",
")",
"self",
".",
"last_skipped",
"=",
"False",
"line_length",
... | Run when a task is skipped. | [
"Run",
"when",
"a",
"task",
"is",
"skipped",
"."
] | python | test |
MacHu-GWU/superjson-project | superjson/pkg/dateutil/zoneinfo/__init__.py | https://github.com/MacHu-GWU/superjson-project/blob/782ca4b2edbd4b4018b8cedee42eeae7c921b917/superjson/pkg/dateutil/zoneinfo/__init__.py#L166-L186 | def gettz_db_metadata():
""" Get the zonefile metadata
See `zonefile_metadata`_
:returns:
A dictionary with the database metadata
.. deprecated:: 2.6
See deprecation warning in :func:`zoneinfo.gettz`. To get metadata,
query the attribute ``zoneinfo.ZoneInfoFile.metadata``.
... | [
"def",
"gettz_db_metadata",
"(",
")",
":",
"warnings",
".",
"warn",
"(",
"\"zoneinfo.gettz_db_metadata() will be removed in future \"",
"\"versions, to use the dateutil-provided zoneinfo files, \"",
"\"ZoneInfoFile object and query the 'metadata' attribute \"",
"\"instead. See the documentat... | Get the zonefile metadata
See `zonefile_metadata`_
:returns:
A dictionary with the database metadata
.. deprecated:: 2.6
See deprecation warning in :func:`zoneinfo.gettz`. To get metadata,
query the attribute ``zoneinfo.ZoneInfoFile.metadata``. | [
"Get",
"the",
"zonefile",
"metadata"
] | python | valid |
ibm-watson-iot/iot-python | src/wiotp/sdk/api/services/__init__.py | https://github.com/ibm-watson-iot/iot-python/blob/195f05adce3fba4ec997017e41e02ebd85c0c4cc/src/wiotp/sdk/api/services/__init__.py#L207-L232 | def find(self, nameFilter=None, typeFilter=None, bindingModeFilter=None, boundFilter=None):
"""
Gets the list of services that the Watson IoT Platform can connect to.
The list can include a mixture of services that are either bound or unbound.
Parameters:
-... | [
"def",
"find",
"(",
"self",
",",
"nameFilter",
"=",
"None",
",",
"typeFilter",
"=",
"None",
",",
"bindingModeFilter",
"=",
"None",
",",
"boundFilter",
"=",
"None",
")",
":",
"queryParms",
"=",
"{",
"}",
"if",
"nameFilter",
":",
"queryParms",
"[",
"\"name... | Gets the list of services that the Watson IoT Platform can connect to.
The list can include a mixture of services that are either bound or unbound.
Parameters:
- nameFilter(string) - Filter the results by the specified name
- typeFilter(string) - Filter the res... | [
"Gets",
"the",
"list",
"of",
"services",
"that",
"the",
"Watson",
"IoT",
"Platform",
"can",
"connect",
"to",
".",
"The",
"list",
"can",
"include",
"a",
"mixture",
"of",
"services",
"that",
"are",
"either",
"bound",
"or",
"unbound",
".",
"Parameters",
":",
... | python | test |
elsampsa/valkka-live | valkka/mvision/yolo3/base.py | https://github.com/elsampsa/valkka-live/blob/218bb2ecf71c516c85b1b6e075454bba13090cd8/valkka/mvision/yolo3/base.py#L162-L169 | def postActivate_(self):
"""Whatever you need to do after creating the shmem client
"""
if (self.requiredGPU_MB(self.required_mb)):
self.analyzer = YoloV3Analyzer(verbose = self.verbose)
else:
self.warning_message = "WARNING: not enough GPU memory!"
se... | [
"def",
"postActivate_",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"requiredGPU_MB",
"(",
"self",
".",
"required_mb",
")",
")",
":",
"self",
".",
"analyzer",
"=",
"YoloV3Analyzer",
"(",
"verbose",
"=",
"self",
".",
"verbose",
")",
"else",
":",
"sel... | Whatever you need to do after creating the shmem client | [
"Whatever",
"you",
"need",
"to",
"do",
"after",
"creating",
"the",
"shmem",
"client"
] | python | train |
aliyun/aliyun-odps-python-sdk | odps/df/expr/merge.py | https://github.com/aliyun/aliyun-odps-python-sdk/blob/4b0de18f5864386df6068f26f026e62f932c41e4/odps/df/expr/merge.py#L1048-L1110 | def intersect(left, *rights, **kwargs):
"""
Calc intersection among datasets,
:param left: collection
:param rights: collection or list of collections
:param distinct: whether to preserve duolicate entries
:return: collection
:Examples:
>>> import pandas as pd
>>> df1 = DataFrame(p... | [
"def",
"intersect",
"(",
"left",
",",
"*",
"rights",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"time",
"from",
".",
".",
"utils",
"import",
"output",
"distinct",
"=",
"kwargs",
".",
"get",
"(",
"'distinct'",
",",
"False",
")",
"if",
"isinstance",
... | Calc intersection among datasets,
:param left: collection
:param rights: collection or list of collections
:param distinct: whether to preserve duolicate entries
:return: collection
:Examples:
>>> import pandas as pd
>>> df1 = DataFrame(pd.DataFrame({'a': [1, 2, 3, 3, 3], 'b': [1, 2, 3, 3,... | [
"Calc",
"intersection",
"among",
"datasets"
] | python | train |
pyviz/param | param/version.py | https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/param/version.py#L231-L244 | def _output_from_file(self, entry='git_describe'):
"""
Read the version from a .version file that may exist alongside __init__.py.
This file can be generated by piping the following output to file:
git describe --long --match v*.*
"""
try:
vfile = os.path.jo... | [
"def",
"_output_from_file",
"(",
"self",
",",
"entry",
"=",
"'git_describe'",
")",
":",
"try",
":",
"vfile",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"self",
".",
"fpath",
")",
",",
"'.version'",
")",
"with",
... | Read the version from a .version file that may exist alongside __init__.py.
This file can be generated by piping the following output to file:
git describe --long --match v*.* | [
"Read",
"the",
"version",
"from",
"a",
".",
"version",
"file",
"that",
"may",
"exist",
"alongside",
"__init__",
".",
"py",
"."
] | python | train |
Yubico/python-pyhsm | examples/yhsm-password-auth.py | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/examples/yhsm-password-auth.py#L108-L120 | def generate_aead(hsm, args, password):
"""
Generate an AEAD using the YubiHSM.
"""
try:
pw = password.ljust(args.min_len, chr(0x0))
return hsm.generate_aead_simple(args.nonce.decode('hex'), args.key_handle, pw)
except pyhsm.exception.YHSM_CommandFailed, e:
if e.status_str ==... | [
"def",
"generate_aead",
"(",
"hsm",
",",
"args",
",",
"password",
")",
":",
"try",
":",
"pw",
"=",
"password",
".",
"ljust",
"(",
"args",
".",
"min_len",
",",
"chr",
"(",
"0x0",
")",
")",
"return",
"hsm",
".",
"generate_aead_simple",
"(",
"args",
"."... | Generate an AEAD using the YubiHSM. | [
"Generate",
"an",
"AEAD",
"using",
"the",
"YubiHSM",
"."
] | python | train |
hyperledger/indy-plenum | plenum/server/replica.py | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/replica.py#L1581-L1595 | def addToPrePrepares(self, pp: PrePrepare) -> None:
"""
Add the specified PRE-PREPARE to this replica's list of received
PRE-PREPAREs and try sending PREPARE
:param pp: the PRE-PREPARE to add to the list
"""
key = (pp.viewNo, pp.ppSeqNo)
self.prePrepares[key] = p... | [
"def",
"addToPrePrepares",
"(",
"self",
",",
"pp",
":",
"PrePrepare",
")",
"->",
"None",
":",
"key",
"=",
"(",
"pp",
".",
"viewNo",
",",
"pp",
".",
"ppSeqNo",
")",
"self",
".",
"prePrepares",
"[",
"key",
"]",
"=",
"pp",
"self",
".",
"lastPrePrepareSe... | Add the specified PRE-PREPARE to this replica's list of received
PRE-PREPAREs and try sending PREPARE
:param pp: the PRE-PREPARE to add to the list | [
"Add",
"the",
"specified",
"PRE",
"-",
"PREPARE",
"to",
"this",
"replica",
"s",
"list",
"of",
"received",
"PRE",
"-",
"PREPAREs",
"and",
"try",
"sending",
"PREPARE"
] | python | train |
adamhadani/python-yelp | yelp/api.py | https://github.com/adamhadani/python-yelp/blob/7694ccb7274cc3c5783250ed0c3396cda2fcfa1a/yelp/api.py#L104-L131 | def by_bounding_box(self, tl_lat, tl_long, br_lat, br_long, term=None, num_biz_requested=None, category=None):
"""
Perform a Yelp Review Search based on a map bounding box.
Args:
tl_lat - bounding box top left latitude
tl_long - bounding box top left longitude
... | [
"def",
"by_bounding_box",
"(",
"self",
",",
"tl_lat",
",",
"tl_long",
",",
"br_lat",
",",
"br_long",
",",
"term",
"=",
"None",
",",
"num_biz_requested",
"=",
"None",
",",
"category",
"=",
"None",
")",
":",
"header",
",",
"content",
"=",
"self",
".",
"_... | Perform a Yelp Review Search based on a map bounding box.
Args:
tl_lat - bounding box top left latitude
tl_long - bounding box top left longitude
br_lat - bounding box bottom right latitude
br_long - bounding box bottom right longitude
term - Searc... | [
"Perform",
"a",
"Yelp",
"Review",
"Search",
"based",
"on",
"a",
"map",
"bounding",
"box",
"."
] | python | train |
saltstack/salt | salt/cloud/clouds/msazure.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L113-L136 | def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_va... | [
"def",
"get_conn",
"(",
")",
":",
"certificate_path",
"=",
"config",
".",
"get_cloud_config_value",
"(",
"'certificate_path'",
",",
"get_configured_provider",
"(",
")",
",",
"__opts__",
",",
"search_global",
"=",
"False",
")",
"subscription_id",
"=",
"salt",
".",
... | Return a conn object for the passed VM data | [
"Return",
"a",
"conn",
"object",
"for",
"the",
"passed",
"VM",
"data"
] | python | train |
coursera/courseraoauth2client | courseraoauth2client/oauth2.py | https://github.com/coursera/courseraoauth2client/blob/4edd991defe26bfc768ab28a30368cace40baf44/courseraoauth2client/oauth2.py#L105-L151 | def _make_handler(state_token, done_function):
'''
Makes a a handler class to use inside the basic python HTTP server.
state_token is the expected state token.
done_function is a function that is called, with the code passed to it.
'''
class LocalServerHandler(BaseHTTPServer.BaseHTTPRequestHan... | [
"def",
"_make_handler",
"(",
"state_token",
",",
"done_function",
")",
":",
"class",
"LocalServerHandler",
"(",
"BaseHTTPServer",
".",
"BaseHTTPRequestHandler",
")",
":",
"def",
"error_response",
"(",
"self",
",",
"msg",
")",
":",
"logging",
".",
"warn",
"(",
... | Makes a a handler class to use inside the basic python HTTP server.
state_token is the expected state token.
done_function is a function that is called, with the code passed to it. | [
"Makes",
"a",
"a",
"handler",
"class",
"to",
"use",
"inside",
"the",
"basic",
"python",
"HTTP",
"server",
"."
] | python | train |
romanz/trezor-agent | libagent/device/interface.py | https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/device/interface.py#L26-L31 | def string_to_identity(identity_str):
"""Parse string into Identity dictionary."""
m = _identity_regexp.match(identity_str)
result = m.groupdict()
log.debug('parsed identity: %s', result)
return {k: v for k, v in result.items() if v} | [
"def",
"string_to_identity",
"(",
"identity_str",
")",
":",
"m",
"=",
"_identity_regexp",
".",
"match",
"(",
"identity_str",
")",
"result",
"=",
"m",
".",
"groupdict",
"(",
")",
"log",
".",
"debug",
"(",
"'parsed identity: %s'",
",",
"result",
")",
"return",... | Parse string into Identity dictionary. | [
"Parse",
"string",
"into",
"Identity",
"dictionary",
"."
] | python | train |
openstax/cnx-archive | cnxarchive/views/in_book_search.py | https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/views/in_book_search.py#L89-L149 | def in_book_search_highlighted_results(request):
"""In-book search - returns a highlighted version of the HTML."""
results = {}
args = request.matchdict
ident_hash = args['ident_hash']
page_ident_hash = args['page_ident_hash']
try:
page_uuid, _ = split_ident_hash(page_ident_hash)
e... | [
"def",
"in_book_search_highlighted_results",
"(",
"request",
")",
":",
"results",
"=",
"{",
"}",
"args",
"=",
"request",
".",
"matchdict",
"ident_hash",
"=",
"args",
"[",
"'ident_hash'",
"]",
"page_ident_hash",
"=",
"args",
"[",
"'page_ident_hash'",
"]",
"try",
... | In-book search - returns a highlighted version of the HTML. | [
"In",
"-",
"book",
"search",
"-",
"returns",
"a",
"highlighted",
"version",
"of",
"the",
"HTML",
"."
] | python | train |
klen/makesite | makesite/modules/django/main/utils/models.py | https://github.com/klen/makesite/blob/f6f77a43a04a256189e8fffbeac1ffd63f35a10c/makesite/modules/django/main/utils/models.py#L40-L67 | def update(instance, full_clean=True, post_save=False, **kwargs):
"Atomically update instance, setting field/value pairs from kwargs"
# apply the updated args to the instance to mimic the change
# note that these might slightly differ from the true database values
# as the DB could have been updated by... | [
"def",
"update",
"(",
"instance",
",",
"full_clean",
"=",
"True",
",",
"post_save",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"# apply the updated args to the instance to mimic the change",
"# note that these might slightly differ from the true database values",
"# as ... | Atomically update instance, setting field/value pairs from kwargs | [
"Atomically",
"update",
"instance",
"setting",
"field",
"/",
"value",
"pairs",
"from",
"kwargs"
] | python | train |
cogniteev/docido-python-sdk | docido_sdk/toolbox/date_ext.py | https://github.com/cogniteev/docido-python-sdk/blob/58ecb6c6f5757fd40c0601657ab18368da7ddf33/docido_sdk/toolbox/date_ext.py#L117-L156 | def from_str(cls, timestr, shaked=False):
"""Use `dateutil` module to parse the give string
:param basestring timestr: string representing a date to parse
:param bool shaked: whether the input parameter been already
cleaned or not.
"""
orig = timestr
if not shake... | [
"def",
"from_str",
"(",
"cls",
",",
"timestr",
",",
"shaked",
"=",
"False",
")",
":",
"orig",
"=",
"timestr",
"if",
"not",
"shaked",
":",
"timestr",
"=",
"cls",
".",
"fix_timezone_separator",
"(",
"timestr",
")",
"try",
":",
"date",
"=",
"parser",
".",... | Use `dateutil` module to parse the give string
:param basestring timestr: string representing a date to parse
:param bool shaked: whether the input parameter been already
cleaned or not. | [
"Use",
"dateutil",
"module",
"to",
"parse",
"the",
"give",
"string"
] | python | train |
wrobstory/vincent | vincent/data.py | https://github.com/wrobstory/vincent/blob/c5a06e50179015fbb788a7a42e4570ff4467a9e9/vincent/data.py#L433-L460 | def _numpy_to_values(data):
'''Convert a NumPy array to values attribute'''
def to_list_no_index(xvals, yvals):
return [{"x": x, "y": np.asscalar(y)}
for x, y in zip(xvals, yvals)]
if len(data.shape) == 1 or data.shape[1] == 1:
xvals = range(data.shap... | [
"def",
"_numpy_to_values",
"(",
"data",
")",
":",
"def",
"to_list_no_index",
"(",
"xvals",
",",
"yvals",
")",
":",
"return",
"[",
"{",
"\"x\"",
":",
"x",
",",
"\"y\"",
":",
"np",
".",
"asscalar",
"(",
"y",
")",
"}",
"for",
"x",
",",
"y",
"in",
"z... | Convert a NumPy array to values attribute | [
"Convert",
"a",
"NumPy",
"array",
"to",
"values",
"attribute"
] | python | train |
ElevenPaths/AtomShields | atomshields/checkers/dsstore.py | https://github.com/ElevenPaths/AtomShields/blob/e75f25393b4a7a315ec96bf9b8e654cb2200866a/atomshields/checkers/dsstore.py#L22-L48 | def run(self):
"""
Finds .DS_Store files into path
"""
filename = ".DS_Store"
command = "find {path} -type f -name \"{filename}\" ".format(path = self.path, filename = filename)
cmd = CommandHelper(command)
cmd.execute()
files = cmd.output.split("\n")
for f in files:
if not f.endswith(filename):
... | [
"def",
"run",
"(",
"self",
")",
":",
"filename",
"=",
"\".DS_Store\"",
"command",
"=",
"\"find {path} -type f -name \\\"{filename}\\\" \"",
".",
"format",
"(",
"path",
"=",
"self",
".",
"path",
",",
"filename",
"=",
"filename",
")",
"cmd",
"=",
"CommandHelper",
... | Finds .DS_Store files into path | [
"Finds",
".",
"DS_Store",
"files",
"into",
"path"
] | python | valid |
saltstack/salt | salt/states/grafana_dashboard.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/grafana_dashboard.py#L452-L466 | def _update(dashboard, profile):
'''Update a specific dashboard.'''
payload = {
'dashboard': dashboard,
'overwrite': True
}
request_url = "{0}/api/dashboards/db".format(profile.get('grafana_url'))
response = requests.post(
request_url,
headers={
"Authoriza... | [
"def",
"_update",
"(",
"dashboard",
",",
"profile",
")",
":",
"payload",
"=",
"{",
"'dashboard'",
":",
"dashboard",
",",
"'overwrite'",
":",
"True",
"}",
"request_url",
"=",
"\"{0}/api/dashboards/db\"",
".",
"format",
"(",
"profile",
".",
"get",
"(",
"'grafa... | Update a specific dashboard. | [
"Update",
"a",
"specific",
"dashboard",
"."
] | python | train |
fboender/ansible-cmdb | src/ansible-cmdb.py | https://github.com/fboender/ansible-cmdb/blob/ebd960ac10684e8c9ec2b12751bba2c4c9504ab7/src/ansible-cmdb.py#L96-L122 | def get_cust_cols(path):
"""
Load custom column definitions.
"""
required_keys = ["title", "id", "sType", "visible"]
with open(path, 'r') as f:
try:
cust_cols = ast.literal_eval(f.read())
except Exception as err:
sys.stderr.write("Invalid custom columns file:... | [
"def",
"get_cust_cols",
"(",
"path",
")",
":",
"required_keys",
"=",
"[",
"\"title\"",
",",
"\"id\"",
",",
"\"sType\"",
",",
"\"visible\"",
"]",
"with",
"open",
"(",
"path",
",",
"'r'",
")",
"as",
"f",
":",
"try",
":",
"cust_cols",
"=",
"ast",
".",
"... | Load custom column definitions. | [
"Load",
"custom",
"column",
"definitions",
"."
] | python | train |
blockstack/blockstack-core | blockstack/lib/atlas.py | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/atlas.py#L1015-L1095 | def atlasdb_add_peer( peer_hostport, discovery_time=None, peer_table=None, con=None, path=None, ping_on_evict=True ):
"""
Add a peer to the peer table.
If the peer conflicts with another peer, ping it first, and only insert
the new peer if the old peer is dead.
Keep the in-RAM peer table cache-cohe... | [
"def",
"atlasdb_add_peer",
"(",
"peer_hostport",
",",
"discovery_time",
"=",
"None",
",",
"peer_table",
"=",
"None",
",",
"con",
"=",
"None",
",",
"path",
"=",
"None",
",",
"ping_on_evict",
"=",
"True",
")",
":",
"# bound the number of peers we add to PEER_MAX_DB"... | Add a peer to the peer table.
If the peer conflicts with another peer, ping it first, and only insert
the new peer if the old peer is dead.
Keep the in-RAM peer table cache-coherent as well.
Return True if this peer was added to the table (or preserved)
Return False if not | [
"Add",
"a",
"peer",
"to",
"the",
"peer",
"table",
".",
"If",
"the",
"peer",
"conflicts",
"with",
"another",
"peer",
"ping",
"it",
"first",
"and",
"only",
"insert",
"the",
"new",
"peer",
"if",
"the",
"old",
"peer",
"is",
"dead",
"."
] | python | train |
edx/i18n-tools | i18n/transifex.py | https://github.com/edx/i18n-tools/blob/99b20c17d1a0ca07a8839f33e0e9068248a581e5/i18n/transifex.py#L103-L111 | def clean_translated_locales(configuration, langs=None):
"""
Strips out the warning from all translated po files
about being an English source file.
"""
if not langs:
langs = configuration.translated_locales
for locale in langs:
clean_locale(configuration, locale) | [
"def",
"clean_translated_locales",
"(",
"configuration",
",",
"langs",
"=",
"None",
")",
":",
"if",
"not",
"langs",
":",
"langs",
"=",
"configuration",
".",
"translated_locales",
"for",
"locale",
"in",
"langs",
":",
"clean_locale",
"(",
"configuration",
",",
"... | Strips out the warning from all translated po files
about being an English source file. | [
"Strips",
"out",
"the",
"warning",
"from",
"all",
"translated",
"po",
"files",
"about",
"being",
"an",
"English",
"source",
"file",
"."
] | python | train |
echinopsii/net.echinopsii.ariane.community.cli.python3 | ariane_clip3/directory.py | https://github.com/echinopsii/net.echinopsii.ariane.community.cli.python3/blob/0a7feddebf66fee4bef38d64f456d93a7e9fcd68/ariane_clip3/directory.py#L3713-L3747 | def del_ostype(self, ostype, sync=True):
"""
delete OS type from this company
:param ostype: the OS type to be deleted from this company
:param sync: If sync=True(default) synchronize with Ariane server. If sync=False,
add the OS type object on list to be removed on next save().
... | [
"def",
"del_ostype",
"(",
"self",
",",
"ostype",
",",
"sync",
"=",
"True",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"Company.del_ostype\"",
")",
"if",
"not",
"sync",
":",
"self",
".",
"ost_2_rm",
".",
"append",
"(",
"ostype",
")",
"else",
":",
"if",
... | delete OS type from this company
:param ostype: the OS type to be deleted from this company
:param sync: If sync=True(default) synchronize with Ariane server. If sync=False,
add the OS type object on list to be removed on next save().
:return: | [
"delete",
"OS",
"type",
"from",
"this",
"company",
":",
"param",
"ostype",
":",
"the",
"OS",
"type",
"to",
"be",
"deleted",
"from",
"this",
"company",
":",
"param",
"sync",
":",
"If",
"sync",
"=",
"True",
"(",
"default",
")",
"synchronize",
"with",
"Ar... | python | train |
ornlneutronimaging/ImagingReso | ImagingReso/_utilities.py | https://github.com/ornlneutronimaging/ImagingReso/blob/2da5cd1f565b3128f59d86bcedfd9adc2b02218b/ImagingReso/_utilities.py#L623-L668 | def set_distance_units(value=np.NaN, from_units='mm', to_units='cm'):
"""convert distance into new units
Parameters:
===========
value: float. value to convert
from_units: string. Must be 'mm', 'cm' or 'm'
to_units: string. must be 'mm','cm' or 'm'
Returns:
========
convert... | [
"def",
"set_distance_units",
"(",
"value",
"=",
"np",
".",
"NaN",
",",
"from_units",
"=",
"'mm'",
",",
"to_units",
"=",
"'cm'",
")",
":",
"if",
"from_units",
"==",
"to_units",
":",
"return",
"value",
"if",
"from_units",
"==",
"'cm'",
":",
"if",
"to_units... | convert distance into new units
Parameters:
===========
value: float. value to convert
from_units: string. Must be 'mm', 'cm' or 'm'
to_units: string. must be 'mm','cm' or 'm'
Returns:
========
converted value
Raises:
=======
ValueError if from_units is not a v... | [
"convert",
"distance",
"into",
"new",
"units",
"Parameters",
":",
"===========",
"value",
":",
"float",
".",
"value",
"to",
"convert",
"from_units",
":",
"string",
".",
"Must",
"be",
"mm",
"cm",
"or",
"m",
"to_units",
":",
"string",
".",
"must",
"be",
"m... | python | train |
saltstack/salt | salt/modules/zonecfg.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zonecfg.py#L393-L443 | def _property(methode, zone, key, value):
'''
internal handler for set and clear_property
methode : string
either set, add, or clear
zone : string
name of zone
key : string
name of property
value : string
value of property
'''
ret = {'status': True}
... | [
"def",
"_property",
"(",
"methode",
",",
"zone",
",",
"key",
",",
"value",
")",
":",
"ret",
"=",
"{",
"'status'",
":",
"True",
"}",
"# generate update script",
"cfg_file",
"=",
"None",
"if",
"methode",
"not",
"in",
"[",
"'set'",
",",
"'clear'",
"]",
":... | internal handler for set and clear_property
methode : string
either set, add, or clear
zone : string
name of zone
key : string
name of property
value : string
value of property | [
"internal",
"handler",
"for",
"set",
"and",
"clear_property"
] | python | train |
dhermes/bezier | docs/make_images.py | https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/docs/make_images.py#L194-L206 | def helper_parallel_lines(start0, end0, start1, end1, filename):
"""Image for :func:`.parallel_lines_parameters` docstring."""
if NO_IMAGES:
return
figure = plt.figure()
ax = figure.gca()
points = stack1d(start0, end0, start1, end1)
ax.plot(points[0, :2], points[1, :2], marker="o")
... | [
"def",
"helper_parallel_lines",
"(",
"start0",
",",
"end0",
",",
"start1",
",",
"end1",
",",
"filename",
")",
":",
"if",
"NO_IMAGES",
":",
"return",
"figure",
"=",
"plt",
".",
"figure",
"(",
")",
"ax",
"=",
"figure",
".",
"gca",
"(",
")",
"points",
"... | Image for :func:`.parallel_lines_parameters` docstring. | [
"Image",
"for",
":",
"func",
":",
".",
"parallel_lines_parameters",
"docstring",
"."
] | python | train |
inspirehep/refextract | refextract/references/engine.py | https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/engine.py#L134-L144 | def format_volume(citation_elements):
"""format volume number (roman numbers to arabic)
When the volume number is expressed in roman numbers (CXXII),
they are converted to their equivalent in arabic numbers (42)
"""
re_roman = re.compile(re_roman_numbers + u'$', re.UNICODE)
for el in citation_e... | [
"def",
"format_volume",
"(",
"citation_elements",
")",
":",
"re_roman",
"=",
"re",
".",
"compile",
"(",
"re_roman_numbers",
"+",
"u'$'",
",",
"re",
".",
"UNICODE",
")",
"for",
"el",
"in",
"citation_elements",
":",
"if",
"el",
"[",
"'type'",
"]",
"==",
"'... | format volume number (roman numbers to arabic)
When the volume number is expressed in roman numbers (CXXII),
they are converted to their equivalent in arabic numbers (42) | [
"format",
"volume",
"number",
"(",
"roman",
"numbers",
"to",
"arabic",
")"
] | python | train |
DarkEnergySurvey/ugali | ugali/utils/plotting.py | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/plotting.py#L74-L101 | def twoDimensionalHistogram(title, title_x, title_y,
z, bins_x, bins_y,
lim_x=None, lim_y=None,
vmin=None, vmax=None):
"""
Create a two-dimension histogram plot or binned map.
If using the outputs of np.histogram2d, remembe... | [
"def",
"twoDimensionalHistogram",
"(",
"title",
",",
"title_x",
",",
"title_y",
",",
"z",
",",
"bins_x",
",",
"bins_y",
",",
"lim_x",
"=",
"None",
",",
"lim_y",
"=",
"None",
",",
"vmin",
"=",
"None",
",",
"vmax",
"=",
"None",
")",
":",
"plt",
".",
... | Create a two-dimension histogram plot or binned map.
If using the outputs of np.histogram2d, remember to transpose the histogram.
INPUTS | [
"Create",
"a",
"two",
"-",
"dimension",
"histogram",
"plot",
"or",
"binned",
"map",
"."
] | python | train |
thiagopbueno/pyrddl | pyrddl/parser.py | https://github.com/thiagopbueno/pyrddl/blob/3bcfa850b1a7532c7744358f3c6b9e0f8ab978c9/pyrddl/parser.py#L419-L426 | def p_action_precond_section(self, p):
'''action_precond_section : ACTION_PRECONDITIONS LCURLY action_precond_list RCURLY SEMI
| ACTION_PRECONDITIONS LCURLY RCURLY SEMI'''
if len(p) == 6:
p[0] = ('preconds', p[3])
elif len(p) == 5:
p[0] =... | [
"def",
"p_action_precond_section",
"(",
"self",
",",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
"==",
"6",
":",
"p",
"[",
"0",
"]",
"=",
"(",
"'preconds'",
",",
"p",
"[",
"3",
"]",
")",
"elif",
"len",
"(",
"p",
")",
"==",
"5",
":",
"p",
"["... | action_precond_section : ACTION_PRECONDITIONS LCURLY action_precond_list RCURLY SEMI
| ACTION_PRECONDITIONS LCURLY RCURLY SEMI | [
"action_precond_section",
":",
"ACTION_PRECONDITIONS",
"LCURLY",
"action_precond_list",
"RCURLY",
"SEMI",
"|",
"ACTION_PRECONDITIONS",
"LCURLY",
"RCURLY",
"SEMI"
] | python | train |
titusjan/argos | argos/application.py | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/application.py#L191-L197 | def deleteProfile(self, profile):
""" Removes a profile from the persistent settings
"""
profGroupName = self.profileGroupName(profile)
logger.debug("Resetting profile settings: {}".format(profGroupName))
settings = QtCore.QSettings()
settings.remove(profGroupName) | [
"def",
"deleteProfile",
"(",
"self",
",",
"profile",
")",
":",
"profGroupName",
"=",
"self",
".",
"profileGroupName",
"(",
"profile",
")",
"logger",
".",
"debug",
"(",
"\"Resetting profile settings: {}\"",
".",
"format",
"(",
"profGroupName",
")",
")",
"settings... | Removes a profile from the persistent settings | [
"Removes",
"a",
"profile",
"from",
"the",
"persistent",
"settings"
] | python | train |
gem/oq-engine | openquake/commonlib/oqzip.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/oqzip.py#L67-L77 | def zip_exposure(exposure_xml, archive_zip='', log=logging.info):
"""
Zip an exposure.xml file with all its .csv subfiles (if any)
"""
archive_zip = archive_zip or exposure_xml[:-4] + '.zip'
if os.path.exists(archive_zip):
sys.exit('%s exists already' % archive_zip)
[exp] = Exposure.read... | [
"def",
"zip_exposure",
"(",
"exposure_xml",
",",
"archive_zip",
"=",
"''",
",",
"log",
"=",
"logging",
".",
"info",
")",
":",
"archive_zip",
"=",
"archive_zip",
"or",
"exposure_xml",
"[",
":",
"-",
"4",
"]",
"+",
"'.zip'",
"if",
"os",
".",
"path",
".",... | Zip an exposure.xml file with all its .csv subfiles (if any) | [
"Zip",
"an",
"exposure",
".",
"xml",
"file",
"with",
"all",
"its",
".",
"csv",
"subfiles",
"(",
"if",
"any",
")"
] | python | train |
Opentrons/opentrons | api/src/opentrons/simulate.py | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/simulate.py#L93-L164 | def simulate(protocol_file,
propagate_logs=False,
log_level='warning') -> List[Mapping[str, Any]]:
"""
Simulate the protocol itself.
This is a one-stop function to simulate a protocol, whether python or json,
no matter the api version, from external (i.e. not bound up in other... | [
"def",
"simulate",
"(",
"protocol_file",
",",
"propagate_logs",
"=",
"False",
",",
"log_level",
"=",
"'warning'",
")",
"->",
"List",
"[",
"Mapping",
"[",
"str",
",",
"Any",
"]",
"]",
":",
"stack_logger",
"=",
"logging",
".",
"getLogger",
"(",
"'opentrons'"... | Simulate the protocol itself.
This is a one-stop function to simulate a protocol, whether python or json,
no matter the api version, from external (i.e. not bound up in other
internal server infrastructure) sources.
To simulate an opentrons protocol from other places, pass in a file like
object as... | [
"Simulate",
"the",
"protocol",
"itself",
"."
] | python | train |
PonteIneptique/collatinus-python | pycollatinus/modele.py | https://github.com/PonteIneptique/collatinus-python/blob/fca37b0b77bc60f47d3c24ab42f6d0bdca6ba0f5/pycollatinus/modele.py#L180-L190 | def desinences(self, d=None):
""" Renvoie la liste des désinence de morpho d du modèle.
:param d: Identifant de morphologie
:type d: int
:return: Liste des désinence de morpho d du modèle ou toutes les désinences du modèle (Applaties en python, doute sur original)
:rtype: list o... | [
"def",
"desinences",
"(",
"self",
",",
"d",
"=",
"None",
")",
":",
"if",
"d",
":",
"return",
"self",
".",
"_desinences",
"[",
"d",
"]",
"return",
"[",
"x",
"for",
"morpho_values",
"in",
"self",
".",
"_desinences",
".",
"values",
"(",
")",
"for",
"x... | Renvoie la liste des désinence de morpho d du modèle.
:param d: Identifant de morphologie
:type d: int
:return: Liste des désinence de morpho d du modèle ou toutes les désinences du modèle (Applaties en python, doute sur original)
:rtype: list of Desinence | [
"Renvoie",
"la",
"liste",
"des",
"désinence",
"de",
"morpho",
"d",
"du",
"modèle",
"."
] | python | train |
softlayer/softlayer-python | SoftLayer/managers/file.py | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/file.py#L287-L314 | def order_modified_volume(self, volume_id, new_size=None, new_iops=None, new_tier_level=None):
"""Places an order for modifying an existing file volume.
:param volume_id: The ID of the volume to be modified
:param new_size: The new size/capacity for the volume
:param new_iops: The new I... | [
"def",
"order_modified_volume",
"(",
"self",
",",
"volume_id",
",",
"new_size",
"=",
"None",
",",
"new_iops",
"=",
"None",
",",
"new_tier_level",
"=",
"None",
")",
":",
"mask_items",
"=",
"[",
"'id'",
",",
"'billingItem'",
",",
"'storageType[keyName]'",
",",
... | Places an order for modifying an existing file volume.
:param volume_id: The ID of the volume to be modified
:param new_size: The new size/capacity for the volume
:param new_iops: The new IOPS for the volume
:param new_tier_level: The new tier level for the volume
:return: Retur... | [
"Places",
"an",
"order",
"for",
"modifying",
"an",
"existing",
"file",
"volume",
"."
] | python | train |
coleifer/walrus | walrus/containers.py | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/containers.py#L491-L503 | def unionstore(self, dest, *others):
"""
Store the union of the current set and one or more
others in a new key.
:param dest: the name of the key to store union
:param others: One or more :py:class:`Set` instances
:returns: A :py:class:`Set` referencing ``dest``.
... | [
"def",
"unionstore",
"(",
"self",
",",
"dest",
",",
"*",
"others",
")",
":",
"keys",
"=",
"[",
"self",
".",
"key",
"]",
"keys",
".",
"extend",
"(",
"[",
"other",
".",
"key",
"for",
"other",
"in",
"others",
"]",
")",
"self",
".",
"database",
".",
... | Store the union of the current set and one or more
others in a new key.
:param dest: the name of the key to store union
:param others: One or more :py:class:`Set` instances
:returns: A :py:class:`Set` referencing ``dest``. | [
"Store",
"the",
"union",
"of",
"the",
"current",
"set",
"and",
"one",
"or",
"more",
"others",
"in",
"a",
"new",
"key",
"."
] | python | train |
jcrist/skein | skein/utils.py | https://github.com/jcrist/skein/blob/16f8b1d3b3d9f79f36e2f152e45893339a1793e8/skein/utils.py#L177-L201 | def format_table(columns, rows):
"""Formats an ascii table for given columns and rows.
Parameters
----------
columns : list
The column names
rows : list of tuples
The rows in the table. Each tuple must be the same length as
``columns``.
"""
rows = [tuple(str(i) for i... | [
"def",
"format_table",
"(",
"columns",
",",
"rows",
")",
":",
"rows",
"=",
"[",
"tuple",
"(",
"str",
"(",
"i",
")",
"for",
"i",
"in",
"r",
")",
"for",
"r",
"in",
"rows",
"]",
"columns",
"=",
"tuple",
"(",
"str",
"(",
"i",
")",
".",
"upper",
"... | Formats an ascii table for given columns and rows.
Parameters
----------
columns : list
The column names
rows : list of tuples
The rows in the table. Each tuple must be the same length as
``columns``. | [
"Formats",
"an",
"ascii",
"table",
"for",
"given",
"columns",
"and",
"rows",
"."
] | python | train |
SUSE-Enceladus/ipa | ipa/ipa_cloud.py | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_cloud.py#L212-L240 | def _log_info(self):
"""Output test run information to top of log file."""
if self.cloud == 'ssh':
self.results['info'] = {
'platform': self.cloud,
'distro': self.distro_name,
'image': self.instance_ip,
'timestamp': self.time_st... | [
"def",
"_log_info",
"(",
"self",
")",
":",
"if",
"self",
".",
"cloud",
"==",
"'ssh'",
":",
"self",
".",
"results",
"[",
"'info'",
"]",
"=",
"{",
"'platform'",
":",
"self",
".",
"cloud",
",",
"'distro'",
":",
"self",
".",
"distro_name",
",",
"'image'"... | Output test run information to top of log file. | [
"Output",
"test",
"run",
"information",
"to",
"top",
"of",
"log",
"file",
"."
] | python | train |
gabrielelanaro/chemview | chemview/utils.py | https://github.com/gabrielelanaro/chemview/blob/2c9768dd23db99e59e27adff2a953bb8ee795fa3/chemview/utils.py#L7-L18 | def encode_numpy(array):
'''Encode a numpy array as a base64 encoded string, to be JSON serialized.
:return: a dictionary containing the fields:
- *data*: the base64 string
- *type*: the array type
- *shape*: the array shape
'''
return {'data' : base64.... | [
"def",
"encode_numpy",
"(",
"array",
")",
":",
"return",
"{",
"'data'",
":",
"base64",
".",
"b64encode",
"(",
"array",
".",
"data",
")",
".",
"decode",
"(",
"'utf8'",
")",
",",
"'type'",
":",
"array",
".",
"dtype",
".",
"name",
",",
"'shape'",
":",
... | Encode a numpy array as a base64 encoded string, to be JSON serialized.
:return: a dictionary containing the fields:
- *data*: the base64 string
- *type*: the array type
- *shape*: the array shape | [
"Encode",
"a",
"numpy",
"array",
"as",
"a",
"base64",
"encoded",
"string",
"to",
"be",
"JSON",
"serialized",
"."
] | python | train |
pytroll/satpy | satpy/readers/viirs_compact.py | https://github.com/pytroll/satpy/blob/1f21d20ac686b745fb0da9b4030d139893e066dd/satpy/readers/viirs_compact.py#L159-L199 | def read_geo(self, key, info):
"""Read angles.
"""
pairs = {('satellite_azimuth_angle', 'satellite_zenith_angle'):
("SatelliteAzimuthAngle", "SatelliteZenithAngle"),
('solar_azimuth_angle', 'solar_zenith_angle'):
("SolarAzimuthAngle", "SolarZeni... | [
"def",
"read_geo",
"(",
"self",
",",
"key",
",",
"info",
")",
":",
"pairs",
"=",
"{",
"(",
"'satellite_azimuth_angle'",
",",
"'satellite_zenith_angle'",
")",
":",
"(",
"\"SatelliteAzimuthAngle\"",
",",
"\"SatelliteZenithAngle\"",
")",
",",
"(",
"'solar_azimuth_ang... | Read angles. | [
"Read",
"angles",
"."
] | python | train |
theislab/scanpy | scanpy/preprocessing/_combat.py | https://github.com/theislab/scanpy/blob/9e4e5ee02e04cf618872d9b098e24f0542e8b227/scanpy/preprocessing/_combat.py#L136-L266 | def combat(adata: AnnData, key: str = 'batch', covariates: Optional[Collection[str]] = None, inplace: bool = True):
"""ComBat function for batch effect correction [Johnson07]_ [Leek12]_ [Pedersen12]_.
Corrects for batch effects by fitting linear models, gains statistical power
via an EB framework where inf... | [
"def",
"combat",
"(",
"adata",
":",
"AnnData",
",",
"key",
":",
"str",
"=",
"'batch'",
",",
"covariates",
":",
"Optional",
"[",
"Collection",
"[",
"str",
"]",
"]",
"=",
"None",
",",
"inplace",
":",
"bool",
"=",
"True",
")",
":",
"# check the input",
... | ComBat function for batch effect correction [Johnson07]_ [Leek12]_ [Pedersen12]_.
Corrects for batch effects by fitting linear models, gains statistical power
via an EB framework where information is borrowed across genes. This uses the
implementation of `ComBat <https://github.com/brentp/combat.py>`__ [Pe... | [
"ComBat",
"function",
"for",
"batch",
"effect",
"correction",
"[",
"Johnson07",
"]",
"_",
"[",
"Leek12",
"]",
"_",
"[",
"Pedersen12",
"]",
"_",
"."
] | python | train |
tanghaibao/goatools | goatools/gosubdag/gosubdag_init.py | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/gosubdag/gosubdag_init.py#L94-L106 | def _init_go_sources(self, go_sources_arg, go2obj_arg):
"""Return GO sources which are present in GODag."""
gos_user = set(go_sources_arg)
if 'children' in self.kws and self.kws['children']:
gos_user |= get_leaf_children(gos_user, go2obj_arg)
gos_godag = set(go2obj_arg)
... | [
"def",
"_init_go_sources",
"(",
"self",
",",
"go_sources_arg",
",",
"go2obj_arg",
")",
":",
"gos_user",
"=",
"set",
"(",
"go_sources_arg",
")",
"if",
"'children'",
"in",
"self",
".",
"kws",
"and",
"self",
".",
"kws",
"[",
"'children'",
"]",
":",
"gos_user"... | Return GO sources which are present in GODag. | [
"Return",
"GO",
"sources",
"which",
"are",
"present",
"in",
"GODag",
"."
] | python | train |
bokeh/bokeh | bokeh/protocol/message.py | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/protocol/message.py#L204-L225 | def write_buffers(self, conn, locked=True):
''' Write any buffer headers and payloads to the given connection.
Args:
conn (object) :
May be any object with a ``write_message`` method. Typically,
a Tornado ``WSHandler`` or ``WebSocketClientConnection``
... | [
"def",
"write_buffers",
"(",
"self",
",",
"conn",
",",
"locked",
"=",
"True",
")",
":",
"if",
"conn",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Cannot write_buffers to connection None\"",
")",
"sent",
"=",
"0",
"for",
"header",
",",
"payload",
"in",
... | Write any buffer headers and payloads to the given connection.
Args:
conn (object) :
May be any object with a ``write_message`` method. Typically,
a Tornado ``WSHandler`` or ``WebSocketClientConnection``
locked (bool) :
Returns:
int ... | [
"Write",
"any",
"buffer",
"headers",
"and",
"payloads",
"to",
"the",
"given",
"connection",
"."
] | python | train |
Varkal/chuda | chuda/shell.py | https://github.com/Varkal/chuda/blob/0d93b716dede35231c21be97bcc19a656655983f/chuda/shell.py#L259-L271 | def run(self, command, block=True, cwd=None, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE):
"""
Create an instance of :class:`~ShellCommand` and run it
Args:
command (str): :class:`~ShellCommand`
block (bool): See :class:`~ShellCommand`
... | [
"def",
"run",
"(",
"self",
",",
"command",
",",
"block",
"=",
"True",
",",
"cwd",
"=",
"None",
",",
"stdin",
"=",
"subprocess",
".",
"PIPE",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
")",
":",
"if... | Create an instance of :class:`~ShellCommand` and run it
Args:
command (str): :class:`~ShellCommand`
block (bool): See :class:`~ShellCommand`
cwd (str): Override the runner cwd. Useb by the :class:`~ShellCommand` instance | [
"Create",
"an",
"instance",
"of",
":",
"class",
":",
"~ShellCommand",
"and",
"run",
"it"
] | python | train |
HPAC/matchpy | matchpy/matching/bipartite.py | https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/matching/bipartite.py#L144-L174 | def find_matching(self) -> Dict[TLeft, TRight]:
"""Finds a matching in the bipartite graph.
This is done using the Hopcroft-Karp algorithm with an implementation from the
`hopcroftkarp` package.
Returns:
A dictionary where each edge of the matching is represented by a key-v... | [
"def",
"find_matching",
"(",
"self",
")",
"->",
"Dict",
"[",
"TLeft",
",",
"TRight",
"]",
":",
"# The directed graph is represented as a dictionary of edges",
"# The key is the tail of all edges which are represented by the value",
"# The value is a set of heads for the all edges origi... | Finds a matching in the bipartite graph.
This is done using the Hopcroft-Karp algorithm with an implementation from the
`hopcroftkarp` package.
Returns:
A dictionary where each edge of the matching is represented by a key-value pair
with the key being from the left part... | [
"Finds",
"a",
"matching",
"in",
"the",
"bipartite",
"graph",
"."
] | python | train |
google/grr | grr/server/grr_response_server/aff4_objects/user_managers.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/aff4_objects/user_managers.py#L247-L291 | def CheckAccess(self, subject, token):
"""Checks for access to given subject with a given token.
CheckAccess runs given subject through all "allow" clauses that
were previously registered with Allow() calls. It returns True on
first match and raises access_control.UnauthorizedAccess if there
are no... | [
"def",
"CheckAccess",
"(",
"self",
",",
"subject",
",",
"token",
")",
":",
"subject",
"=",
"rdfvalue",
".",
"RDFURN",
"(",
"subject",
")",
"subject_str",
"=",
"subject",
".",
"SerializeToString",
"(",
")",
"for",
"check_tuple",
"in",
"self",
".",
"checks",... | Checks for access to given subject with a given token.
CheckAccess runs given subject through all "allow" clauses that
were previously registered with Allow() calls. It returns True on
first match and raises access_control.UnauthorizedAccess if there
are no matches or if any of the additional checks fa... | [
"Checks",
"for",
"access",
"to",
"given",
"subject",
"with",
"a",
"given",
"token",
"."
] | python | train |
gccxml/pygccxml | pygccxml/declarations/type_traits_classes.py | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits_classes.py#L708-L785 | def is_noncopyable(class_, already_visited_cls_vars=None):
"""
Checks if class is non copyable
Args:
class_ (declarations.class_t): the class to be checked
already_visited_cls_vars (list): optional list of vars that should not
be checked a second time, to prevent infinite recurs... | [
"def",
"is_noncopyable",
"(",
"class_",
",",
"already_visited_cls_vars",
"=",
"None",
")",
":",
"logger",
"=",
"utils",
".",
"loggers",
".",
"cxx_parser",
"class_decl",
"=",
"class_traits",
".",
"get_declaration",
"(",
"class_",
")",
"true_header",
"=",
"\"is_no... | Checks if class is non copyable
Args:
class_ (declarations.class_t): the class to be checked
already_visited_cls_vars (list): optional list of vars that should not
be checked a second time, to prevent infinite recursions.
In general you can ignore this argument, it is mainly... | [
"Checks",
"if",
"class",
"is",
"non",
"copyable"
] | python | train |
Erotemic/utool | utool/experimental/euler_tour_tree_avl.py | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/experimental/euler_tour_tree_avl.py#L921-L1016 | def avl_split(root, node):
"""
O(log(n))
Args:
root (Node): tree root
node (Node): node to split at
Returns:
puple: (tl, tr, node)
tl contains all keys in the tree less than node
tr contains all keys in the tree greater than node
node is the ... | [
"def",
"avl_split",
"(",
"root",
",",
"node",
")",
":",
"DEBUG_SPLIT",
"=",
"0",
"# Get the backtrace to the root",
"rpath",
"=",
"backtrace_root",
"(",
"node",
")",
"if",
"len",
"(",
"rpath",
")",
">",
"0",
":",
"assert",
"rpath",
"[",
"-",
"1",
"]",
... | O(log(n))
Args:
root (Node): tree root
node (Node): node to split at
Returns:
puple: (tl, tr, node)
tl contains all keys in the tree less than node
tr contains all keys in the tree greater than node
node is the node we split out
CommandLine:
... | [
"O",
"(",
"log",
"(",
"n",
"))"
] | python | train |
annayqho/TheCannon | code/lamost/mass_age/paper_plots/cn_features.py | https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/code/lamost/mass_age/paper_plots/cn_features.py#L55-L75 | def gen_cannon_grad_spec(base_labels, choose, low, high, coeffs, pivots):
""" Generate Cannon gradient spectra
Parameters
----------
labels: default values for [teff, logg, feh, cfe, nfe, afe, ak]
choose: val of cfe or nfe, whatever you're varying
low: lowest val of cfe or nfe, whatever you're ... | [
"def",
"gen_cannon_grad_spec",
"(",
"base_labels",
",",
"choose",
",",
"low",
",",
"high",
",",
"coeffs",
",",
"pivots",
")",
":",
"# Generate Cannon gradient spectra",
"low_lab",
"=",
"copy",
".",
"copy",
"(",
"base_labels",
")",
"low_lab",
"[",
"choose",
"]"... | Generate Cannon gradient spectra
Parameters
----------
labels: default values for [teff, logg, feh, cfe, nfe, afe, ak]
choose: val of cfe or nfe, whatever you're varying
low: lowest val of cfe or nfe, whatever you're varying
high: highest val of cfe or nfe, whatever you're varying | [
"Generate",
"Cannon",
"gradient",
"spectra"
] | python | train |
SheffieldML/GPy | GPy/core/gp.py | https://github.com/SheffieldML/GPy/blob/54c32d79d289d622fb18b898aee65a2a431d90cf/GPy/core/gp.py#L384-L405 | def predict_quantiles(self, X, quantiles=(2.5, 97.5), Y_metadata=None, kern=None, likelihood=None):
"""
Get the predictive quantiles around the prediction at X
:param X: The points at which to make a prediction
:type X: np.ndarray (Xnew x self.input_dim)
:param quantiles: tuple ... | [
"def",
"predict_quantiles",
"(",
"self",
",",
"X",
",",
"quantiles",
"=",
"(",
"2.5",
",",
"97.5",
")",
",",
"Y_metadata",
"=",
"None",
",",
"kern",
"=",
"None",
",",
"likelihood",
"=",
"None",
")",
":",
"m",
",",
"v",
"=",
"self",
".",
"_raw_predi... | Get the predictive quantiles around the prediction at X
:param X: The points at which to make a prediction
:type X: np.ndarray (Xnew x self.input_dim)
:param quantiles: tuple of quantiles, default is (2.5, 97.5) which is the 95% interval
:type quantiles: tuple
:param kern: optio... | [
"Get",
"the",
"predictive",
"quantiles",
"around",
"the",
"prediction",
"at",
"X"
] | python | train |
tagcubeio/tagcube-cli | tagcube_cli/main.py | https://github.com/tagcubeio/tagcube-cli/blob/709e4b0b11331a4d2791dc79107e5081518d75bf/tagcube_cli/main.py#L6-L26 | def main():
"""
Project's main method which will parse the command line arguments, run a
scan using the TagCubeClient and exit.
"""
cmd_args = TagCubeCLI.parse_args()
try:
tagcube_cli = TagCubeCLI.from_cmd_args(cmd_args)
except ValueError, ve:
# We get here when there are no... | [
"def",
"main",
"(",
")",
":",
"cmd_args",
"=",
"TagCubeCLI",
".",
"parse_args",
"(",
")",
"try",
":",
"tagcube_cli",
"=",
"TagCubeCLI",
".",
"from_cmd_args",
"(",
"cmd_args",
")",
"except",
"ValueError",
",",
"ve",
":",
"# We get here when there are no credentia... | Project's main method which will parse the command line arguments, run a
scan using the TagCubeClient and exit. | [
"Project",
"s",
"main",
"method",
"which",
"will",
"parse",
"the",
"command",
"line",
"arguments",
"run",
"a",
"scan",
"using",
"the",
"TagCubeClient",
"and",
"exit",
"."
] | python | train |
yougov/librarypaste | librarypaste/pmxbot.py | https://github.com/yougov/librarypaste/blob/740fafcb260f493ca5bbd24afd59d49444c2b2ae/librarypaste/pmxbot.py#L14-L23 | def paste(client, event, channel, nick, rest):
"Drop a link to your latest paste"
path = '/last/{nick}'.format(**locals())
paste_root = pmxbot.config.get('librarypaste', 'http://paste.jaraco.com')
url = urllib.parse.urljoin(paste_root, path)
auth = pmxbot.config.get('librarypaste auth')
resp = requests.head(url, ... | [
"def",
"paste",
"(",
"client",
",",
"event",
",",
"channel",
",",
"nick",
",",
"rest",
")",
":",
"path",
"=",
"'/last/{nick}'",
".",
"format",
"(",
"*",
"*",
"locals",
"(",
")",
")",
"paste_root",
"=",
"pmxbot",
".",
"config",
".",
"get",
"(",
"'li... | Drop a link to your latest paste | [
"Drop",
"a",
"link",
"to",
"your",
"latest",
"paste"
] | python | train |
LonamiWebs/Telethon | telethon/tl/custom/button.py | https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon/tl/custom/button.py#L134-L143 | def request_phone(cls, text, *,
resize=None, single_use=None, selective=None):
"""
Creates a new button that will request
the user's phone number upon being clicked.
``resize``, ``single_use`` and ``selective`` are documented in `text`.
"""
return c... | [
"def",
"request_phone",
"(",
"cls",
",",
"text",
",",
"*",
",",
"resize",
"=",
"None",
",",
"single_use",
"=",
"None",
",",
"selective",
"=",
"None",
")",
":",
"return",
"cls",
"(",
"types",
".",
"KeyboardButtonRequestPhone",
"(",
"text",
")",
",",
"re... | Creates a new button that will request
the user's phone number upon being clicked.
``resize``, ``single_use`` and ``selective`` are documented in `text`. | [
"Creates",
"a",
"new",
"button",
"that",
"will",
"request",
"the",
"user",
"s",
"phone",
"number",
"upon",
"being",
"clicked",
"."
] | python | train |
gem/oq-engine | openquake/hazardlib/gsim/edwards_fah_2013a.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/edwards_fah_2013a.py#L183-L190 | def _compute_term_2(self, C, mag, R):
"""
(a8 + a9.*M + a10.*M.*M + a11.*M.*M.*M).*d(r)
"""
return (
(C['a8'] + C['a9'] * mag + C['a10'] * np.power(mag, 2) +
C['a11'] * np.power(mag, 3)) * R
) | [
"def",
"_compute_term_2",
"(",
"self",
",",
"C",
",",
"mag",
",",
"R",
")",
":",
"return",
"(",
"(",
"C",
"[",
"'a8'",
"]",
"+",
"C",
"[",
"'a9'",
"]",
"*",
"mag",
"+",
"C",
"[",
"'a10'",
"]",
"*",
"np",
".",
"power",
"(",
"mag",
",",
"2",
... | (a8 + a9.*M + a10.*M.*M + a11.*M.*M.*M).*d(r) | [
"(",
"a8",
"+",
"a9",
".",
"*",
"M",
"+",
"a10",
".",
"*",
"M",
".",
"*",
"M",
"+",
"a11",
".",
"*",
"M",
".",
"*",
"M",
".",
"*",
"M",
")",
".",
"*",
"d",
"(",
"r",
")"
] | python | train |
zeroSteiner/AdvancedHTTPServer | advancedhttpserver.py | https://github.com/zeroSteiner/AdvancedHTTPServer/blob/8c53cf7e1ddbf7ae9f573c82c5fe5f6992db7b5a/advancedhttpserver.py#L1162-L1204 | def check_authorization(self):
"""
Check for the presence of a basic auth Authorization header and
if the credentials contained within in are valid.
:return: Whether or not the credentials are valid.
:rtype: bool
"""
try:
store = self.__config.get('basic_auth')
if store is None:
return True
... | [
"def",
"check_authorization",
"(",
"self",
")",
":",
"try",
":",
"store",
"=",
"self",
".",
"__config",
".",
"get",
"(",
"'basic_auth'",
")",
"if",
"store",
"is",
"None",
":",
"return",
"True",
"auth_info",
"=",
"self",
".",
"headers",
".",
"get",
"(",... | Check for the presence of a basic auth Authorization header and
if the credentials contained within in are valid.
:return: Whether or not the credentials are valid.
:rtype: bool | [
"Check",
"for",
"the",
"presence",
"of",
"a",
"basic",
"auth",
"Authorization",
"header",
"and",
"if",
"the",
"credentials",
"contained",
"within",
"in",
"are",
"valid",
"."
] | python | train |
marrow/WebCore | web/server/gevent_.py | https://github.com/marrow/WebCore/blob/38d50f8022ca62976a1e5ff23f7714bd647b6532/web/server/gevent_.py#L14-L18 | def serve(application, host='127.0.0.1', port=8080):
"""Gevent-based WSGI-HTTP server."""
# Instantiate the server with a host/port configuration and our application.
WSGIServer((host, int(port)), application).serve_forever() | [
"def",
"serve",
"(",
"application",
",",
"host",
"=",
"'127.0.0.1'",
",",
"port",
"=",
"8080",
")",
":",
"# Instantiate the server with a host/port configuration and our application.",
"WSGIServer",
"(",
"(",
"host",
",",
"int",
"(",
"port",
")",
")",
",",
"applic... | Gevent-based WSGI-HTTP server. | [
"Gevent",
"-",
"based",
"WSGI",
"-",
"HTTP",
"server",
"."
] | python | train |
klmitch/turnstile | turnstile/limits.py | https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/limits.py#L993-L1023 | def format(self, status, headers, environ, bucket, delay):
"""
Formats a response entity. Returns a tuple of the desired
status code and the formatted entity. The default status code
is passed in, as is a dictionary of headers.
:param status: The default status code. Should b... | [
"def",
"format",
"(",
"self",
",",
"status",
",",
"headers",
",",
"environ",
",",
"bucket",
",",
"delay",
")",
":",
"# This is a default response entity, which can be overridden",
"# by limit subclasses.",
"entity",
"=",
"(",
"\"This request was rate-limited. \"",
"\"Ple... | Formats a response entity. Returns a tuple of the desired
status code and the formatted entity. The default status code
is passed in, as is a dictionary of headers.
:param status: The default status code. Should be returned to
the caller, or an alternate selected. The... | [
"Formats",
"a",
"response",
"entity",
".",
"Returns",
"a",
"tuple",
"of",
"the",
"desired",
"status",
"code",
"and",
"the",
"formatted",
"entity",
".",
"The",
"default",
"status",
"code",
"is",
"passed",
"in",
"as",
"is",
"a",
"dictionary",
"of",
"headers"... | python | train |
mongodb/mongo-python-driver | pymongo/mongo_client.py | https://github.com/mongodb/mongo-python-driver/blob/c29c21449e3aae74154207058cf85fd94018d4cd/pymongo/mongo_client.py#L1879-L1895 | def database_names(self, session=None):
"""**DEPRECATED**: Get a list of the names of all databases on the
connected server.
:Parameters:
- `session` (optional): a
:class:`~pymongo.client_session.ClientSession`.
.. versionchanged:: 3.7
Deprecated. Use :... | [
"def",
"database_names",
"(",
"self",
",",
"session",
"=",
"None",
")",
":",
"warnings",
".",
"warn",
"(",
"\"database_names is deprecated. Use list_database_names \"",
"\"instead.\"",
",",
"DeprecationWarning",
",",
"stacklevel",
"=",
"2",
")",
"return",
"self",
".... | **DEPRECATED**: Get a list of the names of all databases on the
connected server.
:Parameters:
- `session` (optional): a
:class:`~pymongo.client_session.ClientSession`.
.. versionchanged:: 3.7
Deprecated. Use :meth:`list_database_names` instead.
.. ver... | [
"**",
"DEPRECATED",
"**",
":",
"Get",
"a",
"list",
"of",
"the",
"names",
"of",
"all",
"databases",
"on",
"the",
"connected",
"server",
"."
] | python | train |
mwouts/jupytext | jupytext/jupytext.py | https://github.com/mwouts/jupytext/blob/eb7d6aee889f80ad779cfc53441c648f0db9246d/jupytext/jupytext.py#L92-L178 | def writes(self, nb, metadata=None, **kwargs):
"""Return the text representation of the notebook"""
if self.fmt.get('format_name') == 'pandoc':
metadata = insert_jupytext_info_and_filter_metadata(metadata, self.ext, self.implementation)
cells = []
for cell in nb.cell... | [
"def",
"writes",
"(",
"self",
",",
"nb",
",",
"metadata",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"fmt",
".",
"get",
"(",
"'format_name'",
")",
"==",
"'pandoc'",
":",
"metadata",
"=",
"insert_jupytext_info_and_filter_metadata",
... | Return the text representation of the notebook | [
"Return",
"the",
"text",
"representation",
"of",
"the",
"notebook"
] | python | train |
hollenstein/maspy | maspy/core.py | https://github.com/hollenstein/maspy/blob/f15fcfd24df306d8420540460d902aa3073ec133/maspy/core.py#L53-L71 | def _getArrays(items, attr, defaultValue):
"""Return arrays with equal size of item attributes from a list of sorted
"items" for fast and convenient data processing.
:param attr: list of item attributes that should be added to the returned
array.
:param defaultValue: if an item is missing an at... | [
"def",
"_getArrays",
"(",
"items",
",",
"attr",
",",
"defaultValue",
")",
":",
"arrays",
"=",
"dict",
"(",
"[",
"(",
"key",
",",
"[",
"]",
")",
"for",
"key",
"in",
"attr",
"]",
")",
"for",
"item",
"in",
"items",
":",
"for",
"key",
"in",
"attr",
... | Return arrays with equal size of item attributes from a list of sorted
"items" for fast and convenient data processing.
:param attr: list of item attributes that should be added to the returned
array.
:param defaultValue: if an item is missing an attribute, the "defaultValue"
is added to th... | [
"Return",
"arrays",
"with",
"equal",
"size",
"of",
"item",
"attributes",
"from",
"a",
"list",
"of",
"sorted",
"items",
"for",
"fast",
"and",
"convenient",
"data",
"processing",
"."
] | python | train |
openearth/mmi-python | mmi/tracker.py | https://github.com/openearth/mmi-python/blob/a2f4ac96b1e7f2fa903f668b3e05c4e86ad42e8d/mmi/tracker.py#L165-L173 | def post(self):
"""Register a new model (models)"""
self.set_header("Content-Type", "application/json")
key = uuid.uuid4().hex
metadata = json.loads(self.request.body.decode())
metadata["uuid"] = key
self.database[key] = metadata
result = json.dumps({"uuid": key})... | [
"def",
"post",
"(",
"self",
")",
":",
"self",
".",
"set_header",
"(",
"\"Content-Type\"",
",",
"\"application/json\"",
")",
"key",
"=",
"uuid",
".",
"uuid4",
"(",
")",
".",
"hex",
"metadata",
"=",
"json",
".",
"loads",
"(",
"self",
".",
"request",
".",... | Register a new model (models) | [
"Register",
"a",
"new",
"model",
"(",
"models",
")"
] | python | train |
inveniosoftware-contrib/invenio-classifier | invenio_classifier/reader.py | https://github.com/inveniosoftware-contrib/invenio-classifier/blob/3c758cf34dca6bf0548e7da5de34e5f72e3b255e/invenio_classifier/reader.py#L58-L91 | def get_cache(taxonomy_id):
"""Return cache for the given taxonomy id.
:param taxonomy_id: identifier of the taxonomy
:type taxonomy_id: str
:return: dictionary object (empty if no taxonomy_id
is found), you must not change anything inside it.
Create a new dictionary and use set_cache ... | [
"def",
"get_cache",
"(",
"taxonomy_id",
")",
":",
"if",
"taxonomy_id",
"in",
"_CACHE",
":",
"ctime",
",",
"taxonomy",
"=",
"_CACHE",
"[",
"taxonomy_id",
"]",
"# check it is fresh version",
"onto_name",
",",
"onto_path",
",",
"onto_url",
"=",
"_get_ontology",
"("... | Return cache for the given taxonomy id.
:param taxonomy_id: identifier of the taxonomy
:type taxonomy_id: str
:return: dictionary object (empty if no taxonomy_id
is found), you must not change anything inside it.
Create a new dictionary and use set_cache if you want
to update the c... | [
"Return",
"cache",
"for",
"the",
"given",
"taxonomy",
"id",
"."
] | python | train |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Executor.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Executor.py#L448-L469 | def get_contents(self):
"""Fetch the signature contents. This is the main reason this
class exists, so we can compute this once and cache it regardless
of how many target or source Nodes there are.
"""
try:
return self._memo['get_contents']
except KeyError:
... | [
"def",
"get_contents",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"_memo",
"[",
"'get_contents'",
"]",
"except",
"KeyError",
":",
"pass",
"env",
"=",
"self",
".",
"get_build_env",
"(",
")",
"action_list",
"=",
"self",
".",
"get_action_list",... | Fetch the signature contents. This is the main reason this
class exists, so we can compute this once and cache it regardless
of how many target or source Nodes there are. | [
"Fetch",
"the",
"signature",
"contents",
".",
"This",
"is",
"the",
"main",
"reason",
"this",
"class",
"exists",
"so",
"we",
"can",
"compute",
"this",
"once",
"and",
"cache",
"it",
"regardless",
"of",
"how",
"many",
"target",
"or",
"source",
"Nodes",
"there... | python | train |
smarter-travel-media/stac | stac/http.py | https://github.com/smarter-travel-media/stac/blob/cdb29a17ede0924b122b3905a500442c62ae53b7/stac/http.py#L69-L102 | def get_most_recent_versions(self, group, artifact, limit, remote=False, integration=False):
"""Get a list of the version numbers of the most recent artifacts (integration
or non-integration), ordered by the version number, for a particular group and
artifact combination.
:param str gro... | [
"def",
"get_most_recent_versions",
"(",
"self",
",",
"group",
",",
"artifact",
",",
"limit",
",",
"remote",
"=",
"False",
",",
"integration",
"=",
"False",
")",
":",
"if",
"limit",
"<",
"1",
":",
"raise",
"ValueError",
"(",
"\"Releases limit must be positive\"... | Get a list of the version numbers of the most recent artifacts (integration
or non-integration), ordered by the version number, for a particular group and
artifact combination.
:param str group: Group of the artifact to get versions of
:param str artifact: Name of the artifact to get ve... | [
"Get",
"a",
"list",
"of",
"the",
"version",
"numbers",
"of",
"the",
"most",
"recent",
"artifacts",
"(",
"integration",
"or",
"non",
"-",
"integration",
")",
"ordered",
"by",
"the",
"version",
"number",
"for",
"a",
"particular",
"group",
"and",
"artifact",
... | python | train |
DistrictDataLabs/yellowbrick | yellowbrick/contrib/missing/dispersion.py | https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/contrib/missing/dispersion.py#L132-L146 | def draw_multi_dispersion_chart(self, nan_locs):
"""Draws a multi dimensional dispersion chart, each color corresponds
to a different target variable.
"""
for index, nan_values in enumerate(nan_locs):
label, nan_locations = nan_values
# if features passed in then... | [
"def",
"draw_multi_dispersion_chart",
"(",
"self",
",",
"nan_locs",
")",
":",
"for",
"index",
",",
"nan_values",
"in",
"enumerate",
"(",
"nan_locs",
")",
":",
"label",
",",
"nan_locations",
"=",
"nan_values",
"# if features passed in then, label as such",
"if",
"sel... | Draws a multi dimensional dispersion chart, each color corresponds
to a different target variable. | [
"Draws",
"a",
"multi",
"dimensional",
"dispersion",
"chart",
"each",
"color",
"corresponds",
"to",
"a",
"different",
"target",
"variable",
"."
] | python | train |
MonashBI/arcana | arcana/repository/xnat.py | https://github.com/MonashBI/arcana/blob/d6271a29d13733d00422d11417af8d200be62acc/arcana/repository/xnat.py#L727-L758 | def _get_labels(self, frequency, subject_id=None, visit_id=None):
"""
Returns the labels for the XNAT subject and sessions given
the frequency and provided IDs.
"""
if frequency == 'per_session':
subj_label = '{}_{}'.format(self.project_id,
... | [
"def",
"_get_labels",
"(",
"self",
",",
"frequency",
",",
"subject_id",
"=",
"None",
",",
"visit_id",
"=",
"None",
")",
":",
"if",
"frequency",
"==",
"'per_session'",
":",
"subj_label",
"=",
"'{}_{}'",
".",
"format",
"(",
"self",
".",
"project_id",
",",
... | Returns the labels for the XNAT subject and sessions given
the frequency and provided IDs. | [
"Returns",
"the",
"labels",
"for",
"the",
"XNAT",
"subject",
"and",
"sessions",
"given",
"the",
"frequency",
"and",
"provided",
"IDs",
"."
] | python | train |
PyCQA/astroid | astroid/inference.py | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/inference.py#L526-L531 | def infer_unaryop(self, context=None):
"""Infer what an UnaryOp should return when evaluated."""
yield from _filter_operation_errors(
self, _infer_unaryop, context, util.BadUnaryOperationMessage
)
return dict(node=self, context=context) | [
"def",
"infer_unaryop",
"(",
"self",
",",
"context",
"=",
"None",
")",
":",
"yield",
"from",
"_filter_operation_errors",
"(",
"self",
",",
"_infer_unaryop",
",",
"context",
",",
"util",
".",
"BadUnaryOperationMessage",
")",
"return",
"dict",
"(",
"node",
"=",
... | Infer what an UnaryOp should return when evaluated. | [
"Infer",
"what",
"an",
"UnaryOp",
"should",
"return",
"when",
"evaluated",
"."
] | python | train |
ronaldguillen/wave | wave/fields.py | https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/fields.py#L547-L554 | def root(self):
"""
Returns the top-level serializer for this field.
"""
root = self
while root.parent is not None:
root = root.parent
return root | [
"def",
"root",
"(",
"self",
")",
":",
"root",
"=",
"self",
"while",
"root",
".",
"parent",
"is",
"not",
"None",
":",
"root",
"=",
"root",
".",
"parent",
"return",
"root"
] | Returns the top-level serializer for this field. | [
"Returns",
"the",
"top",
"-",
"level",
"serializer",
"for",
"this",
"field",
"."
] | python | train |
richardchien/nonebot | nonebot/command/__init__.py | https://github.com/richardchien/nonebot/blob/13ed9e4e87d9824b61592520aabda6d2737c8848/nonebot/command/__init__.py#L671-L680 | def kill_current_session(ctx: Context_T) -> None:
"""
Force kill current session of the given context,
despite whether it is running or not.
:param ctx: message context
"""
ctx_id = context_id(ctx)
if ctx_id in _sessions:
del _sessions[ctx_id] | [
"def",
"kill_current_session",
"(",
"ctx",
":",
"Context_T",
")",
"->",
"None",
":",
"ctx_id",
"=",
"context_id",
"(",
"ctx",
")",
"if",
"ctx_id",
"in",
"_sessions",
":",
"del",
"_sessions",
"[",
"ctx_id",
"]"
] | Force kill current session of the given context,
despite whether it is running or not.
:param ctx: message context | [
"Force",
"kill",
"current",
"session",
"of",
"the",
"given",
"context",
"despite",
"whether",
"it",
"is",
"running",
"or",
"not",
"."
] | python | train |
pyQode/pyqode.core | pyqode/core/panels/checker.py | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/panels/checker.py#L34-L48 | def marker_for_line(self, line):
"""
Returns the marker that is displayed at the specified line number if
any.
:param line: The marker line.
:return: Marker of None
:rtype: pyqode.core.Marker
"""
block = self.editor.document().findBlockByNumber(line)
... | [
"def",
"marker_for_line",
"(",
"self",
",",
"line",
")",
":",
"block",
"=",
"self",
".",
"editor",
".",
"document",
"(",
")",
".",
"findBlockByNumber",
"(",
"line",
")",
"try",
":",
"return",
"block",
".",
"userData",
"(",
")",
".",
"messages",
"except... | Returns the marker that is displayed at the specified line number if
any.
:param line: The marker line.
:return: Marker of None
:rtype: pyqode.core.Marker | [
"Returns",
"the",
"marker",
"that",
"is",
"displayed",
"at",
"the",
"specified",
"line",
"number",
"if",
"any",
"."
] | python | train |
spyder-ide/spyder | spyder/plugins/ipythonconsole/plugin.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/plugin.py#L1129-L1143 | def tunnel_to_kernel(self, connection_info, hostname, sshkey=None,
password=None, timeout=10):
"""
Tunnel connections to a kernel via ssh.
Remote ports are specified in the connection info ci.
"""
lports = zmqtunnel.select_random_ports(4)
... | [
"def",
"tunnel_to_kernel",
"(",
"self",
",",
"connection_info",
",",
"hostname",
",",
"sshkey",
"=",
"None",
",",
"password",
"=",
"None",
",",
"timeout",
"=",
"10",
")",
":",
"lports",
"=",
"zmqtunnel",
".",
"select_random_ports",
"(",
"4",
")",
"rports",... | Tunnel connections to a kernel via ssh.
Remote ports are specified in the connection info ci. | [
"Tunnel",
"connections",
"to",
"a",
"kernel",
"via",
"ssh",
".",
"Remote",
"ports",
"are",
"specified",
"in",
"the",
"connection",
"info",
"ci",
"."
] | python | train |
vmalloc/dessert | dessert/rewrite.py | https://github.com/vmalloc/dessert/blob/fa86b39da4853f2c35f0686942db777c7cc57728/dessert/rewrite.py#L371-L387 | def _saferepr(obj):
"""Get a safe repr of an object for assertion error messages.
The assertion formatting (util.format_explanation()) requires
newlines to be escaped since they are a special character for it.
Normally assertion.util.format_explanation() does this but for a
custom repr it is possib... | [
"def",
"_saferepr",
"(",
"obj",
")",
":",
"repr",
"=",
"py",
".",
"io",
".",
"saferepr",
"(",
"obj",
")",
"if",
"py",
".",
"builtin",
".",
"_istext",
"(",
"repr",
")",
":",
"t",
"=",
"py",
".",
"builtin",
".",
"text",
"else",
":",
"t",
"=",
"... | Get a safe repr of an object for assertion error messages.
The assertion formatting (util.format_explanation()) requires
newlines to be escaped since they are a special character for it.
Normally assertion.util.format_explanation() does this but for a
custom repr it is possible to contain one of the sp... | [
"Get",
"a",
"safe",
"repr",
"of",
"an",
"object",
"for",
"assertion",
"error",
"messages",
"."
] | python | train |
tapanpandita/pocket | pocket.py | https://github.com/tapanpandita/pocket/blob/5a144438cc89bfc0ec94db960718ccf1f76468c1/pocket.py#L190-L198 | def bulk_add(
self, item_id, ref_id=None, tags=None, time=None, title=None,
url=None, wait=True
):
'''
Add a new item to the user's list
http://getpocket.com/developer/docs/v3/modify#action_add
''' | [
"def",
"bulk_add",
"(",
"self",
",",
"item_id",
",",
"ref_id",
"=",
"None",
",",
"tags",
"=",
"None",
",",
"time",
"=",
"None",
",",
"title",
"=",
"None",
",",
"url",
"=",
"None",
",",
"wait",
"=",
"True",
")",
":"
] | Add a new item to the user's list
http://getpocket.com/developer/docs/v3/modify#action_add | [
"Add",
"a",
"new",
"item",
"to",
"the",
"user",
"s",
"list",
"http",
":",
"//",
"getpocket",
".",
"com",
"/",
"developer",
"/",
"docs",
"/",
"v3",
"/",
"modify#action_add"
] | python | train |
evonove/django-stored-messages | stored_messages/backends/redis/backend.py | https://github.com/evonove/django-stored-messages/blob/23b71f952d5d3fd03285f5e700879d05796ef7ba/stored_messages/backends/redis/backend.py#L48-L55 | def _list_key(self, key):
"""
boilerplate
"""
ret = []
for msg_json in self.client.lrange(key, 0, -1):
ret.append(self._fromJSON(msg_json))
return ret | [
"def",
"_list_key",
"(",
"self",
",",
"key",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"msg_json",
"in",
"self",
".",
"client",
".",
"lrange",
"(",
"key",
",",
"0",
",",
"-",
"1",
")",
":",
"ret",
".",
"append",
"(",
"self",
".",
"_fromJSON",
"(",... | boilerplate | [
"boilerplate"
] | python | valid |
tensorflow/datasets | tensorflow_datasets/scripts/create_new_dataset.py | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/scripts/create_new_dataset.py#L155-L164 | def create_dataset_file(root_dir, data):
"""Create a new dataset from a template."""
file_path = os.path.join(root_dir, '{dataset_type}', '{dataset_name}.py')
context = (
_HEADER + _DATASET_DEFAULT_IMPORTS + _CITATION
+ _DESCRIPTION + _DATASET_DEFAULTS
)
with gfile.GFile(file_path.format(**data),... | [
"def",
"create_dataset_file",
"(",
"root_dir",
",",
"data",
")",
":",
"file_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"root_dir",
",",
"'{dataset_type}'",
",",
"'{dataset_name}.py'",
")",
"context",
"=",
"(",
"_HEADER",
"+",
"_DATASET_DEFAULT_IMPORTS",
... | Create a new dataset from a template. | [
"Create",
"a",
"new",
"dataset",
"from",
"a",
"template",
"."
] | python | train |
scnerd/miniutils | miniutils/timing.py | https://github.com/scnerd/miniutils/blob/fe927e26afc5877416dead28dabdf6604387f42c/miniutils/timing.py#L29-L63 | def tic(log_level='DEBUG', fmt="{file}:{line} - {message} - {diff:0.6f}s (total={total:0.1f}s)", verbose=True):
"""A minimalistic ``printf``-type timing utility. Call this function to start timing individual sections of code
:param log_level: The level at which to log block run times
:param fmt: The format... | [
"def",
"tic",
"(",
"log_level",
"=",
"'DEBUG'",
",",
"fmt",
"=",
"\"{file}:{line} - {message} - {diff:0.6f}s (total={total:0.1f}s)\"",
",",
"verbose",
"=",
"True",
")",
":",
"first_time",
"=",
"last_time",
"=",
"time",
"(",
")",
"def",
"toc",
"(",
"message",
"="... | A minimalistic ``printf``-type timing utility. Call this function to start timing individual sections of code
:param log_level: The level at which to log block run times
:param fmt: The format string to use when logging times. Available arguments include:
- file, line, func, code_text: The sta... | [
"A",
"minimalistic",
"printf",
"-",
"type",
"timing",
"utility",
".",
"Call",
"this",
"function",
"to",
"start",
"timing",
"individual",
"sections",
"of",
"code"
] | python | train |
sprockets/sprockets.http | examples.py | https://github.com/sprockets/sprockets.http/blob/8baa4cdc1fa35a162ee226fd6cc4170a0ca0ecd3/examples.py#L10-L27 | def get(self, status_code):
"""
Returns the requested status.
:param int status_code: the status code to return
:queryparam str reason: optional reason phrase
"""
status_code = int(status_code)
if status_code >= 400:
kwargs = {'status_code': status_c... | [
"def",
"get",
"(",
"self",
",",
"status_code",
")",
":",
"status_code",
"=",
"int",
"(",
"status_code",
")",
"if",
"status_code",
">=",
"400",
":",
"kwargs",
"=",
"{",
"'status_code'",
":",
"status_code",
"}",
"if",
"self",
".",
"get_query_argument",
"(",
... | Returns the requested status.
:param int status_code: the status code to return
:queryparam str reason: optional reason phrase | [
"Returns",
"the",
"requested",
"status",
"."
] | python | train |
faide/py3o.template | py3o/template/main.py | https://github.com/faide/py3o.template/blob/1ae8435ab8ba9f469a3e8d1156e7f24271c77c0e/py3o/template/main.py#L49-L66 | def detect_keep_boundary(start, end, namespaces):
"""a helper to inspect a link and see if we should keep the link boundary
"""
result_start, result_end = False, False
parent_start = start.getparent()
parent_end = end.getparent()
if parent_start.tag == "{%s}p" % namespaces['text']:
# mo... | [
"def",
"detect_keep_boundary",
"(",
"start",
",",
"end",
",",
"namespaces",
")",
":",
"result_start",
",",
"result_end",
"=",
"False",
",",
"False",
"parent_start",
"=",
"start",
".",
"getparent",
"(",
")",
"parent_end",
"=",
"end",
".",
"getparent",
"(",
... | a helper to inspect a link and see if we should keep the link boundary | [
"a",
"helper",
"to",
"inspect",
"a",
"link",
"and",
"see",
"if",
"we",
"should",
"keep",
"the",
"link",
"boundary"
] | python | train |
mlperf/training | translation/tensorflow/transformer/utils/tokenizer.py | https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/utils/tokenizer.py#L574-L616 | def _generate_subtokens(
token_counts, alphabet, min_count, num_iterations=4,
reserved_tokens=None):
"""Create a list of subtokens in decreasing order of frequency.
Args:
token_counts: dict mapping str tokens -> int count
alphabet: set of characters
min_count: int minimum number of times a subt... | [
"def",
"_generate_subtokens",
"(",
"token_counts",
",",
"alphabet",
",",
"min_count",
",",
"num_iterations",
"=",
"4",
",",
"reserved_tokens",
"=",
"None",
")",
":",
"if",
"reserved_tokens",
"is",
"None",
":",
"reserved_tokens",
"=",
"RESERVED_TOKENS",
"# Use alph... | Create a list of subtokens in decreasing order of frequency.
Args:
token_counts: dict mapping str tokens -> int count
alphabet: set of characters
min_count: int minimum number of times a subtoken must appear before it is
added to the vocabulary.
num_iterations: int number of iterations to gener... | [
"Create",
"a",
"list",
"of",
"subtokens",
"in",
"decreasing",
"order",
"of",
"frequency",
"."
] | python | train |
ElevenPaths/AtomShields | atomshields/scanner.py | https://github.com/ElevenPaths/AtomShields/blob/e75f25393b4a7a315ec96bf9b8e654cb2200866a/atomshields/scanner.py#L294-L309 | def _addConfig(instance, config, parent_section):
"""
Writes a section for a plugin.
Args:
instance (object): Class instance for plugin
config (object): Object (ConfigParser) which the current config
parent_section (str): Parent section for plugin. Usually 'checkers' or 'reports'
"""
try:
section... | [
"def",
"_addConfig",
"(",
"instance",
",",
"config",
",",
"parent_section",
")",
":",
"try",
":",
"section_name",
"=",
"\"{p}/{n}\"",
".",
"format",
"(",
"p",
"=",
"parent_section",
",",
"n",
"=",
"instance",
".",
"NAME",
".",
"lower",
"(",
")",
")",
"... | Writes a section for a plugin.
Args:
instance (object): Class instance for plugin
config (object): Object (ConfigParser) which the current config
parent_section (str): Parent section for plugin. Usually 'checkers' or 'reports' | [
"Writes",
"a",
"section",
"for",
"a",
"plugin",
"."
] | python | valid |
tomi77/django-extra-tools | django_extra_tools/db/__init__.py | https://github.com/tomi77/django-extra-tools/blob/fb6d226bc5cf3fc0eb8abe61a512c3f5c7dcc8a8/django_extra_tools/db/__init__.py#L12-L26 | def pg_version(using=None):
"""
Return tuple with PostgreSQL version of a specific connection
:type using: str
:param using: Connection name
:rtype: tuple
:return: PostgreSQL version
"""
connection = get_connection(using)
cursor = connection.cursor()
cursor.execute('SHOW server_... | [
"def",
"pg_version",
"(",
"using",
"=",
"None",
")",
":",
"connection",
"=",
"get_connection",
"(",
"using",
")",
"cursor",
"=",
"connection",
".",
"cursor",
"(",
")",
"cursor",
".",
"execute",
"(",
"'SHOW server_version'",
")",
"row",
"=",
"cursor",
".",
... | Return tuple with PostgreSQL version of a specific connection
:type using: str
:param using: Connection name
:rtype: tuple
:return: PostgreSQL version | [
"Return",
"tuple",
"with",
"PostgreSQL",
"version",
"of",
"a",
"specific",
"connection",
":",
"type",
"using",
":",
"str",
":",
"param",
"using",
":",
"Connection",
"name",
":",
"rtype",
":",
"tuple",
":",
"return",
":",
"PostgreSQL",
"version"
] | python | train |
ioam/lancet | lancet/core.py | https://github.com/ioam/lancet/blob/1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e/lancet/core.py#L812-L840 | def _decompose_pattern(self, pattern):
"""
Given a path pattern with format declaration, generates a
four-tuple (glob_pattern, regexp pattern, fields, type map)
"""
sep = '~lancet~sep~'
float_codes = ['e','E','f', 'F','g', 'G', 'n']
typecodes = dict([(k,float) for... | [
"def",
"_decompose_pattern",
"(",
"self",
",",
"pattern",
")",
":",
"sep",
"=",
"'~lancet~sep~'",
"float_codes",
"=",
"[",
"'e'",
",",
"'E'",
",",
"'f'",
",",
"'F'",
",",
"'g'",
",",
"'G'",
",",
"'n'",
"]",
"typecodes",
"=",
"dict",
"(",
"[",
"(",
... | Given a path pattern with format declaration, generates a
four-tuple (glob_pattern, regexp pattern, fields, type map) | [
"Given",
"a",
"path",
"pattern",
"with",
"format",
"declaration",
"generates",
"a",
"four",
"-",
"tuple",
"(",
"glob_pattern",
"regexp",
"pattern",
"fields",
"type",
"map",
")"
] | python | valid |
sethmlarson/virtualbox-python | virtualbox/library.py | https://github.com/sethmlarson/virtualbox-python/blob/706c8e3f6e3aee17eb06458e73cbb4bc2d37878b/virtualbox/library.py#L20926-L20950 | def seek(self, offset, whence):
"""Changes the current file position of this file.
The file current position always applies to the :py:func:`IFile.read`
method. Same for the :py:func:`IFile.write` method it except when
the :py:func:`IFile.access_mode` is :py:attr:`FileAccess... | [
"def",
"seek",
"(",
"self",
",",
"offset",
",",
"whence",
")",
":",
"if",
"not",
"isinstance",
"(",
"offset",
",",
"baseinteger",
")",
":",
"raise",
"TypeError",
"(",
"\"offset can only be an instance of type baseinteger\"",
")",
"if",
"not",
"isinstance",
"(",
... | Changes the current file position of this file.
The file current position always applies to the :py:func:`IFile.read`
method. Same for the :py:func:`IFile.write` method it except when
the :py:func:`IFile.access_mode` is :py:attr:`FileAccessMode.append_only`
or :py:attr:`Fil... | [
"Changes",
"the",
"current",
"file",
"position",
"of",
"this",
"file",
".",
"The",
"file",
"current",
"position",
"always",
"applies",
"to",
"the",
":",
"py",
":",
"func",
":",
"IFile",
".",
"read",
"method",
".",
"Same",
"for",
"the",
":",
"py",
":",
... | python | train |
Pytwitcher/pytwitcherapi | src/pytwitcherapi/chat/client.py | https://github.com/Pytwitcher/pytwitcherapi/blob/d53ac5ad5ca113ecb7da542e8cdcbbf8c762b336/src/pytwitcherapi/chat/client.py#L68-L77 | def shutdown(self):
"""Disconnect all connections and end the loop
:returns: None
:rtype: None
:raises: None
"""
log.debug('Shutting down %s' % self)
self.disconnect_all()
self._looping.clear() | [
"def",
"shutdown",
"(",
"self",
")",
":",
"log",
".",
"debug",
"(",
"'Shutting down %s'",
"%",
"self",
")",
"self",
".",
"disconnect_all",
"(",
")",
"self",
".",
"_looping",
".",
"clear",
"(",
")"
] | Disconnect all connections and end the loop
:returns: None
:rtype: None
:raises: None | [
"Disconnect",
"all",
"connections",
"and",
"end",
"the",
"loop"
] | python | train |
tutorcruncher/pydf | pydf/wkhtmltopdf.py | https://github.com/tutorcruncher/pydf/blob/53dd030f02f112593ed6e2655160a40b892a23c0/pydf/wkhtmltopdf.py#L160-L171 | def get_version():
"""
Get version of pydf and wkhtmltopdf binary
:return: version string
"""
try:
wk_version = _string_execute('-V')
except Exception as e:
# we catch all errors here to make sure we get a version no matter what
wk_version = '%s: %s' % (e.__class__.__nam... | [
"def",
"get_version",
"(",
")",
":",
"try",
":",
"wk_version",
"=",
"_string_execute",
"(",
"'-V'",
")",
"except",
"Exception",
"as",
"e",
":",
"# we catch all errors here to make sure we get a version no matter what",
"wk_version",
"=",
"'%s: %s'",
"%",
"(",
"e",
"... | Get version of pydf and wkhtmltopdf binary
:return: version string | [
"Get",
"version",
"of",
"pydf",
"and",
"wkhtmltopdf",
"binary"
] | python | train |
Erotemic/utool | utool/util_alg.py | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_alg.py#L1365-L1382 | def number_of_decimals(num):
r"""
Args:
num (float):
References:
stackoverflow.com/questions/6189956/finding-decimal-places
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_alg import * # NOQA
>>> num = 15.05
>>> result = number_of_decimals(num)
... | [
"def",
"number_of_decimals",
"(",
"num",
")",
":",
"exp",
"=",
"decimal",
".",
"Decimal",
"(",
"str",
"(",
"num",
")",
")",
".",
"as_tuple",
"(",
")",
".",
"exponent",
"return",
"max",
"(",
"0",
",",
"-",
"exp",
")"
] | r"""
Args:
num (float):
References:
stackoverflow.com/questions/6189956/finding-decimal-places
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_alg import * # NOQA
>>> num = 15.05
>>> result = number_of_decimals(num)
>>> print(result)
2 | [
"r",
"Args",
":",
"num",
"(",
"float",
")",
":"
] | python | train |
pachyderm/python-pachyderm | src/python_pachyderm/pfs_client.py | https://github.com/pachyderm/python-pachyderm/blob/1c58cf91d30e03716a4f45213989e890f7b8a78c/src/python_pachyderm/pfs_client.py#L434-L444 | def inspect_file(self, commit, path):
"""
Returns info about a specific file.
Params:
* commit: A tuple, string, or Commit object representing the commit.
* path: Path to file.
"""
req = proto.InspectFileRequest(file=proto.File(commit=commit_from(commit), path=pa... | [
"def",
"inspect_file",
"(",
"self",
",",
"commit",
",",
"path",
")",
":",
"req",
"=",
"proto",
".",
"InspectFileRequest",
"(",
"file",
"=",
"proto",
".",
"File",
"(",
"commit",
"=",
"commit_from",
"(",
"commit",
")",
",",
"path",
"=",
"path",
")",
")... | Returns info about a specific file.
Params:
* commit: A tuple, string, or Commit object representing the commit.
* path: Path to file. | [
"Returns",
"info",
"about",
"a",
"specific",
"file",
"."
] | python | train |
WebarchivCZ/WA-KAT | src/wa_kat/templates/static/js/Lib/site-packages/components/conspect_handler.py | https://github.com/WebarchivCZ/WA-KAT/blob/16d064a3a775dc1d2713debda7847ded52dd2a06/src/wa_kat/templates/static/js/Lib/site-packages/components/conspect_handler.py#L227-L237 | def init(cls):
"""
Bind elements to callbacks.
"""
for el in cls.switcher_els:
el.checked = False
cls.bind_switcher()
cls._draw_conspects()
cls._create_searchable_typeahead() | [
"def",
"init",
"(",
"cls",
")",
":",
"for",
"el",
"in",
"cls",
".",
"switcher_els",
":",
"el",
".",
"checked",
"=",
"False",
"cls",
".",
"bind_switcher",
"(",
")",
"cls",
".",
"_draw_conspects",
"(",
")",
"cls",
".",
"_create_searchable_typeahead",
"(",
... | Bind elements to callbacks. | [
"Bind",
"elements",
"to",
"callbacks",
"."
] | python | train |
maweigert/gputools | gputools/transforms/transformations.py | https://github.com/maweigert/gputools/blob/6ab26efeb05dceef74cf13aadeeeb9b009b529dd/gputools/transforms/transformations.py#L88-L125 | def shift(data, shift=(0, 0, 0), mode="constant", interpolation="linear"):
"""
translates 3d data by given amount
Parameters
----------
data: ndarray
3d array
shift : float or sequence
The shift along the axes. If a float, `shift` is the same for each axis.
If a ... | [
"def",
"shift",
"(",
"data",
",",
"shift",
"=",
"(",
"0",
",",
"0",
",",
"0",
")",
",",
"mode",
"=",
"\"constant\"",
",",
"interpolation",
"=",
"\"linear\"",
")",
":",
"if",
"np",
".",
"isscalar",
"(",
"shift",
")",
":",
"shift",
"=",
"(",
"shift... | translates 3d data by given amount
Parameters
----------
data: ndarray
3d array
shift : float or sequence
The shift along the axes. If a float, `shift` is the same for each axis.
If a sequence, `shift` should contain one value for each axis.
mode: string
... | [
"translates",
"3d",
"data",
"by",
"given",
"amount",
"Parameters",
"----------",
"data",
":",
"ndarray",
"3d",
"array",
"shift",
":",
"float",
"or",
"sequence",
"The",
"shift",
"along",
"the",
"axes",
".",
"If",
"a",
"float",
"shift",
"is",
"the",
"same",
... | python | train |
lepture/otpauth | otpauth.py | https://github.com/lepture/otpauth/blob/49914d83d36dbcd33c9e26f65002b21ce09a6303/otpauth.py#L105-L131 | def to_uri(self, type, label, issuer, counter=None):
"""Generate the otpauth protocal string.
:param type: Algorithm type, hotp or totp.
:param label: Label of the identifier.
:param issuer: The company, the organization or something else.
:param counter: Counter of the HOTP alg... | [
"def",
"to_uri",
"(",
"self",
",",
"type",
",",
"label",
",",
"issuer",
",",
"counter",
"=",
"None",
")",
":",
"type",
"=",
"type",
".",
"lower",
"(",
")",
"if",
"type",
"not",
"in",
"(",
"'hotp'",
",",
"'totp'",
")",
":",
"raise",
"ValueError",
... | Generate the otpauth protocal string.
:param type: Algorithm type, hotp or totp.
:param label: Label of the identifier.
:param issuer: The company, the organization or something else.
:param counter: Counter of the HOTP algorithm. | [
"Generate",
"the",
"otpauth",
"protocal",
"string",
"."
] | python | train |
Neurita/boyle | boyle/nifti/sets.py | https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/nifti/sets.py#L274-L317 | def to_file(self, output_file, smooth_fwhm=0, outdtype=None):
"""Save the Numpy array created from to_matrix function to the output_file.
Will save into the file: outmat, mask_indices, vol_shape and self.others (put here whatever you want)
data: Numpy array with shape N x prod(vol.shape)
... | [
"def",
"to_file",
"(",
"self",
",",
"output_file",
",",
"smooth_fwhm",
"=",
"0",
",",
"outdtype",
"=",
"None",
")",
":",
"outmat",
",",
"mask_indices",
",",
"mask_shape",
"=",
"self",
".",
"to_matrix",
"(",
"smooth_fwhm",
",",
"outdtype",
")",
"exporter",
... | Save the Numpy array created from to_matrix function to the output_file.
Will save into the file: outmat, mask_indices, vol_shape and self.others (put here whatever you want)
data: Numpy array with shape N x prod(vol.shape)
containing the N files as flat vectors.
mas... | [
"Save",
"the",
"Numpy",
"array",
"created",
"from",
"to_matrix",
"function",
"to",
"the",
"output_file",
"."
] | python | valid |
noahbenson/neuropythy | neuropythy/util/core.py | https://github.com/noahbenson/neuropythy/blob/b588889f6db36ddb9602ae4a72c1c0d3f41586b2/neuropythy/util/core.py#L275-L295 | def to_dataframe(d, **kw):
'''
to_dataframe(d) attempts to coerce the object d to a pandas DataFrame object. If d is a
tuple of 2 items whose second argument is a dictionary, then the dictionary will be taken
as arguments for the dataframe constructor. These arguments may alternately be given as
... | [
"def",
"to_dataframe",
"(",
"d",
",",
"*",
"*",
"kw",
")",
":",
"import",
"pandas",
"if",
"pimms",
".",
"is_itable",
"(",
"d",
")",
":",
"d",
"=",
"d",
".",
"dataframe",
"if",
"is_dataframe",
"(",
"d",
")",
":",
"return",
"d",
"if",
"len",
"(",
... | to_dataframe(d) attempts to coerce the object d to a pandas DataFrame object. If d is a
tuple of 2 items whose second argument is a dictionary, then the dictionary will be taken
as arguments for the dataframe constructor. These arguments may alternately be given as
standard keyword arguments. | [
"to_dataframe",
"(",
"d",
")",
"attempts",
"to",
"coerce",
"the",
"object",
"d",
"to",
"a",
"pandas",
"DataFrame",
"object",
".",
"If",
"d",
"is",
"a",
"tuple",
"of",
"2",
"items",
"whose",
"second",
"argument",
"is",
"a",
"dictionary",
"then",
"the",
... | python | train |
lambdamusic/Ontospy | ontospy/extras/hacks/matcher.py | https://github.com/lambdamusic/Ontospy/blob/eb46cb13792b2b87f21babdf976996318eec7571/ontospy/extras/hacks/matcher.py#L156-L210 | def main():
""" command line script """
print("Ontospy " + ontospy.VERSION)
ontospy.get_or_create_home_repo()
opts, args = parse_options()
if len(args) < 2:
printDebug("Please provide two arguments, or use -h for more options.")
sys.exit(0)
var = input("Match classes or properties? [c|p, c=default]:")
if... | [
"def",
"main",
"(",
")",
":",
"print",
"(",
"\"Ontospy \"",
"+",
"ontospy",
".",
"VERSION",
")",
"ontospy",
".",
"get_or_create_home_repo",
"(",
")",
"opts",
",",
"args",
"=",
"parse_options",
"(",
")",
"if",
"len",
"(",
"args",
")",
"<",
"2",
":",
"... | command line script | [
"command",
"line",
"script"
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.