Search is not available for this dataset
identifier stringlengths 1 155 | parameters stringlengths 2 6.09k | docstring stringlengths 11 63.4k | docstring_summary stringlengths 0 63.4k | function stringlengths 29 99.8k | function_tokens list | start_point list | end_point list | language stringclasses 1
value | docstring_language stringlengths 2 7 | docstring_language_predictions stringlengths 18 23 | is_langid_reliable stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|---|---|---|
get_base_payload | (user_profile: UserProfile) | Common fields for all notification payloads. | Common fields for all notification payloads. | def get_base_payload(user_profile: UserProfile) -> Dict[str, Any]:
"""Common fields for all notification payloads."""
data: Dict[str, Any] = {}
# These will let the app support logging into multiple realms and servers.
data["server"] = settings.EXTERNAL_HOST
data["realm_id"] = user_profile.realm.id... | [
"def",
"get_base_payload",
"(",
"user_profile",
":",
"UserProfile",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"data",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
"=",
"{",
"}",
"# These will let the app support logging into multiple realms and servers.",
... | [
648,
0
] | [
658,
15
] | python | en | ['en', 'en', 'en'] | True |
get_message_payload | (user_profile: UserProfile, message: Message) | Common fields for `message` payloads, for all platforms. | Common fields for `message` payloads, for all platforms. | def get_message_payload(user_profile: UserProfile, message: Message) -> Dict[str, Any]:
"""Common fields for `message` payloads, for all platforms."""
data = get_base_payload(user_profile)
# `sender_id` is preferred, but some existing versions use `sender_email`.
data["sender_id"] = message.sender.id
... | [
"def",
"get_message_payload",
"(",
"user_profile",
":",
"UserProfile",
",",
"message",
":",
"Message",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"data",
"=",
"get_base_payload",
"(",
"user_profile",
")",
"# `sender_id` is preferred, but some existing vers... | [
661,
0
] | [
679,
15
] | python | en | ['en', 'en', 'en'] | True |
get_apns_alert_title | (message: Message) |
On an iOS notification, this is the first bolded line.
|
On an iOS notification, this is the first bolded line.
| def get_apns_alert_title(message: Message) -> str:
"""
On an iOS notification, this is the first bolded line.
"""
if message.recipient.type == Recipient.HUDDLE:
recipients = get_display_recipient(message.recipient)
assert isinstance(recipients, list)
return ", ".join(sorted(r["fu... | [
"def",
"get_apns_alert_title",
"(",
"message",
":",
"Message",
")",
"->",
"str",
":",
"if",
"message",
".",
"recipient",
".",
"type",
"==",
"Recipient",
".",
"HUDDLE",
":",
"recipients",
"=",
"get_display_recipient",
"(",
"message",
".",
"recipient",
")",
"a... | [
682,
0
] | [
693,
35
] | python | en | ['en', 'error', 'th'] | False |
get_apns_alert_subtitle | (message: Message) |
On an iOS notification, this is the second bolded line.
|
On an iOS notification, this is the second bolded line.
| def get_apns_alert_subtitle(message: Message) -> str:
"""
On an iOS notification, this is the second bolded line.
"""
if message.trigger == "mentioned":
return _("{full_name} mentioned you:").format(full_name=message.sender.full_name)
elif message.trigger == "wildcard_mentioned":
ret... | [
"def",
"get_apns_alert_subtitle",
"(",
"message",
":",
"Message",
")",
"->",
"str",
":",
"if",
"message",
".",
"trigger",
"==",
"\"mentioned\"",
":",
"return",
"_",
"(",
"\"{full_name} mentioned you:\"",
")",
".",
"format",
"(",
"full_name",
"=",
"message",
".... | [
696,
0
] | [
707,
41
] | python | en | ['en', 'error', 'th'] | False |
get_message_payload_apns | (user_profile: UserProfile, message: Message) | A `message` payload for iOS, via APNs. | A `message` payload for iOS, via APNs. | def get_message_payload_apns(user_profile: UserProfile, message: Message) -> Dict[str, Any]:
"""A `message` payload for iOS, via APNs."""
zulip_data = get_message_payload(user_profile, message)
zulip_data.update(
message_ids=[message.id],
)
assert message.rendered_content is not None
co... | [
"def",
"get_message_payload_apns",
"(",
"user_profile",
":",
"UserProfile",
",",
"message",
":",
"Message",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"zulip_data",
"=",
"get_message_payload",
"(",
"user_profile",
",",
"message",
")",
"zulip_data",
"... | [
738,
0
] | [
757,
20
] | python | en | ['en', 'en', 'en'] | True |
get_message_payload_gcm | (
user_profile: UserProfile,
message: Message,
) | A `message` payload + options, for Android via GCM/FCM. | A `message` payload + options, for Android via GCM/FCM. | def get_message_payload_gcm(
user_profile: UserProfile,
message: Message,
) -> Tuple[Dict[str, Any], Dict[str, Any]]:
"""A `message` payload + options, for Android via GCM/FCM."""
data = get_message_payload(user_profile, message)
assert message.rendered_content is not None
content, truncated = t... | [
"def",
"get_message_payload_gcm",
"(",
"user_profile",
":",
"UserProfile",
",",
"message",
":",
"Message",
",",
")",
"->",
"Tuple",
"[",
"Dict",
"[",
"str",
",",
"Any",
"]",
",",
"Dict",
"[",
"str",
",",
"Any",
"]",
"]",
":",
"data",
"=",
"get_message_... | [
760,
0
] | [
779,
28
] | python | en | ['en', 'en', 'en'] | True |
get_remove_payload_gcm | (
user_profile: UserProfile,
message_ids: List[int],
) | A `remove` payload + options, for Android via GCM/FCM. | A `remove` payload + options, for Android via GCM/FCM. | def get_remove_payload_gcm(
user_profile: UserProfile,
message_ids: List[int],
) -> Tuple[Dict[str, Any], Dict[str, Any]]:
"""A `remove` payload + options, for Android via GCM/FCM."""
gcm_payload = get_base_payload(user_profile)
gcm_payload.update(
event="remove",
zulip_message_ids="... | [
"def",
"get_remove_payload_gcm",
"(",
"user_profile",
":",
"UserProfile",
",",
"message_ids",
":",
"List",
"[",
"int",
"]",
",",
")",
"->",
"Tuple",
"[",
"Dict",
"[",
"str",
",",
"Any",
"]",
",",
"Dict",
"[",
"str",
",",
"Any",
"]",
"]",
":",
"gcm_pa... | [
782,
0
] | [
796,
35
] | python | en | ['en', 'en', 'en'] | True |
handle_remove_push_notification | (user_profile_id: int, message_ids: List[int]) | This should be called when a message that previously had a
mobile push notification executed is read. This triggers a push to the
mobile app, when the message is read on the server, to remove the
message from the notification.
| This should be called when a message that previously had a
mobile push notification executed is read. This triggers a push to the
mobile app, when the message is read on the server, to remove the
message from the notification.
| def handle_remove_push_notification(user_profile_id: int, message_ids: List[int]) -> None:
"""This should be called when a message that previously had a
mobile push notification executed is read. This triggers a push to the
mobile app, when the message is read on the server, to remove the
message from ... | [
"def",
"handle_remove_push_notification",
"(",
"user_profile_id",
":",
"int",
",",
"message_ids",
":",
"List",
"[",
"int",
"]",
")",
"->",
"None",
":",
"user_profile",
"=",
"get_user_profile_by_id",
"(",
"user_profile_id",
")",
"message_ids",
"=",
"bulk_access_messa... | [
812,
0
] | [
840,
89
] | python | en | ['en', 'en', 'en'] | True |
handle_push_notification | (user_profile_id: int, missed_message: Dict[str, Any]) |
missed_message is the event received by the
zerver.worker.queue_processors.PushNotificationWorker.consume function.
|
missed_message is the event received by the
zerver.worker.queue_processors.PushNotificationWorker.consume function.
| def handle_push_notification(user_profile_id: int, missed_message: Dict[str, Any]) -> None:
"""
missed_message is the event received by the
zerver.worker.queue_processors.PushNotificationWorker.consume function.
"""
if not push_notifications_enabled():
return
user_profile = get_user_prof... | [
"def",
"handle_push_notification",
"(",
"user_profile_id",
":",
"int",
",",
"missed_message",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"None",
":",
"if",
"not",
"push_notifications_enabled",
"(",
")",
":",
"return",
"user_profile",
"=",
"get_user_p... | [
844,
0
] | [
919,
77
] | python | en | ['en', 'error', 'th'] | False |
install_editable | (
install_options, # type: List[str]
global_options, # type: Sequence[str]
prefix, # type: Optional[str]
home, # type: Optional[str]
use_user_site, # type: bool
name, # type: str
setup_py_path, # type: str
isolated, # type: bool
build_env, # type: BuildEnvironment
unpack... | Install a package in editable mode. Most arguments are pass-through
to setuptools.
| Install a package in editable mode. Most arguments are pass-through
to setuptools.
| def install_editable(
install_options, # type: List[str]
global_options, # type: Sequence[str]
prefix, # type: Optional[str]
home, # type: Optional[str]
use_user_site, # type: bool
name, # type: str
setup_py_path, # type: str
isolated, # type: bool
build_env, # type: BuildEn... | [
"def",
"install_editable",
"(",
"install_options",
",",
"# type: List[str]",
"global_options",
",",
"# type: Sequence[str]",
"prefix",
",",
"# type: Optional[str]",
"home",
",",
"# type: Optional[str]",
"use_user_site",
",",
"# type: bool",
"name",
",",
"# type: str",
"setu... | [
18,
0
] | [
51,
13
] | python | en | ['en', 'en', 'en'] | True |
inject_into_urllib3 | () |
Monkey-patch urllib3 with SecureTransport-backed SSL-support.
|
Monkey-patch urllib3 with SecureTransport-backed SSL-support.
| def inject_into_urllib3():
"""
Monkey-patch urllib3 with SecureTransport-backed SSL-support.
"""
util.SSLContext = SecureTransportContext
util.ssl_.SSLContext = SecureTransportContext
util.HAS_SNI = HAS_SNI
util.ssl_.HAS_SNI = HAS_SNI
util.IS_SECURETRANSPORT = True
util.ssl_.IS_SECUR... | [
"def",
"inject_into_urllib3",
"(",
")",
":",
"util",
".",
"SSLContext",
"=",
"SecureTransportContext",
"util",
".",
"ssl_",
".",
"SSLContext",
"=",
"SecureTransportContext",
"util",
".",
"HAS_SNI",
"=",
"HAS_SNI",
"util",
".",
"ssl_",
".",
"HAS_SNI",
"=",
"HAS... | [
179,
0
] | [
188,
39
] | python | en | ['en', 'error', 'th'] | False |
extract_from_urllib3 | () |
Undo monkey-patching by :func:`inject_into_urllib3`.
|
Undo monkey-patching by :func:`inject_into_urllib3`.
| def extract_from_urllib3():
"""
Undo monkey-patching by :func:`inject_into_urllib3`.
"""
util.SSLContext = orig_util_SSLContext
util.ssl_.SSLContext = orig_util_SSLContext
util.HAS_SNI = orig_util_HAS_SNI
util.ssl_.HAS_SNI = orig_util_HAS_SNI
util.IS_SECURETRANSPORT = False
util.ssl_... | [
"def",
"extract_from_urllib3",
"(",
")",
":",
"util",
".",
"SSLContext",
"=",
"orig_util_SSLContext",
"util",
".",
"ssl_",
".",
"SSLContext",
"=",
"orig_util_SSLContext",
"util",
".",
"HAS_SNI",
"=",
"orig_util_HAS_SNI",
"util",
".",
"ssl_",
".",
"HAS_SNI",
"=",... | [
191,
0
] | [
200,
40
] | python | en | ['en', 'error', 'th'] | False |
_read_callback | (connection_id, data_buffer, data_length_pointer) |
SecureTransport read callback. This is called by ST to request that data
be returned from the socket.
|
SecureTransport read callback. This is called by ST to request that data
be returned from the socket.
| def _read_callback(connection_id, data_buffer, data_length_pointer):
"""
SecureTransport read callback. This is called by ST to request that data
be returned from the socket.
"""
wrapped_socket = None
try:
wrapped_socket = _connection_refs.get(connection_id)
if wrapped_socket is ... | [
"def",
"_read_callback",
"(",
"connection_id",
",",
"data_buffer",
",",
"data_length_pointer",
")",
":",
"wrapped_socket",
"=",
"None",
"try",
":",
"wrapped_socket",
"=",
"_connection_refs",
".",
"get",
"(",
"connection_id",
")",
"if",
"wrapped_socket",
"is",
"Non... | [
203,
0
] | [
255,
43
] | python | en | ['en', 'error', 'th'] | False |
_write_callback | (connection_id, data_buffer, data_length_pointer) |
SecureTransport write callback. This is called by ST to request that data
actually be sent on the network.
|
SecureTransport write callback. This is called by ST to request that data
actually be sent on the network.
| def _write_callback(connection_id, data_buffer, data_length_pointer):
"""
SecureTransport write callback. This is called by ST to request that data
actually be sent on the network.
"""
wrapped_socket = None
try:
wrapped_socket = _connection_refs.get(connection_id)
if wrapped_sock... | [
"def",
"_write_callback",
"(",
"connection_id",
",",
"data_buffer",
",",
"data_length_pointer",
")",
":",
"wrapped_socket",
"=",
"None",
"try",
":",
"wrapped_socket",
"=",
"_connection_refs",
".",
"get",
"(",
"connection_id",
")",
"if",
"wrapped_socket",
"is",
"No... | [
258,
0
] | [
306,
43
] | python | en | ['en', 'error', 'th'] | False |
WrappedSocket._raise_on_error | (self) |
A context manager that can be used to wrap calls that do I/O from
SecureTransport. If any of the I/O callbacks hit an exception, this
context manager will correctly propagate the exception after the fact.
This avoids silently swallowing those exceptions.
It also correctly force... |
A context manager that can be used to wrap calls that do I/O from
SecureTransport. If any of the I/O callbacks hit an exception, this
context manager will correctly propagate the exception after the fact.
This avoids silently swallowing those exceptions. | def _raise_on_error(self):
"""
A context manager that can be used to wrap calls that do I/O from
SecureTransport. If any of the I/O callbacks hit an exception, this
context manager will correctly propagate the exception after the fact.
This avoids silently swallowing those except... | [
"def",
"_raise_on_error",
"(",
"self",
")",
":",
"self",
".",
"_exception",
"=",
"None",
"# We explicitly don't catch around this yield because in the unlikely",
"# event that an exception was hit in the block we don't want to swallow",
"# it.",
"yield",
"if",
"self",
".",
"_exce... | [
343,
4
] | [
361,
27
] | python | en | ['en', 'error', 'th'] | False |
WrappedSocket._set_ciphers | (self) |
Sets up the allowed ciphers. By default this matches the set in
util.ssl_.DEFAULT_CIPHERS, at least as supported by macOS. This is done
custom and doesn't allow changing at this time, mostly because parsing
OpenSSL cipher strings is going to be a freaking nightmare.
|
Sets up the allowed ciphers. By default this matches the set in
util.ssl_.DEFAULT_CIPHERS, at least as supported by macOS. This is done
custom and doesn't allow changing at this time, mostly because parsing
OpenSSL cipher strings is going to be a freaking nightmare.
| def _set_ciphers(self):
"""
Sets up the allowed ciphers. By default this matches the set in
util.ssl_.DEFAULT_CIPHERS, at least as supported by macOS. This is done
custom and doesn't allow changing at this time, mostly because parsing
OpenSSL cipher strings is going to be a freak... | [
"def",
"_set_ciphers",
"(",
"self",
")",
":",
"ciphers",
"=",
"(",
"Security",
".",
"SSLCipherSuite",
"*",
"len",
"(",
"CIPHER_SUITES",
")",
")",
"(",
"*",
"CIPHER_SUITES",
")",
"result",
"=",
"Security",
".",
"SSLSetEnabledCiphers",
"(",
"self",
".",
"con... | [
363,
4
] | [
374,
32
] | python | en | ['en', 'error', 'th'] | False |
WrappedSocket._custom_validate | (self, verify, trust_bundle) |
Called when we have set custom validation. We do this in two cases:
first, when cert validation is entirely disabled; and second, when
using a custom trust DB.
|
Called when we have set custom validation. We do this in two cases:
first, when cert validation is entirely disabled; and second, when
using a custom trust DB.
| def _custom_validate(self, verify, trust_bundle):
"""
Called when we have set custom validation. We do this in two cases:
first, when cert validation is entirely disabled; and second, when
using a custom trust DB.
"""
# If we disabled cert validation, just say: cool.
... | [
"def",
"_custom_validate",
"(",
"self",
",",
"verify",
",",
"trust_bundle",
")",
":",
"# If we disabled cert validation, just say: cool.",
"if",
"not",
"verify",
":",
"return",
"# We want data in memory, so load it up.",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"t... | [
376,
4
] | [
431,
13
] | python | en | ['en', 'error', 'th'] | False |
WrappedSocket.handshake | (
self,
server_hostname,
verify,
trust_bundle,
min_version,
max_version,
client_cert,
client_key,
client_key_passphrase,
) |
Actually performs the TLS handshake. This is run automatically by
wrapped socket, and shouldn't be needed in user code.
|
Actually performs the TLS handshake. This is run automatically by
wrapped socket, and shouldn't be needed in user code.
| def handshake(
self,
server_hostname,
verify,
trust_bundle,
min_version,
max_version,
client_cert,
client_key,
client_key_passphrase,
):
"""
Actually performs the TLS handshake. This is run automatically by
wrapped socke... | [
"def",
"handshake",
"(",
"self",
",",
"server_hostname",
",",
"verify",
",",
"trust_bundle",
",",
"min_version",
",",
"max_version",
",",
"client_cert",
",",
"client_key",
",",
"client_key_passphrase",
",",
")",
":",
"# First, we do the initial bits of connection setup.... | [
433,
4
] | [
520,
25
] | python | en | ['en', 'error', 'th'] | False |
SecureTransportContext.check_hostname | (self) |
SecureTransport cannot have its hostname checking disabled. For more,
see the comment on getpeercert() in this file.
|
SecureTransport cannot have its hostname checking disabled. For more,
see the comment on getpeercert() in this file.
| def check_hostname(self):
"""
SecureTransport cannot have its hostname checking disabled. For more,
see the comment on getpeercert() in this file.
"""
return True | [
"def",
"check_hostname",
"(",
"self",
")",
":",
"return",
"True"
] | [
758,
4
] | [
763,
19
] | python | en | ['en', 'error', 'th'] | False |
SecureTransportContext.check_hostname | (self, value) |
SecureTransport cannot have its hostname checking disabled. For more,
see the comment on getpeercert() in this file.
|
SecureTransport cannot have its hostname checking disabled. For more,
see the comment on getpeercert() in this file.
| def check_hostname(self, value):
"""
SecureTransport cannot have its hostname checking disabled. For more,
see the comment on getpeercert() in this file.
"""
pass | [
"def",
"check_hostname",
"(",
"self",
",",
"value",
")",
":",
"pass"
] | [
766,
4
] | [
771,
12
] | python | en | ['en', 'error', 'th'] | False |
flock | (lockfile: Union[int, IO[Any]], shared: bool = False) | Lock a file object using flock(2) for the duration of a 'with' statement.
If shared is True, use a LOCK_SH lock, otherwise LOCK_EX. | Lock a file object using flock(2) for the duration of a 'with' statement. | def flock(lockfile: Union[int, IO[Any]], shared: bool = False) -> Iterator[None]:
"""Lock a file object using flock(2) for the duration of a 'with' statement.
If shared is True, use a LOCK_SH lock, otherwise LOCK_EX."""
fcntl.flock(lockfile, fcntl.LOCK_SH if shared else fcntl.LOCK_EX)
try:
yie... | [
"def",
"flock",
"(",
"lockfile",
":",
"Union",
"[",
"int",
",",
"IO",
"[",
"Any",
"]",
"]",
",",
"shared",
":",
"bool",
"=",
"False",
")",
"->",
"Iterator",
"[",
"None",
"]",
":",
"fcntl",
".",
"flock",
"(",
"lockfile",
",",
"fcntl",
".",
"LOCK_S... | [
9,
0
] | [
18,
44
] | python | en | ['en', 'en', 'en'] | True |
lockfile | (filename: str, shared: bool = False) | Lock a file using flock(2) for the duration of a 'with' statement.
If shared is True, use a LOCK_SH lock, otherwise LOCK_EX.
The file is given by name and will be created if it does not exist. | Lock a file using flock(2) for the duration of a 'with' statement. | def lockfile(filename: str, shared: bool = False) -> Iterator[None]:
"""Lock a file using flock(2) for the duration of a 'with' statement.
If shared is True, use a LOCK_SH lock, otherwise LOCK_EX.
The file is given by name and will be created if it does not exist."""
with open(filename, "w") as lock:
... | [
"def",
"lockfile",
"(",
"filename",
":",
"str",
",",
"shared",
":",
"bool",
"=",
"False",
")",
"->",
"Iterator",
"[",
"None",
"]",
":",
"with",
"open",
"(",
"filename",
",",
"\"w\"",
")",
"as",
"lock",
":",
"with",
"flock",
"(",
"lock",
",",
"share... | [
22,
0
] | [
30,
17
] | python | en | ['en', 'en', 'en'] | True |
Command.send | (self, users: List[UserProfile]) | Sends one-use only links for resetting password to target users | Sends one-use only links for resetting password to target users | def send(self, users: List[UserProfile]) -> None:
"""Sends one-use only links for resetting password to target users"""
for user_profile in users:
context = {
"email": user_profile.delivery_email,
"reset_url": generate_password_reset_url(user_profile, default_... | [
"def",
"send",
"(",
"self",
",",
"users",
":",
"List",
"[",
"UserProfile",
"]",
")",
"->",
"None",
":",
"for",
"user_profile",
"in",
"users",
":",
"context",
"=",
"{",
"\"email\"",
":",
"user_profile",
".",
"delivery_email",
",",
"\"reset_url\"",
":",
"g... | [
41,
4
] | [
57,
13
] | python | en | ['en', 'en', 'en'] | True |
ZulipTestCase.extract_api_suffix_url | (self, url: str) |
Function that extracts the URL after `/api/v1` or `/json` and also
returns the query data in the URL, if there is any.
|
Function that extracts the URL after `/api/v1` or `/json` and also
returns the query data in the URL, if there is any.
| def extract_api_suffix_url(self, url: str) -> Tuple[str, Dict[str, Any]]:
"""
Function that extracts the URL after `/api/v1` or `/json` and also
returns the query data in the URL, if there is any.
"""
url_split = url.split("?")
data: Dict[str, Any] = {}
if len(url... | [
"def",
"extract_api_suffix_url",
"(",
"self",
",",
"url",
":",
"str",
")",
"->",
"Tuple",
"[",
"str",
",",
"Dict",
"[",
"str",
",",
"Any",
"]",
"]",
":",
"url_split",
"=",
"url",
".",
"split",
"(",
"\"?\"",
")",
"data",
":",
"Dict",
"[",
"str",
"... | [
214,
4
] | [
225,
26
] | python | en | ['en', 'error', 'th'] | False |
ZulipTestCase.validate_api_response_openapi | (
self,
url: str,
method: str,
result: HttpResponse,
data: Union[str, bytes, Dict[str, Any]],
http_headers: Dict[str, Any],
intentionally_undocumented: bool = False,
) |
Validates all API responses received by this test against Zulip's API documentation,
declared in zerver/openapi/zulip.yaml. This powerful test lets us use Zulip's
extensive test coverage of corner cases in the API to ensure that we've properly
documented those corner cases.
|
Validates all API responses received by this test against Zulip's API documentation,
declared in zerver/openapi/zulip.yaml. This powerful test lets us use Zulip's
extensive test coverage of corner cases in the API to ensure that we've properly
documented those corner cases.
| def validate_api_response_openapi(
self,
url: str,
method: str,
result: HttpResponse,
data: Union[str, bytes, Dict[str, Any]],
http_headers: Dict[str, Any],
intentionally_undocumented: bool = False,
) -> None:
"""
Validates all API responses re... | [
"def",
"validate_api_response_openapi",
"(",
"self",
",",
"url",
":",
"str",
",",
"method",
":",
"str",
",",
"result",
":",
"HttpResponse",
",",
"data",
":",
"Union",
"[",
"str",
",",
"bytes",
",",
"Dict",
"[",
"str",
",",
"Any",
"]",
"]",
",",
"http... | [
227,
4
] | [
269,
13
] | python | en | ['en', 'error', 'th'] | False |
ZulipTestCase.client_patch | (
self,
url: str,
info: Dict[str, Any] = {},
intentionally_undocumented: bool = False,
**kwargs: Any,
) |
We need to urlencode, since Django's function won't do it for us.
|
We need to urlencode, since Django's function won't do it for us.
| def client_patch(
self,
url: str,
info: Dict[str, Any] = {},
intentionally_undocumented: bool = False,
**kwargs: Any,
) -> HttpResponse:
"""
We need to urlencode, since Django's function won't do it for us.
"""
encoded = urllib.parse.urlencode(... | [
"def",
"client_patch",
"(",
"self",
",",
"url",
":",
"str",
",",
"info",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
"=",
"{",
"}",
",",
"intentionally_undocumented",
":",
"bool",
"=",
"False",
",",
"*",
"*",
"kwargs",
":",
"Any",
",",
")",
"->",
"... | [
272,
4
] | [
294,
21
] | python | en | ['en', 'error', 'th'] | False |
ZulipTestCase.client_patch_multipart | (
self, url: str, info: Dict[str, Any] = {}, **kwargs: Any
) |
Use this for patch requests that have file uploads or
that need some sort of multi-part content. In the future
Django's test client may become a bit more flexible,
so we can hopefully eliminate this. (When you post
with the Django test client, it deals with MULTIPART_CONTENT
... |
Use this for patch requests that have file uploads or
that need some sort of multi-part content. In the future
Django's test client may become a bit more flexible,
so we can hopefully eliminate this. (When you post
with the Django test client, it deals with MULTIPART_CONTENT
... | def client_patch_multipart(
self, url: str, info: Dict[str, Any] = {}, **kwargs: Any
) -> HttpResponse:
"""
Use this for patch requests that have file uploads or
that need some sort of multi-part content. In the future
Django's test client may become a bit more flexible,
... | [
"def",
"client_patch_multipart",
"(",
"self",
",",
"url",
":",
"str",
",",
"info",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
"=",
"{",
"}",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"HttpResponse",
":",
"encoded",
"=",
"encode_multipart",
"(",
... | [
297,
4
] | [
313,
21
] | python | en | ['en', 'error', 'th'] | False |
ZulipTestCase.client_post_request | (self, url: str, req: Any) |
We simulate hitting an endpoint here, although we
actually resolve the URL manually and hit the view
directly. We have this helper method to allow our
instrumentation to work for /notify_tornado and
future similar methods that require doing funny
things to a request obj... |
We simulate hitting an endpoint here, although we
actually resolve the URL manually and hit the view
directly. We have this helper method to allow our
instrumentation to work for /notify_tornado and
future similar methods that require doing funny
things to a request obj... | def client_post_request(self, url: str, req: Any) -> HttpResponse:
"""
We simulate hitting an endpoint here, although we
actually resolve the URL manually and hit the view
directly. We have this helper method to allow our
instrumentation to work for /notify_tornado and
f... | [
"def",
"client_post_request",
"(",
"self",
",",
"url",
":",
"str",
",",
"req",
":",
"Any",
")",
"->",
"HttpResponse",
":",
"match",
"=",
"resolve",
"(",
"url",
")",
"return",
"match",
".",
"func",
"(",
"req",
")"
] | [
362,
4
] | [
373,
30
] | python | en | ['en', 'error', 'th'] | False |
ZulipTestCase._get_page_params | (self, result: HttpResponse) | Helper for parsing page_params after fetching the web app's home view. | Helper for parsing page_params after fetching the web app's home view. | def _get_page_params(self, result: HttpResponse) -> Dict[str, Any]:
"""Helper for parsing page_params after fetching the web app's home view."""
doc = lxml.html.document_fromstring(result.content)
[div] = doc.xpath("//div[@id='page-params']")
page_params_json = div.get("data-params")
... | [
"def",
"_get_page_params",
"(",
"self",
",",
"result",
":",
"HttpResponse",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"doc",
"=",
"lxml",
".",
"html",
".",
"document_fromstring",
"(",
"result",
".",
"content",
")",
"[",
"div",
"]",
"=",
"d... | [
495,
4
] | [
501,
26
] | python | en | ['en', 'en', 'en'] | True |
ZulipTestCase.check_rendered_logged_in_app | (self, result: HttpResponse) | Verifies that a visit of / was a 200 that rendered page_params
and not for a logged-out web-public visitor. | Verifies that a visit of / was a 200 that rendered page_params
and not for a logged-out web-public visitor. | def check_rendered_logged_in_app(self, result: HttpResponse) -> None:
"""Verifies that a visit of / was a 200 that rendered page_params
and not for a logged-out web-public visitor."""
self.assertEqual(result.status_code, 200)
page_params = self._get_page_params(result)
# It is im... | [
"def",
"check_rendered_logged_in_app",
"(",
"self",
",",
"result",
":",
"HttpResponse",
")",
"->",
"None",
":",
"self",
".",
"assertEqual",
"(",
"result",
".",
"status_code",
",",
"200",
")",
"page_params",
"=",
"self",
".",
"_get_page_params",
"(",
"result",
... | [
503,
4
] | [
511,
69
] | python | en | ['en', 'en', 'en'] | True |
ZulipTestCase.check_rendered_web_public_visitor | (self, result: HttpResponse) | Verifies that a visit of / was a 200 that rendered page_params
for a logged-out web-public visitor. | Verifies that a visit of / was a 200 that rendered page_params
for a logged-out web-public visitor. | def check_rendered_web_public_visitor(self, result: HttpResponse) -> None:
"""Verifies that a visit of / was a 200 that rendered page_params
for a logged-out web-public visitor."""
self.assertEqual(result.status_code, 200)
page_params = self._get_page_params(result)
# It is impor... | [
"def",
"check_rendered_web_public_visitor",
"(",
"self",
",",
"result",
":",
"HttpResponse",
")",
"->",
"None",
":",
"self",
".",
"assertEqual",
"(",
"result",
".",
"status_code",
",",
"200",
")",
"page_params",
"=",
"self",
".",
"_get_page_params",
"(",
"resu... | [
513,
4
] | [
520,
68
] | python | en | ['en', 'en', 'en'] | True |
ZulipTestCase.login | (self, name: str) |
Use this for really simple tests where you just need
to be logged in as some user, but don't need the actual
user object for anything else. Try to use 'hamlet' for
non-admins and 'iago' for admins:
self.login('hamlet')
Try to use 'cordelia' or 'othello' as "other"... |
Use this for really simple tests where you just need
to be logged in as some user, but don't need the actual
user object for anything else. Try to use 'hamlet' for
non-admins and 'iago' for admins: | def login(self, name: str) -> None:
"""
Use this for really simple tests where you just need
to be logged in as some user, but don't need the actual
user object for anything else. Try to use 'hamlet' for
non-admins and 'iago' for admins:
self.login('hamlet')
... | [
"def",
"login",
"(",
"self",
",",
"name",
":",
"str",
")",
"->",
"None",
":",
"assert",
"\"@\"",
"not",
"in",
"name",
",",
"\"use login_by_email for email logins\"",
"user",
"=",
"self",
".",
"example_user",
"(",
"name",
")",
"self",
".",
"login_user",
"("... | [
533,
4
] | [
546,
29
] | python | en | ['en', 'error', 'th'] | False |
ZulipTestCase.login_2fa | (self, user_profile: UserProfile) |
We need this function to call request.session.save().
do_two_factor_login doesn't save session; in normal request-response
cycle this doesn't matter because middleware will save the session
when it finds it dirty; however,in tests we will have to do that
explicitly.
|
We need this function to call request.session.save().
do_two_factor_login doesn't save session; in normal request-response
cycle this doesn't matter because middleware will save the session
when it finds it dirty; however,in tests we will have to do that
explicitly.
| def login_2fa(self, user_profile: UserProfile) -> None:
"""
We need this function to call request.session.save().
do_two_factor_login doesn't save session; in normal request-response
cycle this doesn't matter because middleware will save the session
when it finds it dirty; howeve... | [
"def",
"login_2fa",
"(",
"self",
",",
"user_profile",
":",
"UserProfile",
")",
"->",
"None",
":",
"request",
"=",
"HttpRequest",
"(",
")",
"request",
".",
"session",
"=",
"self",
".",
"client",
".",
"session",
"request",
".",
"user",
"=",
"user_profile",
... | [
581,
4
] | [
593,
30
] | python | en | ['en', 'error', 'th'] | False |
ZulipTestCase.submit_reg_form_for_user | (
self,
email: str,
password: str,
realm_name: str = "Zulip Test",
realm_subdomain: str = "zuliptest",
from_confirmation: str = "",
full_name: Optional[str] = None,
timezone: str = "",
realm_in_root_domain: Optional[str] = None,
default_str... |
Stage two of the two-step registration process.
If things are working correctly the account should be fully
registered after this call.
You can pass the HTTP_HOST variable for subdomains via kwargs.
|
Stage two of the two-step registration process. | def submit_reg_form_for_user(
self,
email: str,
password: str,
realm_name: str = "Zulip Test",
realm_subdomain: str = "zuliptest",
from_confirmation: str = "",
full_name: Optional[str] = None,
timezone: str = "",
realm_in_root_domain: Optional[str]... | [
"def",
"submit_reg_form_for_user",
"(",
"self",
",",
"email",
":",
"str",
",",
"password",
":",
"str",
",",
"realm_name",
":",
"str",
"=",
"\"Zulip Test\"",
",",
"realm_subdomain",
":",
"str",
"=",
"\"zuliptest\"",
",",
"from_confirmation",
":",
"str",
"=",
... | [
602,
4
] | [
641,
73
] | python | en | ['en', 'error', 'th'] | False |
ZulipTestCase.encode_uuid | (self, uuid: str) |
identifier: Can be an email or a remote server uuid.
|
identifier: Can be an email or a remote server uuid.
| def encode_uuid(self, uuid: str) -> str:
"""
identifier: Can be an email or a remote server uuid.
"""
if uuid in self.API_KEYS:
api_key = self.API_KEYS[uuid]
else:
api_key = get_remote_server_by_uuid(uuid).api_key
self.API_KEYS[uuid] = api_key
... | [
"def",
"encode_uuid",
"(",
"self",
",",
"uuid",
":",
"str",
")",
"->",
"str",
":",
"if",
"uuid",
"in",
"self",
".",
"API_KEYS",
":",
"api_key",
"=",
"self",
".",
"API_KEYS",
"[",
"uuid",
"]",
"else",
":",
"api_key",
"=",
"get_remote_server_by_uuid",
"(... | [
665,
4
] | [
675,
53
] | python | en | ['en', 'error', 'th'] | False |
ZulipTestCase.encode_credentials | (self, identifier: str, api_key: str) |
identifier: Can be an email or a remote server uuid.
|
identifier: Can be an email or a remote server uuid.
| def encode_credentials(self, identifier: str, api_key: str) -> str:
"""
identifier: Can be an email or a remote server uuid.
"""
credentials = f"{identifier}:{api_key}"
return "Basic " + base64.b64encode(credentials.encode("utf-8")).decode("utf-8") | [
"def",
"encode_credentials",
"(",
"self",
",",
"identifier",
":",
"str",
",",
"api_key",
":",
"str",
")",
"->",
"str",
":",
"credentials",
"=",
"f\"{identifier}:{api_key}\"",
"return",
"\"Basic \"",
"+",
"base64",
".",
"b64encode",
"(",
"credentials",
".",
"en... | [
690,
4
] | [
695,
87
] | python | en | ['en', 'error', 'th'] | False |
ZulipTestCase.get_streams | (self, user_profile: UserProfile) |
Helper function to get the stream names for a user
|
Helper function to get the stream names for a user
| def get_streams(self, user_profile: UserProfile) -> List[str]:
"""
Helper function to get the stream names for a user
"""
subs = get_stream_subscriptions_for_user(user_profile).filter(
active=True,
)
return [check_string("recipient", get_display_recipient(sub.... | [
"def",
"get_streams",
"(",
"self",
",",
"user_profile",
":",
"UserProfile",
")",
"->",
"List",
"[",
"str",
"]",
":",
"subs",
"=",
"get_stream_subscriptions_for_user",
"(",
"user_profile",
")",
".",
"filter",
"(",
"active",
"=",
"True",
",",
")",
"return",
... | [
725,
4
] | [
732,
96
] | python | en | ['en', 'error', 'th'] | False |
ZulipTestCase.assert_json_success | (self, result: HttpResponse) |
Successful POSTs return a 200 and JSON of the form {"result": "success",
"msg": ""}.
|
Successful POSTs return a 200 and JSON of the form {"result": "success",
"msg": ""}.
| def assert_json_success(self, result: HttpResponse) -> Dict[str, Any]:
"""
Successful POSTs return a 200 and JSON of the form {"result": "success",
"msg": ""}.
"""
try:
json = orjson.loads(result.content)
except orjson.JSONDecodeError: # nocoverage
... | [
"def",
"assert_json_success",
"(",
"self",
",",
"result",
":",
"HttpResponse",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"try",
":",
"json",
"=",
"orjson",
".",
"loads",
"(",
"result",
".",
"content",
")",
"except",
"orjson",
".",
"JSONDecod... | [
833,
4
] | [
848,
19
] | python | en | ['en', 'error', 'th'] | False |
ZulipTestCase.assert_json_error | (self, result: HttpResponse, msg: str, status_code: int = 400) |
Invalid POSTs return an error status code and JSON of the form
{"result": "error", "msg": "reason"}.
|
Invalid POSTs return an error status code and JSON of the form
{"result": "error", "msg": "reason"}.
| def assert_json_error(self, result: HttpResponse, msg: str, status_code: int = 400) -> None:
"""
Invalid POSTs return an error status code and JSON of the form
{"result": "error", "msg": "reason"}.
"""
self.assertEqual(self.get_json_error(result, status_code=status_code), msg) | [
"def",
"assert_json_error",
"(",
"self",
",",
"result",
":",
"HttpResponse",
",",
"msg",
":",
"str",
",",
"status_code",
":",
"int",
"=",
"400",
")",
"->",
"None",
":",
"self",
".",
"assertEqual",
"(",
"self",
".",
"get_json_error",
"(",
"result",
",",
... | [
859,
4
] | [
864,
83
] | python | en | ['en', 'error', 'th'] | False |
ZulipTestCase.assert_logged_in_user_id | (self, user_id: Optional[int]) |
Verifies the user currently logged in for the test client has the provided user_id.
Pass None to verify no user is logged in.
|
Verifies the user currently logged in for the test client has the provided user_id.
Pass None to verify no user is logged in.
| def assert_logged_in_user_id(self, user_id: Optional[int]) -> None:
"""
Verifies the user currently logged in for the test client has the provided user_id.
Pass None to verify no user is logged in.
"""
self.assertEqual(get_session_dict_user(self.client.session), user_id) | [
"def",
"assert_logged_in_user_id",
"(",
"self",
",",
"user_id",
":",
"Optional",
"[",
"int",
"]",
")",
"->",
"None",
":",
"self",
".",
"assertEqual",
"(",
"get_session_dict_user",
"(",
"self",
".",
"client",
".",
"session",
")",
",",
"user_id",
")"
] | [
895,
4
] | [
900,
77
] | python | en | ['en', 'error', 'th'] | False |
ZulipTestCase.send_webhook_payload | (
self,
user_profile: UserProfile,
url: str,
payload: Union[str, Dict[str, Any]],
**post_params: Any,
) |
Send a webhook payload to the server, and verify that the
post is successful.
This is a pretty low-level function. For most use cases
see the helpers that call this function, which do additional
checks.
Occasionally tests will call this directly, for unique
si... |
Send a webhook payload to the server, and verify that the
post is successful. | def send_webhook_payload(
self,
user_profile: UserProfile,
url: str,
payload: Union[str, Dict[str, Any]],
**post_params: Any,
) -> Message:
"""
Send a webhook payload to the server, and verify that the
post is successful.
This is a pretty low-... | [
"def",
"send_webhook_payload",
"(",
"self",
",",
"user_profile",
":",
"UserProfile",
",",
"url",
":",
"str",
",",
"payload",
":",
"Union",
"[",
"str",
",",
"Dict",
"[",
"str",
",",
"Any",
"]",
"]",
",",
"*",
"*",
"post_params",
":",
"Any",
",",
")",
... | [
1015,
4
] | [
1065,
18
] | python | en | ['en', 'error', 'th'] | False |
ZulipTestCase.simulated_markdown_failure | (self) |
This raises a failure inside of the try/except block of
markdown.__init__.do_convert.
|
This raises a failure inside of the try/except block of
markdown.__init__.do_convert.
| def simulated_markdown_failure(self) -> Iterator[None]:
"""
This raises a failure inside of the try/except block of
markdown.__init__.do_convert.
"""
with self.settings(ERROR_BOT=None), mock.patch(
"zerver.lib.markdown.timeout", side_effect=subprocess.CalledProcessErr... | [
"def",
"simulated_markdown_failure",
"(",
"self",
")",
"->",
"Iterator",
"[",
"None",
"]",
":",
"with",
"self",
".",
"settings",
"(",
"ERROR_BOT",
"=",
"None",
")",
",",
"mock",
".",
"patch",
"(",
"\"zerver.lib.markdown.timeout\"",
",",
"side_effect",
"=",
"... | [
1074,
4
] | [
1082,
17
] | python | en | ['en', 'error', 'th'] | False |
ZulipTestCase.init_default_ldap_database | (self) |
Takes care of the mock_ldap setup, loads
a directory from zerver/tests/fixtures/ldap/directory.json with various entries
to be used by tests.
If a test wants to specify its own directory, it can just replace
self.mock_ldap.directory with its own content, but in most cases it sho... |
Takes care of the mock_ldap setup, loads
a directory from zerver/tests/fixtures/ldap/directory.json with various entries
to be used by tests.
If a test wants to specify its own directory, it can just replace
self.mock_ldap.directory with its own content, but in most cases it sho... | def init_default_ldap_database(self) -> None:
"""
Takes care of the mock_ldap setup, loads
a directory from zerver/tests/fixtures/ldap/directory.json with various entries
to be used by tests.
If a test wants to specify its own directory, it can just replace
self.mock_ldap... | [
"def",
"init_default_ldap_database",
"(",
"self",
")",
"->",
"None",
":",
"directory",
"=",
"orjson",
".",
"loads",
"(",
"self",
".",
"fixture_data",
"(",
"\"directory.json\"",
",",
"type",
"=",
"\"ldap\"",
")",
")",
"for",
"dn",
",",
"attrs",
"in",
"direc... | [
1115,
4
] | [
1145,
58
] | python | en | ['en', 'error', 'th'] | False |
ZulipTestCase.change_ldap_user_attr | (
self, username: str, attr_name: str, attr_value: Union[str, bytes], binary: bool = False
) |
Method for changing the value of an attribute of a user entry in the mock
directory. Use option binary=True if you want binary data to be loaded
into the attribute from a file specified at attr_value. This changes
the attribute only for the specific test function that calls this method,... |
Method for changing the value of an attribute of a user entry in the mock
directory. Use option binary=True if you want binary data to be loaded
into the attribute from a file specified at attr_value. This changes
the attribute only for the specific test function that calls this method,... | def change_ldap_user_attr(
self, username: str, attr_name: str, attr_value: Union[str, bytes], binary: bool = False
) -> None:
"""
Method for changing the value of an attribute of a user entry in the mock
directory. Use option binary=True if you want binary data to be loaded
... | [
"def",
"change_ldap_user_attr",
"(",
"self",
",",
"username",
":",
"str",
",",
"attr_name",
":",
"str",
",",
"attr_value",
":",
"Union",
"[",
"str",
",",
"bytes",
"]",
",",
"binary",
":",
"bool",
"=",
"False",
")",
"->",
"None",
":",
"dn",
"=",
"f\"u... | [
1147,
4
] | [
1165,
56
] | python | en | ['en', 'error', 'th'] | False |
ZulipTestCase.remove_ldap_user_attr | (self, username: str, attr_name: str) |
Method for removing the value of an attribute of a user entry in the mock
directory. This changes the attribute only for the specific test function
that calls this method, and is isolated from other tests.
|
Method for removing the value of an attribute of a user entry in the mock
directory. This changes the attribute only for the specific test function
that calls this method, and is isolated from other tests.
| def remove_ldap_user_attr(self, username: str, attr_name: str) -> None:
"""
Method for removing the value of an attribute of a user entry in the mock
directory. This changes the attribute only for the specific test function
that calls this method, and is isolated from other tests.
... | [
"def",
"remove_ldap_user_attr",
"(",
"self",
",",
"username",
":",
"str",
",",
"attr_name",
":",
"str",
")",
"->",
"None",
":",
"dn",
"=",
"f\"uid={username},ou=users,dc=zulip,dc=com\"",
"self",
".",
"mock_ldap",
".",
"directory",
"[",
"dn",
"]",
".",
"pop",
... | [
1167,
4
] | [
1174,
57
] | python | en | ['en', 'error', 'th'] | False |
ZulipTestCase.ldap_username | (self, username: str) |
Maps Zulip username to the name of the corresponding LDAP user
in our test directory at zerver/tests/fixtures/ldap/directory.json,
if the LDAP user exists.
|
Maps Zulip username to the name of the corresponding LDAP user
in our test directory at zerver/tests/fixtures/ldap/directory.json,
if the LDAP user exists.
| def ldap_username(self, username: str) -> str:
"""
Maps Zulip username to the name of the corresponding LDAP user
in our test directory at zerver/tests/fixtures/ldap/directory.json,
if the LDAP user exists.
"""
return self.example_user_ldap_username_map[username] | [
"def",
"ldap_username",
"(",
"self",
",",
"username",
":",
"str",
")",
"->",
"str",
":",
"return",
"self",
".",
"example_user_ldap_username_map",
"[",
"username",
"]"
] | [
1176,
4
] | [
1182,
60
] | python | en | ['en', 'error', 'th'] | False |
ZulipTestCase.email_display_from | (self, email_message: EmailMessage) |
Returns the email address that will show in email clients as the
"From" field.
|
Returns the email address that will show in email clients as the
"From" field.
| def email_display_from(self, email_message: EmailMessage) -> str:
"""
Returns the email address that will show in email clients as the
"From" field.
"""
# The extra_headers field may contain a "From" which is used
# for display in email clients, and appears in the RFC822
... | [
"def",
"email_display_from",
"(",
"self",
",",
"email_message",
":",
"EmailMessage",
")",
"->",
"str",
":",
"# The extra_headers field may contain a \"From\" which is used",
"# for display in email clients, and appears in the RFC822",
"# header as `From`. The `.from_email` accessor is t... | [
1187,
4
] | [
1197,
80
] | python | en | ['en', 'error', 'th'] | False |
ZulipTestCase.email_envelope_from | (self, email_message: EmailMessage) |
Returns the email address that will be used if the email bounces.
|
Returns the email address that will be used if the email bounces.
| def email_envelope_from(self, email_message: EmailMessage) -> str:
"""
Returns the email address that will be used if the email bounces.
"""
# See email_display_from, above.
return email_message.from_email | [
"def",
"email_envelope_from",
"(",
"self",
",",
"email_message",
":",
"EmailMessage",
")",
"->",
"str",
":",
"# See email_display_from, above.",
"return",
"email_message",
".",
"from_email"
] | [
1199,
4
] | [
1204,
39
] | python | en | ['en', 'error', 'th'] | False |
WebhookTestCase.check_webhook | (
self,
fixture_name: str,
expected_topic: str,
expected_message: str,
content_type: Optional[str] = "application/json",
**kwargs: Any,
) |
check_webhook is the main way to test "normal" webhooks that
work by receiving a payload from a third party and then writing
some message to a Zulip stream.
We use `fixture_name` to find the payload data in of our test
fixtures. Then we verify that a message gets sent to a str... |
check_webhook is the main way to test "normal" webhooks that
work by receiving a payload from a third party and then writing
some message to a Zulip stream. | def check_webhook(
self,
fixture_name: str,
expected_topic: str,
expected_message: str,
content_type: Optional[str] = "application/json",
**kwargs: Any,
) -> None:
"""
check_webhook is the main way to test "normal" webhooks that
work by receivi... | [
"def",
"check_webhook",
"(",
"self",
",",
"fixture_name",
":",
"str",
",",
"expected_topic",
":",
"str",
",",
"expected_message",
":",
"str",
",",
"content_type",
":",
"Optional",
"[",
"str",
"]",
"=",
"\"application/json\"",
",",
"*",
"*",
"kwargs",
":",
... | [
1283,
4
] | [
1332,
9
] | python | en | ['en', 'error', 'th'] | False |
WebhookTestCase.send_and_test_private_message | (
self,
fixture_name: str,
expected_message: str,
content_type: str = "application/json",
**kwargs: Any,
) |
For the rare cases that you are testing a webhook that sends
private messages, use this function.
Most webhooks send to streams, and you will want to look at
check_webhook.
|
For the rare cases that you are testing a webhook that sends
private messages, use this function. | def send_and_test_private_message(
self,
fixture_name: str,
expected_message: str,
content_type: str = "application/json",
**kwargs: Any,
) -> Message:
"""
For the rare cases that you are testing a webhook that sends
private messages, use this function... | [
"def",
"send_and_test_private_message",
"(",
"self",
",",
"fixture_name",
":",
"str",
",",
"expected_message",
":",
"str",
",",
"content_type",
":",
"str",
"=",
"\"application/json\"",
",",
"*",
"*",
"kwargs",
":",
"Any",
",",
")",
"->",
"Message",
":",
"pay... | [
1345,
4
] | [
1377,
18
] | python | en | ['en', 'error', 'th'] | False |
WebhookTestCase.get_payload | (self, fixture_name: str) |
Generally webhooks that override this should return dicts. |
Generally webhooks that override this should return dicts. | def get_payload(self, fixture_name: str) -> Union[str, Dict[str, str]]:
"""
Generally webhooks that override this should return dicts."""
return self.get_body(fixture_name) | [
"def",
"get_payload",
"(",
"self",
",",
"fixture_name",
":",
"str",
")",
"->",
"Union",
"[",
"str",
",",
"Dict",
"[",
"str",
",",
"str",
"]",
"]",
":",
"return",
"self",
".",
"get_body",
"(",
"fixture_name",
")"
] | [
1401,
4
] | [
1404,
42
] | python | en | ['en', 'error', 'th'] | False |
get_isolated_page | (request: HttpRequest) | Accept a GET param `?nav=no` to render an isolated, navless page. | Accept a GET param `?nav=no` to render an isolated, navless page. | def get_isolated_page(request: HttpRequest) -> bool:
"""Accept a GET param `?nav=no` to render an isolated, navless page."""
return request.GET.get("nav") == "no" | [
"def",
"get_isolated_page",
"(",
"request",
":",
"HttpRequest",
")",
"->",
"bool",
":",
"return",
"request",
".",
"GET",
".",
"get",
"(",
"\"nav\"",
")",
"==",
"\"no\""
] | [
88,
0
] | [
90,
41
] | python | en | ['en', 'en', 'en'] | True |
SetAccessControlsAction.clean | (self) | Check to make sure password fields match. | Check to make sure password fields match. | def clean(self):
'''Check to make sure password fields match.'''
cleaned_data = super(SetAccessControlsAction, self).clean()
if 'admin_pass' in cleaned_data:
if cleaned_data['admin_pass'] != cleaned_data.get(
'confirm_admin_pass', None):
raise form... | [
"def",
"clean",
"(",
"self",
")",
":",
"cleaned_data",
"=",
"super",
"(",
"SetAccessControlsAction",
",",
"self",
")",
".",
"clean",
"(",
")",
"if",
"'admin_pass'",
"in",
"cleaned_data",
":",
"if",
"cleaned_data",
"[",
"'admin_pass'",
"]",
"!=",
"cleaned_dat... | [
601,
4
] | [
608,
27
] | python | en | ['en', 'en', 'en'] | True |
DetailProjectViewTests.test_detail_view_overview_tab | (self) | Test the overview tab of the detail view .
Test the overview tab using directly the url targeting the tab.
| Test the overview tab of the detail view . | def test_detail_view_overview_tab(self):
"""Test the overview tab of the detail view .
Test the overview tab using directly the url targeting the tab.
"""
project = self.tenants.first()
domain = self.domains.first()
self.mock_tenant_get.return_value = project
se... | [
"def",
"test_detail_view_overview_tab",
"(",
"self",
")",
":",
"project",
"=",
"self",
".",
"tenants",
".",
"first",
"(",
")",
"domain",
"=",
"self",
".",
"domains",
".",
"first",
"(",
")",
"self",
".",
"mock_tenant_get",
".",
"return_value",
"=",
"project... | [
1327,
4
] | [
1358,
78
] | python | en | ['en', 'en', 'en'] | True |
sorted_walk | (dir) | Do os.walk in a reproducible way,
independent of indeterministic filesystem readdir order
| Do os.walk in a reproducible way,
independent of indeterministic filesystem readdir order
| def sorted_walk(dir):
"""Do os.walk in a reproducible way,
independent of indeterministic filesystem readdir order
"""
for base, dirs, files in os.walk(dir):
dirs.sort()
files.sort()
yield base, dirs, files | [
"def",
"sorted_walk",
"(",
"dir",
")",
":",
"for",
"base",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"dir",
")",
":",
"dirs",
".",
"sort",
"(",
")",
"files",
".",
"sort",
"(",
")",
"yield",
"base",
",",
"dirs",
",",
"files"
] | [
35,
0
] | [
42,
31
] | python | en | ['en', 'gl', 'en'] | True |
walk_egg | (egg_dir) | Walk an unpacked egg's contents, skipping the metadata directory | Walk an unpacked egg's contents, skipping the metadata directory | def walk_egg(egg_dir):
"""Walk an unpacked egg's contents, skipping the metadata directory"""
walker = sorted_walk(egg_dir)
base, dirs, files = next(walker)
if 'EGG-INFO' in dirs:
dirs.remove('EGG-INFO')
yield base, dirs, files
for bdf in walker:
yield bdf | [
"def",
"walk_egg",
"(",
"egg_dir",
")",
":",
"walker",
"=",
"sorted_walk",
"(",
"egg_dir",
")",
"base",
",",
"dirs",
",",
"files",
"=",
"next",
"(",
"walker",
")",
"if",
"'EGG-INFO'",
"in",
"dirs",
":",
"dirs",
".",
"remove",
"(",
"'EGG-INFO'",
")",
... | [
358,
0
] | [
366,
17
] | python | en | ['en', 'en', 'en'] | True |
scan_module | (egg_dir, base, name, stubs) | Check whether module possibly uses unsafe-for-zipfile stuff | Check whether module possibly uses unsafe-for-zipfile stuff | def scan_module(egg_dir, base, name, stubs):
"""Check whether module possibly uses unsafe-for-zipfile stuff"""
filename = os.path.join(base, name)
if filename[:-1] in stubs:
return True # Extension module
pkg = base[len(egg_dir) + 1:].replace(os.sep, '.')
module = pkg + (pkg and '.' or '')... | [
"def",
"scan_module",
"(",
"egg_dir",
",",
"base",
",",
"name",
",",
"stubs",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"base",
",",
"name",
")",
"if",
"filename",
"[",
":",
"-",
"1",
"]",
"in",
"stubs",
":",
"return",
"True... | [
406,
0
] | [
437,
15
] | python | en | ['en', 'en', 'en'] | True |
iter_symbols | (code) | Yield names and strings used by `code` and its nested code objects | Yield names and strings used by `code` and its nested code objects | def iter_symbols(code):
"""Yield names and strings used by `code` and its nested code objects"""
for name in code.co_names:
yield name
for const in code.co_consts:
if isinstance(const, str):
yield const
elif isinstance(const, CodeType):
for name in iter_symbol... | [
"def",
"iter_symbols",
"(",
"code",
")",
":",
"for",
"name",
"in",
"code",
".",
"co_names",
":",
"yield",
"name",
"for",
"const",
"in",
"code",
".",
"co_consts",
":",
"if",
"isinstance",
"(",
"const",
",",
"str",
")",
":",
"yield",
"const",
"elif",
"... | [
440,
0
] | [
449,
26
] | python | en | ['en', 'en', 'en'] | True |
make_zipfile | (zip_filename, base_dir, verbose=0, dry_run=0, compress=True,
mode='w') | Create a zip file from all the files under 'base_dir'. The output
zip file will be named 'base_dir' + ".zip". Uses either the "zipfile"
Python module (if available) or the InfoZIP "zip" utility (if installed
and found on the default search path). If neither tool is available,
raises DistutilsExecErro... | Create a zip file from all the files under 'base_dir'. The output
zip file will be named 'base_dir' + ".zip". Uses either the "zipfile"
Python module (if available) or the InfoZIP "zip" utility (if installed
and found on the default search path). If neither tool is available,
raises DistutilsExecErro... | def make_zipfile(zip_filename, base_dir, verbose=0, dry_run=0, compress=True,
mode='w'):
"""Create a zip file from all the files under 'base_dir'. The output
zip file will be named 'base_dir' + ".zip". Uses either the "zipfile"
Python module (if available) or the InfoZIP "zip" utility (if... | [
"def",
"make_zipfile",
"(",
"zip_filename",
",",
"base_dir",
",",
"verbose",
"=",
"0",
",",
"dry_run",
"=",
"0",
",",
"compress",
"=",
"True",
",",
"mode",
"=",
"'w'",
")",
":",
"import",
"zipfile",
"mkpath",
"(",
"os",
".",
"path",
".",
"dirname",
"... | [
469,
0
] | [
500,
23
] | python | en | ['en', 'en', 'en'] | True |
bdist_egg.call_command | (self, cmdname, **kw) | Invoke reinitialized command `cmdname` with keyword args | Invoke reinitialized command `cmdname` with keyword args | def call_command(self, cmdname, **kw):
"""Invoke reinitialized command `cmdname` with keyword args"""
for dirname in INSTALL_DIRECTORY_ATTRS:
kw.setdefault(dirname, self.bdist_dir)
kw.setdefault('skip_build', self.skip_build)
kw.setdefault('dry_run', self.dry_run)
cmd... | [
"def",
"call_command",
"(",
"self",
",",
"cmdname",
",",
"*",
"*",
"kw",
")",
":",
"for",
"dirname",
"in",
"INSTALL_DIRECTORY_ATTRS",
":",
"kw",
".",
"setdefault",
"(",
"dirname",
",",
"self",
".",
"bdist_dir",
")",
"kw",
".",
"setdefault",
"(",
"'skip_b... | [
145,
4
] | [
153,
18
] | python | en | ['en', 'en', 'en'] | True |
bdist_egg.copy_metadata_to | (self, target_dir) | Copy metadata (egg info) to the target_dir | Copy metadata (egg info) to the target_dir | def copy_metadata_to(self, target_dir):
"Copy metadata (egg info) to the target_dir"
# normalize the path (so that a forward-slash in egg_info will
# match using startswith below)
norm_egg_info = os.path.normpath(self.egg_info)
prefix = os.path.join(norm_egg_info, '')
for... | [
"def",
"copy_metadata_to",
"(",
"self",
",",
"target_dir",
")",
":",
"# normalize the path (so that a forward-slash in egg_info will",
"# match using startswith below)",
"norm_egg_info",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"self",
".",
"egg_info",
")",
"prefix",... | [
314,
4
] | [
324,
44
] | python | en | ['en', 'pt', 'en'] | True |
bdist_egg.get_ext_outputs | (self) | Get a list of relative paths to C extensions in the output distro | Get a list of relative paths to C extensions in the output distro | def get_ext_outputs(self):
"""Get a list of relative paths to C extensions in the output distro"""
all_outputs = []
ext_outputs = []
paths = {self.bdist_dir: ''}
for base, dirs, files in sorted_walk(self.bdist_dir):
for filename in files:
if os.path.... | [
"def",
"get_ext_outputs",
"(",
"self",
")",
":",
"all_outputs",
"=",
"[",
"]",
"ext_outputs",
"=",
"[",
"]",
"paths",
"=",
"{",
"self",
".",
"bdist_dir",
":",
"''",
"}",
"for",
"base",
",",
"dirs",
",",
"files",
"in",
"sorted_walk",
"(",
"self",
".",... | [
326,
4
] | [
352,
39
] | python | en | ['en', 'en', 'en'] | True |
dump | (o, f, encoder=None) | Writes out dict as toml to a file
Args:
o: Object to dump into toml
f: File descriptor where the toml should be stored
encoder: The ``TomlEncoder`` to use for constructing the output string
Returns:
String containing the toml corresponding to dictionary
Raises:
Typ... | Writes out dict as toml to a file | def dump(o, f, encoder=None):
"""Writes out dict as toml to a file
Args:
o: Object to dump into toml
f: File descriptor where the toml should be stored
encoder: The ``TomlEncoder`` to use for constructing the output string
Returns:
String containing the toml corresponding t... | [
"def",
"dump",
"(",
"o",
",",
"f",
",",
"encoder",
"=",
"None",
")",
":",
"if",
"not",
"f",
".",
"write",
":",
"raise",
"TypeError",
"(",
"\"You can only dump an object to a file descriptor\"",
")",
"d",
"=",
"dumps",
"(",
"o",
",",
"encoder",
"=",
"enco... | [
11,
0
] | [
30,
12
] | python | en | ['en', 'en', 'en'] | True |
dumps | (o, encoder=None) | Stringifies input dict as toml
Args:
o: Object to dump into toml
encoder: The ``TomlEncoder`` to use for constructing the output string
Returns:
String containing the toml corresponding to dict
Examples:
```python
>>> import toml
>>> output = {
... ... | Stringifies input dict as toml | def dumps(o, encoder=None):
"""Stringifies input dict as toml
Args:
o: Object to dump into toml
encoder: The ``TomlEncoder`` to use for constructing the output string
Returns:
String containing the toml corresponding to dict
Examples:
```python
>>> import toml
... | [
"def",
"dumps",
"(",
"o",
",",
"encoder",
"=",
"None",
")",
":",
"retval",
"=",
"\"\"",
"if",
"encoder",
"is",
"None",
":",
"encoder",
"=",
"TomlEncoder",
"(",
"o",
".",
"__class__",
")",
"addtoretval",
",",
"sections",
"=",
"encoder",
".",
"dump_secti... | [
33,
0
] | [
82,
17
] | python | en | ['en', 'en', 'en'] | True |
TomlEncoder.dump_inline_table | (self, section) | Preserve inline table in its compact syntax instead of expanding
into subsection.
https://github.com/toml-lang/toml#user-content-inline-table
| Preserve inline table in its compact syntax instead of expanding
into subsection. | def dump_inline_table(self, section):
"""Preserve inline table in its compact syntax instead of expanding
into subsection.
https://github.com/toml-lang/toml#user-content-inline-table
"""
retval = ""
if isinstance(section, dict):
val_list = []
for ... | [
"def",
"dump_inline_table",
"(",
"self",
",",
"section",
")",
":",
"retval",
"=",
"\"\"",
"if",
"isinstance",
"(",
"section",
",",
"dict",
")",
":",
"val_list",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"section",
".",
"items",
"(",
")",
":",
"val... | [
156,
4
] | [
171,
52
] | python | en | ['en', 'en', 'en'] | True |
__class_factory | (name, meta) |
Factory function
|
Factory function
| def __class_factory(name, meta):
"""
Factory function
"""
attr = {}
attr["uriref"] = meta['uri']
attr["properties"] = meta['properties']
gen_getset = lambda key: \
lambda: property(
lambda self: self.properties[key]["value"] if "value" in self.properties[key] else None,
... | [
"def",
"__class_factory",
"(",
"name",
",",
"meta",
")",
":",
"attr",
"=",
"{",
"}",
"attr",
"[",
"\"uriref\"",
"]",
"=",
"meta",
"[",
"'uri'",
"]",
"attr",
"[",
"\"properties\"",
"]",
"=",
"meta",
"[",
"'properties'",
"]",
"gen_getset",
"=",
"lambda",... | [
15,
0
] | [
31,
40
] | python | en | ['en', 'error', 'th'] | False |
get_valid_target_directories | (user, scratch_org, repo_root) |
Expects to be called from within a `local_github_checkout`.
|
Expects to be called from within a `local_github_checkout`.
| def get_valid_target_directories(user, scratch_org, repo_root):
"""
Expects to be called from within a `local_github_checkout`.
"""
package_directories = {}
project = scratch_org.task.epic.project
repo = get_repo_info(
None, repo_owner=project.repo_owner, repo_name=project.repo_name
... | [
"def",
"get_valid_target_directories",
"(",
"user",
",",
"scratch_org",
",",
"repo_root",
")",
":",
"package_directories",
"=",
"{",
"}",
"project",
"=",
"scratch_org",
".",
"task",
".",
"epic",
".",
"project",
"repo",
"=",
"get_repo_info",
"(",
"None",
",",
... | [
16,
0
] | [
77,
36
] | python | en | ['en', 'error', 'th'] | False |
Git.get_current_branch | (cls, location) |
Return the current branch, or None if HEAD isn't at a branch
(e.g. detached HEAD).
|
Return the current branch, or None if HEAD isn't at a branch
(e.g. detached HEAD).
| def get_current_branch(cls, location):
"""
Return the current branch, or None if HEAD isn't at a branch
(e.g. detached HEAD).
"""
# git-symbolic-ref exits with empty stdout if "HEAD" is a detached
# HEAD rather than a symbolic ref. In addition, the -q causes the
... | [
"def",
"get_current_branch",
"(",
"cls",
",",
"location",
")",
":",
"# git-symbolic-ref exits with empty stdout if \"HEAD\" is a detached",
"# HEAD rather than a symbolic ref. In addition, the -q causes the",
"# command to exit with status code 1 instead of 128 in this case",
"# and to suppre... | [
92,
4
] | [
110,
19
] | python | en | ['en', 'error', 'th'] | False |
Git.export | (self, location, url) | Export the Git repository at the url to the destination location | Export the Git repository at the url to the destination location | def export(self, location, url):
# type: (str, HiddenText) -> None
"""Export the Git repository at the url to the destination location"""
if not location.endswith('/'):
location = location + '/'
with TempDirectory(kind="export") as temp_dir:
self.unpack(temp_dir.... | [
"def",
"export",
"(",
"self",
",",
"location",
",",
"url",
")",
":",
"# type: (str, HiddenText) -> None",
"if",
"not",
"location",
".",
"endswith",
"(",
"'/'",
")",
":",
"location",
"=",
"location",
"+",
"'/'",
"with",
"TempDirectory",
"(",
"kind",
"=",
"\... | [
112,
4
] | [
123,
13
] | python | en | ['en', 'en', 'en'] | True |
Git.get_revision_sha | (cls, dest, rev) |
Return (sha_or_none, is_branch), where sha_or_none is a commit hash
if the revision names a remote branch or tag, otherwise None.
Args:
dest: the repository directory.
rev: the revision name.
|
Return (sha_or_none, is_branch), where sha_or_none is a commit hash
if the revision names a remote branch or tag, otherwise None. | def get_revision_sha(cls, dest, rev):
"""
Return (sha_or_none, is_branch), where sha_or_none is a commit hash
if the revision names a remote branch or tag, otherwise None.
Args:
dest: the repository directory.
rev: the revision name.
"""
# Pass rev to... | [
"def",
"get_revision_sha",
"(",
"cls",
",",
"dest",
",",
"rev",
")",
":",
"# Pass rev to pre-filter the list.",
"output",
"=",
"''",
"try",
":",
"output",
"=",
"cls",
".",
"run_command",
"(",
"[",
"'show-ref'",
",",
"rev",
"]",
",",
"cwd",
"=",
"dest",
"... | [
126,
4
] | [
163,
27
] | python | en | ['en', 'error', 'th'] | False |
Git.resolve_revision | (cls, dest, url, rev_options) |
Resolve a revision to a new RevOptions object with the SHA1 of the
branch, tag, or ref if found.
Args:
rev_options: a RevOptions object.
|
Resolve a revision to a new RevOptions object with the SHA1 of the
branch, tag, or ref if found. | def resolve_revision(cls, dest, url, rev_options):
# type: (str, HiddenText, RevOptions) -> RevOptions
"""
Resolve a revision to a new RevOptions object with the SHA1 of the
branch, tag, or ref if found.
Args:
rev_options: a RevOptions object.
"""
rev =... | [
"def",
"resolve_revision",
"(",
"cls",
",",
"dest",
",",
"url",
",",
"rev_options",
")",
":",
"# type: (str, HiddenText, RevOptions) -> RevOptions",
"rev",
"=",
"rev_options",
".",
"arg_rev",
"# The arg_rev property's implementation for Git ensures that the",
"# rev return valu... | [
166,
4
] | [
208,
26
] | python | en | ['en', 'error', 'th'] | False |
Git.is_commit_id_equal | (cls, dest, name) |
Return whether the current commit hash equals the given name.
Args:
dest: the repository directory.
name: a string name.
|
Return whether the current commit hash equals the given name. | def is_commit_id_equal(cls, dest, name):
"""
Return whether the current commit hash equals the given name.
Args:
dest: the repository directory.
name: a string name.
"""
if not name:
# Then avoid an unnecessary subprocess call.
return ... | [
"def",
"is_commit_id_equal",
"(",
"cls",
",",
"dest",
",",
"name",
")",
":",
"if",
"not",
"name",
":",
"# Then avoid an unnecessary subprocess call.",
"return",
"False",
"return",
"cls",
".",
"get_revision",
"(",
"dest",
")",
"==",
"name"
] | [
211,
4
] | [
223,
45
] | python | en | ['en', 'error', 'th'] | False |
Git.get_remote_url | (cls, location) |
Return URL of the first remote encountered.
Raises RemoteNotFoundError if the repository does not have a remote
url configured.
|
Return URL of the first remote encountered. | def get_remote_url(cls, location):
"""
Return URL of the first remote encountered.
Raises RemoteNotFoundError if the repository does not have a remote
url configured.
"""
# We need to pass 1 for extra_ok_returncodes since the command
# exits with return code 1 if... | [
"def",
"get_remote_url",
"(",
"cls",
",",
"location",
")",
":",
"# We need to pass 1 for extra_ok_returncodes since the command",
"# exits with return code 1 if there are no matching lines.",
"stdout",
"=",
"cls",
".",
"run_command",
"(",
"[",
"'config'",
",",
"'--get-regexp'",... | [
282,
4
] | [
306,
26
] | python | en | ['en', 'error', 'th'] | False |
Git.get_subdirectory | (cls, location) |
Return the path to setup.py, relative to the repo root.
Return None if setup.py is in the repo root.
|
Return the path to setup.py, relative to the repo root.
Return None if setup.py is in the repo root.
| def get_subdirectory(cls, location):
"""
Return the path to setup.py, relative to the repo root.
Return None if setup.py is in the repo root.
"""
# find the repo root
git_dir = cls.run_command(
['rev-parse', '--git-dir'],
cwd=location).strip()
... | [
"def",
"get_subdirectory",
"(",
"cls",
",",
"location",
")",
":",
"# find the repo root",
"git_dir",
"=",
"cls",
".",
"run_command",
"(",
"[",
"'rev-parse'",
",",
"'--git-dir'",
"]",
",",
"cwd",
"=",
"location",
")",
".",
"strip",
"(",
")",
"if",
"not",
... | [
318,
4
] | [
330,
69
] | python | en | ['en', 'error', 'th'] | False |
Git.get_url_rev_and_auth | (cls, url) |
Prefixes stub URLs like 'user@hostname:user/repo.git' with 'ssh://'.
That's required because although they use SSH they sometimes don't
work with a ssh:// scheme (e.g. GitHub). But we need a scheme for
parsing. Hence we remove it again afterwards and return it as a stub.
|
Prefixes stub URLs like 'user | def get_url_rev_and_auth(cls, url):
# type: (str) -> Tuple[str, Optional[str], AuthInfo]
"""
Prefixes stub URLs like 'user@hostname:user/repo.git' with 'ssh://'.
That's required because although they use SSH they sometimes don't
work with a ssh:// scheme (e.g. GitHub). But we nee... | [
"def",
"get_url_rev_and_auth",
"(",
"cls",
",",
"url",
")",
":",
"# type: (str) -> Tuple[str, Optional[str], AuthInfo]",
"# Works around an apparent Git bug",
"# (see https://article.gmane.org/gmane.comp.version-control.git/146500)",
"scheme",
",",
"netloc",
",",
"path",
",",
"quer... | [
333,
4
] | [
365,
34
] | python | en | ['en', 'error', 'th'] | False |
DriveMotorController.get_target_body_velocity | (self) | Returns a copy of the target body velocity. | Returns a copy of the target body velocity. | def get_target_body_velocity(self) -> BodyVelocity:
"""Returns a copy of the target body velocity."""
return copy(self._target_body_velocity) | [
"def",
"get_target_body_velocity",
"(",
"self",
")",
"->",
"BodyVelocity",
":",
"return",
"copy",
"(",
"self",
".",
"_target_body_velocity",
")"
] | [
81,
4
] | [
83,
47
] | python | en | ['en', 'en', 'en'] | True |
DriveMotorController.set_body_velocity | (self, v_x: Real, v_y: Real, omega: Real, immediate: bool = False) |
:param v_x: X velocity [-1, 1].
:param v_y: Y velocity [-1, 1].
:param omega: Rotational velocity [-1, 1]. Positive value corresponds to clockwise rotation.
:param immediate: Set the body velocity as soon as possible, without low-pass filtering.
|
:param v_x: X velocity [-1, 1].
:param v_y: Y velocity [-1, 1].
:param omega: Rotational velocity [-1, 1]. Positive value corresponds to clockwise rotation.
:param immediate: Set the body velocity as soon as possible, without low-pass filtering.
| def set_body_velocity(self, v_x: Real, v_y: Real, omega: Real, immediate: bool = False):
"""
:param v_x: X velocity [-1, 1].
:param v_y: Y velocity [-1, 1].
:param omega: Rotational velocity [-1, 1]. Positive value corresponds to clockwise rotation.
:param immediate: Set the body... | [
"def",
"set_body_velocity",
"(",
"self",
",",
"v_x",
":",
"Real",
",",
"v_y",
":",
"Real",
",",
"omega",
":",
"Real",
",",
"immediate",
":",
"bool",
"=",
"False",
")",
":",
"self",
".",
"_target_body_velocity",
"=",
"BodyVelocity",
"(",
"*",
"np",
".",... | [
97,
4
] | [
107,
54
] | python | en | ['en', 'error', 'th'] | False |
normalize_encoding | (encoding) | Normalize an encoding name.
Normalization works as follows: all non-alphanumeric
characters except the dot used for Python package names are
collapsed and replaced with a single underscore, e.g. ' -;#'
becomes '_'. Leading and trailing underscores are removed.
Note that encod... | Normalize an encoding name. | def normalize_encoding(encoding):
""" Normalize an encoding name.
Normalization works as follows: all non-alphanumeric
characters except the dot used for Python package names are
collapsed and replaced with a single underscore, e.g. ' -;#'
becomes '_'. Leading and trailing undersc... | [
"def",
"normalize_encoding",
"(",
"encoding",
")",
":",
"if",
"isinstance",
"(",
"encoding",
",",
"bytes",
")",
":",
"encoding",
"=",
"str",
"(",
"encoding",
",",
"\"ascii\"",
")",
"chars",
"=",
"[",
"]",
"punct",
"=",
"False",
"for",
"c",
"in",
"encod... | [
42,
0
] | [
68,
25
] | python | en | ['en', 'en', 'en'] | True |
_parse_pitch_class | (pitch_class_str) | Parse pitch class from string, returning scale step and alteration. | Parse pitch class from string, returning scale step and alteration. | def _parse_pitch_class(pitch_class_str):
"""Parse pitch class from string, returning scale step and alteration."""
match = re.match(_PITCH_CLASS_REGEX, pitch_class_str)
step, alter = match.groups()
return step, len(alter) * (1 if '#' in alter else -1) | [
"def",
"_parse_pitch_class",
"(",
"pitch_class_str",
")",
":",
"match",
"=",
"re",
".",
"match",
"(",
"_PITCH_CLASS_REGEX",
",",
"pitch_class_str",
")",
"step",
",",
"alter",
"=",
"match",
".",
"groups",
"(",
")",
"return",
"step",
",",
"len",
"(",
"alter"... | [
304,
0
] | [
308,
55
] | python | en | ['en', 'en', 'en'] | True |
_parse_root | (root_str) | Parse chord root from string. | Parse chord root from string. | def _parse_root(root_str):
"""Parse chord root from string."""
return _parse_pitch_class(root_str) | [
"def",
"_parse_root",
"(",
"root_str",
")",
":",
"return",
"_parse_pitch_class",
"(",
"root_str",
")"
] | [
311,
0
] | [
313,
37
] | python | en | ['en', 'en', 'en'] | True |
_parse_degree | (degree_str) | Parse scale degree from string (from internal kind representation). | Parse scale degree from string (from internal kind representation). | def _parse_degree(degree_str):
"""Parse scale degree from string (from internal kind representation)."""
match = _SCALE_DEGREE_REGEX.match(degree_str)
alter, degree = match.groups()
return int(degree), len(alter) * (1 if '#' in alter else -1) | [
"def",
"_parse_degree",
"(",
"degree_str",
")",
":",
"match",
"=",
"_SCALE_DEGREE_REGEX",
".",
"match",
"(",
"degree_str",
")",
"alter",
",",
"degree",
"=",
"match",
".",
"groups",
"(",
")",
"return",
"int",
"(",
"degree",
")",
",",
"len",
"(",
"alter",
... | [
316,
0
] | [
320,
62
] | python | en | ['en', 'en', 'en'] | True |
_parse_kind | (kind_str) | Parse chord kind from string, returning a scale degree dictionary. | Parse chord kind from string, returning a scale degree dictionary. | def _parse_kind(kind_str):
"""Parse chord kind from string, returning a scale degree dictionary."""
degrees = _CHORD_KINDS_BY_ABBREV[kind_str]
# Here we make the assumption that each scale degree can be present in a chord
# at most once. This is not generally true, as e.g. a chord could contain both
# b9 and ... | [
"def",
"_parse_kind",
"(",
"kind_str",
")",
":",
"degrees",
"=",
"_CHORD_KINDS_BY_ABBREV",
"[",
"kind_str",
"]",
"# Here we make the assumption that each scale degree can be present in a chord",
"# at most once. This is not generally true, as e.g. a chord could contain both",
"# b9 and #... | [
323,
0
] | [
329,
66
] | python | en | ['en', 'en', 'en'] | True |
_parse_modifications | (modifications_str) | Parse scale degree modifications from string.
This returns a list of function-degree-alteration triples. The function, when
applied to the list of scale degrees, the degree to modify, and the
alteration, performs the modification.
Args:
modifications_str: A string containing the scale degree modifications... | Parse scale degree modifications from string. | def _parse_modifications(modifications_str):
"""Parse scale degree modifications from string.
This returns a list of function-degree-alteration triples. The function, when
applied to the list of scale degrees, the degree to modify, and the
alteration, performs the modification.
Args:
modifications_str: ... | [
"def",
"_parse_modifications",
"(",
"modifications_str",
")",
":",
"modifications",
"=",
"[",
"]",
"while",
"modifications_str",
":",
"match",
"=",
"_MODIFICATION_REGEX",
".",
"match",
"(",
"modifications_str",
")",
"type_str",
",",
"degree_str",
"=",
"match",
"."... | [
332,
0
] | [
357,
22
] | python | en | ['en', 'en', 'en'] | True |
_parse_bass | (bass_str) | Parse bass, returning scale step and alteration or None if no bass. | Parse bass, returning scale step and alteration or None if no bass. | def _parse_bass(bass_str):
"""Parse bass, returning scale step and alteration or None if no bass."""
if bass_str:
return _parse_pitch_class(bass_str[1:])
else:
return None | [
"def",
"_parse_bass",
"(",
"bass_str",
")",
":",
"if",
"bass_str",
":",
"return",
"_parse_pitch_class",
"(",
"bass_str",
"[",
"1",
":",
"]",
")",
"else",
":",
"return",
"None"
] | [
360,
0
] | [
365,
15
] | python | en | ['en', 'en', 'en'] | True |
_apply_modifications | (degrees, modifications) | Apply scale degree modifications to a scale degree dictionary. | Apply scale degree modifications to a scale degree dictionary. | def _apply_modifications(degrees, modifications):
"""Apply scale degree modifications to a scale degree dictionary."""
for mod_fn, degree, alter in modifications:
mod_fn(degrees, degree, alter) | [
"def",
"_apply_modifications",
"(",
"degrees",
",",
"modifications",
")",
":",
"for",
"mod_fn",
",",
"degree",
",",
"alter",
"in",
"modifications",
":",
"mod_fn",
"(",
"degrees",
",",
"degree",
",",
"alter",
")"
] | [
368,
0
] | [
371,
34
] | python | en | ['it', 'en', 'en'] | True |
_split_chord_symbol | (figure) | Split a chord symbol into root, kind, degree modifications, and bass. | Split a chord symbol into root, kind, degree modifications, and bass. | def _split_chord_symbol(figure):
"""Split a chord symbol into root, kind, degree modifications, and bass."""
match = _CHORD_SYMBOL_REGEX.match(figure)
if not match:
raise ChordSymbolError('Unable to parse chord symbol: %s' % figure)
root_str, kind_str, modifications_str, bass_str = match.groups()
return r... | [
"def",
"_split_chord_symbol",
"(",
"figure",
")",
":",
"match",
"=",
"_CHORD_SYMBOL_REGEX",
".",
"match",
"(",
"figure",
")",
"if",
"not",
"match",
":",
"raise",
"ChordSymbolError",
"(",
"'Unable to parse chord symbol: %s'",
"%",
"figure",
")",
"root_str",
",",
... | [
374,
0
] | [
380,
56
] | python | en | ['en', 'en', 'en'] | True |
_parse_chord_symbol | (figure) | Parse a chord symbol string.
This converts the chord symbol string to a tuple representation with the
following components:
Root: A tuple containing scale step and alteration.
Degrees: A dictionary where the keys are integer scale degrees, and values
are integer alterations. For example, if 9 -> -... | Parse a chord symbol string. | def _parse_chord_symbol(figure):
"""Parse a chord symbol string.
This converts the chord symbol string to a tuple representation with the
following components:
Root: A tuple containing scale step and alteration.
Degrees: A dictionary where the keys are integer scale degrees, and values
are integ... | [
"def",
"_parse_chord_symbol",
"(",
"figure",
")",
":",
"root_str",
",",
"kind_str",
",",
"modifications_str",
",",
"bass_str",
"=",
"_split_chord_symbol",
"(",
"figure",
")",
"root",
"=",
"_parse_root",
"(",
"root_str",
")",
"degrees",
"=",
"_parse_kind",
"(",
... | [
383,
0
] | [
413,
36
] | python | cy | ['ga', 'cy', 'en'] | False |
_transpose_pitch_class | (step, alter, transpose_amount) | Transposes a chord symbol figure string by the given amount. | Transposes a chord symbol figure string by the given amount. | def _transpose_pitch_class(step, alter, transpose_amount):
"""Transposes a chord symbol figure string by the given amount."""
transpose_amount %= 12
# Transpose up as many steps as we can.
while transpose_amount >= _STEPS_ABOVE[step]:
transpose_amount -= _STEPS_ABOVE[step]
step = chr(ord('A') + (ord(st... | [
"def",
"_transpose_pitch_class",
"(",
"step",
",",
"alter",
",",
"transpose_amount",
")",
":",
"transpose_amount",
"%=",
"12",
"# Transpose up as many steps as we can.",
"while",
"transpose_amount",
">=",
"_STEPS_ABOVE",
"[",
"step",
"]",
":",
"transpose_amount",
"-=",
... | [
416,
0
] | [
434,
20
] | python | en | ['en', 'en', 'en'] | True |
_pitch_class_to_string | (step, alter) | Convert a pitch class scale step and alteration to string. | Convert a pitch class scale step and alteration to string. | def _pitch_class_to_string(step, alter):
"""Convert a pitch class scale step and alteration to string."""
return step + abs(alter) * ('#' if alter >= 0 else 'b') | [
"def",
"_pitch_class_to_string",
"(",
"step",
",",
"alter",
")",
":",
"return",
"step",
"+",
"abs",
"(",
"alter",
")",
"*",
"(",
"'#'",
"if",
"alter",
">=",
"0",
"else",
"'b'",
")"
] | [
437,
0
] | [
439,
57
] | python | en | ['en', 'en', 'en'] | True |
_pitch_class_to_midi | (step, alter) | Convert a pitch class scale step and alteration to MIDI note. | Convert a pitch class scale step and alteration to MIDI note. | def _pitch_class_to_midi(step, alter):
"""Convert a pitch class scale step and alteration to MIDI note."""
return (_STEPS_MIDI[step] + alter) % 12 | [
"def",
"_pitch_class_to_midi",
"(",
"step",
",",
"alter",
")",
":",
"return",
"(",
"_STEPS_MIDI",
"[",
"step",
"]",
"+",
"alter",
")",
"%",
"12"
] | [
442,
0
] | [
444,
41
] | python | en | ['en', 'en', 'en'] | True |
_largest_chord_kind_from_degrees | (degrees) | Find the largest chord that is contained in a set of scale degrees. | Find the largest chord that is contained in a set of scale degrees. | def _largest_chord_kind_from_degrees(degrees):
"""Find the largest chord that is contained in a set of scale degrees."""
best_chord_abbrev = None
best_chord_degrees = []
for chord_abbrevs, chord_degrees in _CHORD_KINDS:
if len(chord_degrees) <= len(best_chord_degrees):
continue
if not set(chord_de... | [
"def",
"_largest_chord_kind_from_degrees",
"(",
"degrees",
")",
":",
"best_chord_abbrev",
"=",
"None",
"best_chord_degrees",
"=",
"[",
"]",
"for",
"chord_abbrevs",
",",
"chord_degrees",
"in",
"_CHORD_KINDS",
":",
"if",
"len",
"(",
"chord_degrees",
")",
"<=",
"len"... | [
447,
0
] | [
456,
26
] | python | en | ['en', 'en', 'en'] | True |
_largest_chord_kind_from_relative_pitches | (relative_pitches) | Find the largest chord contained in a set of relative pitches. | Find the largest chord contained in a set of relative pitches. | def _largest_chord_kind_from_relative_pitches(relative_pitches):
"""Find the largest chord contained in a set of relative pitches."""
scale_degrees = [_SCALE_DEGREES[pitch] for pitch in relative_pitches]
best_chord_abbrev = None
best_degrees = []
for degrees in itertools.product(*scale_degrees):
degree_st... | [
"def",
"_largest_chord_kind_from_relative_pitches",
"(",
"relative_pitches",
")",
":",
"scale_degrees",
"=",
"[",
"_SCALE_DEGREES",
"[",
"pitch",
"]",
"for",
"pitch",
"in",
"relative_pitches",
"]",
"best_chord_abbrev",
"=",
"None",
"best_degrees",
"=",
"[",
"]",
"fo... | [
459,
0
] | [
479,
40
] | python | en | ['en', 'en', 'en'] | True |
_degrees_to_modifications | (chord_degrees, target_chord_degrees) | Find scale degree modifications to turn chord into target chord. | Find scale degree modifications to turn chord into target chord. | def _degrees_to_modifications(chord_degrees, target_chord_degrees):
"""Find scale degree modifications to turn chord into target chord."""
degrees = dict(_parse_degree(degree_str) for degree_str in chord_degrees)
target_degrees = dict(_parse_degree(degree_str)
for degree_str in target_chor... | [
"def",
"_degrees_to_modifications",
"(",
"chord_degrees",
",",
"target_chord_degrees",
")",
":",
"degrees",
"=",
"dict",
"(",
"_parse_degree",
"(",
"degree_str",
")",
"for",
"degree_str",
"in",
"chord_degrees",
")",
"target_degrees",
"=",
"dict",
"(",
"_parse_degree... | [
482,
0
] | [
508,
26
] | python | en | ['en', 'en', 'en'] | True |
transpose_chord_symbol | (figure, transpose_amount) | Transposes a chord symbol figure string by the given amount.
Args:
figure: The chord symbol figure string to transpose.
transpose_amount: The integer number of half steps to transpose.
Returns:
The transposed chord symbol figure string.
Raises:
ChordSymbolError: If the given chord symbol cannot... | Transposes a chord symbol figure string by the given amount. | def transpose_chord_symbol(figure, transpose_amount):
"""Transposes a chord symbol figure string by the given amount.
Args:
figure: The chord symbol figure string to transpose.
transpose_amount: The integer number of half steps to transpose.
Returns:
The transposed chord symbol figure string.
Rai... | [
"def",
"transpose_chord_symbol",
"(",
"figure",
",",
"transpose_amount",
")",
":",
"# Split chord symbol into root, kind, modifications, and bass.",
"root_str",
",",
"kind_str",
",",
"modifications_str",
",",
"bass_str",
"=",
"_split_chord_symbol",
"(",
"figure",
")",
"# Pa... | [
511,
0
] | [
549,
43
] | python | en | ['en', 'en', 'en'] | True |
pitches_to_chord_symbol | (pitches) | Converts a set of pitches to a chord symbol.
This is quite a complicated function and certainly imperfect, even apart from
the inherent ambiguity and context-dependence of chord naming. The basic logic
is as follows:
Consider that each pitch may be the root of the chord. For each potential
root, convert the... | Converts a set of pitches to a chord symbol. | def pitches_to_chord_symbol(pitches):
"""Converts a set of pitches to a chord symbol.
This is quite a complicated function and certainly imperfect, even apart from
the inherent ambiguity and context-dependence of chord naming. The basic logic
is as follows:
Consider that each pitch may be the root of the ch... | [
"def",
"pitches_to_chord_symbol",
"(",
"pitches",
")",
":",
"if",
"not",
"pitches",
":",
"return",
"constants",
".",
"NO_CHORD",
"# Convert to pitch classes and dedupe.",
"pitch_classes",
"=",
"set",
"(",
"pitch",
"%",
"12",
"for",
"pitch",
"in",
"pitches",
")",
... | [
552,
0
] | [
629,
74
] | python | en | ['en', 'en', 'en'] | True |
chord_symbol_pitches | (figure) | Return the pitch classes contained in a chord.
This will generally include the root pitch class, but not the bass if it is
not otherwise one of the pitches in the chord.
Args:
figure: The chord symbol figure string for which pitches are computed.
Returns:
A python list of integer pitch class values.
... | Return the pitch classes contained in a chord. | def chord_symbol_pitches(figure):
"""Return the pitch classes contained in a chord.
This will generally include the root pitch class, but not the bass if it is
not otherwise one of the pitches in the chord.
Args:
figure: The chord symbol figure string for which pitches are computed.
Returns:
A pyth... | [
"def",
"chord_symbol_pitches",
"(",
"figure",
")",
":",
"root",
",",
"degrees",
",",
"_",
"=",
"_parse_chord_symbol",
"(",
"figure",
")",
"root_step",
",",
"root_alter",
"=",
"root",
"root_pitch",
"=",
"_pitch_class_to_midi",
"(",
"root_step",
",",
"root_alter",... | [
632,
0
] | [
653,
50
] | python | en | ['en', 'en', 'en'] | True |
chord_symbol_root | (figure) | Return the root pitch class of a chord.
Args:
figure: The chord symbol figure string for which the root is computed.
Returns:
The pitch class of the chord root, an integer between 0 and 11 inclusive.
Raises:
ChordSymbolError: If the given chord symbol cannot be interpreted.
| Return the root pitch class of a chord. | def chord_symbol_root(figure):
"""Return the root pitch class of a chord.
Args:
figure: The chord symbol figure string for which the root is computed.
Returns:
The pitch class of the chord root, an integer between 0 and 11 inclusive.
Raises:
ChordSymbolError: If the given chord symbol cannot be i... | [
"def",
"chord_symbol_root",
"(",
"figure",
")",
":",
"root_str",
",",
"_",
",",
"_",
",",
"_",
"=",
"_split_chord_symbol",
"(",
"figure",
")",
"root_step",
",",
"root_alter",
"=",
"_parse_root",
"(",
"root_str",
")",
"return",
"_pitch_class_to_midi",
"(",
"r... | [
656,
0
] | [
670,
52
] | python | en | ['en', 'en', 'en'] | True |
chord_symbol_bass | (figure) | Return the bass pitch class of a chord.
Args:
figure: The chord symbol figure string for which the bass is computed.
Returns:
The pitch class of the chord bass, an integer between 0 and 11 inclusive.
Raises:
ChordSymbolError: If the given chord symbol cannot be interpreted.
| Return the bass pitch class of a chord. | def chord_symbol_bass(figure):
"""Return the bass pitch class of a chord.
Args:
figure: The chord symbol figure string for which the bass is computed.
Returns:
The pitch class of the chord bass, an integer between 0 and 11 inclusive.
Raises:
ChordSymbolError: If the given chord symbol cannot be i... | [
"def",
"chord_symbol_bass",
"(",
"figure",
")",
":",
"root_str",
",",
"_",
",",
"_",
",",
"bass_str",
"=",
"_split_chord_symbol",
"(",
"figure",
")",
"bass",
"=",
"_parse_bass",
"(",
"bass_str",
")",
"if",
"bass",
":",
"bass_step",
",",
"bass_alter",
"=",
... | [
673,
0
] | [
692,
52
] | python | en | ['en', 'en', 'en'] | True |
chord_symbol_quality | (figure) | Return the quality (major, minor, dimished, augmented) of a chord.
Args:
figure: The chord symbol figure string for which quality is computed.
Returns:
One of CHORD_QUALITY_MAJOR, CHORD_QUALITY_MINOR, CHORD_QUALITY_AUGMENTED,
CHORD_QUALITY_DIMINISHED, or CHORD_QUALITY_OTHER.
Raises:
ChordSymbol... | Return the quality (major, minor, dimished, augmented) of a chord. | def chord_symbol_quality(figure):
"""Return the quality (major, minor, dimished, augmented) of a chord.
Args:
figure: The chord symbol figure string for which quality is computed.
Returns:
One of CHORD_QUALITY_MAJOR, CHORD_QUALITY_MINOR, CHORD_QUALITY_AUGMENTED,
CHORD_QUALITY_DIMINISHED, or CHORD_QU... | [
"def",
"chord_symbol_quality",
"(",
"figure",
")",
":",
"_",
",",
"degrees",
",",
"_",
"=",
"_parse_chord_symbol",
"(",
"figure",
")",
"if",
"1",
"not",
"in",
"degrees",
"or",
"3",
"not",
"in",
"degrees",
"or",
"5",
"not",
"in",
"degrees",
":",
"return... | [
695,
0
] | [
721,
30
] | python | en | ['en', 'en', 'en'] | True |
Filter.__init__ | (self,
source,
allowed_elements=allowed_elements,
allowed_attributes=allowed_attributes,
allowed_css_properties=allowed_css_properties,
allowed_css_keywords=allowed_css_keywords,
allowed_svg_properties=allowed_svg_prop... | Creates a Filter
:arg allowed_elements: set of elements to allow--everything else will
be escaped
:arg allowed_attributes: set of attributes to allow in
elements--everything else will be stripped
:arg allowed_css_properties: set of CSS properties to allow--everything
... | Creates a Filter | def __init__(self,
source,
allowed_elements=allowed_elements,
allowed_attributes=allowed_attributes,
allowed_css_properties=allowed_css_properties,
allowed_css_keywords=allowed_css_keywords,
allowed_svg_properties=allo... | [
"def",
"__init__",
"(",
"self",
",",
"source",
",",
"allowed_elements",
"=",
"allowed_elements",
",",
"allowed_attributes",
"=",
"allowed_attributes",
",",
"allowed_css_properties",
"=",
"allowed_css_properties",
",",
"allowed_css_keywords",
"=",
"allowed_css_keywords",
"... | [
725,
4
] | [
781,
56
] | python | en | ['en', 'gl', 'en'] | True |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.